Clone any viral video with AI agents. Not just a script, the whole workflow: swap the face, the words, the B-roll, ship 100 variants in one command, and get your 100M views.
TypeScript agentic-aiaiai-agentsai-videocompilerdslffmpeggenerative-aillmmarkup-languagemonorepoplugin-systemprogramming-languagetext-to-videotypescriptvideovideo-automationvideo-clonevideo-editingvideo-generation
feat: expose Studio workspace and package-owned inspector metadata
kashorin947417cd9320
diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.tsindex 2971bb54..0103cde3 100644--- a/packages/cli/src/index.ts+++ b/packages/cli/src/index.ts@@ -1,4 +1,10 @@-export { materializeArtifact, materializeRecord, pinnedRecords, selectArchivedRecord } from "./archive.js";+export {+ collectArtifacts,+ materializeArtifact,+ materializeRecord,+ pinnedRecords,+ selectArchivedRecord,+} from "./archive.js";export type { PinnedRecord } from "./archive.js";export { runCli } from "./main.js";export { discoverSourcePackages } from "./source-discovery.js";@@ -6,6 +12,7 @@ export { loadDiscoveredSourcePackages } from "./source-packages.js";export { collectRunFrontends, loadRunFile } from "./run-file.js";export type { LoadedRunFile } from "./run-file.js";export { hypitHostStateRoot, hypitProjectStateRoot } from "./paths.js";+export { findRuntimeProfile } from "./runtime-selection.js";export { renderCliError, writeCliHelp, writeCliOutput } from "./output.js";export type {CliColorMode,diff --git a/packages/studio-adapter/src/index.ts b/packages/studio-adapter/src/index.tsindex ebee757c..8e16d479 100644--- a/packages/studio-adapter/src/index.ts+++ b/packages/studio-adapter/src/index.ts@@ -92,6 +92,11 @@ export type StudioParameter = {/** Adapter vocabulary name; unlike id this is stable across source files. */readonly name: string;readonly label: string;+ /** Package-owned Inspector page, for example Where / How / When. */+ readonly group?: string;+ /** Package-owned subsection inside the page. */+ readonly section?: string;+ readonly summary?: string;readonly control: StudioParameterControl;readonly value: string;readonly language: StudioParameterLanguage;@@ -342,6 +347,8 @@ export type StudioEntityDraft = {readonly markerId?: string;readonly presentId?: string;readonly renderIds?: readonly string[];+ /** Resolved author references that differ per derived entity, such as one Cue's actual Style. */+ readonly parameterReferences?: Readonly<Record<string, string>>;readonly presentation?: StudioTimelinePresentation;readonly interaction?: StudioInteraction;readonly temporal?: StudioTemporalLineage;diff --git a/packages/studio-video-adapters/src/generic.ts b/packages/studio-video-adapters/src/generic.tsindex 94163b35..62272d77 100644--- a/packages/studio-video-adapters/src/generic.ts+++ b/packages/studio-video-adapters/src/generic.ts@@ -43,6 +43,29 @@ type TerminalAudioTrack = {}[];};+type CaptionVisualTrack = {+ readonly presents?: readonly {+ readonly id: string;+ readonly elements?: readonly {+ readonly kind?: string;+ readonly text?: string;+ readonly attributes?: readonly { readonly name: string; readonly value: string }[];+ }[];+ }[];+};++function captionCueText(present: NonNullable<CaptionVisualTrack["presents"]>[number]): string {+ return (present.elements ?? []).flatMap((element) =>+ element.kind === "text"+ && element.text !== undefined+ && element.attributes?.some((attribute) => attribute.name === "data-caption-word") === true+ ? [element.text]+ : [])+ .join(" ")+ .replace(/([\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}])\s+(?=[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}])/gu, "$1")+ .trim();+}+function withTemporalLineage(context: StudioAdapterContext,entity: StudioEntityDraft,@@ -127,11 +150,24 @@ function projectText(context: StudioAdapterContext): readonly StudioEntityDraft[}function projectCaption(context: StudioAdapterContext): readonly StudioEntityDraft[] {- return context.generic().map((entity) => withTemporalLineage(context, {- ...entity,- presentation: { entity: "caption-cue", shape: "text", depth: 0 },- interaction: readonlyInteraction,- }));+ const cues = new Map(((context.track.value as CaptionVisualTrack).presents ?? []).map((present) => [+ present.id,+ {+ label: captionCueText(present),+ style: present.elements?.flatMap((element) => element.attributes ?? [])+ .find((attribute) => attribute.name === "data-caption-style")?.value,+ },+ ] as const));+ return context.generic().map((entity) => {+ const cue = entity.presentId === undefined ? undefined : cues.get(entity.presentId);+ return withTemporalLineage(context, {+ ...entity,+ ...(cue?.label === undefined || cue.label.length === 0 ? {} : { label: cue.label }),+ presentation: { entity: "caption-cue", shape: "text", depth: 0 },+ interaction: readonlyInteraction,+ ...(cue?.style === undefined ? {} : { parameterReferences: { program: cue.style } }),+ });+ });}function projectGenericComponent(context: StudioAdapterContext): readonly StudioEntityDraft[] {diff --git a/packages/studio/README.md b/packages/studio/README.mdindex eebfb1aa..2af12d7f 100644--- a/packages/studio/README.md+++ b/packages/studio/README.md@@ -10,6 +10,18 @@ cd /path/to/external-video-projecthypit-studio --run build.svrun```+When `--runtime` is omitted, Studio uses the nearest Runtime selection made by+`hypit runtime use`. That selection's directory is the default environment+boundary. The upper-left library is intentionally not a filesystem browser:++- Source is the exact Run + Author closure and writes back only the selected file;+- Tasks are read-only Build Catalog/Archive/Dispatch/Operation views;+- Artifacts are ArtifactStore objects referenced by accepted Records.++No project manifest, Studio database, output-directory scan or inferred campaign+folder structure is involved. With no selected Runtime, Source and Preview still+work while Tasks and Artifacts stay explicitly unavailable.+Studio is an application boundary. Core and domain packages do not import it orregister UI metadata. The installed Distribution supplies the official Studio Adapterdistribution. An external project may explicitly add companion Adapter packagesdiff --git a/packages/studio/preview-check.ts b/packages/studio/preview-check.tsindex f072a8e7..fcc6c895 100644--- a/packages/studio/preview-check.ts+++ b/packages/studio/preview-check.ts@@ -26,7 +26,7 @@ if (runArgument === undefined) {const registry = await loadStudioAdapterRegistry({ workspaceRoot, packageRoot, distributionPackageRoot });const domain = await loadStudioDomain({ run: runPath, workspaceRoot, packageRoot });- const archive = await openStudioArchive(runtimePath, packageRoot, distributionPackageRoot);+ const archive = await openStudioArchive(runtimePath, packageRoot, workspaceRoot, distributionPackageRoot);const awaitingPrefix = "the Studio projection closure requires unresolved capabilities:";let session: Awaited<ReturnType<typeof readStudioSession>> | undefined;diff --git a/packages/studio/src/archive.ts b/packages/studio/src/archive.tsindex f0e299a5..5fcf16fd 100644--- a/packages/studio/src/archive.ts+++ b/packages/studio/src/archive.ts@@ -1,11 +1,20 @@-import type { NodeRuntimeHost } from "@hypit/runtime-host-node";+import { isAbsolute, relative, resolve } from "node:path";++import type { BuildCatalogEntry } from "@hypit/runtime";+import type { NodeRuntimeHost, RuntimeHostStatus } from "@hypit/runtime-host-node";import type { Digest, StoredValue, TypeRef } from "@hypit/protocol";-import { selectArchivedRecord } from "@hypit/cli";+import { collectArtifacts, selectArchivedRecord } from "@hypit/cli";import { videoCliDistribution } from "@hypit/video-cli";+import type { StudioArtifactView, StudioLibraryView, StudioTaskView } from "./shared.js";++type RuntimeArchive = Awaited<ReturnType<NodeRuntimeHost["openArchive"]>>;+export type StudioArchive = {- readonly runtime?: Pick<Awaited<ReturnType<NodeRuntimeHost["openArchive"]>>, "status">;+ readonly profile: string;+ readonly runtime: Pick<RuntimeArchive, "status">;+ readonly library: () => Promise<StudioLibraryView>;readonly resolveBuildRecord: (build: string,output: string,@@ -14,31 +23,160 @@ export type StudioArchive = {readonly close: () => Promise<void>;};+function isWithin(root: string, path: string): boolean {+ const rel = relative(resolve(root), resolve(path));+ return rel === "" || (!rel.startsWith("..") && !isAbsolute(rel));+}++function presentedPath(root: string, path: string): string {+ return isWithin(root, path) ? relative(resolve(root), resolve(path)) || "." : resolve(path);+}++function buildBelongsTo(root: string, entry: BuildCatalogEntry): boolean {+ return isWithin(root, entry.run?.path ?? entry.source.path) || isWithin(root, entry.source.path);+}++function taskStatus(status: RuntimeHostStatus): StudioTaskView["status"] {+ if (status.dispatch !== undefined) {+ if (status.dispatch.phase === "terminal") return status.dispatch.terminal ?? "unknown";+ return status.dispatch.phase;+ }+ return status.build?.state.status ?? "unknown";+}++function targetNames(entry: BuildCatalogEntry, status: RuntimeHostStatus): readonly string[] {+ const state = status.build?.state;+ if (state === undefined) return [];+ const names = new Map(entry.aliases.flatMap((alias) => alias.ref.kind === "logical-output"+ ? [[alias.ref.id, alias.name] as const]+ : []));+ return state.request.targets.map((target) => names.get(target.output) ?? target.output);+}++function taskView(root: string, entry: BuildCatalogEntry, status: RuntimeHostStatus): StudioTaskView {+ const state = status.build?.state;+ return {+ id: entry.build,+ createdAt: entry.createdAt,+ status: taskStatus(status),+ source: presentedPath(root, entry.source.path),+ ...(entry.run === undefined ? {} : { run: presentedPath(root, entry.run.path) }),+ targets: targetNames(entry, status),+ acceptedRecords: state?.records.length ?? 0,+ outstandingCommands: state?.outstanding.length ?? 0,+ operations: status.operations.map((operation) => ({+ status: operation.status,+ ...(operation.progress?.phase === undefined ? {} : { phase: operation.progress.phase }),+ ...(operation.progress?.completed === undefined ? {} : { completed: operation.progress.completed }),+ ...(operation.progress?.total === undefined ? {} : { total: operation.progress.total }),+ ...(operation.progress?.unit === undefined ? {} : { unit: operation.progress.unit }),+ })),+ };+}++function artifactsForBuild(+ root: string,+ entry: BuildCatalogEntry,+ status: RuntimeHostStatus,+): readonly StudioArtifactView[] {+ const state = status.build?.state;+ if (state === undefined) return [];+ const outputsByRecord = new Map<string, Set<string>>();+ const recordForOutput = new Map(state.plan.selections.map((selection) => [selection.output, selection.record]));+ for (const alias of entry.aliases) {+ const record = alias.ref.kind === "record" ? alias.ref.id : recordForOutput.get(alias.ref.id);+ if (record === undefined) continue;+ const names = outputsByRecord.get(record) ?? new Set<string>();+ names.add(alias.name);+ outputsByRecord.set(record, names);+ }++ type Held = {+ readonly digest: Digest;+ readonly size: number;+ readonly mediaType: string;+ readonly records: Set<string>;+ readonly outputs: Set<string>;+ readonly paths: Set<string>;+ };+ const found = new Map<Digest, Held>();+ for (const record of state.records) {+ const value = record.value.kind === "blob" ? record.value : record.value.value;+ for (const artifact of collectArtifacts(value)) {+ const held = found.get(artifact.digest) ?? {+ digest: artifact.digest,+ size: artifact.size,+ mediaType: artifact.mediaType,+ records: new Set<string>(),+ outputs: new Set<string>(),+ paths: new Set<string>(),+ };+ held.records.add(record.id);+ for (const output of outputsByRecord.get(record.id) ?? []) held.outputs.add(output);+ held.paths.add(`${record.id}${artifact.path === "$" ? "" : artifact.path.slice(1)}`);+ found.set(artifact.digest, held);+ }+ }+ return [...found.values()].map((artifact) => ({+ id: `${entry.build}:${artifact.digest}`,+ build: entry.build,+ createdAt: entry.createdAt,+ digest: artifact.digest,+ size: artifact.size,+ mediaType: artifact.mediaType,+ records: [...artifact.records],+ outputs: [...artifact.outputs],+ paths: [...artifact.paths],+ source: presentedPath(root, entry.source.path),+ ...(entry.run === undefined ? {} : { run: presentedPath(root, entry.run.path) }),+ })).sort((left, right) =>+ (left.outputs[0] ?? left.records[0] ?? left.digest)+ .localeCompare(right.outputs[0] ?? right.records[0] ?? right.digest));+}++/** Build the Studio library from the existing Catalog, Archive and Artifact references. */+export async function readStudioLibrary(input: {+ readonly profile: string;+ readonly workspaceRoot: string;+ readonly runtime: Pick<RuntimeArchive, "builds" | "status">;+}): Promise<StudioLibraryView> {+ const entries = (await input.runtime.builds())+ .filter((entry) => buildBelongsTo(input.workspaceRoot, entry));+ const statuses = await Promise.all(entries.map(async (entry) => ({+ entry,+ status: await input.runtime.status(entry.build),+ })));+ return {+ environment: resolve(input.workspaceRoot),+ runtime: resolve(input.profile),+ tasks: statuses.map(({ entry, status }) => taskView(input.workspaceRoot, entry, status)),+ artifacts: statuses.flatMap(({ entry, status }) => artifactsForBuild(input.workspaceRoot, entry, status)),+ };+}+/** Open a Runtime profile read-only; Studio never creates or mutates a Build. */export async function openStudioArchive(profile: string | undefined,packageRoot: string,+ workspaceRoot: string,distributionPackageRoot?: string,): Promise<StudioArchive | undefined> {if (profile === undefined) return undefined;- const host = await videoCliDistribution.openRuntimeHost(profile, {+ const resolvedProfile = resolve(profile);+ const host = await videoCliDistribution.openRuntimeHost(resolvedProfile, {packageRoot,...(distributionPackageRoot === undefined ? {} : { distributionPackageRoot }),});const runtime = await host.openArchive({ readOnly: true });const artifacts = await host.openArtifacts();- const cache = new Map<string, Awaited<ReturnType<typeof runtime.status>>>();- const status = async (build: string) => {- const held = cache.get(build);- if (held !== undefined) return held;- const fresh = await runtime.status(build);- cache.set(build, fresh);- return fresh;- };return {+ profile: resolvedProfile,runtime,+ async library() {+ return await readStudioLibrary({ profile: resolvedProfile, workspaceRoot, runtime });+ },async resolveBuildRecord(build, output) {- const held = await status(build);+ const held = await runtime.status(build);const state = held.build?.state;if (state === undefined) return undefined;const alias = held.catalog?.aliases.find((item) => item.name === output);diff --git a/packages/studio/src/parameters.ts b/packages/studio/src/parameters.tsindex 344d914b..4fda725f 100644--- a/packages/studio/src/parameters.ts+++ b/packages/studio/src/parameters.ts@@ -10,6 +10,7 @@ import type {StudioTemporalLineage,StudioTimelineGesture,} from "@hypit/studio-adapter";+import type { MarkupSurfaceRegistryLike, SurfaceRecipePropertyVocabulary } from "@hypit/markup";import { parseSvs } from "@hypit/svs";import type { Range } from "./shared.js";@@ -19,6 +20,7 @@ export type StudioSourceFile = {readonly path: string;readonly text: string;readonly language: "svml" | "svs" | "svrun";+ readonly role?: "run" | "author" | "dependency";readonly imports?: readonly { readonly alias: string; readonly source: string }[];};@@ -113,17 +115,26 @@ function recipeParameters(input: {readonly referenceName: string;readonly referencePath: string;readonly placements: readonly Placement[];+ readonly surfaces?: MarkupSurfaceRegistryLike;+ readonly vocabulary?: readonly SurfaceRecipePropertyVocabulary[];}): readonly StudioParameter[] {const local = input.placements.find((candidate) => candidate.id === input.referencePath);if (local !== undefined) {const next = ["recipe", "default", "style", "appearance", "motion", "program"]- .map((name) => local.referenceAttributes[name])- .find((value) => value !== undefined);- if (next !== undefined && next !== input.referencePath) {+ .map((name) => ({ name, path: local.referenceAttributes[name] }))+ .find((value): value is { name: string; path: string } => value.path !== undefined);+ if (next !== undefined && next.path !== input.referencePath) {+ const vocabulary = input.surfaces+ ?.resolve(local.module, local.surface)+ ?.vocabulary?.attributes+ .find((attribute) => attribute.name === next.name)+ ?.recipe;+ const selectedVocabulary = vocabulary ?? input.vocabulary;return recipeParameters({...input,current: sourceFor(input.root, local.sourcePath, input.files) ?? input.current,- referencePath: next,+ referencePath: next.path,+ ...(selectedVocabulary === undefined ? {} : { vocabulary: selectedVocabulary }),});}}@@ -138,19 +149,26 @@ function recipeParameters(input: {const recipe = parsed.recipes.find((item) => item.value.path === recipePath);if (recipe === undefined) return [];return recipe.properties.map((property) => {+ const declaration = input.vocabulary?.find((candidate) => candidate.name === property.name);const preimage = source.text.slice(property.valueRange.start, property.valueRange.end);const raw = preimage.trim();- const control = raw === "true" || raw === "false"+ const control = declaration?.values !== undefined+ ? "select" as const+ : raw === "true" || raw === "false"? "boolean" as const: /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?$/u.test(raw) ? "number" as const : "text" as const;return {id: `${input.draft.id}:${input.referenceName}:${property.name}`,name: property.name,- label: `${input.referenceName} · ${property.name}`,+ label: declaration === undefined ? `${input.referenceName} · ${property.name}` : property.name,+ ...(declaration?.group === undefined ? {} : { group: declaration.group }),+ ...(declaration?.section === undefined ? {} : { section: declaration.section }),+ ...(declaration?.summary === undefined ? {} : { summary: declaration.summary }),control,value: raw,language: "svs" as const,writable: true,+ ...(declaration?.values === undefined ? {} : { options: declaration.values }),source: {path: relative(input.root, sourceAbsolute(input.root, source.path)),range: property.valueRange,@@ -216,6 +234,7 @@ export function parametersForDraft(input: {readonly draft: StudioEntityDraft;readonly declarations: readonly StudioParameterDeclaration[];readonly placements?: readonly Placement[];+ readonly surfaces?: MarkupSurfaceRegistryLike;}): readonly StudioParameter[] {const placement = input.placement;if (placement === undefined || input.declarations.length === 0) return [];@@ -256,7 +275,8 @@ export function parametersForDraft(input: {} satisfies StudioParameter];});const recipes = input.declarations.flatMap((declaration) => {- const referencePath = element.references[declaration.name];+ const referencePath = input.draft.parameterReferences?.[declaration.name]+ ?? element.references[declaration.name];if (referencePath === undefined) return [];const reference = declaration.referenced === undefined? []@@ -278,6 +298,7 @@ export function parametersForDraft(input: {referenceName: declaration.label ?? declaration.name,referencePath,placements: input.placements ?? [],+ ...(input.surfaces === undefined ? {} : { surfaces: input.surfaces }),}): [];return [...reference, ...recipe];diff --git a/packages/studio/src/server.ts b/packages/studio/src/server.tsindex ca2fbf60..3f8545df 100644--- a/packages/studio/src/server.ts+++ b/packages/studio/src/server.ts@@ -13,7 +13,7 @@ import type { StudioDomain } from "./domain.js";import type { StudioAdapterRegistry } from "./studio-registry.js";import { loadStudioRun } from "./run.js";import { readStudioSession } from "./session.js";-import type { Range, StudioFailure, StudioMutation, StudioSnapshot } from "./shared.js";+import type { Range, StudioFailure, StudioLibraryView, StudioMutation, StudioSnapshot } from "./shared.js";import { createStudioStoryboard } from "./storyboard.js";import type { StudioStoryboard } from "./storyboard.js";import { findSurfacePreview } from "./surface-preview.js";@@ -62,10 +62,21 @@ export function studioPlugin(options: StudioPluginOptions): Plugin {let mutating = false;let requestedRevision = 0;let currentSource = options.source;+ let library: StudioLibraryView | undefined;let allowedSourceFiles = new Set<string>();const watched = new Map<string, FSWatcher>();const storyboards = new Map<string, Promise<StudioStoryboard>>();+ const readLibrary = async (): Promise<StudioLibraryView> => {+ const next = await options.archive?.library() ?? {+ environment: options.workspaceRoot,+ tasks: [],+ artifacts: [],+ };+ library = next;+ return next;+ };+const watchSource = (path: string): void => {if (watched.has(path)) return;try {@@ -369,18 +380,25 @@ export function studioPlugin(options: StudioPluginOptions): Plugin {const body = JSON.parse(Buffer.concat(chunks).toString("utf8")) as {readonly text?: unknown;readonly revision?: unknown;+ readonly path?: unknown;};- if (typeof body.text !== "string" || typeof body.revision !== "number") {- json(response, 400, { error: "Expected source text and revision." });+ if (typeof body.text !== "string" || typeof body.revision !== "number"+ || (body.path !== undefined && typeof body.path !== "string")) {+ json(response, 400, { error: "Expected source path, text and revision." });return;}if (snapshot !== undefined && body.revision !== snapshot.revision) {json(response, 409, { error: "The Source changed outside Studio." });return;}- const current = await readFile(currentSource, "utf8");+ const sourcePath = body.path ?? relative(options.workspaceRoot, currentSource);+ const absolute = resolve(options.workspaceRoot, sourcePath);+ if (isAbsolute(sourcePath) || !allowedSourceFiles.has(absolute)) {+ throw new Error(`Studio cannot write source file ${sourcePath}.`);+ }+ const current = await readFile(absolute, "utf8");await applyTransaction([{- path: relative(options.workspaceRoot, currentSource),+ path: sourcePath,range: { start: 0, end: current.length },replacement: body.text,preimage: current,@@ -445,6 +463,13 @@ export function studioPlugin(options: StudioPluginOptions): Plugin {})();return;}+ if (url.pathname === "/__studio/library") {+ void readLibrary().then(+ (view) => json(response, 200, view),+ (error) => json(response, 500, { error: error instanceof Error ? error.message : String(error) }),+ );+ return;+ }if (url.pathname === "/__studio/surface-preview") {void (async () => {const module = url.searchParams.get("module");@@ -519,6 +544,33 @@ export function studioPlugin(options: StudioPluginOptions): Plugin {else response.end(Buffer.from(file.bytes));return;}+ const artifactDigest = /^\/__studio\/artifact\/(sha256:[a-f0-9]{64})$/u.exec(url.pathname)?.[1];+ if (artifactDigest !== undefined) {+ void (async () => {+ const view = library ?? await readLibrary();+ const artifact = view.artifacts.find((item) => item.digest === artifactDigest);+ if (artifact === undefined || options.archive === undefined) {+ response.statusCode = 404;+ response.end();+ return;+ }+ const bytes = await options.archive.read(artifactDigest as import("@hypit/protocol").Digest);+ if (bytes === undefined) {+ response.statusCode = 404;+ response.end();+ return;+ }+ response.statusCode = 200;+ response.setHeader("content-type", artifact.mediaType);+ response.setHeader("content-length", String(bytes.byteLength));+ response.setHeader("cache-control", "private, max-age=31536000, immutable");+ if (request.method === "HEAD") response.end();+ else response.end(Buffer.from(bytes));+ })().catch((error) => {+ json(response, 500, { error: error instanceof Error ? error.message : String(error) });+ });+ return;+ }next();});},diff --git a/packages/studio/src/session.ts b/packages/studio/src/session.tsindex 69c96296..6814083f 100644--- a/packages/studio/src/session.ts+++ b/packages/studio/src/session.ts@@ -16,7 +16,7 @@ import type { StudioProjection } from "./studio-preflight.js";import type { StudioSourceFile } from "./parameters.js";function sourceFiles(run: RunPlan): readonly StudioSourceFile[] {- const paths = [run.authorSource, ...run.source.compiled.closure.units.map((unit) => unit.id)];+ const paths = [run.runPath, run.authorSource, ...run.source.compiled.closure.units.map((unit) => unit.id)];return [...new Set(paths)].flatMap((path): StudioSourceFile[] => {if (!existsSync(path)) return [];try {@@ -26,6 +26,7 @@ function sourceFiles(run: RunPlan): readonly StudioSourceFile[] {path,text: readFileSync(path, "utf8"),language,+ role: path === run.runPath ? "run" : path === run.authorSource ? "author" : "dependency",...(unit === undefined ? {} : { imports: unit.imports }),}];} catch {@@ -90,6 +91,7 @@ export async function readStudioSession(input: {preview: { kind: "hyperframes", srcdoc: rendered },workspaceRoot: input.workspaceRoot,sourceFiles: files,+ surfaces: input.domain.surfaces,}),material: built.served,observations: source.observations,diff --git a/packages/studio/src/shared.ts b/packages/studio/src/shared.tsindex c2237b3a..b60ba2b2 100644--- a/packages/studio/src/shared.ts+++ b/packages/studio/src/shared.ts@@ -172,12 +172,64 @@ export type SemanticToken = StudioSemanticToken;/** The semantic timebase projected from the compiled Narrative and its anchors. */export type SemanticTimeline = StudioSemanticTimeline;+export type StudioSourceView = {+ /** Workspace-relative path. It is also the exact source write target. */+ readonly path: string;+ readonly text: string;+ readonly language: "svml" | "svs" | "svrun";+ readonly role: "run" | "author" | "dependency";+ readonly imports: readonly string[];+};++export type StudioTaskView = {+ readonly id: string;+ readonly createdAt: number;+ readonly status: "queued" | "running" | "waiting" | "complete" | "failed" | "cancelled" | "active" | "unknown";+ readonly source: string;+ readonly run?: string;+ readonly targets: readonly string[];+ readonly acceptedRecords: number;+ readonly outstandingCommands: number;+ readonly operations: readonly {+ readonly status: "pending" | "completed" | "failed" | "cancelled";+ readonly phase?: string;+ readonly completed?: number;+ readonly total?: number;+ readonly unit?: string;+ }[];+};++export type StudioArtifactView = {+ /** Build-qualified identity. The same digest in two Builds remains two historical results. */+ readonly id: string;+ readonly build: string;+ readonly createdAt: number;+ readonly digest: string;+ readonly size: number;+ readonly mediaType: string;+ readonly records: readonly string[];+ readonly outputs: readonly string[];+ readonly paths: readonly string[];+ readonly source: string;+ readonly run?: string;+};++/** Read-only view of the Runtime context selected for this Studio environment. */+export type StudioLibraryView = {+ readonly environment: string;+ readonly runtime?: string;+ readonly tasks: readonly StudioTaskView[];+ readonly artifacts: readonly StudioArtifactView[];+};+export type StudioSnapshot = {readonly revision: number;readonly source: {/** Workspace-relative presentation path; the server retains the absolute write target. */readonly path: string;readonly text: string;+ /** The exact Run + Author closure; never a directory scan or inferred project tree. */+ readonly files: readonly StudioSourceView[];};/** Visible Run provenance; Studio never invents a second execution source. */readonly run: {diff --git a/packages/studio/src/snapshot.ts b/packages/studio/src/snapshot.tsindex 8ff0a2d2..a3ee684c 100644--- a/packages/studio/src/snapshot.ts+++ b/packages/studio/src/snapshot.ts@@ -6,6 +6,10 @@* timeline is assembled without knowing what made any of it, and a package that* grows a new Track shows up without this file changing.*/+import { relative } from "node:path";++import type { MarkupSurfaceRegistryLike } from "@hypit/markup";+import type {CandidateProvenance,Clip,@@ -288,6 +292,7 @@ export function snapshot(registry: StudioAdapterRegistry, built: Preview, input:readonly preview: StudioSnapshot["preview"];readonly workspaceRoot: string;readonly sourceFiles: readonly StudioSourceFile[];+ readonly surfaces: MarkupSurfaceRegistryLike;}): StudioSnapshot {const located = authored(built.source.observations.placements);const script = scriptMap(built.source.observations.sourceMaps, built);@@ -357,6 +362,7 @@ export function snapshot(registry: StudioAdapterRegistry, built: Preview, input:draft,declarations: registry.parameterDeclarations(item, placement, draft.lane),placements: built.source.observations.placements,+ surfaces: input.surfaces,});const editHandles = timelineAdjustHandles(parameters,@@ -419,7 +425,17 @@ export function snapshot(registry: StudioAdapterRegistry, built: Preview, input:);return {revision: input.revision,- source: { path: input.path, text: input.text },+ source: {+ path: input.path,+ text: input.text,+ files: input.sourceFiles.map((file) => ({+ path: relative(input.workspaceRoot, file.path),+ text: file.text,+ language: file.language,+ role: file.role ?? "dependency",+ imports: (file.imports ?? []).map((item) => item.source),+ })),+ },run: input.run,...(script === undefined ? {} : { script }),space: {diff --git a/packages/studio/src/style.css b/packages/studio/src/style.cssindex 8d622449..45ffd6ac 100644--- a/packages/studio/src/style.css+++ b/packages/studio/src/style.css@@ -20,6 +20,7 @@--interaction-accent: var(--brand-500);--interaction-pressed: var(--brand-600);--danger: #c00015;+ --ok: #64c99a;/* Track families occupy fixed hue slots; variants stay on their family's hue. */--component: #ac571d;--component-rail: #ff9858;@@ -223,6 +224,232 @@ button:focus-visible, textarea:focus-visible {.tool-button.active:active { color: var(--interaction-pressed); }/* Source */+.library { height: 100%; min-width: 0; min-height: 0; display: flex; flex-direction: column; background: var(--panel); }+.library-tabs {+ height: 58px;+ flex: none;+ display: grid;+ grid-template-columns: repeat(3, minmax(0, 1fr));+ align-items: stretch;+ border-bottom: 1px solid var(--line);+ background: #17181b;+}+.library-tab {+ position: relative;+ min-width: 0;+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ gap: 3px;+ padding: 5px 8px 4px;+ border: 0;+ background: transparent;+ color: #858991;+ transition: color 120ms ease, background 120ms ease;+}+.library-tab:hover { color: #c6c9cf; background: rgba(255, 255, 255, .018); }+.library-tab.active { color: var(--interaction-accent); }+.library-tab.active::after {+ content: "";+ position: absolute;+ right: 22%;+ bottom: -1px;+ left: 22%;+ height: 2px;+ border-radius: 2px 2px 0 0;+ background: var(--interaction-accent);+ box-shadow: 0 -3px 12px color-mix(in srgb, var(--interaction-accent) 28%, transparent);+}+.library-tab > span { position: relative; display: grid; place-items: center; width: 22px; height: 22px; }+.library-tab .icon { width: 20px; height: 20px; stroke-width: 1.45; }+.library-tab > strong { overflow: hidden; font-size: 11px; font-weight: 600; line-height: 14px; text-overflow: ellipsis; white-space: nowrap; }+.library-tab > small {+ position: absolute;+ top: 7px;+ left: calc(50% + 9px);+ min-width: 15px;+ height: 15px;+ padding: 0 4px;+ border-radius: 8px;+ background: #33363c;+ color: #cfd2d8;+ font: 600 9px/15px var(--font-ui);+}+.library-tab > small:empty { display: none; }+.library-view { flex: 1; min-width: 0; min-height: 0; display: none; flex-direction: column; }+.library-view.active { display: flex; }+.library-toolbar {+ min-height: 46px;+ flex: none;+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 12px;+ padding: 0 12px;+ border-bottom: 1px solid rgba(255, 255, 255, .045);+ background: #16171a;+}+.library-toolbar > div { min-width: 0; }+.library-toolbar strong, .library-toolbar small { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+.library-toolbar strong { color: #d9dbe0; font-size: 11px; font-weight: 600; }+.library-toolbar small { margin-top: 1px; color: var(--text-3); font-size: 9px; font-weight: 500; }+.library-context {+ flex: none;+ padding: 3px 6px;+ border: 1px solid #303238;+ border-radius: 4px;+ background: #1d1f23;+ color: #858a93;+ font: 500 9px/1.2 var(--font-mono);+}+.library-refresh {+ width: 27px;+ height: 27px;+ display: grid;+ place-items: center;+ flex: none;+ padding: 0;+ border: 1px solid transparent;+ border-radius: 5px;+ background: transparent;+ color: #777c85;+ transition: color 120ms ease, background 120ms ease, border-color 120ms ease;+}+.library-refresh:hover { border-color: #30333a; background: #202227; color: #d1d4da; }+.library-refresh .icon { width: 14px; height: 14px; }+.library.is-refreshing .library-refresh .icon { animation: library-spin 700ms linear infinite; }+@keyframes library-spin { to { transform: rotate(360deg); } }++.source-browser { flex: 1; min-width: 0; min-height: 0; display: grid; grid-template-columns: minmax(104px, 29%) minmax(0, 1fr); }+.source-files {+ min-width: 0;+ min-height: 0;+ overflow: auto;+ padding: 7px 6px 24px;+ border-right: 1px solid var(--line);+ background: #121316;+}+.source-file {+ width: 100%;+ min-width: 0;+ display: grid;+ grid-template-columns: 24px minmax(0, 1fr);+ align-items: center;+ gap: 6px;+ margin-bottom: 3px;+ padding: 7px 6px;+ border: 1px solid transparent;+ border-radius: 6px;+ background: transparent;+ color: #858a93;+ text-align: left;+ transition: background 100ms ease, border-color 100ms ease, color 100ms ease;+}+.source-file:hover { background: #1a1c20; color: #bfc2c9; }+.source-file.active {+ border-color: color-mix(in srgb, var(--interaction-accent) 25%, #2d3036);+ background: color-mix(in srgb, var(--interaction-accent) 10%, #1b1c20);+ color: #eef0f3;+}+.source-file-icon { width: 24px; height: 24px; display: grid; place-items: center; border-radius: 5px; background: #22242a; color: #8e939d; }+.source-file.active .source-file-icon { background: var(--brand-soft); color: var(--interaction-accent); }+.source-file-icon .icon { width: 14px; height: 14px; }+.source-file-copy { min-width: 0; }+.source-file-copy strong, .source-file-copy small { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+.source-file-copy strong { color: inherit; font-size: 10px; font-weight: 600; }+.source-file-copy small { margin-top: 1px; color: #5f636c; font: 8px/1.2 var(--font-mono); }+.source-file em {+ grid-column: 2;+ justify-self: start;+ margin-top: -2px;+ color: #777c85;+ font: normal 600 8px/1 var(--font-ui);+ text-transform: uppercase;+}+.source-code { min-width: 0; min-height: 0; overflow: hidden; }+.source-code > .code { height: 100%; }+.source-code .pane-heading { height: 38px; padding-right: 7px; padding-left: 9px; background: #151619; }+.source-code .pane-tabs { gap: 8px; }+.source-code .pane-tab { font: 600 9px/1 var(--font-mono); letter-spacing: .04em; }+.source-code .pane-tab.active::after { right: 2px; left: 2px; }+.source-code .code-location { max-width: min(210px, 23vw); color: #777b84; font: 9px/1.2 var(--font-mono); }+.source-code .code-scroll { background: #141518; }++.library-context-row { flex: none; min-height: 36px; padding: 7px 10px; border-bottom: 1px solid rgba(255, 255, 255, .04); background: #141518; }+.runtime-chip {+ min-width: 0;+ display: flex;+ align-items: center;+ gap: 7px;+ padding: 4px 7px;+ border: 1px solid #292c31;+ border-radius: 5px;+ background: #191a1e;+}+.runtime-chip::before { content: ""; width: 6px; height: 6px; flex: none; border-radius: 50%; background: var(--interaction-accent); box-shadow: 0 0 8px var(--brand-soft); }+.runtime-chip > span { min-width: 0; overflow: hidden; color: #a9adb5; font: 9px/1.2 var(--font-mono); text-overflow: ellipsis; white-space: nowrap; }+.runtime-chip > strong { margin-left: auto; color: #666b74; font-size: 9px; font-weight: 500; }+.task-list { flex: 1; min-height: 0; overflow: auto; padding: 8px 9px 28px; background: #121316; }+.task-card {+ min-width: 0;+ display: grid;+ grid-template-columns: 18px minmax(0, 1fr);+ gap: 8px;+ margin-bottom: 6px;+ padding: 10px 10px 9px 8px;+ border: 1px solid #292b31;+ border-radius: 7px;+ background: linear-gradient(135deg, #1c1e22, #191a1e);+ box-shadow: 0 1px 0 rgba(255, 255, 255, .018), 0 6px 18px rgba(0, 0, 0, .08);+ transition: border-color 120ms ease, transform 120ms ease, background 120ms ease;+}+.task-card:hover { border-color: #3a3d44; background: linear-gradient(135deg, #202227, #1b1d21); transform: translateY(-1px); }+.task-state { display: grid; place-items: start center; padding-top: 4px; }+.task-state span { width: 8px; height: 8px; border-radius: 50%; background: #686d76; box-shadow: 0 0 0 3px rgba(104, 109, 118, .1); }+.task-running .task-state span, .task-queued .task-state span, .task-waiting .task-state span, .task-active .task-state span { background: #49b9d0; box-shadow: 0 0 0 3px rgba(73, 185, 208, .11), 0 0 10px rgba(73, 185, 208, .18); }+.task-complete .task-state span { background: var(--ok); box-shadow: 0 0 0 3px rgba(100, 201, 154, .1); }+.task-failed .task-state span, .task-cancelled .task-state span { background: #d8646d; box-shadow: 0 0 0 3px rgba(216, 100, 109, .1); }+.task-copy { min-width: 0; }+.task-title { min-width: 0; display: flex; align-items: center; gap: 7px; }+.task-title strong { min-width: 0; flex: 1; overflow: hidden; color: #dfe1e5; font-size: 11px; font-weight: 600; text-overflow: ellipsis; white-space: nowrap; }+.task-status { flex: none; padding: 2px 5px; border-radius: 8px; background: #292c31; color: #9297a1; font: 600 8px/1.2 var(--font-ui); text-transform: uppercase; }+.task-running .task-status, .task-queued .task-status, .task-waiting .task-status, .task-active .task-status { background: rgba(73, 185, 208, .12); color: #79d1e2; }+.task-complete .task-status { background: rgba(100, 201, 154, .11); color: #86d7b1; }+.task-failed .task-status, .task-cancelled .task-status { background: rgba(216, 100, 109, .1); color: #e58b92; }+.task-source { margin: 3px 0 6px; overflow: hidden; color: #6f747d; font: 9px/1.25 var(--font-mono); text-overflow: ellipsis; white-space: nowrap; }+.task-facts { min-width: 0; display: flex; align-items: center; gap: 5px; overflow: hidden; }+.task-facts span { min-width: 0; overflow: hidden; color: #686d76; font-size: 9px; text-overflow: ellipsis; white-space: nowrap; }+.task-facts span + span::before { content: "·"; margin-right: 5px; color: #3e4148; }+.task-progress { margin-top: 7px; padding-top: 6px; border-top: 1px solid rgba(255, 255, 255, .045); color: #8d929b; font-size: 9px; }++.artifact-filters { min-height: 34px; flex: none; display: flex; align-items: center; gap: 4px; padding: 6px 10px; border-bottom: 1px solid rgba(255, 255, 255, .04); background: #141518; }+.artifact-filters button { height: 22px; padding: 0 9px; border: 0; border-radius: 4px; background: transparent; color: #777c85; font-size: 9px; }+.artifact-filters button:hover { background: #202227; color: #b9bdc5; }+.artifact-filters button.active { background: #2a2c31; color: #eef0f3; }+.artifact-grid { flex: 1; min-height: 0; overflow: auto; display: grid; grid-template-columns: repeat(auto-fill, minmax(142px, 1fr)); align-content: start; gap: 9px; padding: 10px 10px 30px; background: #121316; }+.artifact-card { min-width: 0; overflow: hidden; display: block; border: 1px solid #292b31; border-radius: 7px; background: #1a1c20; color: inherit; text-decoration: none; box-shadow: 0 7px 18px rgba(0, 0, 0, .09); transition: border-color 120ms ease, transform 120ms ease, box-shadow 120ms ease; }+.artifact-card:hover { border-color: #454952; transform: translateY(-2px); box-shadow: 0 10px 22px rgba(0, 0, 0, .17); }+.artifact-preview { position: relative; aspect-ratio: 16 / 10; overflow: hidden; display: grid; place-items: center; border-bottom: 1px solid rgba(255, 255, 255, .055); background: radial-gradient(circle at 35% 24%, #30343c, #202228 58%, #1a1b1f); }+.artifact-preview::after { content: ""; position: absolute; inset: 0; background: linear-gradient(180deg, transparent 54%, rgba(8, 9, 11, .32)); pointer-events: none; }+.artifact-image .artifact-preview { background: #202228; }+.artifact-image .artifact-preview img { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; }+.artifact-glyph { position: relative; z-index: 1; width: 36px; height: 36px; display: grid; place-items: center; border: 1px solid rgba(255, 255, 255, .075); border-radius: 9px; background: rgba(12, 13, 16, .28); color: #aab0ba; backdrop-filter: blur(7px); }+.artifact-image .artifact-glyph { display: none; }+.artifact-glyph .icon { width: 20px; height: 20px; }+.artifact-video .artifact-glyph { color: #75badf; }+.artifact-audio .artifact-glyph { color: #83cf9d; }+.artifact-type { position: absolute; z-index: 2; right: 6px; bottom: 5px; padding: 2px 5px; border-radius: 4px; background: rgba(10, 11, 13, .62); color: #d2d5da; font: 600 8px/1.2 var(--font-ui); backdrop-filter: blur(6px); }+.artifact-copy { min-width: 0; padding: 8px 9px 9px; }+.artifact-copy strong, .artifact-copy span { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+.artifact-copy strong { color: #d8dae0; font-size: 10px; font-weight: 600; }+.artifact-meta { margin-top: 3px; color: #666b74; font-size: 8px; }+.library-empty { grid-column: 1 / -1; min-height: 210px; display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 28px; text-align: center; }+.library-empty-icon { width: 44px; height: 44px; display: grid; place-items: center; margin-bottom: 12px; border: 1px solid #292c31; border-radius: 12px; background: linear-gradient(145deg, #202227, #18191d); color: #666b74; box-shadow: 0 9px 24px rgba(0, 0, 0, .12); }+.library-empty-icon .icon { width: 21px; height: 21px; }+.library-empty strong { color: #aeb2ba; font-size: 11px; font-weight: 600; }+.library-empty p { max-width: 260px; margin: 6px 0 0; color: #666b74; font-size: 9px; line-height: 1.55; }+.code { flex: 1; min-width: 0; min-height: 0; display: flex; flex-direction: column; }.code-actions { display: flex; align-items: center; gap: 5px; }.code-location {@@ -423,6 +650,7 @@ button:focus-visible, textarea:focus-visible {align-items: center;padding: 2px 0;}+.parameter-row.parameter-declared { grid-template-rows: 24px; }.parameter-label { min-width: 0; overflow: hidden; color: var(--text-3); font-size: 11px; text-overflow: ellipsis; white-space: nowrap; }.parameter-right { min-width: 0; display: flex; align-items: center; justify-content: flex-end; gap: 4px; }.parameter-value {@@ -489,6 +717,7 @@ button:focus-visible, textarea:focus-visible {grid-template-columns: var(--timeline-label-width) 8px minmax(0, 1fr);overflow-x: hidden;overflow-y: auto;+ overflow-anchor: none;overscroll-behavior: contain;scrollbar-width: none;background: var(--lane);@@ -664,7 +893,7 @@ button:focus-visible, textarea:focus-visible {overflow: hidden;display: flex;align-items: center;- padding: 0 5px;+ padding: 0;border: 0;border-radius: 0;background: var(--semantic-cell);@@ -693,7 +922,7 @@ button:focus-visible, textarea:focus-visible {flex: 1 1 auto;min-width: 0;overflow: hidden;- text-overflow: ellipsis;+ text-overflow: clip;color: #eef0f3;font-size: 11px;font-weight: 500;@@ -702,7 +931,7 @@ button:focus-visible, textarea:focus-visible {.semantic-selection-label {display: block;overflow: hidden;- text-overflow: ellipsis;+ text-overflow: clip;color: #fff;font-size: 11px;font-weight: 500;@@ -716,8 +945,20 @@ button:focus-visible, textarea:focus-visible {}.semantic-segment:not(.semantic-wide) .semantic-segment-duration { display: none; }.semantic-word.current { background: var(--semantic-current); color: #fff; }-.semantic-word-label { display: block; overflow: hidden; font-size: 11px; font-weight: 500; line-height: 1; white-space: nowrap; }-.semantic-cell-content { min-width: 0; width: 100%; display: flex; align-items: center; gap: 6px; overflow: hidden; }+.semantic-word-label { display: block; min-width: 0; overflow: hidden; font-size: 11px; font-weight: 500; line-height: 1; text-overflow: clip; white-space: nowrap; }+.semantic-cell-content {+ position: absolute;+ top: 0;+ bottom: 0;+ left: var(--item-visible-offset, 0);+ width: var(--item-visible-width, 100%);+ min-width: 0;+ display: flex;+ align-items: center;+ gap: 6px;+ overflow: hidden;+ padding: 0 5px;+}.semantic-moment {position: absolute;top: 4px;@@ -734,9 +975,6 @@ button:focus-visible, textarea:focus-visible {border-radius: 0;background: #181a1f;}-.label-hidden .semantic-word-label,-.label-hidden .semantic-segment-label,-.label-hidden .semantic-selection-label { display: none; }.track-fold {min-width: 17px;height: 17px;@@ -836,8 +1074,8 @@ button:focus-visible, textarea:focus-visible {position: absolute;z-index: 3;top: 0;- right: 0;- left: 0;+ left: var(--item-visible-offset, 0);+ width: var(--item-visible-width, 100%);height: var(--timeline-item-header-height);display: flex;align-items: center;@@ -880,7 +1118,16 @@ button:focus-visible, textarea:focus-visible {opacity: .9;}.clip-material { display: block; }-.clip-content { position: absolute; z-index: 2; inset: 0; min-width: 0; overflow: hidden; }+.clip-content {+ position: absolute;+ z-index: 2;+ top: 0;+ bottom: 0;+ left: var(--item-visible-offset, 0);+ width: var(--item-visible-width, 100%);+ min-width: 0;+ overflow: hidden;+}.clip-content-text {display: none;height: 100%;diff --git a/packages/studio/src/ui/code.ts b/packages/studio/src/ui/code.tsindex 84018de9..a0c796c9 100644--- a/packages/studio/src/ui/code.ts+++ b/packages/studio/src/ui/code.ts@@ -1,4 +1,4 @@-import type { Range, StudioSnapshot } from "../shared.js";+import type { Range, StudioSnapshot, StudioSourceView } from "../shared.js";import { icon, setIcon } from "./icons.js";import { intentTones } from "./markers.js";import { tokenizeSvml } from "./syntax.js";@@ -19,7 +19,9 @@ export type Highlight = {export type CodePane = {readonly element: HTMLElement;- show(snapshot: StudioSnapshot): void;+ /** Returns false only while an unsaved file is being saved before a switch. */+ show(snapshot: StudioSnapshot, source?: StudioSourceView): boolean;+ activePath(): string | undefined;highlight(values: readonly Highlight[], scrollIntoView: boolean): void;/** Mark the word being spoken at the playhead, or nothing outside speech. */speak(range: Range | undefined): void;@@ -73,7 +75,7 @@ export function createCodePane(): CodePane {element.innerHTML = `<div class="pane-heading code-heading"><div class="pane-tabs" role="tablist" aria-label="Workspace views">- <button type="button" class="pane-tab active" role="tab" aria-selected="true">SVML</button>+ <button type="button" class="pane-tab active source-language" role="tab" aria-selected="true" data-language>SVML</button></div><div class="code-actions"><span class="code-location" data-path></span>@@ -86,6 +88,7 @@ export function createCodePane(): CodePane {<div class="code-scroll"><svg class="range-canvas" aria-hidden="true"></svg></div><textarea class="code-editor" data-editor spellcheck="false" aria-label="SVML source"></textarea>`;const path = element.querySelector<HTMLElement>("[data-path]")!;+ const language = element.querySelector<HTMLElement>("[data-language]")!;const scroll = element.querySelector<HTMLElement>(".code-scroll")!;const canvas = element.querySelector<SVGSVGElement>(".range-canvas")!;const editor = element.querySelector<HTMLTextAreaElement>("[data-editor]")!;@@ -99,8 +102,11 @@ export function createCodePane(): CodePane {let snapshotRevision = 0;let editingRevision = 0;let sourceText = "";+ let activeSource: StudioSourceView | undefined;+ let authorPath = "";let editing = false;let dirty = false;+ let saveInFlight = false;let saveTimer: number | undefined;const setEditing = (value: boolean): void => {@@ -117,21 +123,30 @@ export function createCodePane(): CodePane {};const save = async (): Promise<void> => {- if (!editing || !dirty) return;+ if (!editing || !dirty || saveInFlight) return;+ const savingPath = activeSource?.path;+ const savingText = editor.value;+ const savingRevision = editingRevision;+ if (savingPath === undefined) return;+ saveInFlight = true;+ let accepted = false;saveState.textContent = "Saving";saveState.className = "code-save-state saving";try {const response = await fetch("/__studio/source", {method: "PUT",headers: { "content-type": "application/json" },- body: JSON.stringify({ text: editor.value, revision: editingRevision }),+ body: JSON.stringify({ path: savingPath, text: savingText, revision: savingRevision }),});if (!response.ok) {const reason = await response.text();throw new Error(reason || `Save failed (${response.status})`);}- sourceText = editor.value;- dirty = false;+ accepted = true;+ if (activeSource?.path === savingPath && editor.value === savingText) {+ sourceText = savingText;+ dirty = false;+ }saveState.textContent = "Saved";saveState.className = "code-save-state saved";window.setTimeout(() => {@@ -142,6 +157,12 @@ export function createCodePane(): CodePane {? "Changed outside Studio": "Save failed";saveState.className = "code-save-state error";+ } finally {+ saveInFlight = false;+ if (accepted && dirty && activeSource?.path === savingPath) {+ if (saveTimer !== undefined) window.clearTimeout(saveTimer);+ saveTimer = window.setTimeout(() => void save(), 240);+ }}};@@ -254,9 +275,29 @@ export function createCodePane(): CodePane {return {element,- show(snapshot) {- path.textContent = snapshot.source.path;- const source = snapshot.source.text;+ show(snapshot, selected) {+ const sourceFile = selected+ ?? snapshot.source.files.find((file) => file.path === snapshot.source.path)+ ?? {+ path: snapshot.source.path,+ text: snapshot.source.text,+ language: "svml" as const,+ role: "author" as const,+ imports: [],+ };+ if (activeSource !== undefined && activeSource.path !== sourceFile.path && dirty) {+ saveState.textContent = "Saving before switch";+ saveState.className = "code-save-state saving";+ void save();+ return false;+ }+ if (activeSource !== undefined && activeSource.path !== sourceFile.path && editing) setEditing(false);+ activeSource = sourceFile;+ authorPath = snapshot.source.path;+ path.textContent = sourceFile.path;+ path.title = sourceFile.path;+ language.textContent = sourceFile.language.toUpperCase();+ const source = sourceFile.text;snapshotRevision = snapshot.revision;sourceText = source;if (!editing || !dirty) {@@ -324,11 +365,13 @@ export function createCodePane(): CodePane {scroll.replaceChildren(canvas, fragment);draw();+ return true;},+ activePath() { return activeSource?.path; },speak(range) {spoken?.remove();spoken = undefined;- if (range === undefined) return;+ if (range === undefined || activeSource?.path !== authorPath) return;const line = lineAt(range.start);const piece = line?.pieces.find((item) => range.start >= item.start && range.start < item.end);// A word is highlighted by drawing over it rather than by rewriting the@@ -347,9 +390,9 @@ export function createCodePane(): CodePane {spoken = mark;},highlight(values, scrollIntoView) {- current = values;+ current = activeSource?.path === authorPath ? values : [];draw();- const first = values[0];+ const first = current[0];if (!scrollIntoView || first === undefined) return;lineAt(first.range.start)?.element.scrollIntoView({ behavior: "smooth", block: "center" });},diff --git a/packages/studio/src/ui/icons.ts b/packages/studio/src/ui/icons.tsindex e864e6a5..98b37998 100644--- a/packages/studio/src/ui/icons.ts+++ b/packages/studio/src/ui/icons.ts@@ -28,6 +28,7 @@ const paths: Readonly<Record<string, string>> = {component: '<rect x="4" y="4" width="6" height="6" rx="1"/><rect x="14" y="4" width="6" height="6" rx="1"/><rect x="4" y="14" width="6" height="6" rx="1"/><rect x="14" y="14" width="6" height="6" rx="1"/>',layers: '<path d="m12 3 9 5-9 5-9-5 9-5Z"/><path d="m3 12 9 5 9-5M3 16l9 5 9-5"/>',ranking: '<path d="M5 19V9h4v10M10 19V5h4v14M15 19v-7h4v7M3 19h18"/>',+ refresh: '<path d="M20 7v5h-5M4 17v-5h5"/><path d="M18.5 9a7 7 0 0 0-11.8-2.3L4 9M5.5 15a7 7 0 0 0 11.8 2.3L20 15"/>',};export function icon(name: string, className = "icon"): string {diff --git a/packages/studio/src/ui/library.ts b/packages/studio/src/ui/library.tsnew file mode 100644index 00000000..ba69d20c--- /dev/null+++ b/packages/studio/src/ui/library.ts@@ -0,0 +1,323 @@+import type {+ StudioArtifactView,+ StudioLibraryView,+ StudioSnapshot,+ StudioSourceView,+ StudioTaskView,+} from "../shared.js";+import type { CodePane } from "./code.js";+import { icon } from "./icons.js";++type LibrarySection = "source" | "tasks" | "artifacts";++export type LibraryPane = {+ readonly element: HTMLElement;+ show(snapshot: StudioSnapshot): void;+ refresh(): Promise<void>;+};++function leaf(path: string): string {+ return path.split(/[\\/]/u).filter(Boolean).at(-1) ?? path;+}++function compactId(value: string): string {+ return value.length <= 18 ? value : `${value.slice(0, 9)}…${value.slice(-6)}`;+}++function formatBytes(value: number): string {+ if (value < 1_000) return `${value} B`;+ if (value < 1_000_000) return `${(value / 1_000).toFixed(value < 10_000 ? 1 : 0)} KB`;+ if (value < 1_000_000_000) return `${(value / 1_000_000).toFixed(value < 10_000_000 ? 1 : 0)} MB`;+ return `${(value / 1_000_000_000).toFixed(1)} GB`;+}++const date = new Intl.DateTimeFormat(undefined, {+ month: "short",+ day: "numeric",+ hour: "2-digit",+ minute: "2-digit",+});++function emptyState(iconName: string, title: string, detail: string): HTMLElement {+ const node = document.createElement("div");+ node.className = "library-empty";+ node.innerHTML = `<span class="library-empty-icon">${icon(iconName)}</span><strong></strong><p></p>`;+ node.querySelector("strong")!.textContent = title;+ node.querySelector("p")!.textContent = detail;+ return node;+}++function taskProgress(task: StudioTaskView): string | undefined {+ const progress = task.operations.find((operation) => operation.status === "pending" && operation.phase !== undefined);+ if (progress === undefined) return undefined;+ if (progress.completed === undefined) return progress.phase;+ const amount = progress.total === undefined+ ? String(progress.completed)+ : `${progress.completed}/${progress.total}`;+ return `${progress.phase} · ${amount}${progress.unit === undefined ? "" : ` ${progress.unit}`}`;+}++function taskCard(task: StudioTaskView): HTMLElement {+ const node = document.createElement("article");+ node.className = `task-card task-${task.status}`;+ const title = task.targets.length === 0 ? leaf(task.run ?? task.source) : task.targets.join(", ");+ const progress = taskProgress(task);+ node.innerHTML = `+ <div class="task-state"><span></span></div>+ <div class="task-copy">+ <div class="task-title"><strong></strong><span class="task-status"></span></div>+ <p class="task-source"></p>+ <div class="task-facts"><span data-time></span><span data-records></span><span data-command></span></div>+ <div class="task-progress" data-progress></div>+ </div>`;+ node.querySelector("strong")!.textContent = title;+ node.querySelector<HTMLElement>(".task-status")!.textContent = task.status;+ const source = task.run ?? task.source;+ node.querySelector<HTMLElement>(".task-source")!.textContent = source;+ node.querySelector<HTMLElement>(".task-source")!.title = source;+ node.querySelector<HTMLElement>("[data-time]")!.textContent = date.format(task.createdAt);+ node.querySelector<HTMLElement>("[data-records]")!.textContent = `${task.acceptedRecords} records`;+ node.querySelector<HTMLElement>("[data-command]")!.textContent = task.outstandingCommands === 0+ ? compactId(task.id)+ : `${task.outstandingCommands} remaining`;+ const progressNode = node.querySelector<HTMLElement>("[data-progress]")!;+ if (progress === undefined) progressNode.remove();+ else progressNode.textContent = progress;+ node.title = `${task.id}\n${source}`;+ return node;+}++function artifactKind(mediaType: string): { readonly label: string; readonly icon: string } {+ if (mediaType.startsWith("video/")) return { label: "Video", icon: "video" };+ if (mediaType.startsWith("image/")) return { label: "Image", icon: "preview" };+ if (mediaType.startsWith("audio/")) return { label: "Audio", icon: "waveform" };+ return { label: "Data", icon: "code" };+}++function artifactCard(artifact: StudioArtifactView): HTMLElement {+ const kind = artifactKind(artifact.mediaType);+ const link = document.createElement("a");+ link.className = `artifact-card artifact-${kind.label.toLowerCase()}`;+ link.href = `/__studio/artifact/${artifact.digest}`;+ link.target = "_blank";+ link.rel = "noreferrer";+ const title = artifact.outputs[0] ?? artifact.records[0] ?? kind.label;+ link.innerHTML = `+ <div class="artifact-preview">+ <span class="artifact-glyph">${icon(kind.icon)}</span>+ <span class="artifact-type"></span>+ </div>+ <div class="artifact-copy">+ <strong></strong>+ <span class="artifact-meta"></span>+ </div>`;+ link.querySelector<HTMLElement>(".artifact-type")!.textContent = kind.label;+ link.querySelector("strong")!.textContent = title;+ link.querySelector<HTMLElement>(".artifact-meta")!.textContent = `${formatBytes(artifact.size)} · ${date.format(artifact.createdAt)}`;+ if (artifact.mediaType.startsWith("image/")) {+ const image = document.createElement("img");+ image.src = link.href;+ image.alt = "";+ image.loading = "lazy";+ link.querySelector<HTMLElement>(".artifact-preview")!.prepend(image);+ }+ link.title = [title, artifact.mediaType, artifact.digest, artifact.run ?? artifact.source].join("\n");+ return link;+}++export function createLibraryPane(code: CodePane): LibraryPane {+ const element = document.createElement("section");+ element.className = "library";+ element.innerHTML = `+ <div class="library-tabs" role="tablist" aria-label="Studio library">+ <button type="button" class="library-tab active" data-library-tab="source" role="tab" aria-selected="true">+ <span>${icon("code")}</span><strong>Source</strong>+ </button>+ <button type="button" class="library-tab" data-library-tab="tasks" role="tab" aria-selected="false">+ <span>${icon("timeline")}</span><strong>Tasks</strong><small data-task-badge></small>+ </button>+ <button type="button" class="library-tab" data-library-tab="artifacts" role="tab" aria-selected="false">+ <span>${icon("layers")}</span><strong>Artifacts</strong><small data-artifact-badge></small>+ </button>+ </div>+ <section class="library-view active" data-library-view="source">+ <div class="library-toolbar">+ <div><strong>Live closure</strong><small data-source-count></small></div>+ <span class="library-context">Run → Author</span>+ </div>+ <div class="source-browser">+ <nav class="source-files" aria-label="Referenced source files" data-source-files></nav>+ <div class="source-code" data-source-code></div>+ </div>+ </section>+ <section class="library-view" data-library-view="tasks">+ <div class="library-toolbar">+ <div><strong>Build archive</strong><small data-task-count></small></div>+ <button type="button" class="library-refresh" data-library-refresh aria-label="Refresh tasks" title="Refresh">${icon("refresh")}</button>+ </div>+ <div class="library-context-row" data-runtime-context></div>+ <div class="task-list" data-task-list></div>+ </section>+ <section class="library-view" data-library-view="artifacts">+ <div class="library-toolbar">+ <div><strong>Accepted artifacts</strong><small data-artifact-count></small></div>+ <button type="button" class="library-refresh" data-library-refresh aria-label="Refresh artifacts" title="Refresh">${icon("refresh")}</button>+ </div>+ <div class="artifact-filters" role="tablist" aria-label="Artifact kinds" data-artifact-filters></div>+ <div class="artifact-grid" data-artifact-grid></div>+ </section>`;++ element.querySelector<HTMLElement>("[data-source-code]")!.append(code.element);+ const sourceList = element.querySelector<HTMLElement>("[data-source-files]")!;+ const taskList = element.querySelector<HTMLElement>("[data-task-list]")!;+ const artifactGrid = element.querySelector<HTMLElement>("[data-artifact-grid]")!;+ const artifactFilters = element.querySelector<HTMLElement>("[data-artifact-filters]")!;+ const runtimeContext = element.querySelector<HTMLElement>("[data-runtime-context]")!;+ const taskBadge = element.querySelector<HTMLElement>("[data-task-badge]")!;+ const artifactBadge = element.querySelector<HTMLElement>("[data-artifact-badge]")!;+ let snapshot: StudioSnapshot | undefined;+ let selectedSource = "";+ let active: LibrarySection = "source";+ let library: StudioLibraryView | undefined;+ let artifactFilter = "all";+ let refreshing = false;++ const renderSources = (): void => {+ if (snapshot === undefined) return;+ const files = snapshot.source.files;+ const selected = files.find((file) => file.path === selectedSource)+ ?? files.find((file) => file.path === snapshot!.source.path)+ ?? files[0];+ selectedSource = selected?.path ?? snapshot.source.path;+ if (selected !== undefined && !code.show(snapshot, selected)) {+ selectedSource = code.activePath() ?? snapshot.source.path;+ }+ sourceList.replaceChildren(...files.map((file) => {+ const button = document.createElement("button");+ button.type = "button";+ button.className = `source-file${file.path === selectedSource ? " active" : ""}`;+ button.innerHTML = `<span class="source-file-icon">${icon(file.language === "svrun" ? "timeline" : file.language === "svs" ? "tune" : "code")}</span><span class="source-file-copy"><strong></strong><small></small></span><em></em>`;+ button.querySelector("strong")!.textContent = leaf(file.path);+ button.querySelector("small")!.textContent = file.path;+ button.querySelector("em")!.textContent = file.role === "dependency" ? file.language : file.role;+ button.title = `${file.role} · ${file.path}${file.imports.length === 0 ? "" : `\nimports ${file.imports.join(", ")}`}`;+ button.addEventListener("click", () => {+ selectedSource = file.path;+ renderSources();+ });+ return button;+ }));+ element.querySelector<HTMLElement>("[data-source-count]")!.textContent = `${files.length} referenced file${files.length === 1 ? "" : "s"}`;+ };++ const renderTasks = (): void => {+ const tasks = library?.tasks ?? [];+ const runtime = library?.runtime;+ taskBadge.textContent = tasks.length === 0 ? "" : String(tasks.filter((task) =>+ ["queued", "running", "waiting", "active"].includes(task.status)).length || tasks.length);+ element.querySelector<HTMLElement>("[data-task-count]")!.textContent = `${tasks.length} build${tasks.length === 1 ? "" : "s"}`;+ runtimeContext.replaceChildren();+ const context = document.createElement("span");+ context.className = "runtime-chip";+ context.innerHTML = `<span></span><strong></strong>`;+ context.querySelector("span")!.textContent = runtime === undefined ? "Runtime" : leaf(runtime);+ context.querySelector("strong")!.textContent = runtime === undefined ? "not selected" : leaf(library!.environment);+ context.title = runtime === undefined ? "No Runtime selected for this environment" : `${library!.environment}\n${runtime}`;+ runtimeContext.append(context);+ if (tasks.length === 0) {+ taskList.replaceChildren(emptyState("timeline",+ runtime === undefined ? "No Runtime selected" : "No builds yet",+ runtime === undefined+ ? "Select one with hypit runtime use, then reopen Studio."+ : "Builds created from this environment will appear here."));+ return;+ }+ taskList.replaceChildren(...tasks.map(taskCard));+ };++ const renderArtifacts = (): void => {+ const artifacts = library?.artifacts ?? [];+ artifactBadge.textContent = artifacts.length === 0 ? "" : String(artifacts.length);+ element.querySelector<HTMLElement>("[data-artifact-count]")!.textContent = `${artifacts.length} stored object${artifacts.length === 1 ? "" : "s"}`;+ const filters = [+ ["all", "All"],+ ["video", "Video"],+ ["image", "Image"],+ ["audio", "Audio"],+ ] as const;+ artifactFilters.replaceChildren(...filters.map(([id, label]) => {+ const button = document.createElement("button");+ button.type = "button";+ button.className = id === artifactFilter ? "active" : "";+ button.textContent = label;+ button.addEventListener("click", () => { artifactFilter = id; renderArtifacts(); });+ return button;+ }));+ const shown = artifactFilter === "all"+ ? artifacts+ : artifacts.filter((artifact) => artifact.mediaType.startsWith(`${artifactFilter}/`));+ if (shown.length === 0) {+ artifactGrid.replaceChildren(emptyState("layers",+ artifacts.length === 0 ? "No accepted artifacts" : `No ${artifactFilter} artifacts`,+ library?.runtime === undefined+ ? "Artifacts appear only from a selected Runtime archive."+ : "Only ArtifactStore objects referenced by accepted Records appear here."));+ return;+ }+ artifactGrid.replaceChildren(...shown.map(artifactCard));+ };++ const switchTo = (next: LibrarySection): void => {+ active = next;+ for (const tab of Array.from(element.querySelectorAll<HTMLButtonElement>("[data-library-tab]"))) {+ const selected = tab.dataset.libraryTab === next;+ tab.classList.toggle("active", selected);+ tab.setAttribute("aria-selected", String(selected));+ }+ for (const view of Array.from(element.querySelectorAll<HTMLElement>("[data-library-view]"))) {+ view.classList.toggle("active", view.dataset.libraryView === next);+ }+ if (next !== "source") void refresh();+ };++ for (const tab of Array.from(element.querySelectorAll<HTMLButtonElement>("[data-library-tab]"))) {+ tab.addEventListener("click", () => switchTo(tab.dataset.libraryTab as LibrarySection));+ }++ const refresh = async (): Promise<void> => {+ if (refreshing) return;+ refreshing = true;+ element.classList.add("is-refreshing");+ try {+ const response = await fetch("/__studio/library");+ const value = await response.json() as StudioLibraryView | { readonly error: string };+ if (!response.ok || "error" in value) throw new Error("error" in value ? value.error : "Library unavailable");+ library = value;+ renderTasks();+ renderArtifacts();+ } catch (error) {+ const detail = error instanceof Error ? error.message : String(error);+ if (active === "tasks") taskList.replaceChildren(emptyState("timeline", "Archive unavailable", detail));+ if (active === "artifacts") artifactGrid.replaceChildren(emptyState("layers", "ArtifactStore unavailable", detail));+ } finally {+ refreshing = false;+ element.classList.remove("is-refreshing");+ }+ };++ for (const button of Array.from(element.querySelectorAll<HTMLButtonElement>("[data-library-refresh]"))) {+ button.addEventListener("click", () => void refresh());+ }+ window.setInterval(() => {+ if (document.visibilityState === "visible" && active !== "source") void refresh();+ }, 3_000);++ return {+ element,+ show(value) {+ snapshot = value;+ renderSources();+ },+ refresh,+ };+}diff --git a/packages/studio/src/ui/main.ts b/packages/studio/src/ui/main.tsindex 24714f26..17b3c913 100644--- a/packages/studio/src/ui/main.ts+++ b/packages/studio/src/ui/main.ts@@ -1,6 +1,7 @@import type { Clip, StudioFailure, StudioSnapshot } from "../shared.js";import { createCodePane } from "./code.js";import { setIcon } from "./icons.js";+import { createLibraryPane } from "./library.js";import { createHandle } from "./resize.js";import type { Highlight } from "./code.js";import { intentAtOffset, spanAtOffset } from "./markers.js";@@ -38,7 +39,7 @@ app.innerHTML = `</header><main class="studio-shell"><section class="upper-shell">- <aside class="source-panel" data-code></aside>+ <aside class="source-panel" data-library></aside><div class="preview-panel" data-stage></div><aside class="workspace-panel"><div class="pane-heading workspace-heading">@@ -59,9 +60,10 @@ app.innerHTML = `const store = createStore();const code = createCodePane();+const library = createLibraryPane(code);const timeline = createTimeline(store);const stage = createStage(store);-app.querySelector<HTMLElement>("[data-code]")!.append(code.element);+app.querySelector<HTMLElement>("[data-library]")!.append(library.element);app.querySelector<HTMLElement>("[data-timeline]")!.append(timeline.element);app.querySelector<HTMLElement>("[data-stage]")!.append(stage.element);@@ -138,10 +140,11 @@ function group(label: string, items: readonly HTMLElement[], className = ""): HTfunction parameterControl(entityId: string, parameter: Clip["parameters"][number]): HTMLElement {const row = document.createElement("label");- row.className = `parameter-row${parameter.writable ? " parameter-editable" : " parameter-readonly"}`;+ row.className = `parameter-row${parameter.writable ? " parameter-editable" : " parameter-readonly"}${parameter.group === undefined ? "" : " parameter-declared"}`;const name = document.createElement("span");name.className = "parameter-label";name.textContent = parameter.label;+ name.title = parameter.summary ?? parameter.label;const source = document.createElement("small");source.className = "parameter-source";source.textContent = `${parameter.language.toUpperCase()} · ${parameter.source.path}:${parameter.source.range.start}`;@@ -181,7 +184,9 @@ function parameterControl(entityId: string, parameter: Clip["parameters"][numberunit.textContent = suffix;right.append(unit);}- row.append(name, right, source);+ row.append(name, right);+ if (parameter.group === undefined) row.append(source);+ else row.title = `${parameter.summary ?? parameter.label}\n${source.textContent}`;if (!parameter.writable) row.title = parameter.disabledReason ?? "Read-only source parameter";return row;}@@ -190,14 +195,18 @@ function parameterGroups(entityId: string, parameters: readonly Clip["parameterstype StudioParameterValue = Clip["parameters"][number];const groups = new Map<string, StudioParameterValue[]>();for (const parameter of parameters) {- const key = `${parameter.language}\u0000${parameter.source.path}`;+ const key = parameter.group === undefined+ ? `source\u0000${parameter.language}\u0000${parameter.source.path}`+ : `recipe\u0000${parameter.group}\u0000${parameter.section ?? "parameters"}`;const held = groups.get(key) ?? [];held.push(parameter);groups.set(key, held);}return [...groups].map(([key, values]) => {- const [language, path = ""] = key.split("\u0000");- const title = path.length === 0 ? language!.toUpperCase() : `${language!.toUpperCase()} · ${path}`;+ const [kind, first = "", second = ""] = key.split("\u0000");+ const title = kind === "recipe"+ ? `${first.slice(0, 1).toUpperCase()}${first.slice(1)} · ${second.replaceAll("-", " ")}`+ : second.length === 0 ? first.toUpperCase() : `${first.toUpperCase()} · ${second}`;return group(title, values.map((parameter) => parameterControl(entityId, parameter)), "parameter-group");});}@@ -281,7 +290,35 @@ function renderInspector(snapshot: StudioSnapshot, clipId: string | undefined):const clip = clipId === undefined ? undefined : store.clip(clipId);if (clip === undefined) {- inspector.replaceChildren();+ const fps = snapshot.space.frameRate.numerator / snapshot.space.frameRate.denominator;+ const hero = document.createElement("div");+ hero.className = "selection-hero overview-hero";+ hero.innerHTML = `+ <span class="selection-icon" data-selection-icon></span>+ <div class="selection-title"><strong></strong><small></small></div>+ <span class="selection-kind">Project</span>`;+ setIcon(hero.querySelector("[data-selection-icon]")!, "preview");+ hero.querySelector("strong")!.textContent = snapshot.source.path.split(/[\\/]/u).at(-1) ?? snapshot.source.path;+ hero.querySelector("small")!.textContent = `${snapshot.tracks.length} tracks · ${snapshot.source.files.length} source files`;+ inspector.replaceChildren(hero,+ group("Canvas", [+ property("Size", `${snapshot.space.canvasWidth} × ${snapshot.space.canvasHeight}`, "property-number"),+ property("Frame rate", `${fps.toFixed(Number.isInteger(fps) ? 0 : 2)} fps`, "property-number"),+ property("Duration", `${snapshot.space.durationSec.toFixed(2)}s`, "property-number"),+ property("Frames", String(snapshot.space.frameCount), "property-number"),+ ]),+ group("Source", [+ property("Author", snapshot.source.path, "property-wide property-code"),+ property("Run", snapshot.run.path, "property-wide property-code"),+ property("Closure", `${snapshot.source.files.length} referenced files`),+ ]),+ group("Build intent", [+ property("Targets", snapshot.run.targets+ .map((target) => target.split("::output::").at(-1) ?? target)+ .join(", ") || "—", "property-wide property-code"),+ property("Candidates", String(snapshot.run.satisfactions.length), "property-number"),+ ]),+ );return;}@@ -322,20 +359,17 @@ function renderInspector(snapshot: StudioSnapshot, clipId: string | undefined):property("To", clip.temporal.projection.endExpression, "property-wide property-code"),]),]);- const run = track === undefined ? undefined : group("Run", [- property("Run", snapshot.run.path, "property-wide property-code"),- property("Target", snapshot.run.targets.join(", "), "property-wide property-code"),+ const provenance = track === undefined ? undefined : group("Provenance", [property("Output", track.provenance.output, "property-wide property-code"),...(track.provenance.candidateId === undefined ? [] : [property("Candidate", track.provenance.candidateId, "property-wide property-code"),]),property("Status", track.provenance.status),- property("Writeback", "Run source · read-only"),]);const operations = operationGroups(clip.editHandles);const parameters = parameterGroups(clip.id, clip.parameters);inspector.replaceChildren(hero, placement, timing, ...operations, ...parameters,- ...(source === undefined ? [] : [source]), ...(run === undefined ? [] : [run]));+ ...(source === undefined ? [] : [source]), ...(provenance === undefined ? [] : [provenance]));}function renderSemanticInspector(snapshot: StudioSnapshot, segmentId: string): void {@@ -491,6 +525,7 @@ code.element.addEventListener("click", (event) => {if ((event.target as HTMLElement | null)?.closest("button, textarea") !== null) return;const state = store.current();if (state === undefined) return;+ if (code.activePath() !== state.snapshot.source.path) return;const offset = code.offsetAt(event);// Below the last line, or in the heading: nothing is being pointed at.if (offset === undefined) {@@ -575,7 +610,7 @@ function applySnapshot(snapshot: StudioSnapshot): void {status.className = "status";status.textContent = "";renderMeta(snapshot);- code.show(snapshot);+ library.show(snapshot);store.load(snapshot);}@@ -600,6 +635,7 @@ const response = await fetch("/__studio/session");const initial = await response.json() as StudioSnapshot | StudioFailure;if (response.ok && "tracks" in initial) applySnapshot(initial);else applyFailure(initial as StudioFailure);+void library.refresh();type Hot = { on(event: string, listener: (value: unknown) => void): void };const hot = (import.meta as ImportMeta & { hot?: Hot }).hot;diff --git a/packages/studio/src/ui/timeline.ts b/packages/studio/src/ui/timeline.tsindex d604dfb4..0ac5fcd8 100644--- a/packages/studio/src/ui/timeline.ts+++ b/packages/studio/src/ui/timeline.ts@@ -26,20 +26,42 @@ const itemMetrics = {gapPx: 1,} as const;-const measuredText = (() => {- const context = document.createElement("canvas").getContext("2d");- const cache = new Map<string, number>();- return (value: string, font: string): number => {- const key = `${font}\u0000${value}`;- const existing = cache.get(key);- if (existing !== undefined) return existing;- if (context === null) return value.length * 7;- context.font = font;- const width = context.measureText(value).width;- cache.set(key, width);- return width;- };-})();+const labelFont = '500 11px -apple-system, BlinkMacSystemFont, "SF Pro Text", "Helvetica Neue", "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif';+const monoLabelFont = '500 11px "SF Mono", "SFMono-Regular", ui-monospace, Menlo, Monaco, "Cascadia Mono", "Segoe UI Mono", Consolas, monospace';+const graphemes = new Intl.Segmenter(undefined, { granularity: "grapheme" });+const textMeasure = document.createElement("canvas").getContext("2d");+const textWidths = new Map<string, number>();++function measuredText(value: string, font = labelFont): number {+ const key = `${font}\u0000${value}`;+ const cached = textWidths.get(key);+ if (cached !== undefined) return cached;+ if (textMeasure === null) return [...graphemes.segment(value)].length * 7;+ textMeasure.font = font;+ const width = textMeasure.measureText(value).width;+ textWidths.set(key, width);+ return width;+}++/** Return the longest prefix whose final grapheme is wholly visible. */+function fittedText(value: string, width: number): string {+ const available = Math.max(0, width - 1);+ if (measuredText(value) <= available) return value;+ const parts = [...graphemes.segment(value)].map((part) => part.segment);+ let low = 0;+ let high = parts.length;+ while (low < high) {+ const middle = Math.ceil((low + high) / 2);+ if (measuredText(parts.slice(0, middle).join("")) <= available) low = middle;+ else high = middle - 1;+ }+ return parts.slice(0, low).join("");+}++function fitLabel(node: HTMLElement, value: string, width: number): void {+ node.dataset.fullLabel = value;+ node.textContent = fittedText(value, width);+}function timecode(seconds: number): string {const whole = Math.floor(seconds);@@ -76,6 +98,25 @@ function clipBodyLabel(clip: StudioSnapshot["tracks"][number]["clips"][number]):return clip.presentation.shape === "text" ? clip.label : "";}+/**+ * Keep an item's authored geometry intact while placing its text inside the+ * portion of that geometry which is actually visible in the current window.+ * Material, phases and edit handles must continue to use the full rectangle.+ */+function placeVisibleLabel(+ node: HTMLElement,+ from: number,+ to: number,+ laneWidth: number,+): number {+ const visibleFrom = Math.max(0, from);+ const visibleTo = Math.min(1, to);+ const visibleWidth = Math.max(0, visibleTo - visibleFrom) * laneWidth;+ node.style.setProperty("--item-visible-offset", `${Math.max(0, visibleFrom - from) * laneWidth}px`);+ node.style.setProperty("--item-visible-width", `${Math.max(1, visibleWidth - itemMetrics.gapPx)}px`);+ return visibleWidth;+}+export function createTimeline(store: Store): Timeline {const element = document.createElement("section");element.className = "timeline";@@ -603,23 +644,24 @@ export function createTimeline(store: Store): Timeline {node.className = "semantic-cell semantic-segment";node.tabIndex = 0;node.setAttribute("role", "button");+ node.setAttribute("aria-label", `Segment ${segment.id}`);node.dataset.semanticSegment = segment.id;node.style.left = `${from * 100}%`;const segmentWidth = Math.max(0, to - from) * 100;node.style.width = `max(2px, calc(${segmentWidth}% - ${itemMetrics.gapPx}px))`;+ const visibleWidthPx = placeVisibleLabel(node, from, to, laneWidth);node.title = `${segment.id} · ${segment.startFrame}-${segment.endFrameExclusive}f`;const segmentLabel = document.createElement("span");segmentLabel.className = "semantic-segment-label";- segmentLabel.textContent = segment.id;- const visibleWidthPx = Math.max(0, to - from) * laneWidth;node.classList.toggle("semantic-wide", visibleWidthPx >= 140);- node.classList.toggle("label-hidden",- measuredText(segment.id, "500 11px -apple-system, system-ui, Segoe UI, sans-serif") + 18 > visibleWidthPx);const head = document.createElement("div");head.className = "semantic-cell-content";const segmentDuration = document.createElement("span");segmentDuration.className = "semantic-segment-duration";- segmentDuration.textContent = `${segment.endFrameExclusive - segment.startFrame}f`;+ const segmentDurationText = `${segment.endFrameExclusive - segment.startFrame}f`;+ segmentDuration.textContent = segmentDurationText;+ fitLabel(segmentLabel, segment.id, visibleWidthPx - itemMetrics.gapPx - 10+ - (visibleWidthPx >= 140 ? measuredText(segmentDurationText, monoLabelFont) + 6 : 0));head.append(segmentLabel, segmentDuration);node.append(head);node.addEventListener("click", (event) => {@@ -650,16 +692,18 @@ export function createTimeline(store: Store): Timeline {const word = document.createElement("span");word.className = "semantic-cell semantic-word";word.dataset.semanticToken = token.id;+ word.setAttribute("aria-label", token.text);word.style.left = `${wordFrom * 100}%`;word.style.width = `max(1px, calc(${Math.max(0, wordTo - wordFrom) * 100}% - 1px))`;+ const wordVisibleWidth = placeVisibleLabel(word, wordFrom, wordTo, laneWidth);word.title = `${token.text} · ${token.startFrame}-${token.endFrameExclusive}f`;const text = document.createElement("span");text.className = "semantic-word-label";- text.textContent = token.text;- word.append(text);- const widthPx = Math.max(0, wordTo - wordFrom) * laneWidth;- word.classList.toggle("label-hidden",- measuredText(token.text, "500 11px -apple-system, system-ui, Segoe UI, sans-serif") + 18 > widthPx);+ fitLabel(text, token.text, wordVisibleWidth - itemMetrics.gapPx - 10);+ const wordContent = document.createElement("span");+ wordContent.className = "semantic-cell-content";+ wordContent.append(text);+ word.append(wordContent);word.addEventListener("click", (event) => {event.stopPropagation();store.seek(token.startFrame, "timeline");@@ -678,17 +722,15 @@ export function createTimeline(store: Store): Timeline {node.setAttribute("aria-label", `Selection ${selection.id}`);node.style.left = `${from * 100}%`;node.style.width = `max(2px, calc(${Math.max(0, to - from) * 100}% - ${itemMetrics.gapPx}px))`;+ const selectionVisibleWidth = placeVisibleLabel(node, from, to, laneWidth);node.title = `${selection.id} · ${selection.startFrame}-${selection.endFrameExclusive}f`;const selectionLabel = document.createElement("span");selectionLabel.className = "semantic-selection-label";- selectionLabel.textContent = selection.id;+ fitLabel(selectionLabel, selection.id, selectionVisibleWidth - itemMetrics.gapPx - 10);const selectionContent = document.createElement("div");selectionContent.className = "semantic-cell-content";selectionContent.append(selectionLabel);node.append(selectionContent);- const selectionWidthPx = Math.max(0, to - from) * laneWidth;- node.classList.toggle("label-hidden",- measuredText(selection.id, "500 11px -apple-system, system-ui, Segoe UI, sans-serif") + 18 > selectionWidthPx);node.addEventListener("click", (event) => {event.stopPropagation();store.selectSemanticSelection(selection.id, "timeline");@@ -788,11 +830,12 @@ export function createTimeline(store: Store): Timeline {node.className = `clip clip-${kind} clip-facet-${track.binding.facet} clip-shape-${clip.presentation.shape}`;node.classList.toggle("clip-editable", clip.editHandles.some((handle) => handle.enabled));node.dataset.clip = clip.id;+ node.setAttribute("aria-label", clip.label);node.style.left = `${from * 100}%`;node.style.width = `max(2px, calc(${Math.max(0, to - from) * 100}% - ${itemMetrics.gapPx}px))`;- const widthPx = Math.max(0, to - from) * laneWidth;- node.classList.toggle("clip-wide", widthPx >= 110);- node.classList.toggle("clip-preview-wide", widthPx >= 92);+ const visibleWidthPx = placeVisibleLabel(node, from, to, laneWidth);+ node.classList.toggle("clip-wide", visibleWidthPx >= 110);+ node.classList.toggle("clip-preview-wide", visibleWidthPx >= 92);node.style.top = `${row * laneHeight}px`;node.title = `${clip.label} · ${clip.startFrame}-${clip.endFrameExclusive}f`;node.innerHTML = `<span class="clip-head"><span class="clip-name"></span><span class="clip-meta"></span></span><span class="clip-body"><span class="clip-material" aria-hidden="true"></span><span class="clip-content"><span class="clip-content-text"></span></span><span class="clip-phases"></span></span><span class="clip-selection" aria-hidden="true"></span>`;@@ -810,9 +853,13 @@ export function createTimeline(store: Store): Timeline {phaseNode.style.width = `${(phase.endFrameExclusive - phase.startFrame) / Math.max(1, clip.endFrameExclusive - clip.startFrame) * 100}%`;phaseLayer.append(phaseNode);}- node.querySelector(".clip-name")!.textContent = clipHeaderLabel(clip);- node.querySelector(".clip-meta")!.textContent = `${((clip.endFrameExclusive - clip.startFrame) / fps(snapshot)).toFixed(2)}s`;- node.querySelector(".clip-content-text")!.textContent = clipBodyLabel(clip);+ const metaText = `${((clip.endFrameExclusive - clip.startFrame) / fps(snapshot)).toFixed(2)}s`;+ const headerLabel = node.querySelector<HTMLElement>(".clip-name")!;+ const bodyLabel = node.querySelector<HTMLElement>(".clip-content-text")!;+ node.querySelector(".clip-meta")!.textContent = metaText;+ fitLabel(headerLabel, clipHeaderLabel(clip), visibleWidthPx - itemMetrics.gapPx - 10+ - (visibleWidthPx >= 110 ? measuredText(metaText, monoLabelFont) + 6 : 0));+ fitLabel(bodyLabel, clipBodyLabel(clip), visibleWidthPx - itemMetrics.gapPx - 10);node.addEventListener("pointerdown", (event) => {const rect = node.getBoundingClientRect();const edge = Math.min(8, Math.max(4, rect.width / 3));@@ -861,6 +908,7 @@ export function createTimeline(store: Store): Timeline {};const build = (snapshot: StudioSnapshot): void => {+ const scrollTop = body.scrollTop;labels.replaceChildren();rows.replaceChildren();semanticNodes = [];@@ -883,6 +931,9 @@ export function createTimeline(store: Store): Timeline {}clipNodes = nextClipNodes;drawRuler(snapshot);+ // Replacing every row briefly collapses the scroll surface. Preserve the+ // vertical reading position when a horizontal pan rebuilds the window.+ body.scrollTop = scrollTop;};const paint = (): void => {diff --git a/packages/studio/start.ts b/packages/studio/start.tsindex 833c0d00..b4d23e74 100644--- a/packages/studio/start.ts+++ b/packages/studio/start.ts@@ -2,6 +2,7 @@ import { dirname, resolve } from "node:path";import { fileURLToPath } from "node:url";import { createServer } from "vite";+import { findRuntimeProfile } from "@hypit/cli";import { videoCliDistribution } from "@hypit/video-cli";import { openStudioArchive } from "./src/archive.js";@@ -21,7 +22,8 @@ function usage(message?: string): never {[--studio-profile <hypit.studio.json>]Studio opens one explicit Run Source, requires a Film/Render target and a-resolved deterministic semantic projection, and writes only its Author SVML.+resolved deterministic semantic projection, and writes only the selected file+inside that exact Run and Author Source closure.`);process.exit(1);}@@ -47,14 +49,20 @@ if (runArgument === undefined || runArgument.trim().length === 0) usage("Missingconst runPath = resolve(invokedFrom, runArgument);const packageRootArgument = values.get("package-root");const workspaceArgument = values.get("workspace");-const workspaceRoot = workspaceArgument === undefined- ? dirname(runPath)+const requestedWorkspaceRoot = workspaceArgument === undefined+ ? undefined: resolve(invokedFrom, workspaceArgument);+const selectedRuntime = await findRuntimeProfile(requestedWorkspaceRoot ?? dirname(runPath));+const workspaceRoot = workspaceArgument === undefined+ ? selectedRuntime?.projectRoot ?? dirname(runPath)+ : requestedWorkspaceRoot!;const packageRoot = packageRootArgument === undefined? workspaceRoot: resolve(invokedFrom, packageRootArgument);const runtimeArgument = values.get("runtime");-const runtimePath = runtimeArgument === undefined ? undefined : resolve(invokedFrom, runtimeArgument);+const runtimePath = runtimeArgument === undefined+ ? selectedRuntime?.profile+ : resolve(invokedFrom, runtimeArgument);const studioProfileArgument = values.get("studio-profile");const studioProfilePath = studioProfileArgument === undefined ? undefined : resolve(invokedFrom, studioProfileArgument);const port = Number(values.get("port") ?? "5179");@@ -68,7 +76,7 @@ const registry = await loadStudioAdapterRegistry({...(studioProfilePath === undefined ? {} : { profile: studioProfilePath }),});const domain = await loadStudioDomain({ run: runPath, workspaceRoot, packageRoot });-const archive = await openStudioArchive(runtimePath, packageRoot, distributionPackageRoot);+const archive = await openStudioArchive(runtimePath, packageRoot, workspaceRoot, distributionPackageRoot);let run;try {run = await loadStudioRun({diff --git a/packages/studio/test/archive.test.ts b/packages/studio/test/archive.test.tsnew file mode 100644index 00000000..9e3267cf--- /dev/null+++ b/packages/studio/test/archive.test.ts@@ -0,0 +1,99 @@+import assert from "node:assert/strict";+import test from "node:test";++import type { BuildState, Digest } from "@hypit/protocol";+import type { BuildCatalogEntry } from "@hypit/runtime";+import type { RuntimeHostStatus } from "@hypit/runtime-host-node";++import { readStudioLibrary } from "../src/archive.js";++const digest = `sha256:${"a".repeat(64)}` as Digest;++function state(): BuildState {+ return {+ format: "hypit.build@1",+ program: { closure: { format: "hypit.closure@1", modules: [] }, records: [] },+ graph: { format: "hypit.graph@1", outputs: [], candidates: [], operations: [] },+ request: { format: "hypit.build-request@1", targets: [{ output: "final-output" }] },+ plan: {+ format: "hypit.plan@1",+ steps: [],+ goals: [{ record: "final-record", type: { module: { name: "example", version: "1" }, name: "Video" } }],+ selections: [{ output: "final-output", candidate: "render", record: "final-record" }],+ },+ status: "complete",+ records: [{+ id: "final-record",+ type: { module: { name: "example", version: "1" }, name: "Video" },+ value: { kind: "blob", digest, size: 42, mediaType: "video/mp4" },+ }],+ steps: [],+ needs: [],+ outstanding: [],+ diagnostics: [],+ };+}++function catalog(build: string, root: string): BuildCatalogEntry {+ return {+ build,+ createdAt: 100,+ source: { path: `${root}/author/main.svml` },+ run: { path: `${root}/runs/build.svrun` },+ aliases: [{ name: "final.video", ref: { kind: "logical-output", id: "final-output" } }],+ };+}++test("Studio library shows only this environment's archived Builds and accepted Artifacts", async () => {+ const relevant = catalog("build-inside", "/project");+ const unrelated = catalog("build-outside", "/another-project");+ const status: RuntimeHostStatus = {+ build: { build: relevant.build, definition: {} as never, facts: [], state: state() },+ catalog: relevant,+ operations: [],+ dispatch: {+ build: relevant.build,+ componentPackages: [],+ createdAt: 100,+ availableAt: 100,+ phase: "terminal",+ terminal: "complete",+ },+ };+ const view = await readStudioLibrary({+ profile: "/project/hypit.runtime.json",+ workspaceRoot: "/project",+ runtime: {+ async builds() { return [relevant, unrelated]; },+ async status(build) {+ assert.equal(build, relevant.build);+ return status;+ },+ },+ });++ assert.deepEqual(view.tasks.map((task) => ({+ id: task.id,+ status: task.status,+ source: task.source,+ run: task.run,+ targets: task.targets,+ })), [{+ id: "build-inside",+ status: "complete",+ source: "author/main.svml",+ run: "runs/build.svrun",+ targets: ["final.video"],+ }]);+ assert.deepEqual(view.artifacts.map((artifact) => ({+ build: artifact.build,+ digest: artifact.digest,+ mediaType: artifact.mediaType,+ outputs: artifact.outputs,+ })), [{+ build: "build-inside",+ digest,+ mediaType: "video/mp4",+ outputs: ["final.video"],+ }]);+});diff --git a/packages/studio/test/parameters.test.ts b/packages/studio/test/parameters.test.tsindex c11bd141..7e1be01e 100644--- a/packages/studio/test/parameters.test.ts+++ b/packages/studio/test/parameters.test.ts@@ -1,7 +1,12 @@import assert from "node:assert/strict";import test from "node:test";-import type { StudioSemanticTimeline, StudioTemporalLineage } from "@hypit/studio-adapter";+import type {+ StudioPlacement,+ StudioSemanticTimeline,+ StudioTemporalLineage,+} from "@hypit/studio-adapter";+import type { MarkupSurfaceRegistryLike, RegisteredSurface } from "@hypit/markup";import { parametersForDraft, timelineAdjustHandles } from "../src/parameters.js";@@ -107,3 +112,78 @@ test("parameter Source paths stay relative to the author workspace", () => {assert.equal(parameters[0]!.source.path, "main.svml");assert.equal(parameters[0]!.source.preimage, "1f");});++test("a derived entity follows its actual Style and the package-owned Recipe vocabulary", () => {+ const main = "<caption-fine:Track id=\"captions\" program={caption-program}/>";+ const sheet = `<sheet version="1">+ caption.alt { x: 0.4; handoff: overlap; }+</sheet>`;+ const placement = (input: {+ id: string;+ module: string;+ surface: string;+ references: Readonly<Record<string, string>>;+ }): StudioPlacement => ({+ sourcePath: "main.svml",+ tag: input.surface,+ module: { name: input.module, version: "1" },+ surface: input.surface,+ id: input.id,+ range: { start: 0, end: main.length },+ records: [], values: [], outputs: [], outputPorts: [], children: [], attributes: {},+ attributeValueRanges: {}, referenceAttributes: input.references, referenceTypes: {},+ references: Object.values(input.references),+ });+ const track = placement({+ id: "captions", module: "@hypit/caption-fine", surface: "track",+ references: { program: "caption-program" },+ });+ const style = placement({+ id: "alternate-caption", module: "@hypit/caption-fine", surface: "style",+ references: { recipe: "recipes.caption.alt" },+ });+ const surface = {+ module: { name: "@hypit/caption-fine", version: "1" },+ surface: "style", tag: "Style", mode: "structured", outputs: [],+ vocabulary: { summary: "Caption Style", example: "<Style/>", attributes: [{+ name: "recipe", kind: "reference", required: true, summary: "Recipe",+ recipe: [+ { name: "x", required: true, summary: "Horizontal position", group: "where", section: "region" },+ { name: "handoff", required: false, summary: "Cue handoff", group: "when", section: "envelope", values: ["cut", "overlap"] },+ ],+ }] },+ handler: () => ({ records: [], components: [], fragments: [], exports: [] }),+ } as RegisteredSurface;+ const surfaces: MarkupSurfaceRegistryLike = {+ resolve(module, name) {+ return module.name === surface.module.name && name === surface.surface ? surface : undefined;+ },+ surfaces() { return [surface]; },+ };++ const parameters = parametersForDraft({+ root: "/workspace",+ files: [+ { path: "main.svml", text: main, language: "svml", imports: [{ alias: "recipes", source: "./recipes.svs" }] },+ { path: "recipes.svs", text: sheet, language: "svs" },+ ],+ placement: track,+ placements: [track, style],+ draft: {+ id: "captions:cue:2", authoredId: "captions", presentId: "cue:2", label: "cue:2",+ startFrame: 0, endFrameExclusive: 10, stackOrder: 70,+ elementRange: track.range,+ parameterReferences: { program: "alternate-caption" },+ },+ declarations: [{ name: "program", label: "Program", writable: false }],+ surfaces,+ });++ assert.deepEqual(parameters.map(({ name, group, section, control, options }) => ({+ name, group, section, control, options,+ })), [+ { name: "x", group: "where", section: "region", control: "number", options: undefined },+ { name: "handoff", group: "when", section: "envelope", control: "select", options: ["cut", "overlap"] },+ ]);+ assert.ok(parameters.every((parameter) => parameter.source.path === "recipes.svs"));+});