Skip to content

armgit / hypit

Public Imported from GitHub
0

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.

feat: preserve Result references and refine Studio workflows

kashorindf129a3c65d3
diff --git a/package.json b/package.json
index b5c75d08..b77b27db 100644
--- a/package.json
+++ b/package.json
@@ -259,6 +259,7 @@
},
"dependencies": {
"@puppeteer/browsers": "3.2.2",
+ "koffi": "3.2.1",
"puppeteer-core": "25.10.0",
"sharp": "0.35.3",
"cmu-pronouncing-dictionary": "3.0.0",
diff --git a/packages/build-result-fs/README.md b/packages/build-result-fs/README.md
index 25891f88..2a305aa4 100644
--- a/packages/build-result-fs/README.md
+++ b/packages/build-result-fs/README.md
@@ -15,7 +15,7 @@ An explicit selection can move the same repository elsewhere:
```
Relative paths are resolved from the project root. Results are grouped by the UTC date already encoded
-in their ordered Build ids, and each Build then owns one intact directory with its `result.json`, public
+in their ordered Build ids. Each Build has a directory containing its `result.json`, new public
Resource files and Composite Value Documents:
```text
@@ -27,3 +27,25 @@ project-wide history database. Browsing sorts the shallow date buckets and enume
only inside the dates reached while filling the requested cursor page; only those Result manifests are
opened. File reads support byte ranges. Active diagnosis checks the selected directory (or its nearest
existing parent) for read/write access without creating a probe file.
+
+Existing resources keep their addresses, including inside nested Composite values. External Workspace
+files remain live references; reused Result files retain their original owning Build. See the shared
+[Result value and reference model](../build-result/README.md) for ownership and export behavior.
+
+## Publication
+
+Runtime execution state stays in the Runtime's store. Result synchronization publishes newly accepted
+public Outputs: it saves new Resource files and Value Documents, then replaces `result.json`.
+Internal graph progress and already published Outputs cause no Result writes. A private `.writer.json`
+holds the file assignments needed while publishing and is removed at completion. The Runtime saves
+all accepted public Outputs and the final outcome before removing active execution state, including
+when the Build fails or is cancelled.
+
+Files are written completely beside their destination before publication. POSIX systems use `rename`;
+Windows uses `SetFileInformationByHandle(FileRenameInfoEx)` with replacement and POSIX semantics through
+Koffi. Existing readers keep their old file, while subsequent opens see the new one. This platform code
+belongs to the filesystem implementation; the Result model and other repository adapters do not
+depend on it. A filesystem that rejects this operation reports the Windows error without timed retries.
+
+The Windows behavior is defined by Microsoft's
+[FileRenameInformationEx documentation](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-fscc/4217551b-d2c0-42cb-9dc1-69a716cf6d0c).
diff --git a/packages/build-result-s3/README.md b/packages/build-result-s3/README.md
index 7ce2febd..942e8ffd 100644
--- a/packages/build-result-s3/README.md
+++ b/packages/build-result-s3/README.md
@@ -33,6 +33,11 @@ The repository exposes the same logical shape as the filesystem adapter:
Filesystem and S3 use the same Record-to-Result encoder. The adapter only writes the selected
relative document or byte path; it does not interpret domain values. A Value Document keeps canonical
domain data separate from the paths of nested Resources.
+Nested reuse retains each Resource's original Build and path. Workspace files remain explicit external
+references rather than being uploaded merely because this repository uses S3. The shared
+[Result value and reference model](../build-result/README.md) describes ownership and external access.
+Synchronization uploads new public Outputs and then their updated manifest. Internal graph progress
+and repeated synchronization of already published Outputs produce no object writes.
Physical object prefixes use a reversible descending-time form derived from the ordered Build id, so
S3 can return a newest-first delimiter page directly. This is only adapter key layout: callers still
diff --git a/packages/build-result-s3/src/repository.ts b/packages/build-result-s3/src/repository.ts
index 3a36594e..27af802b 100644
--- a/packages/build-result-s3/src/repository.ts
+++ b/packages/build-result-s3/src/repository.ts
@@ -1,5 +1,6 @@
import type {
BuildResultFileRef,
+ ExternalFileAccess,
BuildResultFileRange,
BuildResultFinish,
BuildResultManifest,
@@ -22,6 +23,8 @@ import {
encodeBuildResultManifest,
normalizeBuildResultForwards,
syncBuildResultOutputs,
+ currentFileReference,
+ localExternalFiles,
} from "@hypit/build-result";
import { assertOrderedBuildId, buildIdCreatedAt } from "@hypit/protocol";
@@ -31,6 +34,7 @@ import type { AwsBuildResultS3ClientOptions, BuildResultS3Client } from "./clien
export type S3BuildResultRepositoryOptions = AwsBuildResultS3ClientOptions & {
readonly prefix?: string;
readonly client?: BuildResultS3Client;
+ readonly externalFiles?: ExternalFileAccess;
};
function assert(condition: unknown, message: string): asserts condition {
@@ -102,6 +106,7 @@ class S3BuildResultWriter implements BuildResultWriter {
},
},
});
+ if (!updated.changed) return manifest;
await this.#repository.writeWriter(this.#build, updated.writer);
await this.#repository.writeManifest(this.#build, updated.manifest);
return updated.manifest;
@@ -132,10 +137,12 @@ class S3BuildResultWriter implements BuildResultWriter {
export class S3BuildResultRepository implements BuildResultRepository {
readonly #client: BuildResultS3Client;
readonly #prefix: string;
+ readonly #externalFiles: ExternalFileAccess;
constructor(options: S3BuildResultRepositoryOptions) {
assert(options.bucket.trim().length > 0, "S3 Build Result bucket must not be empty");
this.#prefix = normalizePrefix(options.prefix);
+ this.#externalFiles = options.externalFiles ?? localExternalFiles;
this.#client = options.client ?? new AwsBuildResultS3Client(options);
}
@@ -194,6 +201,7 @@ export class S3BuildResultRepository implements BuildResultRepository {
resources: {},
values: {},
publishedOutputs: seed.publishedOutputs,
+ ...(seed.resourceReferences === undefined ? {} : { resourceReferences: seed.resourceReferences }),
forwards,
});
await this.writeManifest(seed.id, manifest);
@@ -285,8 +293,9 @@ export class S3BuildResultRepository implements BuildResultRepository {
currentOutput = entry.value.output;
continue;
}
- return entry.value.kind === "build-file"
- ? { type: entry.type, kind: "resource", size: entry.value.size, mediaType: entry.value.mediaType }
+ const file = entry.value.kind === "external-file" ? await currentFileReference(entry.value, this.#externalFiles) : entry.value;
+ return file.kind === "build-file" || file.kind === "external-file"
+ ? { type: entry.type, kind: "resource", size: file.size, mediaType: file.mediaType }
: entry.value.kind === "value"
? { type: entry.type, kind: "composite" }
: { type: entry.type, kind: "scalar" };
@@ -324,29 +333,34 @@ export class S3BuildResultRepository implements BuildResultRepository {
};
}
const terminalKind = (entry.value as { readonly kind?: unknown }).kind;
- assert(terminalKind === "build-file" || terminalKind === "inline",
+ assert(terminalKind === "build-file" || terminalKind === "external-file" || terminalKind === "inline",
`Build ${currentBuild} Output ${currentOutput} has unsupported Result value kind ${String(terminalKind)}`);
return {
build: currentBuild,
output: currentOutput,
type: entry.type,
- value: entry.value,
+ value: entry.value.kind === "external-file" ? await currentFileReference(entry.value, this.#externalFiles) : entry.value,
};
}
}
+ async describeFile(_build: string, file: BuildResultFileRef): Promise<BuildResultFileRef> {
+ return await currentFileReference(file, this.#externalFiles);
+ }
+
async openFile(
build: string,
file: BuildResultFileRef,
range?: BuildResultFileRange,
): Promise<AsyncIterable<Uint8Array> | undefined> {
+ if (file.kind === "external-file") return await this.#externalFiles.open(file.uri, range);
if (range !== undefined) {
assert(Number.isSafeInteger(range.start) && range.start >= 0, "Build Result file range start is invalid");
assert(Number.isSafeInteger(range.endExclusive) && range.endExclusive > range.start,
"Build Result file range end is invalid");
assert(range.endExclusive <= file.size, "Build Result file range exceeds the declared file size");
}
- return await this.#client.open(this.#key(build, file.path), range);
+ return await this.#client.open(this.#key(file.build ?? build, file.path), range);
}
/** Verify that the configured bucket/prefix can be listed without loading Result history. */
diff --git a/packages/build-result-s3/test/repository.test.ts b/packages/build-result-s3/test/repository.test.ts
index 8d6043b9..12bac9e8 100644
--- a/packages/build-result-s3/test/repository.test.ts
+++ b/packages/build-result-s3/test/repository.test.ts
@@ -16,6 +16,7 @@ const takeType: TypeRef = {
class MemoryS3 implements BuildResultS3Client {
readonly objects = new Map<string, Uint8Array>();
+ readonly writes: string[] = [];
readonly listRequests: {
readonly prefix: string;
readonly limit?: number;
@@ -24,10 +25,12 @@ class MemoryS3 implements BuildResultS3Client {
}[] = [];
async put(key: string, bytes: Uint8Array): Promise<void> {
+ this.writes.push(key);
this.objects.set(key, Uint8Array.from(bytes));
}
async putStream(key: string, chunks: AsyncIterable<Uint8Array>): Promise<void> {
+ this.writes.push(key);
const values: Uint8Array[] = [];
let size = 0;
for await (const chunk of chunks) {
@@ -81,6 +84,33 @@ class MemoryS3 implements BuildResultS3Client {
}
}
+test("S3 publishes new Outputs without uploading unchanged Result documents", async () => {
+ const client = new MemoryS3();
+ const repository = new S3BuildResultRepository({ bucket: "unused", prefix: "project", client });
+ const writer = await repository.create({
+ id: "bld_20260902T100000000Z_0000000001",
+ source: { path: "/project/main.svml" }, targets: ["answer"],
+ publishedOutputs: [{ name: "answer", output: "logical:answer" }],
+ });
+ const resources = { async open() { throw new Error("unexpected Resource read"); } };
+ const count = client.writes.length;
+ await writer.sync({ state: state({ records: [], bindings: [] }), resources });
+ assert.equal(client.writes.length, count);
+ const accepted = state({
+ records: [{ id: "record:answer", type: videoType, value: { kind: "inline", value: 42 } }],
+ bindings: [{ output: "logical:answer", record: "record:answer" }],
+ });
+ await writer.sync({ state: accepted, resources });
+ const published = client.writes.length;
+ assert.ok(published > count);
+ assert.deepEqual((await writer.read()).outputs.answer?.value, { kind: "inline", value: 42 });
+ await writer.sync({ state: accepted, resources });
+ assert.equal(client.writes.length, published);
+ await writer.finish({ outcome: "cancelled" });
+ assert.equal((await writer.read()).outcome, "cancelled");
+ assert.deepEqual((await writer.read()).outputs.answer?.value, { kind: "inline", value: 42 });
+});
+
function state(input: {
readonly status?: BuildState["status"];
readonly records: BuildState["records"];
@@ -197,10 +227,13 @@ test("S3 keeps the same Build Result model as the filesystem repository", async
);
assert.deepEqual((await repository.browse({ limit: 20 })).results.map((item) => item.id), ["bld_20260902T100000000Z_0000000001"]);
const presented = await repository.updatePresentation("bld_20260902T100000000Z_0000000001", {
+ outputDisplayNames: { "shot.video": "Opening portrait" },
title: "Episode 12 opening",
note: "Preferred composite.",
highlightedOutputs: ["shot.video"],
});
+ assert.equal(presented.outputs["shot.video"]?.displayName, "Opening portrait");
+ assert.equal((await repository.read(presented.id))?.outputs["shot.video"]?.displayName, "Opening portrait");
assert.equal(presented.title, "Episode 12 opening");
assert.equal(presented.note, "Preferred composite.");
assert.deepEqual(presented.highlightedOutputs, ["shot.video"]);
@@ -405,3 +438,56 @@ test("S3 reduces repeated reuse to its finished content owner without copying by
assert.equal(new TextDecoder().decode(Uint8Array.from(chunks.flatMap((chunk) => [...chunk]))), "historical video");
assert.equal([...client.objects.keys()].filter((key) => key.includes("/files/")).length, 1);
});
+
+test("S3 Composite values retain external and prior-Result Resource references", async () => {
+ const client = new MemoryS3();
+ let external = new Uint8Array([1, 2, 3]);
+ const repository = new S3BuildResultRepository({ bucket: "test", prefix: "project", client,
+ externalFiles: {
+ async size(uri) { assert.equal(uri, "asset://selected/photo"); return external.length; },
+ async open(uri, range) {
+ assert.equal(uri, "asset://selected/photo");
+ return (async function* () { yield range === undefined ? external : external.slice(range.start, range.endExclusive); })();
+ },
+ },
+ });
+ const originalId = "bld_20260902T100000000Z_0000000001";
+ const reusedId = "bld_20260902T100000001Z_0000000001";
+ const video: BlobRef = { kind: "blob", resource: "res_generated", size: 2, mediaType: "video/mp4" };
+ const original = await repository.create({ id: originalId, source: { path: "main.svml" },
+ targets: ["video"], publishedOutputs: [{ name: "video", output: "video" }] });
+ await original.sync({ state: state({ records: [{ id: "r", type: videoType, value: video }],
+ bindings: [{ output: "video", record: "r" }] }),
+ resources: { async open() { return (async function* () { yield new Uint8Array([8, 9]); })(); } } });
+ await original.finish({ outcome: "complete" });
+ const saved = (await repository.resolve(originalId, "video"))!;
+ assert.equal(saved.value.kind, "build-file");
+ if (saved.value.kind !== "build-file") throw new Error("expected file");
+ const photo: BlobRef = { kind: "blob", resource: "res_photo", size: 3, mediaType: "image/png" };
+ const writer = await repository.create({ id: reusedId, source: { path: "main.svml" }, targets: ["layout"],
+ publishedOutputs: [{ name: "layout", output: "layout" }], resourceReferences: {
+ [photo.resource]: { kind: "external-file", uri: "asset://selected/photo", size: 3, mediaType: "image/png" },
+ [video.resource]: { ...saved.value, build: originalId },
+ } });
+ await writer.sync({ state: state({ records: [{ id: "r", type: takeType,
+ value: { kind: "inline", value: { layers: [{ parts: [photo, { clip: video, repeated: photo }] }] } } }],
+ bindings: [{ output: "layout", record: "r" }] }),
+ resources: { async open() { throw new Error("Referenced resources cannot be uploaded again"); } } });
+ await writer.finish({ outcome: "complete" });
+ assert.equal([...client.objects.keys()].filter((key) => key.includes("/files/")).length, 1);
+ const resolved = (await repository.resolve(reusedId, "layout"))!;
+ assert.equal(resolved.value.kind, "value");
+ if (resolved.value.kind !== "value") throw new Error("expected composite");
+ assert.equal(resolved.value.document.resources.length, 3);
+ const oldVideo = resolved.value.document.resources.find((binding) => binding.file.kind === "build-file")!;
+ assert.deepEqual(oldVideo.file, { ...saved.value, build: originalId });
+ const chunks: Uint8Array[] = [];
+ for await (const chunk of (await repository.openFile(reusedId, oldVideo.file))!) chunks.push(chunk);
+ assert.deepEqual(Buffer.concat(chunks), Buffer.from([8, 9]));
+ const externalRef = resolved.value.document.resources.find((binding) => binding.file.kind === "external-file")!.file;
+ external = new Uint8Array([4, 5, 6, 7]);
+ assert.equal((await repository.describeFile(reusedId, externalRef)).size, 4);
+ const selected: Uint8Array[] = [];
+ for await (const chunk of (await repository.openFile(reusedId, externalRef, { start: 1, endExclusive: 3 }))!) selected.push(chunk);
+ assert.deepEqual(Buffer.concat(selected), Buffer.from([5, 6]));
+});
diff --git a/packages/build-result/README.md b/packages/build-result/README.md
new file mode 100644
index 00000000..c4fd9e22
--- /dev/null
+++ b/packages/build-result/README.md
@@ -0,0 +1,58 @@
+# `@hypit/build-result`
+
+Build Results retain accepted public Outputs and the attempt's final outcome. Execution state belongs
+to Runtime. A Result records which value satisfied each Output; a new Output record does not imply a
+new media file.
+
+## Values and file ownership
+
+| Value source | Persisted representation |
+| --- | --- |
+| New Resource without an existing durable address | One file owned by this Build |
+| Explicit Workspace file | `external-file` with the Workspace's URI |
+| Resource from an earlier Result | `build-file` with its original `build` and `path` |
+| Entire earlier public Output | `build-output` pointing to its terminal Build and Output |
+| Composite value | A Value Document whose Resource bindings follow the same rules at every depth |
+
+A local `build-file` omits `build` when its owner is the containing Result. When imported into another
+Build, its owner becomes explicit. Arrays and nested objects do not change ownership: a new Composite
+can save new structure while referencing old video, audio and images. Only newly produced Resources
+get new files. The encoder recognizes Resource values, independently of their domain Type or field name.
+
+An `external-file` stays live. Replacing that file changes subsequent reads; deleting it leaves an
+unavailable dependency. The stored size describes the file when admitted; `describeFile` and public
+Output resolution obtain its current size. Readers use the explicit address without searching for
+alternatives or comparing file contents.
+
+## Passing references through execution
+
+Workspace attachments may supply a `location` URI. The Node compiler preserves it, and the CLI maps
+these addresses and explicitly imported Result files to the compilation's Resource identities. It
+passes that map as `BuildResultSeed.resourceReferences` alongside whole-Output `forwards`.
+
+The Result writer keeps this per-Build map in its private writer state while publishing. It uses the
+map for both direct Resource Outputs and all nested Resource bindings. Persistent Output documents
+contain the references they actually use; private writer state is removed at the terminal outcome.
+Core still receives ordinary typed Records, Candidates and Resource identities. It has no knowledge
+of file paths or Result repositories. Runtime may stage input bytes for execution independently of
+Result publication.
+
+Repositories own address access. `describeFile` obtains metadata and `openFile` streams bytes or a byte
+range. The filesystem and S3 implementations accept `ExternalFileAccess` for external addresses; the
+Node default opens Workspace `file:` URIs. A custom adapter can supply a different address reader.
+Selecting S3 for Result storage does not implicitly upload external file dependencies.
+
+`fileReferenceIdentity` identifies the explicit URI or owning Build and path. Studio uses this identity
+to group multiple uses of a file. Separate files remain separate even when their bytes happen to match.
+
+An explicit `hypit get` export collects the selected Output's referenced bytes into its destination.
+Composite exports rewrite bindings to local files, including references with different owners but the
+same relative filename. This makes that export self-contained; ordinary Build publication preserves
+references. Moving editable projects also requires preserving or updating their external file addresses.
+
+Published Outputs can carry an optional author `displayName` for browsers such as Studio.
+It is presentation text only: Output names, forwarding and file ownership do not change.
+
+`updatePresentation` accepts `outputDisplayNames`, keyed by exact public Output name. Each
+nonempty string sets that Output’s `displayName`; null removes it. Like title and note editing,
+this applies to finished Results and preserves all values, file references and Output identifiers.
diff --git a/packages/build-result/package.json b/packages/build-result/package.json
index 34660ee8..e711dc99 100644
--- a/packages/build-result/package.json
+++ b/packages/build-result/package.json
@@ -8,6 +8,7 @@
".": "./src/index.ts"
},
"dependencies": {
- "@hypit/protocol": "workspace:*"
+ "@hypit/protocol": "workspace:*",
+ "koffi": "3.2.1"
}
}
diff --git a/packages/build-result/src/decode.ts b/packages/build-result/src/decode.ts
index 61baaa52..d5690630 100644
--- a/packages/build-result/src/decode.ts
+++ b/packages/build-result/src/decode.ts
@@ -70,14 +70,9 @@ function resultPath(value: unknown, subject: string): string {
function outputValue(value: unknown, subject: string): BuildResultOutputValue {
const item = object(value, subject);
- if (item.kind === "build-file") {
+ if (item.kind === "build-file" || item.kind === "external-file") {
assertBuildResultFileRef(item, subject);
- return {
- kind: "build-file",
- path: item.path,
- size: item.size,
- mediaType: item.mediaType,
- };
+ return { ...item };
}
if (item.kind === "build-output") {
return {
@@ -106,6 +101,7 @@ function outputs(value: unknown, subject: string): Readonly<Record<string, Build
text(name, `${subject} Output name`);
const item = object(value, `${subject}[${JSON.stringify(name)}]`);
return [name, {
+ ...(item.displayName === undefined ? {} : { displayName: text(item.displayName, `${subject}.displayName`) }),
type: typeRef(item.type, `${subject}[${JSON.stringify(name)}].type`),
value: outputValue(item.value, `${subject}[${JSON.stringify(name)}].value`),
}] as const;
@@ -255,7 +251,7 @@ export function decodeBuildResultWriterState(
if (logicalOutputs.has(output)) throw new Error(`${subject} publishes Logical Output ${output} more than once`);
names.add(name);
logicalOutputs.add(output);
- return { name, output };
+ return { name, output, ...(published.displayName === undefined ? {} : { displayName: text(published.displayName, `${subject}.displayName`) }) };
});
const forwardedOutputs = new Set<string>();
const forwards = item.forwards.map((value, index) => {
@@ -270,6 +266,12 @@ export function decodeBuildResultWriterState(
};
});
return {
+ ...(item.resourceReferences === undefined ? {} : { resourceReferences: Object.fromEntries(
+ Object.entries(object(item.resourceReferences, `${subject}.resourceReferences`)).map(([resource, reference]) => {
+ assertBuildResultFileRef(reference, `${subject}.resourceReferences.${resource}`);
+ return [resource, reference];
+ }),
+ ) }),
resources: pathMap(item.resources, `${subject}.resources`),
values: pathMap(item.values, `${subject}.values`),
publishedOutputs,
diff --git a/packages/build-result/src/file-reference.ts b/packages/build-result/src/file-reference.ts
new file mode 100644
index 00000000..f8bbc21a
--- /dev/null
+++ b/packages/build-result/src/file-reference.ts
@@ -0,0 +1,42 @@
+import { createReadStream } from "node:fs";
+import { stat } from "node:fs/promises";
+import { fileURLToPath } from "node:url";
+import type { BuildResultFileRange, BuildResultFileRef } from "./types.js";
+
+/** Address access belongs to the Repository adapter, not the value or domain graph. */
+export type ExternalFileAccess = {
+ size(uri: string): Promise<number>;
+ open(uri: string, range?: BuildResultFileRange): Promise<AsyncIterable<Uint8Array>>;
+};
+
+/** The Node distribution's external files are explicit file: URLs supplied by its Workspace. */
+export const localExternalFiles: ExternalFileAccess = {
+ async size(uri) { return (await stat(fileURLToPath(uri))).size; },
+ async open(uri, range) {
+ if (range !== undefined) {
+ const size = await localExternalFiles.size(uri);
+ if (!Number.isSafeInteger(range.start) || range.start < 0
+ || !Number.isSafeInteger(range.endExclusive) || range.endExclusive <= range.start
+ || range.endExclusive > size) throw new Error(`Invalid file range for ${uri}`);
+ }
+ return createReadStream(fileURLToPath(uri), range === undefined ? {} : { start: range.start, end: range.endExclusive - 1 });
+ },
+};
+
+export function fileReferenceIdentity(owner: string, file: BuildResultFileRef): string {
+ return file.kind === "external-file" ? JSON.stringify(["external", file.uri])
+ : JSON.stringify(["result", file.build ?? owner, file.path]);
+}
+
+/** Make a relative Result file reference independent of its enclosing value document. */
+export function ownedFileReference(owner: string, file: BuildResultFileRef): BuildResultFileRef {
+ return file.kind === "build-file" ? { ...file, build: file.build ?? owner } : file;
+}
+
+/** Reopening an external reference reads its current metadata, without comparing versions. */
+export async function currentFileReference(
+ file: BuildResultFileRef,
+ access: ExternalFileAccess = localExternalFiles,
+): Promise<BuildResultFileRef> {
+ return file.kind === "external-file" ? { ...file, size: await access.size(file.uri) } : file;
+}
diff --git a/packages/build-result/src/index.ts b/packages/build-result/src/index.ts
index 4ad0dad6..8ce9d898 100644
--- a/packages/build-result/src/index.ts
+++ b/packages/build-result/src/index.ts
@@ -23,3 +23,6 @@ export {
} from "./store.js";
export type * from "./types.js";
export type * from "./writer.js";
+
+export { currentFileReference, fileReferenceIdentity, ownedFileReference, localExternalFiles } from "./file-reference.js";
+export type { ExternalFileAccess } from "./file-reference.js";
diff --git a/packages/build-result/src/replace-file-windows.ts b/packages/build-result/src/replace-file-windows.ts
new file mode 100644
index 00000000..1e64fc53
--- /dev/null
+++ b/packages/build-result/src/replace-file-windows.ts
@@ -0,0 +1,55 @@
+import { toNamespacedPath } from "node:path";
+import koffi from "koffi";
+
+const kernel = koffi.load("kernel32.dll");
+const createFile = kernel.func("intptr_t __stdcall CreateFileW(const char16_t *path, uint32_t access, uint32_t share, void *security, uint32_t disposition, uint32_t attributes, intptr_t templateFile)");
+const setInformation = kernel.func("int __stdcall SetFileInformationByHandle(intptr_t file, int infoClass, void *info, uint32_t size)");
+const closeHandle = kernel.func("int __stdcall CloseHandle(intptr_t file)");
+const getLastError = kernel.func("uint32_t __stdcall GetLastError()");
+
+const renameInfo = koffi.struct({
+ Flags: "uint32_t",
+ RootDirectory: "void *",
+ FileNameLength: "uint32_t",
+ FileName: koffi.array("uint16_t", 1),
+});
+
+const DELETE = 0x00010000;
+const SHARE_READ_WRITE_DELETE = 0x7;
+const OPEN_EXISTING = 3;
+const FILE_ATTRIBUTE_NORMAL = 0x80;
+const FileRenameInfoEx = 22;
+const REPLACE_IF_EXISTS = 0x1;
+const POSIX_SEMANTICS = 0x2;
+
+function failure(syscall: string, from: string, to: string): Error {
+ const win32Code = getLastError() as number;
+ return Object.assign(new Error(`Windows file replacement failed (${win32Code}): '${from}' -> '${to}'`), {
+ code: `WIN32_${win32Code}`, win32Code, syscall, path: from, dest: to,
+ });
+}
+
+/**
+ * FileRenameInfoEx preserves open readers of the old file while publishing the new name.
+ * Node's Windows rename uses MoveFileExW, whose replacement semantics differ here.
+ * https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-fscc/4217551b-d2c0-42cb-9dc1-69a716cf6d0c
+ */
+export function replaceWindowsFile(from: string, to: string): void {
+ const filename = Buffer.from(toNamespacedPath(to), "utf16le");
+ const nameOffset = koffi.offsetof(renameInfo, "FileName");
+ const info = Buffer.alloc(Math.max(koffi.sizeof(renameInfo), nameOffset + filename.length));
+ info.writeUInt32LE(REPLACE_IF_EXISTS | POSIX_SEMANTICS, koffi.offsetof(renameInfo, "Flags"));
+ info.writeUInt32LE(filename.length, koffi.offsetof(renameInfo, "FileNameLength"));
+ filename.copy(info, nameOffset);
+
+ const handle = createFile(toNamespacedPath(from), DELETE, SHARE_READ_WRITE_DELETE,
+ null, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0) as number | bigint;
+ if (handle === -1 || handle === -1n) throw failure("CreateFileW", from, to);
+ try {
+ if (!setInformation(handle, FileRenameInfoEx, info, info.length)) {
+ throw failure("SetFileInformationByHandle", from, to);
+ }
+ } finally {
+ closeHandle(handle);
+ }
+}
diff --git a/packages/build-result/src/replace-file.ts b/packages/build-result/src/replace-file.ts
new file mode 100644
index 00000000..448aaa98
--- /dev/null
+++ b/packages/build-result/src/replace-file.ts
@@ -0,0 +1,11 @@
+import { rename } from "node:fs/promises";
+
+/** Publish a complete file without changing the bytes held by existing readers. */
+export async function replaceFile(from: string, to: string): Promise<void> {
+ if (process.platform === "win32") {
+ const { replaceWindowsFile } = await import("./replace-file-windows.js");
+ replaceWindowsFile(from, to);
+ } else {
+ await rename(from, to);
+ }
+}
diff --git a/packages/build-result/src/store.ts b/packages/build-result/src/store.ts
index 574a5c8c..c6fe96c1 100644
--- a/packages/build-result/src/store.ts
+++ b/packages/build-result/src/store.ts
@@ -1,3 +1,5 @@
+import { currentFileReference, localExternalFiles } from "./file-reference.js";
+import type { ExternalFileAccess } from "./file-reference.js";
import { randomUUID } from "node:crypto";
import {
mkdir,
@@ -40,6 +42,7 @@ import {
encodeBuildResultManifest,
} from "./decode.js";
import { syncBuildResultOutputs } from "./writer.js";
+import { replaceFile } from "./replace-file.js";
const manifestName = "result.json";
const writerStateName = ".writer.json";
@@ -83,6 +86,22 @@ export function applyBuildResultPresentation(
if (highlighted.length === 0) delete base.highlightedOutputs;
else base.highlightedOutputs = highlighted;
}
+ if (update.outputDisplayNames !== undefined) {
+ const outputs = { ...manifest.outputs };
+ for (const [name, value] of Object.entries(update.outputDisplayNames)) {
+ const entry = manifest.outputs[name];
+ assert(Object.hasOwn(manifest.outputs, name) && entry !== undefined,
+ `Build Result ${manifest.id} has no Output ${name}`);
+ const { displayName: _priorName, ...rest } = entry;
+ if (value === null) outputs[name] = rest;
+ else {
+ const displayName = value.trim();
+ assert(displayName.length > 0, "Output display name must not be empty");
+ outputs[name] = { ...rest, displayName };
+ }
+ }
+ return { ...base, outputs };
+ }
return base;
}
@@ -90,29 +109,6 @@ async function exists(path: string): Promise<boolean> {
return await stat(path).then((item) => item.isFile(), () => false);
}
-/**
- * Replace `to` with `from`, allowing brief filesystem contention to clear.
- *
- * Windows CI observed EPERM when publishing result.json after execution completed. Sharing modes
- * and filesystem filters can temporarily prevent replacement; an open reader alone does not prove
- * the cause. Retry the same rename briefly, keeping the old file intact until replacement succeeds.
- * Persistent permission or sharing errors still fail this write with the original filesystem error.
- */
-async function replaceFile(from: string, to: string): Promise<void> {
- const deadline = Date.now() + 2_000;
- while (true) {
- try {
- await rename(from, to);
- return;
- } catch (error) {
- const code = error instanceof Error && "code" in error ? error.code : undefined;
- const contended = code === "EPERM" || code === "EACCES" || code === "EBUSY";
- if (!contended || Date.now() >= deadline) throw error;
- await new Promise((settle) => { setTimeout(settle, 20); });
- }
- }
-}
-
async function writeJsonAtomic(path: string, value: unknown): Promise<void> {
await mkdir(dirname(path), { recursive: true });
const temporary = `${path}.part-${randomUUID()}`;
@@ -244,6 +240,7 @@ export async function resolveBuildResultOutput(
root: string,
build: string,
output: string,
+ externalFiles: ExternalFileAccess = localExternalFiles,
): Promise<ResolvedBuildResultOutput | undefined> {
const seen = new Set<string>();
let currentBuild = build;
@@ -277,14 +274,14 @@ export async function resolveBuildResultOutput(
};
}
const terminalKind = (entry.value as { readonly kind?: unknown }).kind;
- assert(terminalKind === "build-file" || terminalKind === "inline",
+ assert(terminalKind === "build-file" || terminalKind === "external-file" || terminalKind === "inline",
`Build ${currentBuild} Output ${currentOutput} has unsupported Result value kind ${String(terminalKind)}`);
return {
build: currentBuild,
output: currentOutput,
directory,
type: entry.type,
- value: entry.value,
+ value: entry.value.kind === "external-file" ? await currentFileReference(entry.value, externalFiles) : entry.value,
};
}
}
@@ -293,6 +290,7 @@ export async function describeBuildResultOutput(
root: string,
build: string,
output: string,
+ externalFiles: ExternalFileAccess = localExternalFiles,
): Promise<RepositoryBuildResultOutputDescription | undefined> {
const seen = new Set<string>();
let currentBuild = build;
@@ -309,8 +307,9 @@ export async function describeBuildResultOutput(
currentOutput = entry.value.output;
continue;
}
- return entry.value.kind === "build-file"
- ? { type: entry.type, kind: "resource", size: entry.value.size, mediaType: entry.value.mediaType }
+ const file = entry.value.kind === "external-file" ? await currentFileReference(entry.value, externalFiles) : entry.value;
+ return file.kind === "build-file" || file.kind === "external-file"
+ ? { type: entry.type, kind: "resource", size: file.size, mediaType: file.mediaType }
: entry.value.kind === "value"
? { type: entry.type, kind: "composite" }
: { type: entry.type, kind: "scalar" };
@@ -357,12 +356,12 @@ export class FileBuildResult {
this.directory = resolve(directory);
}
- static async create(root: string, seed: BuildResultSeed): Promise<FileBuildResult> {
+ static async create(root: string, seed: BuildResultSeed, externalFiles: ExternalFileAccess = localExternalFiles): Promise<FileBuildResult> {
assertOrderedBuildId(seed.id);
assertBuildResultSeed(seed);
const forwards = await normalizeBuildResultForwards({
read: async (build) => await readBuildResult(buildResultDirectory(root, build)),
- resolve: async (build, output) => await resolveBuildResultOutput(root, build, output),
+ resolve: async (build, output) => await resolveBuildResultOutput(root, build, output, externalFiles),
}, seed.forwards ?? []);
const directory = buildResultDirectory(root, seed.id);
await mkdir(dirname(directory), { recursive: true });
@@ -383,6 +382,7 @@ export class FileBuildResult {
resources: {},
values: {},
publishedOutputs: seed.publishedOutputs,
+ ...(seed.resourceReferences === undefined ? {} : { resourceReferences: seed.resourceReferences }),
forwards,
});
await rename(temporary, directory);
@@ -428,6 +428,7 @@ export class FileBuildResult {
},
},
});
+ if (!updated.changed) return manifest;
await writeJsonAtomic(join(this.directory, writerStateName), updated.writer);
await writeManifestAtomic(join(this.directory, manifestName), updated.manifest);
return updated.manifest;
@@ -457,15 +458,17 @@ export class FileBuildResult {
/** Default zero-configuration project repository backed by one ordinary directory tree. */
export class FileBuildResultRepository implements BuildResultRepository {
+ readonly externalFiles: ExternalFileAccess;
readonly root: string;
- constructor(root: string) {
+ constructor(root: string, externalFiles: ExternalFileAccess = localExternalFiles) {
+ this.externalFiles = externalFiles;
assert(root.trim().length > 0, "Build Result root must not be empty");
this.root = resolve(root);
}
async create(seed: BuildResultSeed): Promise<FileBuildResult> {
- return await FileBuildResult.create(this.root, seed);
+ return await FileBuildResult.create(this.root, seed, this.externalFiles);
}
async openWriter(build: string): Promise<FileBuildResult | undefined> {
@@ -500,22 +503,27 @@ export class FileBuildResultRepository implements BuildResultRepository {
}
async describeOutput(build: string, output: string): Promise<RepositoryBuildResultOutputDescription | undefined> {
- return await describeBuildResultOutput(this.root, build, output);
+ return await describeBuildResultOutput(this.root, build, output, this.externalFiles);
}
async resolve(build: string, output: string): Promise<RepositoryBuildResultOutput | undefined> {
- const resolvedOutput = await resolveBuildResultOutput(this.root, build, output);
+ const resolvedOutput = await resolveBuildResultOutput(this.root, build, output, this.externalFiles);
if (resolvedOutput === undefined) return undefined;
const { directory: _directory, ...portable } = resolvedOutput;
return portable;
}
+ async describeFile(_build: string, file: BuildResultFileRef): Promise<BuildResultFileRef> {
+ return await currentFileReference(file, this.externalFiles);
+ }
+
async openFile(
build: string,
file: BuildResultFileRef,
range?: BuildResultFileRange,
): Promise<AsyncIterable<Uint8Array> | undefined> {
- const directory = buildResultDirectory(this.root, build);
+ if (file.kind === "external-file") return await this.externalFiles.open(file.uri, range);
+ const directory = buildResultDirectory(this.root, file.build ?? build);
const path = containedResultPath(directory, file.path);
if (!await exists(path)) return undefined;
if (range === undefined) return createReadStream(path);
diff --git a/packages/build-result/src/types.ts b/packages/build-result/src/types.ts
index 7dbc36af..9d01ed1a 100644
--- a/packages/build-result/src/types.ts
+++ b/packages/build-result/src/types.ts
@@ -1,3 +1,4 @@
+import { assertOrderedBuildId } from "@hypit/protocol";
import type {
BlobRef,
BuildState,
@@ -9,12 +10,19 @@ import type {
export type BuildResultOutcome = "complete" | "failed" | "cancelled";
export type BuildResultFileRef = {
+ readonly size: number;
+ readonly mediaType: string;
+} & ({
readonly kind: "build-file";
+ /** Absent for a file owned by the containing Result; explicit when reused elsewhere. */
+ readonly build?: string;
/** Forward-only path relative to the owning Build's result directory. */
readonly path: string;
- readonly size: number;
- readonly mediaType: string;
-};
+} | {
+ readonly kind: "external-file";
+ /** Explicit address supplied by the Workspace; remains a live external dependency. */
+ readonly uri: string;
+});
/** A normalized half-open byte range within one Result file. */
export type BuildResultFileRange = {
@@ -38,7 +46,7 @@ export type BuildResultResourceBinding = {
/**
* Durable encoding of one Composite value. Domain data stays ordinary canonical data while
- * Result-local Resource addresses live beside it, so reserved-looking domain objects cannot be
+ * Resource references live beside it, so reserved-looking domain objects cannot be
* mistaken for persistence metadata.
*/
export type BuildResultValueDocument = {
@@ -77,12 +85,18 @@ export function assertBuildResultFileRef(value: unknown, subject: string): asser
throw new Error(`${subject} is not a Build file reference`);
}
const item = value as Readonly<Record<string, unknown>>;
- if (item.kind !== "build-file"
+ if ((item.kind !== "build-file" && item.kind !== "external-file")
|| typeof item.size !== "number" || !Number.isSafeInteger(item.size) || item.size < 0
|| typeof item.mediaType !== "string" || item.mediaType.length === 0) {
throw new Error(`${subject} is not a valid Build file reference`);
}
- assertBuildResultPath(item.path, `${subject}.path`);
+ if (item.kind === "external-file") {
+ if (typeof item.uri !== "string" || item.uri.length === 0) throw new Error(`${subject}.uri is missing`);
+ new URL(item.uri);
+ } else {
+ assertBuildResultPath(item.path, `${subject}.path`);
+ if (item.build !== undefined) assertOrderedBuildId(item.build as string);
+ }
}
function valueAtPath(value: CanonicalValue, path: BuildResultValuePath, subject: string): CanonicalValue {
@@ -150,6 +164,8 @@ export type BuildResultOutputValue =
| { readonly kind: "value"; readonly path: string };
export type BuildResultOutput = {
+ /** Author-provided display name; the Output identifier remains unchanged. */
+ readonly displayName?: string;
readonly type: TypeRef;
readonly value: BuildResultOutputValue;
};
@@ -198,6 +214,8 @@ export type FinishedBuildResultManifest = BuildResultManifest & {
};
export type BuildResultPublishedOutput = {
+ /** Author-provided display name; the Output identifier remains unchanged. */
+ readonly displayName?: string;
readonly name: string;
readonly output: string;
};
@@ -217,6 +235,8 @@ export type BuildResultSeed = {
readonly targets: readonly string[];
readonly publishedOutputs: readonly BuildResultPublishedOutput[];
readonly forwards?: readonly BuildResultForward[];
+ /** Known file locations for admitted Resource identities, including nested uses. */
+ readonly resourceReferences?: Readonly<Record<string, BuildResultFileRef>>;
};
/** Validate the one-name-per-Output public Result surface before storage is touched. */
@@ -224,6 +244,11 @@ export function assertBuildResultSeed(seed: BuildResultSeed): void {
if (seed.title !== undefined && seed.title.trim().length === 0) {
throw new Error("Build Result title must not be empty");
}
+ for (const [resource, file] of Object.entries(seed.resourceReferences ?? {})) {
+ if (resource.length === 0) throw new Error("Resource reference has no identity");
+ assertBuildResultFileRef(file, `Resource ${resource}`);
+ if (file.kind === "build-file" && file.build === undefined) throw new Error(`Resource ${resource} needs its owning Build`);
+ }
const names = new Set<string>();
const outputs = new Set<string>();
for (const published of seed.publishedOutputs) {
@@ -275,6 +300,8 @@ export type BuildResultFinish = {
};
export type BuildResultPresentationUpdate = {
+ /** Exact public Output names; null removes an override. */
+ readonly outputDisplayNames?: Readonly<Record<string, string | null>>;
/** `null` removes the current title; omission leaves it unchanged. */
readonly title?: string | null;
/** `null` removes the current note; omission leaves it unchanged. */
@@ -325,13 +352,14 @@ export type RepositoryBuildResultOutputDescription = {
export type BuildResultWriter = {
read(): Promise<BuildResultManifest>;
+ /** Publish newly accepted public Outputs; no storage writes when none are new. */
sync(input: BuildResultSync): Promise<BuildResultManifest>;
finish(input: BuildResultFinish): Promise<BuildResultManifest>;
};
/**
- * Project result history addressed only by Build id, Output name and Build-relative file path.
- * Filesystem paths, bucket keys and service URLs remain implementation details.
+ * Project result history addressed by Build id and Output name. File references carry their
+ * ownership or explicit external address; each repository supplies the corresponding byte access.
*/
export type BuildResultRepository = {
create(seed: BuildResultSeed): Promise<BuildResultWriter>;
@@ -346,6 +374,8 @@ export type BuildResultRepository = {
/** Follow explicit Output forwarding and describe its terminal value without opening content. */
describeOutput(build: string, output: string): Promise<RepositoryBuildResultOutputDescription | undefined>;
resolve(build: string, output: string): Promise<RepositoryBuildResultOutput | undefined>;
+ /** Read current metadata for a file reference, including external dependencies. */
+ describeFile(build: string, file: BuildResultFileRef): Promise<BuildResultFileRef>;
openFile(
build: string,
file: BuildResultFileRef,
diff --git a/packages/build-result/src/writer.ts b/packages/build-result/src/writer.ts
index b6157232..e1e1da63 100644
--- a/packages/build-result/src/writer.ts
+++ b/packages/build-result/src/writer.ts
@@ -13,8 +13,9 @@ import type {
export type BuildResultWriterState = {
readonly resources: Readonly<Record<string, string>>;
+ readonly resourceReferences?: Readonly<Record<string, BuildResultFileRef>>;
readonly values: Readonly<Record<string, string>>;
- readonly publishedOutputs: readonly { readonly name: string; readonly output: string }[];
+ readonly publishedOutputs: readonly { readonly name: string; readonly output: string; readonly displayName?: string }[];
readonly forwards: readonly { readonly output: string; readonly build: string; readonly sourceOutput: string }[];
};
@@ -28,6 +29,8 @@ export type BuildResultWriteTarget = {
};
export type BuildResultSyncResult = {
+ /** Whether accepted public Outputs were added to the manifest. */
+ readonly changed: boolean;
readonly manifest: BuildResultManifest;
readonly writer: BuildResultWriterState;
};
@@ -97,6 +100,8 @@ export async function syncBuildResultOutputs(input: {
const outputs: Record<string, BuildResultOutput> = { ...input.manifest.outputs };
const materialize = async (artifact: BlobRef): Promise<BuildResultFileRef> => {
+ const reference = input.writer.resourceReferences?.[artifact.resource];
+ if (reference !== undefined) return { ...reference, mediaType: artifact.mediaType };
const identity = artifact.resource;
assert(identity.length > 0, "Build resource has no instance identity");
let path = resources.get(identity);
@@ -166,14 +171,20 @@ export async function syncBuildResultOutputs(input: {
}).sort((left, right) => outputRank(left.record, left.forward) - outputRank(right.record, right.forward)
|| left.published.name.localeCompare(right.published.name));
+ if (ready.length === 0) {
+ return { changed: false, manifest: input.manifest, writer: input.writer };
+ }
+
for (const { published, record, forward } of ready) {
outputs[published.name] = {
+ ...(published.displayName === undefined ? {} : { displayName: published.displayName }),
type: record.type,
value: forward ?? await outputValue(record),
};
}
return {
+ changed: true,
manifest: { ...input.manifest, outputs },
writer: {
...input.writer,
diff --git a/packages/build-result/test/result.test.ts b/packages/build-result/test/result.test.ts
index 248ae1b9..a080e453 100644
--- a/packages/build-result/test/result.test.ts
+++ b/packages/build-result/test/result.test.ts
@@ -1,10 +1,8 @@
import assert from "node:assert/strict";
-import { execFile } from "node:child_process";
-import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises";
+import { mkdir, mkdtemp, open, readFile, readdir, rm, stat, utimes, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import test from "node:test";
-import { promisify } from "node:util";
import { buildResultDirectory, FileBuildResult, FileBuildResultRepository } from "@hypit/build-result";
import type { BlobRef, BuildState, TypeRef } from "@hypit/protocol";
@@ -18,39 +16,6 @@ const takeType: TypeRef = {
name: "SemanticTake",
};
-test("a short-lived writer stays alive through a transient file replacement failure", async () => {
- const root = await mkdtemp(join(tmpdir(), "hypit-result-replace-"));
- try {
- const script = `
- import fs from 'node:fs/promises';
- import { syncBuiltinESMExports } from 'node:module';
- const rename = fs.rename;
- let contended = false;
- fs.rename = async (from, to) => {
- if (!contended && String(to).endsWith('result.json')) {
- contended = true;
- throw Object.assign(new Error('temporary file contention'), { code: 'EBUSY' });
- }
- return rename(from, to);
- };
- syncBuiltinESMExports();
- const { FileBuildResult } = await import(${JSON.stringify(new URL("../src/store.ts", import.meta.url).href)});
- await FileBuildResult.create(process.argv[1], {
- id: 'bld_20260902T100000000Z_0000000001',
- source: { path: '/project/main.svml' }, targets: [], publishedOutputs: [],
- });
- if (!contended) throw new Error('replacement was not exercised');
- process.stdout.write('result saved');
- `;
- const { stdout } = await promisify(execFile)(process.execPath,
- ["--import", "tsx", "--input-type=module", "-e", script, root]);
- assert.equal(stdout, "result saved");
- assert.ok((await new FileBuildResultRepository(root).read("bld_20260902T100000000Z_0000000001")) !== undefined);
- } finally {
- await rm(root, { recursive: true, force: true });
- }
-});
-
function state(input: {
readonly status?: BuildState["status"];
readonly records: BuildState["records"];
@@ -68,6 +33,80 @@ function state(input: {
} as unknown as BuildState;
}
+test("internal progress and already published Outputs leave Result files untouched", async () => {
+ const root = await mkdtemp(join(tmpdir(), "hypit-result-progress-"));
+ try {
+ const result = await FileBuildResult.create(root, {
+ id: "bld_20260902T100000000Z_0000000001",
+ source: { path: "/project/main.svml" }, targets: ["answer"],
+ publishedOutputs: [{ name: "answer", output: "logical:answer", displayName: "Answer" }],
+ });
+ const paths = ["result.json", ".writer.json"].map((name) => join(result.directory, name));
+ const resources = { async open() { throw new Error("scalar Outputs have no Resource bytes"); } };
+ const snapshot = (ready: boolean) => state({
+ records: [{ id: "record:answer", type: videoType, value: { kind: "inline", value: 42 } }],
+ bindings: ready ? [{ output: "logical:answer", record: "record:answer" }] : [],
+ });
+ const unchanged = async (ready: boolean) => {
+ // A fixed old mtime exposes even identical-byte rewrites, without timer-resolution assumptions.
+ for (const path of paths) await utimes(path, 1, 1);
+ const before = await Promise.all(paths.map((path) => stat(path, { bigint: true })));
+ await result.sync({ state: snapshot(ready), resources });
+ const after = await Promise.all(paths.map((path) => stat(path, { bigint: true })));
+ assert.deepEqual(after.map((item) => [item.ino, item.mtimeNs]), before.map((item) => [item.ino, item.mtimeNs]));
+ };
+ await unchanged(false);
+ assert.deepEqual((await result.read()).outputs, {});
+ await result.sync({ state: snapshot(true), resources });
+ assert.deepEqual((await result.read()).outputs.answer?.value, { kind: "inline", value: 42 });
+ assert.equal((await result.read()).outputs.answer?.displayName, "Answer");
+ await unchanged(true);
+ const finished = await result.finish({ outcome: "failed", failure: "a later Need failed" });
+ assert.equal(finished.outcome, "failed");
+ assert.equal(finished.outputs.answer?.displayName, "Answer");
+ assert.deepEqual(finished.outputs.answer?.value, { kind: "inline", value: 42 });
+ assert.equal((await readdir(result.directory)).includes(".writer.json"), false);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("publishing and finishing preserve open readers of the previous Result files", async () => {
+ const root = await mkdtemp(join(tmpdir(), "hypit-result-读者-"));
+ const readers: Awaited<ReturnType<typeof open>>[] = [];
+ try {
+ const result = await FileBuildResult.create(root, {
+ id: "bld_20260902T100000000Z_0000000001",
+ source: { path: "/project/main.svml" }, targets: ["answer"],
+ publishedOutputs: [{ name: "answer", output: "logical:answer" }],
+ });
+ const manifestPath = join(result.directory, "result.json");
+ const oldManifest = await open(manifestPath, "r");
+ readers.push(oldManifest);
+ const oldWriter = await open(join(result.directory, ".writer.json"), "r");
+ readers.push(oldWriter);
+ const writerBytes = await readFile(join(result.directory, ".writer.json"), "utf8");
+ await result.sync({
+ state: state({
+ records: [{ id: "record:answer", type: videoType, value: { kind: "inline", value: 42 } }],
+ bindings: [{ output: "logical:answer", record: "record:answer" }],
+ }),
+ resources: { async open() { throw new Error("unexpected Resource read"); } },
+ });
+ assert.deepEqual(JSON.parse(await oldManifest.readFile("utf8")).outputs, {});
+ assert.equal(await oldWriter.readFile("utf8"), writerBytes);
+ assert.deepEqual((await result.read()).outputs.answer?.value, { kind: "inline", value: 42 });
+ const publishedReader = await open(manifestPath, "r");
+ readers.push(publishedReader);
+ await result.finish({ outcome: "complete" });
+ assert.equal(JSON.parse(await publishedReader.readFile("utf8")).outcome, undefined);
+ assert.equal((await result.read()).outcome, "complete");
+ } finally {
+ await Promise.all(readers.map((reader) => reader.close()));
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
test("one same-Build resource backs a public video and a SemanticTake payload", async () => {
const root = await mkdtemp(join(tmpdir(), "hypit-build-result-"));
const bytes = new Uint8Array([1, 2, 3, 4]);
@@ -159,11 +198,18 @@ test("one same-Build resource backs a public video and a SemanticTake payload",
);
const repository = new FileBuildResultRepository(root);
const presented = await repository.updatePresentation("bld_20260902T100000000Z_0000000001", {
+ outputDisplayNames: { "shot.video": "Opening portrait" },
title: "Episode 12 opening",
note: "Use the quieter take.",
highlightedOutputs: ["shot.video", "shot.take", "shot.video"],
});
assert.equal(presented.title, "Episode 12 opening");
+ assert.equal(presented.outputs["shot.video"]?.displayName, "Opening portrait");
+ assert.deepEqual(presented.outputs["shot.video"]?.value, failed.outputs["shot.video"]?.value);
+ assert.equal(presented.outputs["shot.take"]?.displayName, undefined);
+ assert.equal((await repository.read(presented.id))?.outputs["shot.video"]?.displayName, "Opening portrait");
+ await assert.rejects(repository.updatePresentation(presented.id, { outputDisplayNames: { missing: "Oops" } }), /has no Output/);
+ await assert.rejects(repository.updatePresentation(presented.id, { outputDisplayNames: { "shot.video": " " } }), /must not be empty/);
assert.equal(presented.note, "Use the quieter take.");
assert.deepEqual(presented.highlightedOutputs, ["shot.video", "shot.take"]);
await assert.rejects(
@@ -171,10 +217,12 @@ test("one same-Build resource backs a public video and a SemanticTake payload",
/has no Output missing\.output/u,
);
const cleared = await repository.updatePresentation("bld_20260902T100000000Z_0000000001", {
+ outputDisplayNames: { "shot.video": null },
title: null,
note: null,
highlightedOutputs: [],
});
+ assert.equal(cleared.outputs["shot.video"]?.displayName, undefined);
assert.equal(cleared.title, undefined);
assert.equal(cleared.note, undefined);
assert.equal(cleared.highlightedOutputs, undefined);
diff --git a/packages/cli/README.md b/packages/cli/README.md
index 1e09f327..4555dc86 100644
--- a/packages/cli/README.md
+++ b/packages/cli/README.md
@@ -15,6 +15,31 @@ Human output is compact by default. `--json` emits a command-specific view rathe
Runtime or Repository objects. `--verbose` adds operational detail; it never turns the command into
an internal state dump.
+## Project and Runtime context
+
+`--workspace` explicitly selects the project. Otherwise the nearest `package.json` above the command's
+current directory establishes its root; with none, the current directory is the root. Source and Run
+arguments locate files within that context. Relative command-line paths are resolved from the current
+directory, including when `--workspace` is supplied.
+
+Runtime-aware commands use an explicit `--runtime` for that invocation, or read exactly the resolved
+project's `.hypit/runtime` pointer. `runtime use` writes the pointer; a Profile filename by itself does
+not select it. Project selection is also available on `paths`, `doctor`, execution status/control,
+Runtime operations, `programs` and `auth`. Machine-wide `packages` operations have no project selector.
+
+`paths` shows the effective locations and whether the Profile came from a command argument, a project
+selection or neither. Its JSON fields `profileSource` and `selectionFile` expose that distinction; the
+selection-file location is shown even when no selection exists. `doctor` states whether it checked
+only project Results or also a selected Runtime. An unselected Runtime is not a completed environment
+diagnosis. Result repository selection and project-package resolution remain independent of Runtime.
+
+For a command invoked outside the project, name both the project and its input explicitly:
+
+```bash
+hypit paths --workspace /path/to/video-project
+hypit plan /path/to/video-project/build.svrun --workspace /path/to/video-project
+```
+
`plan` lists every Endpoint request in the frozen Build graph. Exact-model packages expose their own
port tables and request-assembly edges, so the CLI can show authored prompt, duration and generation
settings without searching arbitrary records for a request-shaped object. When an input file will be
diff --git a/packages/cli/src/arguments.ts b/packages/cli/src/arguments.ts
index 04eba6b2..a6f9a648 100644
--- a/packages/cli/src/arguments.ts
+++ b/packages/cli/src/arguments.ts
@@ -157,7 +157,7 @@ export function parseCommand(argv: readonly string[]): CliCommand {
}
case "status": {
const [build, rest] = requiredPositional(tail, "status requires one Build id");
- const options = commandOptions(command, rest, "--runtime", "--watch", "--max-wait-ms", "--limit");
+ const options = commandOptions(command, rest, "--runtime", "--workspace", "--watch", "--max-wait-ms", "--limit");
if (!options.watch && options.maxWaitMs !== undefined) {
throw new Error("--max-wait-ms applies to status --watch");
}
@@ -172,7 +172,7 @@ export function parseCommand(argv: readonly string[]): CliCommand {
};
}
case "activity": {
- const options = commandOptions(command, tail, "--runtime", "--watch", "--jsonl", "--limit");
+ const options = commandOptions(command, tail, "--runtime", "--workspace", "--watch", "--jsonl", "--limit");
if (options.presentation.jsonl === true && !options.watch) {
throw new Error("--jsonl applies only to activity --watch");
}
@@ -189,7 +189,7 @@ export function parseCommand(argv: readonly string[]): CliCommand {
}
case "cancel": {
const [build, rest] = requiredPositional(tail, "cancel requires one Build id");
- const options = commandOptions(command, rest, "--runtime", "--reason");
+ const options = commandOptions(command, rest, "--runtime", "--workspace", "--reason");
return {
command,
build,
@@ -205,17 +205,20 @@ export function parseCommand(argv: readonly string[]): CliCommand {
case "auth": return parseAuthCommand(tail);
case "doctor": {
const [profile, rest] = optionalPositional(tail);
- const options = commandOptions(command, rest, "--workspace", "--limit");
+ const options = commandOptions(command, rest, "--workspace", "--runtime", "--limit");
+ if (profile !== undefined && options.runtimeProfile !== undefined) {
+ throw new Error("doctor accepts the Runtime Profile either positionally or with --runtime, not both");
+ }
return {
command,
presentation: options.presentation,
limit: options.limit,
...optionalProject(options),
- ...runtimeOption(profile),
+ ...runtimeOption(profile ?? options.runtimeProfile),
};
}
case "paths": {
- const options = commandOptions(command, tail, "--runtime");
+ const options = commandOptions(command, tail, "--runtime", "--workspace");
return { command, presentation: options.presentation, ...optionalRuntime(options) };
}
case "_worker": {
@@ -244,7 +247,7 @@ function parseResultCommand(tail: readonly string[]): ProjectResultCommand | Exe
}
const [build, rest] = requiredPositional(values, `result ${action} requires one Build id`);
if (action === "finish" || action === "discard") {
- const options = commandOptions(`result ${action}`, rest, "--runtime");
+ const options = commandOptions(`result ${action}`, rest, "--runtime", "--workspace");
return { command: "result", action, build, presentation: options.presentation, ...optionalRuntime(options) };
}
const options = commandOptions("result edit", rest,
@@ -306,7 +309,7 @@ function parseRuntimeCommand(tail: readonly string[]): RuntimeSelectionCommand |
: action === "status"
? ["--runtime", "--limit"] as const
: ["--runtime", "--lines"] as const;
- const options = commandOptions(`runtime ${action}`, rest, ...allowed);
+ const options = commandOptions(`runtime ${action}`, rest, "--workspace", ...allowed);
rejectDuplicateProfile("runtime", profile, options.runtimeProfile);
const runtime = runtimeOption(profile ?? options.runtimeProfile);
const common = {
@@ -314,6 +317,7 @@ function parseRuntimeCommand(tail: readonly string[]): RuntimeSelectionCommand |
action,
presentation: options.presentation,
...runtime,
+ ...optionalProject(options),
};
if (action === "up" || action === "down") {
return { ...common, action, ...(options.maxWaitMs === undefined ? {} : { maxWaitMs: options.maxWaitMs }) };
@@ -329,7 +333,7 @@ function parseProgramsCommand(tail: readonly string[]): ProgramsCommand {
}
const [profile, rest] = optionalPositional(values);
const options = commandOptions(`programs ${action}`, rest,
- "--runtime", "--limit", "--max-wait-ms");
+ "--runtime", "--workspace", "--limit", "--max-wait-ms");
if (action !== "up" && options.maxWaitMs !== undefined) {
throw new Error("--max-wait-ms applies to programs up");
}
@@ -341,6 +345,7 @@ function parseProgramsCommand(tail: readonly string[]): ProgramsCommand {
presentation: options.presentation,
limit: options.limit,
...runtime,
+ ...optionalProject(options),
};
return action === "up"
? { ...common, action, ...(options.maxWaitMs === undefined ? {} : { maxWaitMs: options.maxWaitMs }) }
@@ -362,7 +367,7 @@ function parseAuthCommand(tail: readonly string[]): AuthCommand {
}
const [endpoint, rest] = requiredPositional(values, `auth ${action} requires one Endpoint instance`);
const options = commandOptions(`auth ${action}`, rest,
- "--runtime", "--slot", ...(action === "login" ? ["--from"] as const : []),
+ "--runtime", "--workspace", "--slot", ...(action === "login" ? ["--from"] as const : []),
...(action === "status" ? ["--limit"] as const : []));
const common = {
command: "auth" as const,
@@ -576,7 +581,7 @@ function optionalProject(options: RawOptions): ProjectOption {
}
function optionalRuntime(options: RawOptions): RuntimeOption {
- return runtimeOption(options.runtimeProfile);
+ return { ...runtimeOption(options.runtimeProfile), ...optionalProject(options) };
}
function runtimeOption(profile: string | undefined): RuntimeOption {
diff --git a/packages/cli/src/build-planning.ts b/packages/cli/src/build-planning.ts
index 4dfe92ba..6fada047 100644
--- a/packages/cli/src/build-planning.ts
+++ b/packages/cli/src/build-planning.ts
@@ -24,7 +24,12 @@ export function createCatalogDescriptor(options: {
if (item.ref.kind === "operation-result") {
throw new Error(`public output ${item.name} was not lowered to a stable Record or Logical Output`);
}
- return item.ref.kind === "logical-output" ? [{ name: item.name, ref: item.ref }] : [];
+ if (item.ref.kind !== "logical-output") return [];
+ const outputId = item.ref.id;
+ const element = options.compilation.provenance.elements.find((element) => element.outputs.some((output) => output.id === outputId));
+ const authored = element?.outputs.find((output) => output.id === outputId);
+ const displayName = element?.components.find((component) => component.id === authored?.component)?.local;
+ return [{ name: item.name, ref: item.ref, ...(displayName === undefined ? {} : { displayName }) }];
});
const names = new Set<string>();
const outputs = new Set<string>();
diff --git a/packages/cli/src/command.ts b/packages/cli/src/command.ts
index 70ea7baa..813606de 100644
--- a/packages/cli/src/command.ts
+++ b/packages/cli/src/command.ts
@@ -4,7 +4,7 @@ type CommandBase = {
readonly presentation: CliOutputOptions;
};
-export type RuntimeOption = {
+export type RuntimeOption = ProjectOption & {
readonly runtimeProfile: string | undefined;
};
diff --git a/packages/cli/src/commands/environment.ts b/packages/cli/src/commands/environment.ts
index b40c58d7..d4c8ffae 100644
--- a/packages/cli/src/commands/environment.ts
+++ b/packages/cli/src/commands/environment.ts
@@ -41,6 +41,7 @@ export function isEnvironmentCommand(args: CliCommand): args is EnvironmentComma
export async function runEnvironmentCommand(input: {
readonly args: EnvironmentCommand;
readonly runtimeProfile: string | undefined;
+ readonly runtimeSelectionFile: string | undefined;
readonly io: CliIo;
readonly distribution: CliDistribution;
readonly projectRoot: string;
@@ -50,8 +51,13 @@ export async function runEnvironmentCommand(input: {
readonly write: OperationalWriter;
}): Promise<void> {
const {
- args, runtimeProfile, io, distribution, projectRoot, packageRootForProject, runtimeHost, runtimeController, write,
+ args, runtimeProfile, runtimeSelectionFile, io, distribution, projectRoot, packageRootForProject, runtimeHost, runtimeController, write,
} = input;
+ const profileSource: "none" | "argument" | "project" = runtimeProfile === undefined
+ ? "none" : runtimeSelectionFile === undefined ? "argument" : "project";
+ const selectionDescription = profileSource === "argument"
+ ? "command argument (this invocation only)"
+ : runtimeSelectionFile ?? "none";
const reportProgramProgress = args.presentation.json
? undefined
: (event: { readonly id: string; readonly phase: "checking" | "installing" | "starting" | "waiting" | "ready"; readonly logPath?: string }): void => {
@@ -81,6 +87,8 @@ export async function runEnvironmentCommand(input: {
const machine = {
format: "hypit.cli-paths@1" as const,
project: projectRoot,
+ profileSource,
+ selectionFile: resolve(projectRoot, ".hypit/runtime"),
projectState: hypitProjectStateRoot(projectRoot),
...(runtimeProfile === undefined ? {} : { profile: runtimeProfile }),
...(runtimePaths === undefined ? {} : { runtimeData: runtimePaths.runtimeDataRoot }),
@@ -92,11 +100,14 @@ export async function runEnvironmentCommand(input: {
["Project", machine.project],
["Project state", machine.projectState],
["Runtime Profile", machine.profile ?? "not selected"],
+ ["Runtime selection", selectionDescription],
["Runtime data", machine.runtimeData ?? "not selected"],
["Host state", machine.hostState],
["Machine packages", machine.machinePackages],
["Distribution", machine.distribution ?? "embedded"],
- ]);
+ ], runtimeProfile === undefined
+ ? ["Select an existing Profile with hypit runtime use <profile> --workspace <project>, or create one with hypit runtime init."]
+ : []);
return;
}
@@ -140,6 +151,8 @@ export async function runEnvironmentCommand(input: {
format: "hypit.cli-doctor@1" as const,
ok: !diagnostics.some((item) => item.severity === "error"),
project: projectRoot,
+ profileSource,
+ ...(runtimeSelectionFile === undefined ? {} : { selectionFile: runtimeSelectionFile }),
...(profile === undefined ? {} : { profile }),
diagnosticCount: diagnostics.length,
diagnostics: diagnostics.slice(0, args.limit),
diff --git a/packages/cli/src/machine-view.ts b/packages/cli/src/machine-view.ts
index 81fd3637..371c37c4 100644
--- a/packages/cli/src/machine-view.ts
+++ b/packages/cli/src/machine-view.ts
@@ -15,7 +15,7 @@ type AttentionView = { readonly message: string; readonly action?: string };
export type OperationalMachineView =
| { readonly format: "hypit.cli-runtime-init@1"; readonly profile: string; readonly project: string; readonly selected: true }
| { readonly format: "hypit.cli-runtime-selection@1"; readonly selected: boolean; readonly removed?: boolean; readonly profile?: string; readonly project?: string }
- | { readonly format: "hypit.cli-paths@1"; readonly project: string; readonly projectState: string; readonly profile?: string; readonly runtimeData?: string; readonly hostState: string; readonly machinePackages: string; readonly distribution?: string }
+ | { readonly format: "hypit.cli-paths@1"; readonly project: string; readonly projectState: string; readonly profileSource: "argument" | "project" | "none"; readonly selectionFile: string; readonly profile?: string; readonly runtimeData?: string; readonly hostState: string; readonly machinePackages: string; readonly distribution?: string }
| { readonly format: "hypit.cli-package@1"; readonly action: "install" | "status"; readonly package: string; readonly ready: boolean }
| { readonly format: "hypit.cli-programs@1"; readonly action: "up" | "down" | "status"; readonly ready: boolean; readonly programs: readonly ProgramStateView[]; readonly omittedPrograms?: number }
| { readonly format: "hypit.cli-runtime-up@1"; readonly ready: boolean; readonly worker: string; readonly preparedPackages: number; readonly programs: { readonly total: number; readonly ready: number; readonly items: readonly ProgramStateView[] } }
diff --git a/packages/cli/src/main.ts b/packages/cli/src/main.ts
index 0f64f7cc..27485d71 100644
--- a/packages/cli/src/main.ts
+++ b/packages/cli/src/main.ts
@@ -177,12 +177,14 @@ export async function runCli(
}
let runtimeProfile = acceptsRuntimeContext(args) ? args.runtimeProfile : undefined;
+ let runtimeSelectionFile: string | undefined;
const runtimeWasExplicit = runtimeProfile !== undefined;
let runtimeNeedsHint = runtimeWasExplicit;
if (acceptsRuntimeContext(args) && runtimeProfile === undefined) {
const selected = await findRuntimeProfile(await commandProjectRoot());
if (selected !== undefined) {
runtimeProfile = selected.profile;
+ runtimeSelectionFile = selected.selectionFile;
runtimeNeedsHint = false;
}
}
@@ -196,6 +198,7 @@ export async function runCli(
await runEnvironmentCommand({
args,
runtimeProfile,
+ runtimeSelectionFile,
io,
distribution,
projectRoot: await commandProjectRoot(),
@@ -387,6 +390,7 @@ export async function runCli(
result: {
repository: buildResults.location,
...(args.title === undefined ? {} : { title: args.title }),
+ resourceReferences: loadedRun.resultResourceReferences,
forwards: result.resultForwards.filter((forward) =>
catalog.publishedOutputs.some((published) => published.ref.id === forward.output)),
},
diff --git a/packages/cli/src/output.ts b/packages/cli/src/output.ts
index 320a6dc2..b555b58d 100644
--- a/packages/cli/src/output.ts
+++ b/packages/cli/src/output.ts
@@ -43,6 +43,8 @@ export type DoctorOutput = {
readonly ok: boolean;
readonly project: string;
readonly profile?: string;
+ readonly profileSource?: "argument" | "project" | "none";
+ readonly selectionFile?: string;
readonly diagnosticCount: number;
readonly diagnostics: readonly CliDiagnostic[];
readonly omittedDiagnostics?: number;
@@ -272,9 +274,16 @@ function renderDoctor(view: Extract<CliPresentation, { kind: "doctor" }>, io: Cl
const lines = [colors.accent(colors.strong("Hypit Doctor")), ""];
lines.push(...facts([
["Project", shortPath(view.machine.project)],
- ...(view.machine.profile === undefined ? [] : [["Profile", shortPath(view.machine.profile)] as const]),
+ ["Runtime Profile", view.machine.profile === undefined ? "not selected" : shortPath(view.machine.profile)],
+ ...(view.machine.profileSource === "argument"
+ ? [["Runtime selection", "command argument (this invocation only)"] as const]
+ : view.machine.selectionFile === undefined ? [] : [["Runtime selection", shortPath(view.machine.selectionFile)] as const]),
+ ["Scope", view.machine.profile === undefined ? "project Results only" : "selected Runtime and project Results"],
], colors));
lines.push("");
+ if (view.machine.profile === undefined) {
+ lines.push("Select an existing Profile with hypit runtime use <profile>, or pass --runtime <profile> to check it.", "");
+ }
if (view.machine.diagnostics.length === 0) {
lines.push(heading("success", "No problems found", io, colors));
} else {
@@ -770,7 +779,8 @@ function commandHelp(topic: string, colors: Palette): readonly string[] | undefi
colors.accent(colors.strong("hypit doctor")),
colors.dim("Diagnose project Results and, when selected or supplied, one Runtime Profile."),
"",
- " hypit doctor [<runtime-profile>] [--workspace <project>]",
+ " hypit doctor [--runtime <profile>] [--workspace <project>]",
+ " A positional Profile is also accepted in place of --runtime.",
" Without a Runtime Profile, checks only the project's selected Result Store.",
],
plan: [
@@ -819,6 +829,7 @@ function commandHelp(topic: string, colors: Palette): readonly string[] | undefi
" hypit runtime down [<profile>] stop the Worker; external programs keep running",
"",
"The project is resolved first. Selection is read only from that project's .hypit/runtime.",
+ "All runtime actions accept --workspace <project>; operational actions also accept --runtime <profile>.",
"No Profile filename discovery or parent-project inheritance is performed.",
"Remote Endpoints such as HypiHub are not started by this command; use doctor to test them.",
],
@@ -836,22 +847,26 @@ function commandHelp(topic: string, colors: Palette): readonly string[] | undefi
colors.accent(colors.strong("hypit programs")),
colors.dim("Prepare and operate external programs declared by Endpoints in one Runtime Profile."),
"",
- " hypit programs up [<profile>] [--max-wait-ms <ms>]",
- " hypit programs status [<profile>]",
- " hypit programs down [<profile>]",
+ " hypit programs up [--runtime <profile>] [--workspace <project>] [--max-wait-ms <ms>]",
+ " hypit programs status [--runtime <profile>] [--workspace <project>]",
+ " hypit programs down [--runtime <profile>] [--workspace <project>]",
+ " A positional Profile is also accepted in place of --runtime.",
],
activity: [
colors.accent(colors.strong("hypit activity")),
colors.dim("Inspect active Builds and Provider pool capacity."),
"",
- " hypit activity [--runtime <profile>] [--watch]",
- " hypit activity [--runtime <profile>] --watch --jsonl",
+ " hypit activity [--workspace <project>] [--runtime <profile>] [--watch]",
+ " hypit activity [--workspace <project>] [--runtime <profile>] --watch --jsonl",
],
paths: [
colors.accent(colors.strong("hypit paths")),
colors.dim("Show project, Runtime and host state locations without creating them."),
"",
- " hypit paths [--runtime <profile>]",
+ " hypit paths [--workspace <project>] [--runtime <profile>]",
+ " Shows whether Runtime selection comes from a command argument or the project's .hypit/runtime.",
+ " Without --workspace, the nearest package.json above cwd defines the project (otherwise cwd).",
+ " Relative command-line paths start at cwd, including when --workspace is supplied.",
],
builds: [
colors.accent(colors.strong("hypit builds")),
@@ -863,7 +878,7 @@ function commandHelp(topic: string, colors: Palette): readonly string[] | undefi
colors.accent(colors.strong("hypit status")),
colors.dim("Show one Build now, or keep watching it without owning execution."),
"",
- " hypit status <build-id> [--runtime <profile>] [--watch]",
+ " hypit status <build-id> [--workspace <project>] [--runtime <profile>] [--watch]",
" --watch observe until a Result outcome or operator attention",
" --max-wait-ms <ms> stop watching after a bounded wait",
],
@@ -892,14 +907,14 @@ function commandHelp(topic: string, colors: Palette): readonly string[] | undefi
colors.accent(colors.strong("hypit cancel")),
colors.dim("Stop one Build and request cancellation of submitted work when supported."),
"",
- " hypit cancel <build-id> [--runtime <profile>] [--reason <text>]",
+ " hypit cancel <build-id> [--workspace <project>] [--runtime <profile>] [--reason <text>]",
],
result: [
colors.accent(colors.strong("hypit result")),
colors.dim("Edit one Result, finish an interrupted Result write, or discard an incomplete submission."),
"",
- " hypit result finish <build-id> [--runtime <profile>]",
- " hypit result discard <build-id> [--runtime <profile>]",
+ " hypit result finish <build-id> [--workspace <project>] [--runtime <profile>]",
+ " hypit result discard <build-id> [--workspace <project>] [--runtime <profile>]",
" hypit result edit <build-id> [--workspace <project>] [--title <text>] [--note <text>]",
" [--highlight <output> ...]",
" --clear-title remove the Result's human title",
@@ -913,6 +928,7 @@ function commandHelp(topic: string, colors: Palette): readonly string[] | undefi
" hypit auth status <endpoint-instance> [--runtime <profile>] [--slot <name>]",
" hypit auth login <endpoint-instance> [--runtime <profile>] [--slot <name>] [--from <secret-file>]",
" hypit auth logout <endpoint-instance> [--runtime <profile>] [--slot <name>]",
+ " All auth actions accept --workspace <project> to use that project's selection.",
],
};
const selected = topics[topic];
diff --git a/packages/cli/src/result-export.ts b/packages/cli/src/result-export.ts
index 43219d96..aaa04c73 100644
--- a/packages/cli/src/result-export.ts
+++ b/packages/cli/src/result-export.ts
@@ -1,3 +1,4 @@
+import { fileReferenceIdentity } from "@hypit/build-result";
import { randomUUID } from "node:crypto";
import { lstat, mkdir, rename, rm, writeFile } from "node:fs/promises";
import { basename, dirname, join, relative, resolve, sep } from "node:path";
@@ -53,7 +54,7 @@ async function openResultFile(
file: BuildResultFileRef,
): Promise<AsyncIterable<Uint8Array>> {
const input = await repository.openFile(build, file);
- if (input === undefined) throw new Error(`Build ${build} file ${file.path} is unavailable`);
+ if (input === undefined) throw new Error(`File ${fileReferenceIdentity(build, file)} is unavailable`);
return input;
}
@@ -83,20 +84,28 @@ async function exportComposite(
const temporary = join(dirname(target), `.${basename(target)}.part-${randomUUID()}`);
try {
await mkdir(temporary);
- const copied = new Set<string>();
+ const copied = new Map<string, BuildResultFileRef>();
+ const paths = new Set<string>();
+ const bindings = [];
for (const binding of resolvedOutput.value.document.resources) {
- const file = binding.file;
- if (copied.has(file.path)) continue;
- copied.add(file.path);
- assert(file.path !== "value.json", "Composite Result file value.json conflicts with its exported value document");
- await writeStream(
- containedPath(temporary, file.path),
- await openResultFile(repository, resolvedOutput.build, file),
- );
+ const file = await repository.describeFile(resolvedOutput.build, binding.file);
+ const identity = fileReferenceIdentity(resolvedOutput.build, file);
+ let local = copied.get(identity);
+ if (local === undefined) {
+ let path = file.kind === "build-file" ? file.path : `files/file-${copied.size + 1}`;
+ const name = basename(path);
+ let index = copied.size + 1;
+ while (paths.has(path) || path === "value.json") path = `files/import-${index++}/${name}`;
+ paths.add(path);
+ local = { kind: "build-file", path, size: file.size, mediaType: file.mediaType };
+ copied.set(identity, local);
+ await writeStream(containedPath(temporary, path), await openResultFile(repository, resolvedOutput.build, file));
+ }
+ bindings.push({ at: binding.at, file: local });
}
await writeFile(
join(temporary, "value.json"),
- `${JSON.stringify(resolvedOutput.value.document, null, 2)}\n`,
+ `${JSON.stringify({ ...resolvedOutput.value.document, resources: bindings }, null, 2)}\n`,
{ flag: "wx" },
);
await rename(temporary, target);
@@ -122,7 +131,7 @@ export async function exportBuildResultOutput(
const target = resolve(destination);
if (resolvedOutput.value.kind === "value") {
await exportComposite(repository, { ...resolvedOutput, value: resolvedOutput.value }, target);
- } else if (resolvedOutput.value.kind === "build-file") {
+ } else if ((resolvedOutput.value.kind === "build-file" || resolvedOutput.value.kind === "external-file")) {
const resource = resolvedOutput.value;
await exportFile(target, async (temporary) => {
await writeStream(
@@ -142,7 +151,7 @@ export async function exportBuildResultOutput(
type: publishedOutput.type,
kind: resolvedOutput.value.kind === "inline"
? "scalar"
- : resolvedOutput.value.kind === "build-file" ? "resource" : "composite",
+ : (resolvedOutput.value.kind === "build-file" || resolvedOutput.value.kind === "external-file") ? "resource" : "composite",
path: target,
};
}
diff --git a/packages/cli/src/run-file.ts b/packages/cli/src/run-file.ts
index 53286f14..95ed260d 100644
--- a/packages/cli/src/run-file.ts
+++ b/packages/cli/src/run-file.ts
@@ -1,3 +1,4 @@
+import { fileReferenceIdentity, ownedFileReference } from "@hypit/build-result";
import { randomUUID } from "node:crypto";
import type {
BuildResultRepository,
@@ -24,15 +25,17 @@ import type { RunFrontend } from "@hypit/run";
export type LoadedRunFile = NodeCompiledRun & {
readonly path: string;
readonly compiler: NodeRunCompiler;
+ readonly resultResourceReferences: Readonly<Record<string, BuildResultFileRef>>;
};
type BuildResultResolutionSession = {
readonly files: Map<string, ArtifactAttachment>;
+ readonly references: Map<string, BuildResultFileRef>;
readonly outputs: Map<string, Promise<RepositoryBuildResultOutput | undefined>>;
};
function createBuildResultResolutionSession(): BuildResultResolutionSession {
- return { files: new Map(), outputs: new Map() };
+ return { files: new Map(), outputs: new Map(), references: new Map() };
}
export async function checkRunFile(options: {
@@ -88,9 +91,10 @@ export async function resolveBuildResultValue(
const manifest = await repository.read(build);
if (manifest?.outcome === undefined) return undefined;
const resultAttachment = async (owner: string, file: BuildResultFileRef): Promise<ArtifactAttachment> => {
- const address = `${owner}\u0000${file.path}`;
+ const address = fileReferenceIdentity(owner, file);
const existing = session.files.get(address);
if (existing !== undefined) return existing;
+ file = await repository.describeFile(owner, file);
const artifact: BlobRef = {
kind: "blob",
resource: `res_${randomUUID()}`,
@@ -101,11 +105,12 @@ export async function resolveBuildResultValue(
artifact,
async open() {
const stream = await repository.openFile(owner, file);
- if (stream === undefined) throw new Error(`Build ${owner} file ${file.path} is unavailable`);
+ if (stream === undefined) throw new Error(`File ${address} is unavailable`);
return stream;
},
};
session.files.set(address, attachment);
+ session.references.set(artifact.resource, ownedFileReference(owner, file));
return attachment;
};
const attachments = new Map<string, ArtifactAttachment>();
@@ -120,7 +125,7 @@ export async function resolveBuildResultValue(
const owner = resolved.build === build ? manifest : await repository.read(resolved.build);
if (owner?.outcome === undefined) return undefined;
let value: StoredValue;
- if (resolved.value.kind === "build-file") {
+ if (resolved.value.kind === "build-file" || resolved.value.kind === "external-file") {
const attachment = await resultAttachment(resolved.build, resolved.value);
attachments.set(attachment.artifact.resource, attachment);
value = attachment.artifact;
@@ -147,8 +152,7 @@ function createRunCompiler(options: {
readonly frontends: readonly RunFrontend[];
readonly packageContributions: readonly NodePackageContribution[];
readonly results?: BuildResultRepository;
-}): NodeRunCompiler {
- const resultSession = createBuildResultResolutionSession();
+}, resultSession = createBuildResultResolutionSession()): NodeRunCompiler {
const fragments = new RunFragmentRegistry();
for (const item of options.packageContributions) {
installRunFragmentHostFacets(item.hostFacets ?? [], fragments);
@@ -180,7 +184,14 @@ export async function loadRunFile(options: {
readonly packageContributions: readonly NodePackageContribution[];
readonly results?: BuildResultRepository;
}): Promise<LoadedRunFile> {
- const compiler = createRunCompiler(options);
+ const resultSession = createBuildResultResolutionSession();
+ const compiler = createRunCompiler(options, resultSession);
const compiled = await compiler.compileSource(options.workspace.entry, options.workspace);
- return { path: options.workspace.entry.id, compiler, ...compiled };
+ const references = new Map<string, BuildResultFileRef>(compiled.attachments.flatMap((attachment) =>
+ attachment.location === undefined ? [] : [[attachment.artifact.resource, {
+ kind: "external-file" as const, uri: attachment.location,
+ size: attachment.artifact.size, mediaType: attachment.artifact.mediaType,
+ }]]));
+ for (const [resource, file] of resultSession.references) references.set(resource, file);
+ return { path: options.workspace.entry.id, compiler, ...compiled, resultResourceReferences: Object.fromEntries(references) };
}
diff --git a/packages/cli/test/build-programs.test.ts b/packages/cli/test/build-programs.test.ts
index c59bde18..963583e5 100644
--- a/packages/cli/test/build-programs.test.ts
+++ b/packages/cli/test/build-programs.test.ts
@@ -56,6 +56,7 @@ function distribution(
supportsFrontend: () => false,
compileSource: async (entry: { readonly id: string }) => ({
closure: { entry: entry.id, units: [] },
+ provenance: { format: "hypit.author-provenance@1", elements: [] },
program: { closure: { format: "hypit.closure@1", modules: [{ manifest: {
format: "hypit.module@1",
name: "example.value",
diff --git a/packages/cli/test/build-results.test.ts b/packages/cli/test/build-results.test.ts
index 90f85882..76a63084 100644
--- a/packages/cli/test/build-results.test.ts
+++ b/packages/cli/test/build-results.test.ts
@@ -1,7 +1,8 @@
import assert from "node:assert/strict";
-import { mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
+import { mkdtemp, readFile, readdir, realpath, rm, stat, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
+import { pathToFileURL } from "node:url";
import test from "node:test";
import { FileBuildResult, FileBuildResultRepository } from "@hypit/build-result";
@@ -13,6 +14,7 @@ import { runMarkupFrontend } from "@hypit/run-markup";
import { NodeFilesystemWorkspace } from "@hypit/workspace-fs-node";
import type { CliDistribution } from "../src/distribution.js";
+import { createCatalogDescriptor } from "../src/build-planning.js";
import { runCli } from "../src/main.js";
import { loadRunFile } from "../src/run-file.js";
@@ -471,6 +473,13 @@ test("build-record selects one exact Result Output without leaking its storage a
packageContributions: [],
results: countedRepository,
});
+ const catalog = createCatalogDescriptor({ source: authorFile, compilation: loaded.author });
+ assert.equal(catalog.publishedOutputs.find((output) => output.name === "shot.video")?.displayName, "shot");
+ const renamed = createCatalogDescriptor({ source: authorFile, compilation: {
+ ...loaded.author,
+ exports: loaded.author.exports.map((output) => ({ ...output, name: `public.${output.name}` })),
+ } });
+ assert.equal(renamed.publishedOutputs.find((output) => output.name === "public.shot.video")?.displayName, "shot");
const candidate = loaded.run.graph.candidates[0];
assert.equal(candidate?.root.kind, "value");
const value = candidate?.root.kind === "value" ? candidate.root.value.value : undefined;
@@ -486,12 +495,104 @@ test("build-record selects one exact Result Output without leaking its storage a
sourceOutput: "shot.video",
}]);
assert.equal(loaded.attachments.length, 1);
+ assert.deepEqual(Object.values(loaded.resultResourceReferences), [{
+ kind: "build-file", build: "bld_20260902T110000001Z_0000000001",
+ path: "files/file-0001.mp4", size: bytes.byteLength, mediaType: "video/mp4",
+ }]);
assert.equal(opens, 0, "compilation does not read or summarize historical bytes");
const reused: number[] = [];
for await (const chunk of await loaded.attachments[0]!.open()) reused.push(...chunk);
assert.deepEqual(Uint8Array.from(reused), bytes);
assert.equal(opens, 1, "Runtime staging opens the historical Result exactly once");
assert.equal(loaded.compiler.planCompilation(loaded).state.plan.steps.length, 0);
+
+ // New Composite records may wrap imported values at arbitrary depth. Their Resource ownership
+ // must survive multiple Builds, including a mix of old media and newly produced bytes.
+ let imported = loaded;
+ const owner = "bld_20260902T110000001Z_0000000001";
+ for (const id of ["bld_20260902T110000002Z_0000000001", "bld_20260902T110000003Z_0000000001"]) {
+ const rootValue = imported.run.graph.candidates[0]!.root;
+ assert.equal(rootValue.kind, "value");
+ if (rootValue.kind !== "value") throw new Error("expected value");
+ const extra = { kind: "blob" as const, resource: `res_${id}`, size: 1, mediaType: "image/png" };
+ const current = await repository.create({
+ id, source: { path: authorFile }, targets: ["shot.video"],
+ publishedOutputs: [{ name: "shot.video", output: "wrapped" }],
+ resourceReferences: imported.resultResourceReferences,
+ });
+ await current.sync({
+ state: { status: "complete", records: [{ id: "record:wrapped", type: videoType,
+ value: { kind: "inline", value: { layers: [{ nested: rootValue.value.value }], extra } } }],
+ plan: { outputBindings: [{ output: "wrapped", record: "record:wrapped", type: videoType }] },
+ } as unknown as BuildState,
+ resources: { async open(artifact) {
+ assert.equal(artifact.resource, extra.resource, "Only genuinely new bytes may be copied");
+ return (async function* () { yield new Uint8Array([7]); })();
+ } },
+ });
+ await current.finish({ outcome: "complete" });
+ assert.deepEqual(await readdir(join(current.directory, "files")), ["file-0001.png"]);
+ const saved = await repository.resolve(id, "shot.video");
+ assert.equal(saved?.value.kind, "value");
+ if (saved?.value.kind !== "value") throw new Error("expected composite");
+ const original = saved.value.document.resources.find((binding) => binding.file.mediaType === "video/mp4")!;
+ assert.deepEqual(original.file, { kind: "build-file", build: owner, path: "files/file-0001.mp4", size: bytes.length, mediaType: "video/mp4" });
+ const received: number[] = [];
+ for await (const chunk of (await repository.openFile(id, original.file))!) received.push(...chunk);
+ assert.deepEqual(Uint8Array.from(received), bytes);
+ await writeFile(runFile, (await readFile(runFile, "utf8")).replace(/build="[^"]+"/, `build="${id}"`));
+ imported = await loadRunFile({ workspace: await authorCompiler.openFile(runFile), authorCompiler,
+ frontends: [runMarkupFrontend], packageContributions: [], results: repository });
+ }
+
+ // Explicit export collects a standalone bundle, including same-named files with different owners.
+ const bundle = join(root, "exported-layout");
+ await jsonCommand(["get", "bld_20260902T110000003Z_0000000001", "--output", "shot.video", "--to", bundle], root);
+ const exported = JSON.parse(await readFile(join(bundle, "value.json"), "utf8")) as import("@hypit/build-result").BuildResultValueDocument;
+ assert.equal(exported.resources.length, 3);
+ const exportedPaths = new Set<string>();
+ for (const binding of exported.resources) {
+ assert.equal(binding.file.kind, "build-file");
+ if (binding.file.kind !== "build-file") throw new Error("expected local export");
+ assert.equal(binding.file.build, undefined);
+ exportedPaths.add(binding.file.path);
+ assert.deepEqual(await readFile(join(bundle, binding.file.path)),
+ binding.file.mediaType === "video/mp4" ? Buffer.from(bytes) : Buffer.from([7]));
+ }
+ assert.equal(exportedPaths.size, 3);
+
+ // A file Candidate is a live address, even when republished by separate Builds.
+ const externalPath = join(root, "selected.mp4");
+ await writeFile(externalPath, bytes);
+ await writeFile(runFile, `<?svml using="@hypit/run-markup@1"?>
+<svrun version="1"><author source="./main.svml"/><target output="shot.video"/>
+<file id="selected" type="example.result-reuse@1#Video" from="./selected.mp4" media-type="video/mp4"/>
+<satisfy output="shot.video" candidate="selected"/></svrun>`);
+ const externalRun = await loadRunFile({ workspace: await authorCompiler.openFile(runFile), authorCompiler,
+ frontends: [runMarkupFrontend], packageContributions: [], results: repository });
+ assert.deepEqual(Object.values(externalRun.resultResourceReferences), [{
+ kind: "external-file", uri: pathToFileURL(await realpath(externalPath)).href, size: bytes.length, mediaType: "video/mp4",
+ }]);
+ for (const id of ["bld_20260902T110000004Z_0000000001", "bld_20260902T110000005Z_0000000001"]) {
+ const current = await repository.create({ id, source: { path: authorFile }, targets: ["shot.video"],
+ publishedOutputs: [{ name: "shot.video", output: logicalOutput!.id }],
+ resourceReferences: externalRun.resultResourceReferences });
+ await current.sync({ state: externalRun.compiler.planCompilation(externalRun).state,
+ resources: { async open() { throw new Error("External files must stay references"); } } });
+ await current.finish({ outcome: "complete" });
+ assert.deepEqual(await readdir(current.directory), ["result.json"]);
+ }
+ const externalBuild = "bld_20260902T110000005Z_0000000001";
+ await writeFile(externalPath, "replacement");
+ const changed = await repository.resolve(externalBuild, "shot.video");
+ assert.equal(changed?.value.kind, "external-file");
+ if (changed?.value.kind !== "external-file") throw new Error("expected file");
+ assert.equal(changed.value.size, 11);
+ const chunks: Uint8Array[] = [];
+ for await (const chunk of (await repository.openFile(externalBuild, changed.value))!) chunks.push(chunk);
+ assert.equal(Buffer.concat(chunks).toString(), "replacement");
+ await rm(externalPath);
+ await assert.rejects(repository.resolve(externalBuild, "shot.video"), /ENOENT/);
} finally {
await rm(root, { recursive: true, force: true });
}
diff --git a/packages/cli/test/control-commands.test.ts b/packages/cli/test/control-commands.test.ts
index 362a4ea4..380e11fc 100644
--- a/packages/cli/test/control-commands.test.ts
+++ b/packages/cli/test/control-commands.test.ts
@@ -359,9 +359,9 @@ test("command options fail closed instead of being silently ignored", async () =
const io = { write() {} };
await assert.rejects(
async () => await runCli([
- "status", "build-1", "--runtime", "/tmp/runtime.json", "--workspace", "/tmp",
+ "status", "build-1", "--runtime", "/tmp/runtime.json", "--asset-root", "/tmp",
], io, distribution),
- /--workspace does not apply to status/u,
+ /--asset-root does not apply to status/u,
);
await assert.rejects(
async () => await runCli([
@@ -411,6 +411,7 @@ test("doctor diagnoses project Results without requiring a Runtime Profile", asy
format: "hypit.cli-doctor@1",
ok: true,
project: projectRoot,
+ profileSource: "none",
diagnosticCount: 0,
diagnostics: [],
});
diff --git a/packages/cli/test/output.test.ts b/packages/cli/test/output.test.ts
index 638f0faf..6edd28d7 100644
--- a/packages/cli/test/output.test.ts
+++ b/packages/cli/test/output.test.ts
@@ -16,6 +16,21 @@ function capture(
const human = { json: false, color: "auto", verbose: false } as const;
+test("doctor makes its checked scope and explicit Runtime selection visible", () => {
+ const machine = {
+ format: "hypit.cli-doctor@1" as const, ok: true, project: "/project",
+ diagnosticCount: 0, diagnostics: [],
+ };
+ const resultsOnly = capture(human, { kind: "doctor", machine });
+ assert.match(resultsOnly, /Runtime Profile\s+not selected/u);
+ assert.match(resultsOnly, /Scope\s+project Results only/u);
+ const selected = capture(human, { kind: "doctor", machine: {
+ ...machine, profile: "/project/chosen.json", profileSource: "argument",
+ } });
+ assert.match(selected, /command argument \(this invocation only\)/u);
+ assert.match(selected, /Scope\s+selected Runtime and project Results/u);
+});
+
test("author check keeps the default summary compact and reserves Output types for verbose", () => {
const presentation = {
kind: "check-author",
diff --git a/packages/cli/test/runtime-selection.test.ts b/packages/cli/test/runtime-selection.test.ts
index 5a73918e..212ba157 100644
--- a/packages/cli/test/runtime-selection.test.ts
+++ b/packages/cli/test/runtime-selection.test.ts
@@ -18,6 +18,57 @@ test("check has no Runtime context", () => {
);
});
+test("Runtime-aware commands accept an explicit project without changing relative argument paths", () => {
+ const project = resolve("another-project");
+ for (const command of [
+ ["paths"], ["doctor"], ["status", "build-id"], ["activity"], ["cancel", "build-id"],
+ ["result", "finish", "build-id"], ["result", "discard", "build-id"],
+ ["runtime", "up"], ["runtime", "down"], ["runtime", "status"], ["runtime", "logs"],
+ ["programs", "up"], ["programs", "down"], ["programs", "status"],
+ ["auth", "status", "endpoint"], ["auth", "login", "endpoint"], ["auth", "logout", "endpoint"],
+ ]) {
+ const parsed = parseCommand([...command, "--workspace", project, "--runtime", "chosen.json"]);
+ assert.ok("workspaceRoot" in parsed && "runtimeProfile" in parsed, command.join(" "));
+ assert.equal(parsed.workspaceRoot, project);
+ assert.equal(parsed.runtimeProfile, resolve("chosen.json"));
+ }
+ assert.throws(() => parseCommand(["doctor", "one.json", "--runtime", "two.json"]), /not both/u);
+});
+
+test("paths reports project selection, invocation override and no selection without changing the pointer", async () => {
+ const root = await mkdtemp(join(tmpdir(), "hypit-path-context-"));
+ try {
+ const profile = join(root, "selected.json");
+ const override = join(root, "override.json");
+ await writeFile(profile, "{}\n");
+ await writeFile(override, "{}\n");
+ const distribution = {
+ openRuntimeHost: async (path: string) => ({ resolvePaths: async () => ({ runtimeDataRoot: `${path}.data` }) }),
+ } as unknown as CliDistribution;
+ const readPaths = async (options: string[] = []) => {
+ let output = "";
+ await runCli(["paths", "--workspace", root, "--json", ...options],
+ { write(text) { output += text; } }, distribution);
+ return JSON.parse(output);
+ };
+ const absent = await readPaths();
+ assert.equal(absent.project, resolve(root));
+ assert.equal(absent.profileSource, "none");
+ assert.equal(absent.profile, undefined);
+ assert.equal(absent.selectionFile, join(root, ".hypit", "runtime"));
+ const selected = await selectRuntimeProfile(root, profile);
+ const project = await readPaths();
+ assert.equal(project.profileSource, "project");
+ assert.equal(project.profile, selected.profile);
+ const explicit = await readPaths(["--runtime", override]);
+ assert.equal(explicit.profileSource, "argument");
+ assert.equal(explicit.profile, override);
+ assert.equal((await readPaths()).profile, selected.profile);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
test("project resolution precedes exact project Runtime selection", async () => {
const root = await mkdtemp(join(tmpdir(), "hypit-runtime-selection-"));
try {
diff --git a/packages/compiler-node/src/compiler.ts b/packages/compiler-node/src/compiler.ts
index c9f927f7..5ee3245a 100644
--- a/packages/compiler-node/src/compiler.ts
+++ b/packages/compiler-node/src/compiler.ts
@@ -51,6 +51,7 @@ export function mergeAttachments(groups: readonly (readonly ArtifactAttachment[]
merged.set(key, {
artifact: { ...item.artifact },
open: item.open,
+ ...(item.location === undefined ? {} : { location: item.location }),
});
}
return [...merged.values()]
diff --git a/packages/ranking-studio/README.md b/packages/ranking-studio/README.md
index 853db636..7e4d8f65 100644
--- a/packages/ranking-studio/README.md
+++ b/packages/ranking-studio/README.md
@@ -1,3 +1,14 @@
# `@hypit/ranking-studio`
Hypit Studio Companion for the Ranking module's Column, Tier and Top Three surfaces.
+
+The root lane represents the board; `attachments` expose reveal or activation
+events on a detail lane. Both use Studio's ordinary item selection and overlap
+behavior. Their time ranges remain the authored event ranges.
+
+Ranking's renderer assigns `subjectId` to each item's rendered phases. The
+Companion associates those phases with the item's `renderIds`, so clicking an
+entering or settled icon selects the same detail entity. The board and preset
+items without a detail event remain associated with the root. Studio measures
+the visible parts at the current frame; the Companion does not duplicate motion
+geometry or infer identities from rendered ID strings.
diff --git a/packages/ranking-studio/src/index.ts b/packages/ranking-studio/src/index.ts
index b3c02c03..f8924266 100644
--- a/packages/ranking-studio/src/index.ts
+++ b/packages/ranking-studio/src/index.ts
@@ -133,6 +133,7 @@ function projectRanking(context: StudioTrackCompanionContext): readonly StudioEn
return [{
id: `${context.track.outputRef}:entity:${entry.itemId}`,
authoredId: entry.itemId,
+ renderIds: context.spans.filter((span) => span.subjectId === entry.itemId).map((span) => span.id),
...(semanticSource?.id === undefined ? {} : { markerId: semanticSource.id }),
display: {
title: label,
@@ -147,7 +148,8 @@ function projectRanking(context: StudioTrackCompanionContext): readonly StudioEn
...(temporal === undefined ? {} : { temporal }),
}];
}).sort((left, right) => left.startFrame - right.startFrame || left.id.localeCompare(right.id));
- return [group, ...reveals];
+ const childRenderIds = new Set(reveals.flatMap((entity) => entity.renderIds ?? []));
+ return [{ ...group, renderIds: group.renderIds!.filter((id) => !childRenderIds.has(id)) }, ...reveals];
}
const commonBindings: readonly StudioSourceBindingDeclaration[] = [
diff --git a/packages/ranking/src/render.ts b/packages/ranking/src/render.ts
index 672a3e16..f35ac53b 100644
--- a/packages/ranking/src/render.ts
+++ b/packages/ranking/src/render.ts
@@ -183,6 +183,7 @@ function iconElement(input: {
function present(input: {
readonly id: string;
+ readonly subjectId: string;
readonly start: number;
readonly end: number;
readonly stacking: number;
@@ -191,6 +192,7 @@ function present(input: {
}): VisualPresent {
return {
id: input.id,
+ subjectId: input.subjectId,
span: { startFrame: input.start, endFrameExclusive: input.end },
stacking: { order: input.stacking, tieBreak: input.tieBreak },
elements: input.elements,
@@ -307,7 +309,7 @@ export function renderTierBoard(space: ProgramSpace, program: TierBoardProgram):
}));
}
presents.push(present({
- id: `${program.id}:board`, start: schedule.outer.startFrame, end: schedule.outer.endFrameExclusive,
+ id: `${program.id}:board`, subjectId: program.id, start: schedule.outer.startFrame, end: schedule.outer.endFrameExclusive,
stacking: style.boardStackingOrder, tieBreak: `${program.id}:0000:board`, elements: boardElements,
}));
const entries = new Map(schedule.entries.map((entry) => [entry.itemId, entry]));
@@ -351,7 +353,7 @@ export function renderTierBoard(space: ProgramSpace, program: TierBoardProgram):
: (localFrame) => fromHighTierItemPose(
localFrame, duration, stage, absoluteCell, style.motion.appearFrames, style.motion.moveFrames));
presents.push(present({
- id: `${program.id}:item:${item.id}:reveal`,
+ id: `${program.id}:item:${item.id}:reveal`, subjectId: item.id,
start: entry.window.startFrame,
end: entry.window.endFrameExclusive,
stacking: item.stackingOrder ?? (item.entry === "drop" ? style.stageStackingOrder : style.itemStackingOrder),
@@ -360,7 +362,7 @@ export function renderTierBoard(space: ProgramSpace, program: TierBoardProgram):
}));
}
if (entry.settled.endFrameExclusive > entry.settled.startFrame) presents.push(present({
- id: `${program.id}:item:${item.id}:settled`,
+ id: `${program.id}:item:${item.id}:settled`, subjectId: item.id,
start: entry.settled.startFrame,
end: entry.settled.endFrameExclusive,
stacking: item.stackingOrder ?? style.itemStackingOrder,
@@ -506,7 +508,7 @@ export function renderColumn(space: ProgramSpace, program: ColumnProgram): Visua
],
}));
}
- presents.push(present({ id: `${program.id}:board`, start: schedule.outer.startFrame, end: schedule.outer.endFrameExclusive,
+ presents.push(present({ id: `${program.id}:board`, subjectId: program.id, start: schedule.outer.startFrame, end: schedule.outer.endFrameExclusive,
stacking: style.boardStackingOrder, tieBreak: `${program.id}:0000:board`, elements: boardElements }));
for (const [index, item] of program.items.entries()) {
const entry = entries.get(item.id)!;
@@ -549,13 +551,13 @@ export function renderColumn(space: ProgramSpace, program: ColumnProgram): Visua
stageSize: style.stageSizePx, finalSize: contentSize, easing: style.motion.easing,
});
presents.push(present({
- id: `${program.id}:item:${item.id}:stage`, start: entry.window.startFrame, end: entry.window.endFrameExclusive,
+ id: `${program.id}:item:${item.id}:stage`, subjectId: item.id, start: entry.window.startFrame, end: entry.window.endFrameExclusive,
stacking: item.stackingOrder ?? style.stageStackingOrder,
tieBreak: `${program.id}:item:${String(item.rank).padStart(4, "0")}:${item.id}:stage`, elements: itemElements(rootAnimation),
}));
}
if (entry.settled.endFrameExclusive > entry.settled.startFrame) presents.push(present({
- id: `${program.id}:item:${item.id}:settled`, start: entry.settled.startFrame, end: entry.settled.endFrameExclusive,
+ id: `${program.id}:item:${item.id}:settled`, subjectId: item.id, start: entry.settled.startFrame, end: entry.settled.endFrameExclusive,
stacking: item.stackingOrder ?? style.itemStackingOrder,
tieBreak: `${program.id}:item:${String(item.rank).padStart(4, "0")}:${item.id}:settled`, elements: itemElements(),
}));
@@ -599,7 +601,7 @@ export function renderTopThree(space: ProgramSpace, program: TopThreeProgram): V
}));
}
const presents: VisualPresent[] = [present({
- id: `${program.id}:slots`, start: schedule.outer.startFrame, end: schedule.outer.endFrameExclusive,
+ id: `${program.id}:slots`, subjectId: program.id, start: schedule.outer.startFrame, end: schedule.outer.endFrameExclusive,
stacking: style.boardStackingOrder, tieBreak: `${program.id}:0000:slots`, elements: boardElements,
})];
for (const [index, item] of program.items.entries()) {
@@ -640,12 +642,12 @@ export function renderTopThree(space: ProgramSpace, program: TopThreeProgram): V
return elements;
};
presents.push(present({
- id: `${program.id}:item:${item.id}:stage`, start: entry.stage.startFrame, end: entry.stage.endFrameExclusive,
+ id: `${program.id}:item:${item.id}:stage`, subjectId: item.id, start: entry.stage.startFrame, end: entry.stage.endFrameExclusive,
stacking: item.stackingOrder ?? style.itemStackingOrder,
tieBreak: `${program.id}:item:${String(index).padStart(4, "0")}:${item.id}:stage`, elements: itemElements(true),
}));
if (entry.settled.endFrameExclusive > entry.settled.startFrame) presents.push(present({
- id: `${program.id}:item:${item.id}:settled`, start: entry.settled.startFrame, end: entry.settled.endFrameExclusive,
+ id: `${program.id}:item:${item.id}:settled`, subjectId: item.id, start: entry.settled.startFrame, end: entry.settled.endFrameExclusive,
stacking: item.stackingOrder ?? style.itemStackingOrder,
tieBreak: `${program.id}:item:${String(index).padStart(4, "0")}:${item.id}:settled`, elements: itemElements(false),
}));
diff --git a/packages/ranking/test/ranking.test.ts b/packages/ranking/test/ranking.test.ts
index 55c8e3b6..1864c6ec 100644
--- a/packages/ranking/test/ranking.test.ts
+++ b/packages/ranking/test/ranking.test.ts
@@ -345,6 +345,9 @@ test("TierBoard separates its board Frame from the Canvas stage and holds drop I
assert.equal(track.presents.find((item) => item.id.endsWith(":item:preset:settled"))?.span.startFrame, 10);
const direct = track.presents.find((item) => item.id.endsWith(":item:early:reveal"))!;
const drop = track.presents.find((item) => item.id.endsWith(":item:late:reveal"))!;
+ assert.equal(direct.subjectId, "early");
+ assert.equal(track.presents.find((item) => item.id.endsWith(":item:early:settled"))?.subjectId, "early");
+ assert.equal(track.presents.find((item) => item.id.endsWith(":board"))?.subjectId, program.id);
assert.ok(direct.elements[0]?.animation);
const geometry = tierBoardGeometry(tierFrame.widthPx, tierFrame.heightPx, style);
const stage = tierStageGeometry(canvas.widthPx, canvas.heightPx, style);
diff --git a/packages/runtime-host-node/src/index.ts b/packages/runtime-host-node/src/index.ts
index 4ea67045..0833064f 100644
--- a/packages/runtime-host-node/src/index.ts
+++ b/packages/runtime-host-node/src/index.ts
@@ -119,6 +119,7 @@ export type RuntimeHostExecution = RuntimeHostControl & RuntimeHostCredentialCon
readonly repository: BuildResultRepositoryLocation;
readonly title?: string;
readonly forwards?: readonly BuildResultForward[];
+ readonly resourceReferences?: Readonly<Record<string, import("@hypit/build-result").BuildResultFileRef>>;
};
}, options?: {
readonly follow?: boolean;
diff --git a/packages/runtime-local/README.md b/packages/runtime-local/README.md
index e59f0ba0..39274254 100644
--- a/packages/runtime-local/README.md
+++ b/packages/runtime-local/README.md
@@ -104,6 +104,15 @@ through the same adapter registry as an explicit `@hypit/build-result-s3` select
filesystem Repository shortcut.
Runtime working Resources remain internal and Build-local; there is no ResourceStore selector. After
a Result has an outcome, history is read from the selected repository, not Runtime SQLite.
+The submission passes known Resource references to the Result writer, separately from the execution
+graph. Staging bytes for a running Build does not make them new Result files: external and reused
+resources keep their addresses even when a Producer embeds them inside a new Composite value.
+
+While execution advances, Result synchronization publishes newly accepted public Outputs. The
+repository leaves its files or objects untouched when no new public Output is available; internal
+execution progress remains in SQLite. Once execution has a final decision, all accepted public Outputs
+and the outcome are saved before active state and working Resources are removed. This order applies
+to completed, failed and cancelled Builds alike.
Saving a finished Result is a separate, idempotent storage action. If that write is interrupted, the
Build keeps its already-decided outcome and reports exact operator attention. `hypit result finish
diff --git a/packages/runtime-local/src/runtime.ts b/packages/runtime-local/src/runtime.ts
index d2c22fb4..cc245b85 100644
--- a/packages/runtime-local/src/runtime.ts
+++ b/packages/runtime-local/src/runtime.ts
@@ -268,6 +268,7 @@ export async function createLocalRuntime(
try {
const publishedOutputs = request.catalog.publishedOutputs.map((published) => ({
name: published.name,
+ ...(published.displayName === undefined ? {} : { displayName: published.displayName }),
output: published.ref.id,
}));
const names = new Map<string, string>();
@@ -291,6 +292,7 @@ export async function createLocalRuntime(
targets,
publishedOutputs,
...(resultRequest.forwards === undefined ? {} : { forwards: resultRequest.forwards }),
+ ...(resultRequest.resourceReferences === undefined ? {} : { resourceReferences: resultRequest.resourceReferences }),
});
} finally {
await opened.close?.();
diff --git a/packages/runtime-local/test/local.test.ts b/packages/runtime-local/test/local.test.ts
index 9cbef1c5..a567a8af 100644
--- a/packages/runtime-local/test/local.test.ts
+++ b/packages/runtime-local/test/local.test.ts
@@ -3,12 +3,14 @@ import {
mkdir,
mkdtemp,
readFile,
+ readdir,
rm,
stat,
writeFile,
} from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
+import { pathToFileURL } from "node:url";
import test from "node:test";
import { FileResourceStore } from "@hypit/resource-store-fs";
@@ -554,6 +556,7 @@ test("an interrupted Result write finishes explicitly without rerunning the Buil
browse: async (request) => await base.browse(request),
describeOutput: async (build, output) => await base.describeOutput(build, output),
resolve: async (build, output) => await base.resolve(build, output),
+ describeFile: async (build, file) => await base.describeFile(build, file),
openFile: async (build, file) => await base.openFile(build, file),
};
return { repository };
@@ -603,6 +606,7 @@ test("a failed Result creation leaves no active Build", async () => {
async browse() { return { results: [] }; },
async describeOutput() { return undefined; },
async resolve() { return undefined; },
+ async describeFile(_build, file) { return file; },
async openFile() { return undefined; },
};
try {
@@ -666,7 +670,7 @@ test("an immediate Command left in started state fails its Build without invokin
}
});
-test("a selected historical file is staged once before its Build becomes active", async () => {
+test("a selected file is staged once and remains referenced in the produced Composite Result", async () => {
const directory = await mkdtemp(join(tmpdir(), "hypit-local-bld_20260902T120000009Z_0000000001-"));
const initial = createGreetingBuild();
const bytes = new Uint8Array([4, 3, 2, 1]);
@@ -699,7 +703,7 @@ test("a selected historical file is staged once before its Build becomes active"
}, {
producer: producers.assemble,
handler: ({ inputs }) => ({
- outputs: { document: { kind: "inline", value: { text: inputs.generated!.id } } },
+ outputs: { document: { kind: "inline", value: { layers: [{ content: inputs.generated!.value }] } } },
needs: {},
}),
}],
@@ -718,11 +722,13 @@ test("a selected historical file is staged once before its Build becomes active"
const source = (need.constraints as { readonly source: typeof historical }).source;
assert.equal(await resources.has(source.resource), true);
assert.deepEqual(await resources.get(source.resource), bytes);
- return { value: { kind: "inline", value: "generated from history" } };
+ return { value: { kind: "inline", value: { image: source } } };
},
}],
});
try {
+ const inputPath = join(directory, "selected.png");
+ await writeFile(inputPath, bytes);
const runtime = await createLocalRuntime({
...projectRuntimeFixture(directory),
components: [components],
@@ -742,7 +748,10 @@ test("a selected historical file is staged once before its Build becomes active"
return (async function* () { yield bytes; })();
},
}],
- result: resultDestination(directory),
+ result: { ...resultDestination(directory), resourceReferences: {
+ [historical.resource]: { kind: "external-file", uri: pathToFileURL(inputPath).href,
+ size: bytes.length, mediaType: historical.mediaType },
+ } },
});
assert.equal(attachmentOpens, 1);
const work = new FileResourceStore(join(directory, ".hypit", "work", "bld_20260902T120000009Z_0000000001"));
@@ -754,6 +763,16 @@ test("a selected historical file is staged once before its Build becomes active"
assert.equal(endpointCalls, 1);
assert.equal(attachmentOpens, 1);
assert.equal(await work.has(historical.resource), false);
+ const results = new FileBuildResultRepository(join(directory, "results"));
+ const resolved = (await results.resolve("bld_20260902T120000009Z_0000000001", "final.document"))!;
+ assert.equal(resolved.value.kind, "value");
+ if (resolved.value.kind !== "value") throw new Error("expected composite");
+ assert.deepEqual(resolved.value.document.resources.map((binding) => binding.file), [{
+ kind: "external-file", uri: pathToFileURL(inputPath).href, size: bytes.length, mediaType: historical.mediaType,
+ }]);
+ const resultDirectory = join(directory, "results", "2026-09-02", "bld_20260902T120000009Z_0000000001");
+ assert.deepEqual((await readdir(resultDirectory)).sort(), ["result.json", "values"]);
+ assert.deepEqual(await readFile(inputPath), Buffer.from(bytes));
await runtime.close();
} finally {
await rm(directory, { recursive: true, force: true });
diff --git a/packages/runtime/src/catalog.ts b/packages/runtime/src/catalog.ts
index 706f48fc..96e060b0 100644
--- a/packages/runtime/src/catalog.ts
+++ b/packages/runtime/src/catalog.ts
@@ -3,6 +3,8 @@ import type {
} from "@hypit/protocol";
export type BuildPublishedOutput = {
+ /** Author-provided display name; the Output identifier remains unchanged. */
+ readonly displayName?: string;
readonly name: string;
readonly ref: LogicalOutputRef;
};
diff --git a/packages/studio-adapter/README.md b/packages/studio-adapter/README.md
index 6a3a3158..b5a2814d 100644
--- a/packages/studio-adapter/README.md
+++ b/packages/studio-adapter/README.md
@@ -48,6 +48,22 @@ nominal output Type and authored input names of the component. A Companion does
author attribute. Omitting `project` uses generic terminal entities; `poster` adds the declared
Surface preview when one exists, without changing the component's rendered video.
+Each lane occupies one timeline row. Entities overlap in ascending `stackOrder`,
+with later projected entities above earlier ones when orders tie. Studio keeps
+overlapping entities mounted and raises the selected entity within its lane;
+selection does not change the rendered composition or write stacking back to Source.
+Expose `presentId` or `renderIds` for visual entities so picture selection can
+address the same entity shown in the timeline. Attached lanes represent distinct
+Companion projections, not extra rows allocated to avoid temporal overlap.
+
+An entity's timeline interval describes the operation being edited; its rendered
+parts may remain visible afterward. Associate every relevant phase through
+`renderIds` (for example, an entrance and the settled object). Studio picks the
+currently visible part in rendered stacking order and selects the same entity,
+without extending its editable interval. Give the parent the board or background
+parts and its children their own parts when they should be independently selectable.
+The component decides this granularity. A composite can remain one selectable entity.
+
Merge the facet into the package's existing activation. In this example `authorContribution`
exports its existing modules, deterministic component and Markup facets:
diff --git a/packages/studio-adapter/src/index.ts b/packages/studio-adapter/src/index.ts
index 024a6685..c1f5f1ea 100644
--- a/packages/studio-adapter/src/index.ts
+++ b/packages/studio-adapter/src/index.ts
@@ -308,6 +308,7 @@ export type StudioEntityDisplay = {
};
export type StudioLaneDescription = {
+ /** Height of this single timeline lane; overlapping entities share it. */
readonly heightPx: number;
readonly groupId?: string;
readonly attachedTo?: string;
@@ -482,10 +483,12 @@ export type StudioEntityDraft = {
readonly display: StudioEntityDisplay;
readonly startFrame: number;
readonly endFrameExclusive: number;
+ /** Back-to-front timeline order. Ties preserve projection order. Selection raises only the timeline item. */
readonly stackOrder: number;
readonly elementRange?: Range;
readonly markerId?: string;
readonly presentId?: string;
+ /** Rendered parts belonging to this entity, including phases beyond its editable timeline interval. */
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>>;
diff --git a/packages/studio/README.md b/packages/studio/README.md
index 412d1ce6..3756712f 100644
--- a/packages/studio/README.md
+++ b/packages/studio/README.md
@@ -14,11 +14,55 @@ When `--runtime` is omitted, Studio reads the resolved project's `.hypit/runtime
selection made by `hypit runtime use`. It does not search parent projects for a
Profile. `--workspace` explicitly selects the project boundary; `--package-root`
overrides the author package resolution root when those locations intentionally differ.
+Startup prints the project, Run, Profile and whether the Profile came from the command argument or
+the project's selection file. Relative command-line paths start at the invoking directory;
+`--workspace` selects the project without rebasing `--run` or `--runtime`.
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 combine finished project Results with read-only active `BuildView` and Operation information;
-- Artifacts are public files exposed by project Build Results.
+- Tasks show one card per Build, with All, In progress and Finished filters. Active progress comes from
+ the selected Runtime's read-only control interface; completed, failed and cancelled Builds come
+ from the project's Result Repository. Saving a Result and an issue requiring attention remain
+ visible, with the source Run and available progress or failure reason.
+- Artifacts show top-level file Outputs whose declared MIME type is image, video or audio,
+ including files already published by ongoing Builds. Composite Outputs retain their structure:
+ the library does not extract their embedded resources. Forwarded file Outputs resolve to their
+ owner; references to the same owner file share one card and retain their origins. Highlighted
+ Outputs sort first, without excluding other media.
+
+Source, Tasks and Artifacts use the shared `ui/sidebar-panel.ts` layout and navigation buttons. Each view
+owns its toolbar content, data and actions; the shared shell owns geometry and navigation styling.
+
+Views load on entry; returning to Tasks preserves its loaded list and selection. Explicit Refresh reads the latest state. There is no library polling.
+Refresh replaces the current snapshot; scrolling to the end loads more finished Results. Failed
+refreshes preserve the last view and show the error. Artifacts show project media through an icon sidebar: All media, Videos, Images and Audio.
+The header names the category and offers Refresh. Selecting a Task adds its name beside the category in the existing header, establishing a session-local task context without shifting the list; its arrow opens that Build's media. The context remains across tab changes. Click its name to return to the selected Task, or clear it to browse project media. Task selection does not write Source, Result or Runtime state. Selected tasks expand the complete error text with a copy action. Source details are available on each media card. A media category is sent to the server, which
+walks Result metadata pages until it collects a useful batch of matching files or reaches the end.
+This keeps Build storage unchanged while avoiding empty category pages. The browser appends
+older matches on scroll; Refresh reads the latest results for the current category.
+
+Media cards use fixed-size square cells, contain the file at its own aspect ratio, and show up to two
+wrapped name lines below. Selection colors the thumbnail area and name separately, without an
+outer card border. Resizing the
+sidebar distributes spare width between columns, then adds a column when another fixed-size
+card fits. Card size stays unchanged. Video thumbnails decode a frame in the browser; audio waveforms are also
+browser presentation, not additional Result files. Thumbnails load as their cells enter view.
+The CLI carries the author's component name from compilation provenance into the Result's
+optional Output `displayName`. The public Output identifier stays intact for references;
+Outputs without a display name show that identifier unchanged. Double-click a name or press F2
+to edit it in full; Enter or blur saves, Escape cancels. Failed saves retain the text and show the
+reason. A completed, failed or cancelled Build's name is written through Result Repository
+`updatePresentation` to that exact Output's `displayName`. Ongoing Builds become editable when
+they finish, following the existing Result presentation-edit boundary. Renaming never changes
+Output identity, referenced media files or other Builds' names for the same file.
+
+The composition has a frame-snapped progress slider and current/total time.
+Clicking a card opens the file in the central preview and pauses the composition. Images need
+no transport; video and audio share the play/mute controls and a seconds-based scrubber above
+the playback bar. The previous/next buttons skip five seconds for media, and step one frame
+for the composition. Back to composition restores the existing composition playhead. Selecting
+or seeking in the composition timeline also returns to it. Opening media changes no Source,
+Run, or Candidate selection.
No project manifest, Studio database, output-directory scan or inferred campaign
folder structure is involved. With no selected Runtime, finished Result tasks and
@@ -32,7 +76,10 @@ The selected targets must reach one Film and its resolved time source. Studio re
distinct Films in one view; use separate Runs/sessions for those. A SemanticTrack supplies the
Script lane and performance timing, including wordless Segments with media spans. A declared
ProgramSpace supplies authored animation time without a Script lane. Both show their component
-tracks and use the same rendering and parameter-editing machinery.
+tracks and use the same rendering and parameter-editing machinery. When the snapshot contains
+a semantic timeline, its lane and label stay pinned directly below the time ruler while
+component tracks scroll. Its presence follows the resolved semantic timeline, including
+wordless content, rather than a component name or the presence of spoken words.
Open the URL printed by Vite. Studio requests port 5179 by default, accepts `--port`,
and Vite can choose another available port when it is occupied. Reuse that process
@@ -82,7 +129,7 @@ source binding is never shown merely because Studio can reach it. Material layer
Resource id or Surface identity, never a Studio HTTP URL. Studio always owns
time formatting and transport resolution, so chrome and material cannot hide a
title or its time.
-Studio owns session-wide behavior and chrome: Companion assembly, collision rules,
+Studio owns session-wide behavior and chrome: Companion assembly, single-row overlap display,
fallback defaults, selection treatment, playback, zoom,
scrolling, the finite Inspector control set and source mutation transport. A
companion cannot ship arbitrary DOM or CSS into the application.
diff --git a/packages/studio/src/build-library.ts b/packages/studio/src/build-library.ts
index 7108b231..a3ddc24e 100644
--- a/packages/studio/src/build-library.ts
+++ b/packages/studio/src/build-library.ts
@@ -1,3 +1,4 @@
+import { fileReferenceIdentity } from "@hypit/build-result";
import { isAbsolute, relative, resolve, sep } from "node:path";
import { buildIdCreatedAt } from "@hypit/protocol";
@@ -5,17 +6,16 @@ import type { BuildView, NodeRuntimeHost, RuntimeHostTransientExecution } from "
import type { StoredValue, TypeRef } from "@hypit/protocol";
import type {
BuildResultFileRange,
- BuildResultFileRef,
BuildResultManifest,
BuildResultRepository,
FinishedBuildResultManifest,
- RepositoryBuildResultOutput,
} from "@hypit/build-result";
import { resolveBuildResultValue } from "@hypit/cli";
import { videoCliDistribution } from "@hypit/video-cli";
-import type { StudioArtifactView, StudioLibraryView, StudioTaskView } from "./shared.js";
+import type { StudioArtifactView, StudioLibraryRequest, StudioLibraryView, StudioTaskView } from "./shared.js";
+import { mergeStudioArtifacts } from "./library-media.js";
type RuntimeControl = Awaited<ReturnType<NodeRuntimeHost["openControl"]>>;
@@ -24,7 +24,8 @@ export type StudioBuildLibrary = {
readonly runtime?: Pick<RuntimeControl, "activity">;
/** Runtime-owned, disposable execution for the current authoring session. */
readonly transientExecution?: RuntimeHostTransientExecution;
- readonly library: (before?: string) => Promise<StudioLibraryView>;
+ readonly library: (request: StudioLibraryRequest) => Promise<StudioLibraryView>;
+ readonly renameArtifact: (build: string, output: string, displayName: string | null) => Promise<string | undefined>;
readonly resolveHistoricalOutput: (
build: string,
output: string,
@@ -36,7 +37,6 @@ export type StudioBuildLibrary = {
readonly openArtifact: (
build: string,
output: string,
- valuePath: string,
) => Promise<{
readonly mediaType: string;
readonly size: number;
@@ -51,7 +51,7 @@ function projectPath(root: string, path: string): string {
function isWithin(root: string, path: string): boolean {
const rel = relative(resolve(root), projectPath(root, path));
- return rel === "" || (!rel.startsWith("..") && !isAbsolute(rel));
+ return rel === "" || (rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel));
}
/**
@@ -65,15 +65,9 @@ function presentedPath(root: string, path: string): string {
return (relative(resolve(root), absolute) || ".").split(sep).join("/");
}
-function buildBelongsTo(root: string, view: BuildView): boolean {
- return view.source !== undefined
- && (isWithin(root, view.run?.path ?? view.source.path) || isWithin(root, view.source.path));
-}
-
function taskStatus(view: BuildView): StudioTaskView["status"] {
- if (view.issue !== undefined) return "blocked";
+ if (view.issue !== undefined) return "attention";
if (view.activity === "submitting" || view.activity === "ready") return "queued";
- if (view.activity === "saving-result") return "active";
return view.activity;
}
@@ -83,18 +77,20 @@ function taskView(
result?: BuildResultManifest,
): StudioTaskView {
if (view.source === undefined) throw new Error(`Active Build ${view.id} has no source`);
+ const detail = view.issue?.message ?? view.stop?.reason;
return {
id: view.id,
...(result?.title === undefined ? {} : { title: result.title }),
...(result?.note === undefined ? {} : { note: result.note }),
...(result?.highlightedOutputs === undefined ? {} : { highlightedOutputs: result.highlightedOutputs }),
createdAt: view.createdAt,
+ ongoing: true,
status: taskStatus(view),
+ ...(detail === undefined ? {} : { detail }),
+ ...(view.requests === undefined ? {} : { requests: view.requests }),
source: presentedPath(root, view.source.path),
...(view.run === undefined ? {} : { run: presentedPath(root, view.run.path) }),
targets: result?.targets ?? view.targets,
- acceptedRecords: view.acceptedRecords,
- outstandingCommands: view.outstandingCommands,
operations: view.operations.map((operation) => ({
status: operation.status,
...(operation.progress?.phase === undefined ? {} : { phase: operation.progress.phase }),
@@ -112,107 +108,117 @@ function resultTaskView(root: string, result: FinishedBuildResultManifest): Stud
...(result.note === undefined ? {} : { note: result.note }),
...(result.highlightedOutputs === undefined ? {} : { highlightedOutputs: result.highlightedOutputs }),
createdAt: buildIdCreatedAt(result.id)!,
+ finishedAt: result.finishedAt,
+ ongoing: false,
status: result.outcome,
+ ...(result.failure === undefined ? {} : { detail: result.failure }),
source: presentedPath(root, result.source.path),
...(result.run === undefined ? {} : { run: presentedPath(root, result.run.path) }),
targets: result.targets,
- acceptedRecords: Object.keys(result.outputs).length,
- outstandingCommands: 0,
operations: [],
};
}
-function presentedValuePath(path: readonly (string | number)[]): string {
- return path.reduce<string>((current, segment) => typeof segment === "number"
- ? `${current}[${segment}]`
- : /^[A-Za-z_$][A-Za-z0-9_$]*$/u.test(segment)
- ? `${current}.${segment}`
- : `${current}[${JSON.stringify(segment)}]`, "$");
-}
-
-function filesInResolvedOutput(resolved: RepositoryBuildResultOutput): readonly {
- readonly valuePath: string;
- readonly file: BuildResultFileRef;
-}[] {
- if (resolved.value.kind === "build-file") return [{ valuePath: "$", file: resolved.value }];
- if (resolved.value.kind === "value") {
- return resolved.value.document.resources.map((binding) => ({
- valuePath: presentedValuePath(binding.at),
- file: binding.file,
- }));
- }
- return [];
+function isMedia(mediaType: string): boolean {
+ return /^(image|video|audio)\//u.test(mediaType);
}
async function artifactsForResults(
root: string,
repository: BuildResultRepository,
manifests: readonly BuildResultManifest[],
+ media?: StudioLibraryRequest["media"],
): Promise<readonly StudioArtifactView[]> {
const nested = await Promise.all(manifests.flatMap((manifest) =>
- Object.keys(manifest.outputs).map(async (output) => {
- const resolved = await repository.resolve(manifest.id, output);
- if (resolved === undefined) return [];
- return filesInResolvedOutput(resolved).map(({ valuePath, file }) => ({
- id: `${manifest.id}:${output}:${valuePath}`,
+ Object.entries(manifest.outputs).map(async ([output, entry]): Promise<StudioArtifactView[]> => {
+ // Composite Outputs remain intact. Listing media never opens their Value Documents.
+ if (entry.value.kind !== "build-file" && entry.value.kind !== "external-file" && entry.value.kind !== "build-output") return [];
+ const description = entry.value.kind === "build-file" || entry.value.kind === "external-file"
+ ? { kind: "resource", mediaType: entry.value.mediaType }
+ : await repository.describeOutput(manifest.id, output);
+ if (description?.kind !== "resource" || (description.mediaType === undefined || !isMedia(description.mediaType))) return [];
+ if (media !== undefined && !description.mediaType.startsWith(`${media}/`)) return [];
+ const resolved = entry.value.kind === "build-file"
+ ? { build: manifest.id, output, value: entry.value }
+ : await repository.resolve(manifest.id, output);
+ if (resolved === undefined || (resolved.value.kind !== "build-file" && resolved.value.kind !== "external-file")) return [];
+ const file = resolved.value;
+ const source = presentedPath(root, manifest.source.path);
+ const run = manifest.run === undefined ? undefined : presentedPath(root, manifest.run.path);
+ return [{
+ id: fileReferenceIdentity(resolved.build, file),
build: manifest.id,
createdAt: buildIdCreatedAt(manifest.id)!,
output,
+ nameEditable: manifest.outcome !== undefined,
+ ...(entry.displayName === undefined ? {} : { displayName: entry.displayName }),
highlighted: manifest.highlightedOutputs?.includes(output) === true,
...(manifest.title === undefined ? {} : { buildTitle: manifest.title }),
...(manifest.note === undefined ? {} : { buildNote: manifest.note }),
- valuePath,
- ownerBuild: resolved.build,
+ ...(file.kind === "external-file" ? {} : { ownerBuild: file.build ?? resolved.build }),
ownerOutput: resolved.output,
- filePath: file.path,
+ filePath: file.kind === "external-file" ? file.uri : file.path,
size: file.size,
mediaType: file.mediaType,
- source: presentedPath(root, manifest.source.path),
- ...(manifest.run === undefined ? {} : { run: presentedPath(root, manifest.run.path) }),
- }));
+ source,
+ ...(run === undefined ? {} : { run }),
+ origins: [{ build: manifest.id, output, source, ...(run === undefined ? {} : { run }) }],
+ }];
})));
- return nested.flat().sort((left, right) =>
- Number(right.highlighted) - Number(left.highlighted)
- || right.createdAt - left.createdAt
- || left.output.localeCompare(right.output)
- || left.valuePath.localeCompare(right.valuePath));
+ return mergeStudioArtifacts(nested.flat());
}
-/** Build the Studio library from execution status and project-owned Build Results. */
-export async function readStudioLibrary(input: {
+/** Query only the selected library view, through Runtime and Repository interfaces. */
+export async function readStudioLibrary(input: StudioLibraryRequest & {
readonly profile?: string;
readonly workspaceRoot: string;
readonly runtime?: Pick<RuntimeControl, "activity">;
readonly results: BuildResultRepository;
- readonly before?: string;
}): Promise<StudioLibraryView> {
- const page = await input.results.browse({
- limit: 25,
- ...(input.before === undefined ? {} : { before: input.before }),
- });
- const manifests = page.results.filter((manifest) =>
- isWithin(input.workspaceRoot, manifest.run?.path ?? manifest.source.path)
- || isWithin(input.workspaceRoot, manifest.source.path));
- const resultsByBuild = new Map(manifests.map((manifest) => [manifest.id, manifest]));
+ const matches = (item: { readonly id: string; readonly source: { readonly path: string }; readonly run?: { readonly path: string } }) =>
+ (isWithin(input.workspaceRoot, item.run?.path ?? item.source.path) || isWithin(input.workspaceRoot, item.source.path))
+ && (input.build === undefined || item.id === input.build)
+ && (input.run === undefined || (item.run !== undefined
+ && projectPath(input.workspaceRoot, item.run.path) === projectPath(input.workspaceRoot, input.run)));
+ // Read activity before Results so a Build that finishes during this query is still represented.
const active = input.runtime === undefined || input.before !== undefined
- ? []
- : (await input.runtime.activity()).builds;
- const views = active.filter((view) => buildBelongsTo(input.workspaceRoot, view));
+ ? [] : (await input.runtime.activity()).builds;
+ const views = active.filter((view) => view.source !== undefined && matches({ ...view, source: view.source }));
+ let page = input.build === undefined
+ ? await input.results.browse({ limit: 25, ...(input.before === undefined ? {} : { before: input.before }) })
+ : { results: [await input.results.read(input.build)].filter((item): item is BuildResultManifest => item !== undefined) };
+ const manifests = page.results.filter(matches);
+ const resultsByBuild = new Map(manifests.map((manifest) => [manifest.id, manifest]));
+ await Promise.all(views.filter((view) => !resultsByBuild.has(view.id)).map(async (view) => {
+ const result = await input.results.read(view.id);
+ if (result !== undefined && matches(result)) resultsByBuild.set(view.id, result);
+ }));
+ let artifacts: readonly StudioArtifactView[] = [];
+ if (input.section === "artifacts") {
+ artifacts = await artifactsForResults(input.workspaceRoot, input.results, [...resultsByBuild.values()], input.media);
+ // Page through Result metadata until there is a useful media page. The repository still
+ // owns Build order and cursors; no media directory or secondary persistent index is needed.
+ while (artifacts.length < 25 && "next" in page && page.next !== undefined) {
+ const cursor = page.next;
+ page = await input.results.browse({ limit: 25, before: cursor });
+ if ("next" in page && page.next === cursor) throw new Error("Result pagination did not advance");
+ artifacts = mergeStudioArtifacts([...artifacts,
+ ...await artifactsForResults(input.workspaceRoot, input.results, page.results.filter(matches), input.media)]);
+ }
+ }
return {
+ section: input.section,
environment: resolve(input.workspaceRoot),
...(input.profile === undefined ? {} : { runtime: resolve(input.profile) }),
- ...(page.next === undefined ? {} : { next: page.next }),
- tasks: [
- ...views.map((view) => taskView(
- input.workspaceRoot,
- view,
- resultsByBuild.get(view.id),
- )),
+ ...("next" in page && page.next !== undefined ? { next: page.next } : {}),
+ tasks: input.section !== "tasks" ? [] : [
+ ...views.map((view) => taskView(input.workspaceRoot, view, resultsByBuild.get(view.id))),
...manifests
- .filter((manifest) => !views.some((view) => view.id === manifest.id))
+ .filter((manifest): manifest is FinishedBuildResultManifest => manifest.outcome !== undefined
+ && !views.some((view) => view.id === manifest.id))
.map((manifest) => resultTaskView(input.workspaceRoot, manifest)),
].sort((left, right) => right.createdAt - left.createdAt || left.id.localeCompare(right.id)),
- artifacts: await artifactsForResults(input.workspaceRoot, input.results, manifests),
+ artifacts,
};
}
@@ -245,31 +251,40 @@ export async function openStudioBuildLibrary(
throw error;
}
const results = openedResults.repository;
+ let presentationWrite: Promise<unknown> = Promise.resolve();
return {
...(resolvedProfile === undefined ? {} : { profile: resolvedProfile }),
...(runtime === undefined ? {} : { runtime }),
...(transientExecution === undefined ? {} : { transientExecution }),
- async library(before) {
+ async library(request) {
return await readStudioLibrary({
...(resolvedProfile === undefined ? {} : { profile: resolvedProfile }),
workspaceRoot,
...(runtime === undefined ? {} : { runtime }),
results,
- ...(before === undefined ? {} : { before }),
+ ...request,
+ });
+ },
+ async renameArtifact(build, output, displayName) {
+ const saved = presentationWrite.then(async () => {
+ const updated = await results.updatePresentation(build, { outputDisplayNames: { [output]: displayName } });
+ return updated.outputs[output]?.displayName;
});
+ presentationWrite = saved.catch(() => undefined);
+ return await saved;
},
async resolveHistoricalOutput(build, output) {
return await resolveBuildResultValue(results, build, output);
},
- async openArtifact(build, output, valuePath) {
+ async openArtifact(build, output) {
const resolved = await results.resolve(build, output);
if (resolved === undefined) return undefined;
- const match = filesInResolvedOutput(resolved).find((item) => item.valuePath === valuePath);
- if (match === undefined) return undefined;
+ if ((resolved.value.kind !== "build-file" && resolved.value.kind !== "external-file") || !isMedia(resolved.value.mediaType)) return undefined;
+ const file = resolved.value;
return {
- mediaType: match.file.mediaType,
- size: match.file.size,
- open: async (range) => await results.openFile(resolved.build, match.file, range),
+ mediaType: file.mediaType,
+ size: file.size,
+ open: async (range) => await results.openFile(resolved.build, file, range),
};
},
async close() {
diff --git a/packages/studio/src/library-media.ts b/packages/studio/src/library-media.ts
new file mode 100644
index 00000000..9731fac3
--- /dev/null
+++ b/packages/studio/src/library-media.ts
@@ -0,0 +1,19 @@
+import type { StudioArtifactView } from "./shared.js";
+
+/** Merge known references, without reading or comparing media bytes. */
+export function mergeStudioArtifacts(items: readonly StudioArtifactView[]): StudioArtifactView[] {
+ const files = new Map<string, StudioArtifactView>();
+ for (const item of items) {
+ const prior = files.get(item.id);
+ if (prior === undefined) {
+ files.set(item.id, item);
+ continue;
+ }
+ const latest = item.createdAt > prior.createdAt ? item : prior;
+ const origins = new Map([...prior.origins, ...item.origins].map((origin) =>
+ [JSON.stringify([origin.build, origin.output]), origin]));
+ files.set(item.id, { ...latest, highlighted: prior.highlighted || item.highlighted, origins: [...origins.values()] });
+ }
+ return [...files.values()].sort((left, right) => Number(right.highlighted) - Number(left.highlighted)
+ || right.createdAt - left.createdAt || left.output.localeCompare(right.output));
+}
diff --git a/packages/studio/src/server.ts b/packages/studio/src/server.ts
index b22b43eb..fbf970d1 100644
--- a/packages/studio/src/server.ts
+++ b/packages/studio/src/server.ts
@@ -17,7 +17,7 @@ import type { StudioCompanionRegistry } from "./studio-registry.js";
import { loadStudioRun } from "./run.js";
import { serializeParameterValue, validateParameterValue } from "./parameter-values.js";
import { readStudioSession } from "./session.js";
-import type { Range, StudioFailure, StudioLibraryView, StudioMutation, StudioSnapshot } from "./shared.js";
+import type { Range, StudioFailure, StudioLibraryRequest, StudioLibraryView, StudioMutation, StudioSnapshot } from "./shared.js";
import { createStudioStoryboard } from "./storyboard.js";
import type { StudioStoryboard } from "./storyboard.js";
import { findSurfacePreview } from "./surface-preview.js";
@@ -93,8 +93,9 @@ export function studioPlugin(options: StudioPluginOptions): Plugin {
const watchedFiles = new Set<string>();
const storyboards = new Map<string, Promise<StudioStoryboard>>();
- const readLibrary = async (before?: string): Promise<StudioLibraryView> => {
- return await options.buildLibrary?.library(before) ?? {
+ const readLibrary = async (request: StudioLibraryRequest): Promise<StudioLibraryView> => {
+ return await options.buildLibrary?.library(request) ?? {
+ section: request.section,
environment: options.workspaceRoot,
tasks: [],
artifacts: [],
@@ -525,6 +526,28 @@ export function studioPlugin(options: StudioPluginOptions): Plugin {
})();
return;
}
+ if (request.method === "PUT" && url.pathname === "/__studio/artifact-name") {
+ void (async () => {
+ try {
+ const chunks: Buffer[] = [];
+ for await (const chunk of request) chunks.push(Buffer.from(chunk));
+ const body = JSON.parse(Buffer.concat(chunks).toString("utf8")) as {
+ build?: unknown; output?: unknown; displayName?: unknown;
+ };
+ if (typeof body.build !== "string" || typeof body.output !== "string"
+ || (typeof body.displayName !== "string" && body.displayName !== null)) {
+ json(response, 400, { error: "Expected Build, Output and displayName" });
+ return;
+ }
+ if (options.buildLibrary === undefined) throw new Error("Result Repository is unavailable");
+ const displayName = await options.buildLibrary.renameArtifact(body.build, body.output, body.displayName);
+ json(response, 200, { displayName: displayName ?? null });
+ } catch (error) {
+ json(response, 422, { error: error instanceof Error ? error.message : String(error) });
+ }
+ })();
+ return;
+ }
if (request.method === "POST" && url.pathname === "/__studio/mutation") {
void (async () => {
try {
@@ -577,8 +600,21 @@ export function studioPlugin(options: StudioPluginOptions): Plugin {
return;
}
if (url.pathname === "/__studio/library") {
+ const section = url.searchParams.get("section");
+ if (section !== "tasks" && section !== "artifacts") {
+ json(response, 400, { error: "Choose tasks or artifacts with the section parameter" });
+ return;
+ }
+ const media = url.searchParams.get("media") ?? undefined;
+ if (media !== undefined && media !== "image" && media !== "video" && media !== "audio") {
+ json(response, 400, { error: "Choose image, video or audio with the media parameter" });
+ return;
+ }
const before = url.searchParams.get("before") ?? undefined;
- void readLibrary(before).then(
+ const run = url.searchParams.get("run") ?? undefined;
+ const build = url.searchParams.get("build") ?? undefined;
+ void readLibrary({ section, ...(media === undefined ? {} : { media }), ...(before === undefined ? {} : { before }),
+ ...(run === undefined ? {} : { run }), ...(build === undefined ? {} : { build }) }).then(
(view) => json(response, 200, view),
(error) => json(response, 500, { error: error instanceof Error ? error.message : String(error) }),
);
@@ -662,13 +698,12 @@ export function studioPlugin(options: StudioPluginOptions): Plugin {
void (async () => {
const build = url.searchParams.get("build");
const output = url.searchParams.get("output");
- const valuePath = url.searchParams.get("path");
- if (build === null || output === null || valuePath === null || options.buildLibrary === undefined) {
+ if (build === null || output === null || options.buildLibrary === undefined) {
response.statusCode = 404;
response.end();
return;
}
- const artifact = await options.buildLibrary.openArtifact(build, output, valuePath);
+ const artifact = await options.buildLibrary.openArtifact(build, output);
if (artifact === undefined) {
response.statusCode = 404;
response.end();
diff --git a/packages/studio/src/shared.ts b/packages/studio/src/shared.ts
index d3c8f3d8..3148c6d8 100644
--- a/packages/studio/src/shared.ts
+++ b/packages/studio/src/shared.ts
@@ -190,12 +190,14 @@ export type StudioTaskView = {
readonly note?: string;
readonly highlightedOutputs?: readonly string[];
readonly createdAt: number;
- readonly status: "queued" | "running" | "waiting" | "complete" | "failed" | "cancelled" | "active" | "blocked" | "unknown";
+ readonly finishedAt?: number;
+ readonly ongoing: boolean;
+ readonly status: "queued" | "running" | "waiting" | "complete" | "failed" | "cancelled" | "saving-result" | "attention";
+ readonly detail?: string;
+ readonly requests?: { readonly total: number; readonly completed: number };
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;
@@ -206,7 +208,10 @@ export type StudioTaskView = {
};
export type StudioArtifactView = {
- /** Build-qualified identity derived from the public Output and its value path. */
+ readonly nameEditable?: boolean;
+ /** Author-provided display name; the Output identifier remains unchanged. */
+ readonly displayName?: string;
+ /** File-owner identity; references to the same file share one card. */
readonly id: string;
readonly build: string;
readonly createdAt: number;
@@ -214,18 +219,27 @@ export type StudioArtifactView = {
readonly highlighted: boolean;
readonly buildTitle?: string;
readonly buildNote?: string;
- readonly valuePath: string;
- readonly ownerBuild: string;
+ readonly ownerBuild?: string;
readonly ownerOutput: string;
readonly filePath: string;
readonly size: number;
readonly mediaType: string;
readonly source: string;
readonly run?: string;
+ readonly origins: readonly { readonly build: string; readonly output: string; readonly run?: string; readonly source: string }[];
+};
+
+export type StudioLibraryRequest = {
+ readonly media?: "image" | "video" | "audio";
+ readonly section: "tasks" | "artifacts";
+ readonly before?: string;
+ readonly run?: string;
+ readonly build?: string;
};
/** Read-only view of the Runtime context selected for this Studio environment. */
export type StudioLibraryView = {
+ readonly section: StudioLibraryRequest["section"];
readonly environment: string;
readonly runtime?: string;
/** Cursor for the next older page of immutable Build Results. */
diff --git a/packages/studio/src/style.css b/packages/studio/src/style.css
index 16cdba00..4a23f808 100644
--- a/packages/studio/src/style.css
+++ b/packages/studio/src/style.css
@@ -51,8 +51,8 @@
--tone-neutral: #6a737c;
--tone-neutral-rail: #aeb9c4;
--timeline-label-width: 188px;
- --source-width: 350px;
- --workspace-width: 300px;
+ --source-width: 416px;
+ --workspace-width: 320px;
--timeline-height: 390px;
--timeline-item-radius: 2px;
--timeline-selection-stroke: 1px;
@@ -261,33 +261,10 @@ button:focus-visible, textarea:focus-visible {
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: 16px; height: 16px; flex: none; }
+.library .icon { width: 14px; height: 14px; }
.library-tab > strong { overflow: hidden; font-size: 12px; font-weight: 500; text-overflow: ellipsis; white-space: nowrap; }
.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;
@@ -306,7 +283,7 @@ button:focus-visible, textarea:focus-visible {
.library.is-refreshing .library-refresh .icon { animation: library-spin 700ms linear infinite; }
@keyframes library-spin { to { transform: rotate(360deg); } }
-.source-workspace {
+.sidebar-panel {
flex: 1;
min-width: 0;
min-height: 0;
@@ -314,20 +291,20 @@ button:focus-visible, textarea:focus-visible {
grid-template-columns: 44px minmax(0, 1fr);
grid-template-rows: 36px minmax(0, 1fr);
}
-.source-sidebar-heading,
-.source-code-heading {
+.sidebar-panel-heading,
+.sidebar-panel-toolbar {
min-width: 0;
display: flex;
align-items: center;
border-bottom: 1px solid var(--line);
background: #151619;
}
-.source-sidebar-heading { justify-content: center; border-right: 1px solid var(--line); }
-.source-sidebar-mark { width: 28px; height: 28px; display: grid; place-items: center; color: var(--text-3); }
-.source-sidebar-mark .icon { width: 14px; height: 14px; }
-.source-code-heading { padding: 0 7px 0 10px; }
-.source-code-heading .code-toolbar { width: 100%; }
-.source-files {
+.sidebar-panel-heading { justify-content: center; border-right: 1px solid var(--line); }
+.sidebar-panel-mark { width: 28px; height: 28px; display: grid; place-items: center; color: var(--text-3); }
+.sidebar-panel-mark .icon { width: 14px; height: 14px; }
+.sidebar-panel-toolbar { padding: 0 7px 0 10px; }
+.sidebar-panel-toolbar .code-toolbar { width: 100%; }
+.sidebar-panel-nav {
min-width: 0;
min-height: 0;
overflow-y: auto;
@@ -337,14 +314,12 @@ button:focus-visible, textarea:focus-visible {
background: #121316;
scrollbar-width: none;
}
-.source-files::-webkit-scrollbar { width: 0; }
-.source-file {
+.sidebar-panel-nav::-webkit-scrollbar { width: 0; }
+.sidebar-panel-item {
width: 32px;
height: 32px;
display: grid;
- grid-template-columns: 16px;
- justify-content: center;
- align-items: center;
+ place-items: center;
margin: 0 auto 2px;
padding: 0;
border: 0;
@@ -354,105 +329,89 @@ button:focus-visible, textarea:focus-visible {
text-align: left;
transition: color 100ms ease;
}
-.source-file:hover { color: #bfc2c9; }
-.source-file.active {
+.sidebar-panel-item:hover { color: #bfc2c9; }
+.sidebar-panel-item.active {
background: #181a1f;
color: #cfd2d8;
}
-.source-file-icon { width: 16px; height: 16px; display: grid; place-items: center; color: #858a93; }
-.source-file.active .source-file-icon { color: #858a93; }
-.source-file-icon .icon { width: 14px; height: 14px; }
+.sidebar-panel-item .icon { width: 14px; height: 14px; }
+.sidebar-panel-content { min-width: 0; min-height: 0; display: flex; flex-direction: column; overflow: hidden; }
+.sidebar-panel-toolbar { justify-content: space-between; gap: 8px; }
+.media-status { padding: 8px 10px; color: #e58b92; font-size: 10px; }
.source-code { min-width: 0; min-height: 0; overflow: hidden; }
.source-code > .code { height: 100%; }
.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, .task-blocked .task-state span { background: #d8646d; box-shadow: 0 0 0 3px rgba(216, 100, 109, .1); }
+.task-list { flex: 1; min-height: 0; overflow: auto; padding: 12px 10px 28px; background: #121316; }
+.task-card { min-width: 0; display: grid; grid-template-columns: 24px minmax(0, 1fr) 20px; align-items: start; gap: 9px; margin-bottom: 8px; padding: 11px 9px; border: 1px solid #25272c; border-radius: 4px; background: #191b20; }
+.task-state { display: grid; place-items: center; width: 24px; height: 24px; color: #858c98; }
+.task-state .icon { width: 17px; height: 17px; }
.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, .task-blocked .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; }
+.task-title { min-width: 0; }
+.task-name { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; max-width: 100%; overflow: hidden; padding: 0; border: 0; background: none; color: #dfe1e5; font: 500 11px/17px var(--font-ui); text-align: left; overflow-wrap: anywhere; cursor: pointer; }
+.task-name:hover { color: #fff; }
+.task-name:focus-visible { outline: 1px solid #626875; outline-offset: 2px; border-radius: 2px; }
+.task-facts { min-width: 0; display: flex; flex-wrap: wrap; align-items: center; gap: 3px 10px; margin-top: 5px; line-height: 14px; }
+.task-status { color: #949aa5; font-size: 10px; }
+.task-facts time { color: #727985; font-size: 9px; }
+.task-running .task-state, .task-running .task-status, .task-queued .task-state, .task-queued .task-status, .task-waiting .task-state, .task-waiting .task-status, .task-saving-result .task-state, .task-saving-result .task-status { color: #8daabb; }
+.task-complete .task-state, .task-complete .task-status { color: #87a896; }
+.task-failed .task-state, .task-failed .task-status, .task-attention .task-state, .task-attention .task-status { color: #c99490; }
+.task-progress { margin-top: 7px; overflow: hidden; color: #9ba1ac; font-size: 10px; line-height: 15px; white-space: nowrap; text-overflow: ellipsis; }
+.task-detail { margin-top: 7px; color: #bc9693; font-size: 10px; line-height: 15px; }
+.task-error-message { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; overflow: hidden; overflow-wrap: anywhere; white-space: pre-wrap; user-select: text; }
+.task-card.selected { background: #24272d; }
+.task-card.selected .task-error-message { display: block; }
+.task-copy-error { display: none; margin-top: 6px; padding: 0; border: 0; background: transparent; color: #aeb4bf; font: inherit; cursor: pointer; }
+.task-card.selected .task-copy-error { display: inline-block; }
+.task-card:focus-visible { outline: 1px solid #626875; outline-offset: -1px; }
+.task-context { flex: 1; min-width: 0; display: flex; align-items: center; gap: 3px; color: #b9bfca; }
+.task-context::before { content: "/"; flex: none; color: #5d6572; margin-right: 3px; }
+.sidebar-panel-toolbar > .library-refresh { margin-left: auto; }
+.sidebar-panel-toolbar:has(.task-context:not([hidden])) > .code-location { flex: none; max-width: 90px; }
+.task-context[hidden] { display: none; }
+.task-context-name { flex: 1; min-width: 0; display: flex; align-items: center; gap: 6px; padding: 3px 0; border: 0; background: transparent; color: inherit; font: 500 10px/16px var(--font-ui); text-align: left; }
+.task-context-name .icon { flex: none; }
+.task-context-name span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.task-context-clear { flex: none; display: grid; place-items: center; width: 22px; height: 22px; padding: 0; border: 0; border-radius: 3px; background: transparent; color: #929aa7; }
+.task-context-clear:hover, .task-context-name:hover { color: #f1f2f5; }
+.task-context-clear:hover { background: #30343c; }
+.task-context button:focus-visible { outline: 1px solid #626875; }
+.task-open { display: grid; place-items: center; width: 20px; height: 24px; padding: 0; border: 0; border-radius: 3px; background: transparent; color: #707885; }
+.task-open .icon { width: 14px; height: 14px; }
+.task-open:hover { color: #dfe1e5; background: #25282f; }
+.task-open:focus-visible { outline: 1px solid #626875; }
-.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 { height: 190px; min-width: 0; overflow: hidden; display: flex; flex-direction: column; 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.artifact-highlighted { border-color: rgba(237, 152, 185, .55); box-shadow: 0 0 0 1px rgba(237, 152, 185, .08), 0 9px 22px rgba(0, 0, 0, .14); }
-.artifact-card:hover { border-color: #454952; transform: translateY(-2px); box-shadow: 0 10px 22px rgba(0, 0, 0, .17); }
-.artifact-preview { position: relative; flex: 1 1 auto; min-height: 0; 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-highlight { position: absolute; z-index: 2; left: 6px; top: 6px; padding: 3px 6px; border-radius: 4px; background: rgba(77, 38, 55, .82); color: #f1abc5; font: 600 8px/1 var(--font-ui); letter-spacing: .02em; }
-.artifact-copy { min-width: 0; flex: none; min-height: 45px; 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; }
+.artifact-grid { flex: 1; min-height: 0; overflow: auto; display: grid; grid-template-columns: repeat(auto-fill, 104px); align-content: start; justify-content: space-between; gap: 12px; padding: 14px 12px 30px; background: #121316; }
+.artifact-card { --artifact-selection: #24272d; min-width: 0; padding: 0; border: 0; border-radius: 3px; display: flex; flex-direction: column; color: inherit; text-decoration: none; }
+.artifact-card:focus-visible { outline: none; }
+.artifact-card:focus-visible .artifact-preview { outline: 1px solid #656b79; outline-offset: 2px; border-radius: 3px; }
+.artifact-preview { position: relative; flex: none; min-height: 0; width: 100%; aspect-ratio: 1; display: flex; align-items: center; justify-content: center; }
+.artifact-preview img, .artifact-preview video { position: absolute; display: block; max-width: 100%; max-height: 100%; width: auto; height: auto; border-radius: 2px; object-fit: contain; }
+.artifact-video .artifact-preview video { opacity: 0; pointer-events: none; }
+.artifact-video .artifact-preview video.is-ready { opacity: 1; }
+.artifact-glyph { display: none; }
+.artifact-audio .artifact-glyph { display: grid; position: absolute; place-items: center; width: 100%; height: 42px; color: #87a896; background: #202824; border-radius: 2px; }
+.artifact-audio .artifact-waveform { display: block; visibility: hidden; width: 100%; height: 42px; padding: 8px 4px; background: #202824; }
+.artifact-audio .artifact-waveform.is-ready { visibility: visible; }
+.artifact-waveform.is-ready ~ .artifact-glyph { display: none; }
+.artifact-type { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); }
+.artifact-copy { min-width: 0; height: 44px; padding-top: 6px; text-align: center; }
+.artifact-name, .artifact-name-editor { box-sizing: border-box; width: 100%; margin: 0; padding: 0 4px; border: 1px solid transparent; border-radius: 3px; color: #d8dae0; background: transparent; font: 500 11px/18px var(--font-ui); text-align: center; word-break: break-all; overflow-wrap: anywhere; }
+.artifact-name { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; max-height: 38px; overflow: hidden; white-space: normal; cursor: text; }
+.artifact-name-text { padding: 1px 2px; border-radius: 3px; -webkit-box-decoration-break: clone; box-decoration-break: clone; }
+.artifact-name:focus-visible { outline: none; box-shadow: inset 0 0 0 1px #626875; }
+.artifact-name[hidden] { display: none; }
+.artifact-copy.editing { height: auto; min-height: 44px; }
+.artifact-name-editor { display: block; min-height: 20px; resize: none; overflow: hidden; outline: none; color: #f1f2f5; box-shadow: inset 0 0 0 1px #626875; }
+.artifact-name-editor:focus-visible { outline: none; box-shadow: inset 0 0 0 1px #626875; }
+.artifact-name-editor::selection { color: #fff; background: #4b5263; }
+.artifact-name-error { display: block; color: #bd9c92; font-size: 9px; line-height: 13px; overflow-wrap: anywhere; }
.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; }
-.library-older {
- grid-column: 1 / -1;
- width: 100%;
- min-height: 32px;
- margin-top: 3px;
- border: 1px solid #292c31;
- border-radius: 6px;
- background: #191a1e;
- color: #858a93;
- font-size: 9px;
-}
-.library-older:hover { border-color: #3a3d44; background: #202227; color: #d1d4da; }
.code { --code-inline-end: 12px; flex: 1; min-width: 0; min-height: 0; display: flex; flex-direction: column; }
.code-toolbar { min-width: 0; display: flex; align-items: center; justify-content: space-between; gap: 8px; }
@@ -945,6 +904,7 @@ button:focus-visible, textarea:focus-visible {
font-variant-numeric: tabular-nums;
letter-spacing: .01em;
}
+.timeline { --timeline-ruler-height: 22px; }
.timeline-body {
flex: 1;
min-height: 0;
@@ -969,7 +929,7 @@ button:focus-visible, textarea:focus-visible {
position: sticky;
top: 0;
z-index: 10;
- height: 22px;
+ height: var(--timeline-ruler-height);
display: flex;
align-items: center;
justify-content: flex-end;
@@ -1014,8 +974,6 @@ button:focus-visible, textarea:focus-visible {
text-align: left;
}
.track-copy strong { color: #cfd2d8; font-size: 11px; font-weight: 500; line-height: 18px; }
-.track-label-has-state { grid-template-columns: 18px minmax(0, 1fr) 18px; }
-.track-state { display: grid; place-items: center; }
.track-attachment-mark {
position: relative;
width: 18px;
@@ -1056,7 +1014,7 @@ button:focus-visible, textarea:focus-visible {
position: sticky;
top: 0;
z-index: 9;
- height: 22px;
+ height: var(--timeline-ruler-height);
overflow: hidden;
border-bottom: 1px solid var(--line);
background: #111216;
@@ -1102,8 +1060,8 @@ button:focus-visible, textarea:focus-visible {
}
.tick-last { padding-right: 4px; padding-left: 0; border-right: 1px solid #45484e; border-left: 0; transform: translateX(-100%); }
.lanes { min-height: 0; cursor: default; }
-.lane { position: relative; min-height: 0; overflow: hidden; border-bottom: 1px solid #191b1f; background: var(--lane); }
-.semantic-lane { min-height: 0; background: var(--lane); }
+.lane { position: relative; isolation: isolate; min-height: 0; overflow: hidden; border-bottom: 1px solid #191b1f; background: var(--lane); }
+.semantic-lane { position: sticky; top: var(--timeline-ruler-height); z-index: 8; min-height: 0; border-bottom: 1px solid var(--line); background: var(--lane); }
.semantic-band {
position: absolute;
right: 0;
@@ -1208,21 +1166,11 @@ button:focus-visible, textarea:focus-visible {
background: var(--semantic-intent);
}
.semantic-moment:focus-visible { outline: 0; }
+.track-label-semantic { position: sticky; top: var(--timeline-ruler-height); z-index: 8; border-bottom: 1px solid var(--line); background: #111216; }
.track-label-semantic::before {
border-radius: 0;
background: #181a1f;
}
-.track-fold {
- min-width: 17px;
- height: 17px;
- padding: 0 3px;
- border: 0;
- border-radius: 3px;
- background: #24262a;
- color: #92969e;
- font-size: 11px;
- line-height: 17px;
-}
.track-label-attached {
/* The branch marker occupies the same 18px prefix as a root icon;
attached and root labels therefore share one exact text column. */
@@ -1231,6 +1179,7 @@ button:focus-visible, textarea:focus-visible {
}
.track-label-attached::before { inset: var(--timeline-item-inset-y) 6px; background: #181a1f; }
.clip {
+ z-index: 0;
--track: var(--visual);
--item-head: color-mix(in srgb, var(--track) 58%, var(--lane));
--item-body: color-mix(in srgb, var(--track) 20%, var(--lane));
@@ -1274,7 +1223,7 @@ button:focus-visible, textarea:focus-visible {
cursor: ew-resize !important;
}
.clip.selected {
- z-index: 4;
+ z-index: 1;
overflow: visible;
box-shadow: none;
color: #fff;
@@ -1520,6 +1469,34 @@ button:focus-visible, textarea:focus-visible {
@media (max-width: 920px) {
.meta, .topbar-right { display: none; }
.topbar { grid-template-columns: 1fr minmax(120px, 1fr); }
- .upper-shell { grid-template-columns: minmax(280px, var(--source-width)) 8px minmax(300px, 1fr); }
+ .upper-shell { grid-template-columns: minmax(320px, var(--source-width)) 8px minmax(300px, 1fr); }
.workspace-handle, .workspace-panel { display: none; }
}
+
+
+/* The same transport serves the composition and selected Result media. */
+.stage-transport { display: flex; align-items: center; gap: 2px; }
+.stage-bar button[hidden], .stage-transport[hidden], .stage-artifact[hidden], .stage-scaler[hidden] { display: none; }
+.stage-bar .stage-mute { position: absolute; right: 12px; margin: 0; }
+.stage-time { position: absolute; left: 12px; color: #969ba5; font: 10px var(--font-mono); }
+.stage-title { min-width: 0; }
+.stage-title strong { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.stage-return { flex: none; margin-left: auto; border: 0; background: transparent; color: #aeb3bd; font: 10px var(--font-ui); cursor: pointer; }
+.stage-return[hidden] { display: none; }
+.stage-artifact { position: relative; display: flex; align-items: center; justify-content: center; width: 100%; height: 100%; min-height: 0; }
+.stage-artifact > img, .stage-artifact > video { max-width: 100%; max-height: 100%; width: auto; height: auto; object-fit: contain; }
+.stage-artifact audio { display: none; }
+.stage-audio-wave { width: 85%; padding: 24px 12px; border-radius: 2px; color: #b5c2bb; background: #202824; text-align: center; }
+.stage-audio-wave img { display: block; width: 100%; height: 100px; }
+.stage-media-error { position: absolute; bottom: 12px; padding: 8px; background: #24262b; color: #cacdd4; font-size: 11px; }
+.stage-scrubber { flex: none; width: 100%; height: 10px; padding: 0; margin: -5px 0; z-index: 2; appearance: none; background: transparent; cursor: pointer; }
+.stage-scrubber::-webkit-slider-runnable-track { height: 2px; background: #676c75; }
+.stage-scrubber::-webkit-slider-thumb { appearance: none; width: 8px; height: 8px; border-radius: 50%; margin-top: -3px; background: #e1e4e9; }
+.stage-scrubber::-moz-range-track { height: 2px; background: #676c75; }
+.stage-scrubber::-moz-range-thumb { width: 8px; height: 8px; border: 0; background: #e1e4e9; }
+
+.preview-unavailable .artifact-type { position: static; width: auto; height: auto; clip-path: none; color: #9298a2; font-size: 10px; }
+
+.artifact-card.selected .artifact-preview { background: var(--artifact-selection); border-radius: 3px; }
+.artifact-card.selected .artifact-name-text { color: #f1f2f5; background: var(--artifact-selection); }
+.library-continuation { grid-column: 1 / -1; height: 28px; display: grid; place-items: center; color: #777e89; font-size: 10px; }
diff --git a/packages/studio/src/ui/artifact-name.ts b/packages/studio/src/ui/artifact-name.ts
new file mode 100644
index 00000000..5d12ece7
--- /dev/null
+++ b/packages/studio/src/ui/artifact-name.ts
@@ -0,0 +1,80 @@
+/** Two-line label with an expanding editor; the caller owns persistence. */
+export function createArtifactName(options: {
+ readonly name: string;
+ readonly editable: boolean;
+ readonly select: () => void;
+ readonly save: (name: string) => Promise<string>;
+}) {
+ const element = document.createElement("div");
+ element.className = "artifact-copy";
+ const label = document.createElement("button");
+ label.type = "button";
+ label.className = "artifact-name";
+ let name = options.name;
+ const text = document.createElement("span");
+ text.className = "artifact-name-text";
+ text.textContent = name;
+ label.append(text);
+ label.title = options.editable ? `${name}\nDouble-click or press F2 to rename` : `${name}\nNaming is available when this Build finishes`;
+ element.append(label);
+ label.addEventListener("click", (event) => { event.stopPropagation(); options.select(); });
+ let editing = false;
+
+ function edit(): void {
+ if (editing || !options.editable) return;
+ options.select();
+ editing = true;
+ element.classList.add("editing");
+ label.hidden = true;
+ const field = document.createElement("textarea");
+ field.className = "artifact-name-editor";
+ field.value = name;
+ field.rows = 1;
+ field.setAttribute("aria-label", "Display name");
+ const error = document.createElement("span");
+ error.className = "artifact-name-error";
+ error.setAttribute("role", "status");
+ element.append(field, error);
+ const resize = () => { field.style.height = "0px"; field.style.height = `${field.scrollHeight + field.offsetHeight - field.clientHeight}px`; };
+ resize();
+ field.focus();
+ field.setSelectionRange(name.length, name.length);
+ field.addEventListener("input", resize);
+ field.addEventListener("click", (event) => event.stopPropagation());
+ let saving = false;
+ const close = () => {
+ editing = false;
+ field.remove();
+ error.remove();
+ label.hidden = false;
+ element.classList.remove("editing");
+ };
+ const save = async () => {
+ if (!editing || saving) return;
+ const value = field.value.trim();
+ if (value === name) { close(); return; }
+ if (value.length === 0) { error.textContent = "Enter a name."; return; }
+ saving = true;
+ field.readOnly = true;
+ error.textContent = "Saving…";
+ try {
+ name = await options.save(value);
+ text.textContent = name;
+ label.title = `${name}\nDouble-click or press F2 to rename`;
+ close();
+ } catch (cause) {
+ error.textContent = cause instanceof Error ? cause.message : String(cause);
+ } finally {
+ saving = false;
+ field.readOnly = false;
+ }
+ };
+ field.addEventListener("blur", () => { void save(); });
+ field.addEventListener("keydown", (event) => {
+ if (event.key === "Escape" && !saving) { event.preventDefault(); event.stopPropagation(); close(); label.focus(); }
+ else if (event.key === "Enter" && !event.shiftKey) { event.preventDefault(); void save(); }
+ });
+ }
+ label.addEventListener("dblclick", (event) => { event.preventDefault(); event.stopPropagation(); edit(); });
+ return { element, edit };
+}
diff --git a/packages/studio/src/ui/artifact-preview.ts b/packages/studio/src/ui/artifact-preview.ts
new file mode 100644
index 00000000..4fcff89e
--- /dev/null
+++ b/packages/studio/src/ui/artifact-preview.ts
@@ -0,0 +1,99 @@
+import type { StudioArtifactView } from "../shared.js";
+import { audioPreview } from "./material-preview.js";
+
+/** A media viewer only: it does not change the composition or its playhead. */
+export function createArtifactPreview(changed: () => void) {
+ const element = document.createElement("div");
+ element.className = "stage-artifact";
+ element.hidden = true;
+ let selected: StudioArtifactView | undefined;
+ let media: HTMLMediaElement | undefined;
+ let generation = 0;
+
+ function close(): void {
+ generation += 1;
+ selected = undefined;
+ if (media !== undefined) {
+ media.pause();
+ media.removeAttribute("src");
+ media.load();
+ }
+ media = undefined;
+ element.replaceChildren();
+ element.hidden = true;
+ }
+
+ function open(artifact: StudioArtifactView, muted: boolean): void {
+ close();
+ const current = generation;
+ selected = artifact;
+ element.hidden = false;
+ const url = `/__studio/artifact?${new URLSearchParams({ build: artifact.build, output: artifact.output })}`;
+ const error = document.createElement("p");
+ error.className = "stage-media-error";
+ error.hidden = true;
+ error.setAttribute("role", "status");
+ const failed = () => {
+ if (generation !== current) return;
+ error.textContent = "This media could not be opened in the browser.";
+ error.hidden = false;
+ changed();
+ };
+ if (artifact.mediaType.startsWith("image/")) {
+ const image = document.createElement("img");
+ image.alt = artifact.displayName ?? artifact.output;
+ image.addEventListener("error", failed);
+ image.src = url;
+ element.append(image);
+ } else {
+ const audio = artifact.mediaType.startsWith("audio/");
+ const player = document.createElement(audio ? "audio" : "video");
+ media = player;
+ if (player instanceof HTMLVideoElement) player.playsInline = true;
+ player.preload = "metadata";
+ player.muted = muted;
+ for (const event of ["loadedmetadata", "durationchange", "timeupdate", "play", "pause", "ended", "seeking", "seeked"]) {
+ player.addEventListener(event, () => { if (generation === current) changed(); });
+ }
+ player.addEventListener("error", failed);
+ player.src = url;
+ element.append(player);
+ if (audio) {
+ const wave = document.createElement("div");
+ wave.className = "stage-audio-wave";
+ wave.textContent = "Audio";
+ element.append(wave);
+ void audioPreview(url).then((waveform) => {
+ if (generation !== current || waveform === undefined) return;
+ const image = document.createElement("img");
+ image.src = waveform;
+ image.alt = "Audio waveform";
+ wave.replaceChildren(image);
+ });
+ }
+ }
+ element.append(error);
+ changed();
+ }
+
+ function seek(seconds: number): void {
+ if (media === undefined || !Number.isFinite(media.duration)) return;
+ media.currentTime = Math.max(0, Math.min(media.duration, seconds));
+ changed();
+ }
+
+ function toggle(): void {
+ const player = media;
+ if (player === undefined) return;
+ if (!player.paused) player.pause();
+ else {
+ if (player.ended) player.currentTime = 0;
+ void player.play().catch(() => changed());
+ }
+ }
+
+ return { element, open, close, seek, toggle,
+ get selected() { return selected; },
+ get media() { return media; },
+ };
+}
diff --git a/packages/studio/src/ui/icons.ts b/packages/studio/src/ui/icons.ts
index fa060a21..8f031a69 100644
--- a/packages/studio/src/ui/icons.ts
+++ b/packages/studio/src/ui/icons.ts
@@ -14,7 +14,6 @@ const paths: Readonly<Record<string, string>> = {
results: '<path d="M4 8v12h16V8M3 4h18v4H3zM9 12h6"/>',
run: '<circle cx="12" cy="12" r="9"/><path d="m10 8 6 4-6 4V8Z"/>',
image: '<rect x="3" y="4" width="18" height="16" rx="2"/><circle cx="8.5" cy="9" r="2"/><path d="m4 18 5-5 3 3 3-4 5 6"/>',
- sidebarCollapse: '<rect x="3" y="4" width="18" height="16" rx="2"/><path d="M8 4v16m7-11-3 3 3 3"/>',
wrap: '<path d="M4 6h16M4 10h12a4 4 0 0 1 0 8h-5m3-3-3 3 3 3M4 14h5M4 18h4"/>',
timeline: '<path d="M3 6h18M3 12h18M3 18h18"/><path d="M8 4v4M16 10v4M11 16v4"/>',
minus: '<path d="M5 12h14"/>',
@@ -40,6 +39,11 @@ const paths: Readonly<Record<string, string>> = {
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"/>',
+ check: '<circle cx="12" cy="12" r="9"/><path d="m8 12 3 3 5-6"/>',
+ alert: '<circle cx="12" cy="12" r="9"/><path d="M12 7v6M12 17h.01"/>',
+ arrowRight: '<path d="M5 12h14m-6-6 6 6-6 6"/>',
+ close: '<path d="m6 6 12 12M18 6 6 18"/>',
+ panel: '<rect x="3" y="4" width="18" height="16" rx="2"/><path d="M8 4v16M8 9h13"/>',
};
export function icon(name: string, className = "icon"): string {
diff --git a/packages/studio/src/ui/library.ts b/packages/studio/src/ui/library.ts
index e5c71b27..e4bc08b3 100644
--- a/packages/studio/src/ui/library.ts
+++ b/packages/studio/src/ui/library.ts
@@ -6,7 +6,11 @@ import type {
StudioTaskView,
} from "../shared.js";
import type { CodePane } from "./code.js";
+import { createArtifactName } from "./artifact-name.js";
+import { audioPreview } from "./material-preview.js";
+import { createSidebarPanel, sidebarItem } from "./sidebar-panel.js";
import { icon } from "./icons.js";
+import { mergeStudioArtifacts } from "../library-media.js";
type LibrarySection = "source" | "tasks" | "artifacts";
@@ -14,6 +18,7 @@ export type LibraryPane = {
readonly element: HTMLElement;
show(snapshot: StudioSnapshot): void;
refresh(): Promise<void>;
+ selectArtifact(id: string | undefined): void;
};
function leaf(path: string): string {
@@ -26,10 +31,6 @@ function stem(path: string): string {
return dot > 0 ? name.slice(0, dot) : name;
}
-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`;
@@ -55,7 +56,8 @@ function emptyState(iconName: string, title: string, detail: string): HTMLElemen
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 === undefined) return task.requests === undefined ? undefined
+ : `${task.requests.completed}/${task.requests.total} steps complete`;
if (progress.completed === undefined) return progress.phase;
const amount = progress.total === undefined
? String(progress.completed)
@@ -63,33 +65,60 @@ function taskProgress(task: StudioTaskView): string | undefined {
return `${progress.phase} · ${amount}${progress.unit === undefined ? "" : ` ${progress.unit}`}`;
}
-function taskCard(task: StudioTaskView): HTMLElement {
+function taskCard(task: StudioTaskView, selected: boolean, select: () => void, showMedia: () => void): HTMLElement {
const node = document.createElement("article");
- node.className = `task-card task-${task.status}`;
- const title = task.title ?? (task.targets.length === 0 ? leaf(task.run ?? task.source) : task.targets.join(", "));
- const progress = taskProgress(task);
+ node.className = `task-card task-${task.status}${selected ? " selected" : ""}`;
+ node.tabIndex = 0;
+ node.setAttribute("aria-label", task.title ?? stem(task.run ?? task.source));
+ node.addEventListener("click", select);
+ node.addEventListener("keydown", (event) => {
+ if (event.target === node && (event.key === "Enter" || event.key === " ")) { event.preventDefault(); select(); }
+ });
+ node.dataset.taskId = task.id;
+ const source = task.run ?? task.source;
+ const title = task.title ?? stem(source);
+ const statuses: Record<StudioTaskView["status"], string> = {
+ queued: "Queued", running: "Running", waiting: "Waiting", complete: "Completed",
+ failed: "Failed", cancelled: "Cancelled", "saving-result": "Saving", attention: "Needs attention",
+ };
node.innerHTML = `
- <div class="task-state"><span></span></div>
+ <div class="task-state" aria-hidden="true">${icon(task.ongoing ? "when" : task.status === "complete" ? "check" : task.status === "failed" ? "alert" : "tasks")}</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-title"><button type="button" class="task-name"></button></div>
+ <div class="task-facts"><span class="task-status"></span><time></time></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`;
+ <div class="task-detail" data-detail></div>
+ </div>
+ <button type="button" class="task-open" aria-label="View task media" title="View media">${icon("arrowRight")}</button>`;
+ const name = node.querySelector<HTMLButtonElement>(".task-name")!;
+ name.textContent = title;
+ name.addEventListener("click", (event) => { event.stopPropagation(); select(); });
+ node.querySelector<HTMLElement>(".task-status")!.textContent = statuses[task.status];
+ const time = node.querySelector("time")!;
+ time.dateTime = new Date(task.createdAt).toISOString();
+ time.textContent = date.format(task.createdAt);
+ const progress = task.ongoing ? taskProgress(task) : undefined;
const progressNode = node.querySelector<HTMLElement>("[data-progress]")!;
if (progress === undefined) progressNode.remove();
- else progressNode.textContent = progress;
- node.title = [title, task.id, source, task.note].filter((item) => item !== undefined).join("\n");
+ else { progressNode.textContent = progress; progressNode.title = progress; }
+ const detailNode = node.querySelector<HTMLElement>("[data-detail]")!;
+ if (task.detail === undefined) detailNode.remove();
+ else {
+ const message = document.createElement("div");
+ message.className = "task-error-message";
+ message.textContent = task.detail;
+ detailNode.append(message);
+ const copy = document.createElement("button");
+ copy.type = "button"; copy.className = "task-copy-error"; copy.textContent = "Copy error";
+ copy.addEventListener("click", (event) => {
+ event.stopPropagation();
+ void navigator.clipboard.writeText(task.detail!).then(() => { copy.textContent = "Copied"; }, () => { copy.textContent = "Select the text to copy"; });
+ });
+ detailNode.append(copy);
+ detailNode.addEventListener("click", (event) => { event.stopPropagation(); if (!node.classList.contains("selected")) select(); });
+ }
+ node.querySelector<HTMLButtonElement>(".task-open")!.addEventListener("click", (event) => { event.stopPropagation(); showMedia(); });
+ name.title = [title, source, task.id, task.note].filter((item) => item !== undefined).join("\n");
return node;
}
@@ -100,63 +129,115 @@ function artifactKind(mediaType: string): { readonly label: string; readonly ico
return { label: "Data", icon: "code" };
}
-function artifactCard(artifact: StudioArtifactView): HTMLElement {
+function sizeThumbnail(media: HTMLElement, width: number, height: number): void {
+ if (width <= 0 || height <= 0) return;
+ const longest = Math.max(width, height);
+ media.style.width = `${100 * width / longest}%`;
+ media.style.height = `${100 * height / longest}%`;
+}
+
+function artifactCard(artifact: StudioArtifactView, open: (artifact: StudioArtifactView) => void, renamed: (artifact: StudioArtifactView) => void): HTMLElement {
const kind = artifactKind(artifact.mediaType);
- const link = document.createElement("a");
+ const link = document.createElement("div");
+ link.tabIndex = 0;
link.className = `artifact-card artifact-${kind.label.toLowerCase()}${artifact.highlighted ? " artifact-highlighted" : ""}`;
const query = new URLSearchParams({
build: artifact.build,
output: artifact.output,
- path: artifact.valuePath,
});
- link.href = `/__studio/artifact?${query.toString()}`;
- link.target = "_blank";
- link.rel = "noreferrer";
- const title = artifact.valuePath === "$" ? artifact.output : `${artifact.output} ${artifact.valuePath}`;
+ const href = `/__studio/artifact?${query.toString()}`;
+
+ link.dataset.artifactId = artifact.id;
+ link.dataset.build = artifact.build;
+ link.dataset.output = artifact.output;
+ link.dataset.displayName = artifact.displayName ?? "";
+ link.dataset.nameEditable = String(artifact.nameEditable === true);
+ const title = artifact.displayName ?? artifact.output;
link.innerHTML = `
<div class="artifact-preview">
<span class="artifact-glyph">${icon(kind.icon)}</span>
<span class="artifact-type"></span>
- ${artifact.highlighted ? '<span class="artifact-highlight">Highlighted</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 = [
- artifact.buildTitle,
- formatBytes(artifact.size),
- date.format(artifact.createdAt),
- ].filter((item) => item !== undefined).join(" · ");
+ const preview = link.querySelector<HTMLElement>(".artifact-preview")!;
+ preview.setAttribute("role", "button");
+ preview.setAttribute("aria-label", `Preview ${title}`);
+ preview.addEventListener("click", () => open(artifact));
+ const name = createArtifactName({
+ name: title,
+ editable: artifact.nameEditable === true,
+ select: () => { if (!link.classList.contains("selected")) open(artifact); },
+ async save(displayName) {
+ const response = await fetch("/__studio/artifact-name", {
+ method: "PUT", headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ build: artifact.build, output: artifact.output, displayName }),
+ });
+ const result = await response.json() as { displayName?: string; error?: string };
+ if (!response.ok || typeof result.displayName !== "string") throw new Error(result.error ?? "Could not save the name");
+ artifact = { ...artifact, displayName: result.displayName };
+ link.dataset.displayName = result.displayName;
+ renamed(artifact);
+ preview.setAttribute("aria-label", `Preview ${result.displayName}`);
+ preview.title = [result.displayName, ...preview.title.split("\n").slice(1)].join("\n");
+ return result.displayName;
+ },
+ });
+ link.append(name.element);
+ link.addEventListener("keydown", (event) => {
+ if (event.target instanceof HTMLTextAreaElement) return;
+ if (event.key === "F2") { event.preventDefault(); name.edit(); }
+ else if (event.key === "Enter" && event.target === link) { event.preventDefault(); open(artifact); }
+ });
if (artifact.mediaType.startsWith("image/")) {
const image = document.createElement("img");
- image.src = link.href;
+ image.addEventListener("load", () => sizeThumbnail(image, image.naturalWidth, image.naturalHeight));
+ image.addEventListener("error", () => { link.classList.add("preview-unavailable"); link.querySelector<HTMLElement>(".artifact-type")!.textContent = "Preview unavailable"; });
+ image.src = href;
image.alt = "";
image.loading = "lazy";
link.querySelector<HTMLElement>(".artifact-preview")!.prepend(image);
+ } else if (artifact.mediaType.startsWith("video/")) {
+ const video = document.createElement("video");
+ video.preload = "none";
+ video.muted = true;
+ video.playsInline = true;
+ video.dataset.previewSource = href;
+ video.setAttribute("aria-hidden", "true");
+ const label = link.querySelector<HTMLElement>(".artifact-type")!;
+ label.textContent = "Video · Loading preview";
+ const ready = () => {
+ if (video.readyState < 2 || video.seeking) return;
+ video.classList.add("is-ready");
+ label.textContent = "Video";
+ };
+ video.addEventListener("loadedmetadata", () => {
+ sizeThumbnail(video, video.videoWidth, video.videoHeight);
+ video.currentTime = Number.isFinite(video.duration) ? Math.min(0.1, video.duration / 2) : 0.1;
+ }, { once: true });
+ video.addEventListener("loadeddata", ready);
+ video.addEventListener("seeked", ready);
+ video.addEventListener("error", () => { label.textContent = "Preview unavailable"; link.classList.add("preview-unavailable"); });
+ link.querySelector<HTMLElement>(".artifact-preview")!.prepend(video);
+ } else if (artifact.mediaType.startsWith("audio/")) {
+ const waveform = document.createElement("img");
+ waveform.className = "artifact-waveform";
+ waveform.alt = "";
+ waveform.dataset.audioSource = href;
+ link.querySelector<HTMLElement>(".artifact-preview")!.prepend(waveform);
}
- link.title = [
+ preview.title = [
title,
artifact.mediaType,
- `${artifact.ownerBuild}/${artifact.ownerOutput}/${artifact.filePath}`,
- artifact.run ?? artifact.source,
+ formatBytes(artifact.size),
+ date.format(artifact.createdAt),
+ artifact.ownerBuild === undefined ? artifact.filePath : `${artifact.ownerBuild}/${artifact.filePath}`,
+ ...artifact.origins.map((origin) => `${origin.run ?? origin.source} · ${origin.build} · ${origin.output}`),
artifact.buildNote,
].filter((item) => item !== undefined).join("\n");
return link;
}
-function olderButton(load: () => void): HTMLButtonElement {
- const button = document.createElement("button");
- button.type = "button";
- button.className = "library-older";
- button.textContent = "Load older";
- button.addEventListener("click", load);
- return button;
-}
-
-export function createLibraryPane(code: CodePane): LibraryPane {
+export function createLibraryPane(code: CodePane, openArtifact: (artifact: StudioArtifactView) => void, renamedArtifact: (artifact: StudioArtifactView) => void): LibraryPane {
const element = document.createElement("section");
element.className = "library";
element.innerHTML = `
@@ -172,46 +253,83 @@ export function createLibraryPane(code: CodePane): LibraryPane {
</button>
</div>
<section class="library-view active" data-library-view="source">
- <div class="source-workspace" data-source-workspace>
- <div class="source-sidebar-heading">
- <span class="source-sidebar-mark" aria-hidden="true">${icon("sidebarCollapse")}</span>
- </div>
- <div class="source-code-heading" data-source-toolbar></div>
- <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 Results</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="tasks"></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-toolbar]")!.append(code.toolbar);
- element.querySelector<HTMLElement>("[data-source-code]")!.append(code.element);
- const sourceList = element.querySelector<HTMLElement>("[data-source-files]")!;
+ const sourcePanel = createSidebarPanel("panel", "Referenced source files");
+ sourcePanel.toolbar.append(code.toolbar);
+ sourcePanel.content.classList.add("source-code");
+ sourcePanel.content.append(code.element);
+ element.querySelector('[data-library-view="source"]')!.append(sourcePanel.element);
+ const taskPanel = createSidebarPanel("panel", "Task categories");
+ taskPanel.toolbar.innerHTML = `<span class="code-location" data-task-heading>All tasks</span><div class="task-context" data-task-context hidden></div>
+ <button type="button" class="library-refresh" data-library-refresh aria-label="Refresh tasks" title="Refresh">${icon("refresh")}</button>`;
+ taskPanel.content.innerHTML = `<div class="media-status" data-library-status="tasks" role="status" hidden></div><div class="task-list" data-task-list></div>`;
+ element.querySelector('[data-library-view="tasks"]')!.append(taskPanel.element);
+ const mediaPanel = createSidebarPanel("panel", "Media categories");
+ mediaPanel.toolbar.innerHTML = `<span class="code-location" data-media-heading>All media</span><div class="task-context" data-task-context hidden></div>
+ <button type="button" class="library-refresh" data-library-refresh aria-label="Refresh media" title="Refresh">${icon("refresh")}</button>`;
+ mediaPanel.content.innerHTML = `<div class="media-status" data-library-status="artifacts" role="status" hidden></div><div class="artifact-grid" data-artifact-grid></div>`;
+ element.querySelector('[data-library-view="artifacts"]')!.append(mediaPanel.element);
+ const sourceList = sourcePanel.navigation;
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 artifactFilters = mediaPanel.navigation;
let snapshot: StudioSnapshot | undefined;
let selectedSource = "";
let active: LibrarySection = "source";
- let library: StudioLibraryView | undefined;
+ const libraries: Partial<Record<"tasks" | "artifacts", StudioLibraryView>> = {};
+ let taskFilter: "all" | "ongoing" | "finished" = "all";
let artifactFilter = "all";
- let refreshing = false;
- let expanded = false;
+ let selectedArtifact: string | undefined;
+ let selectedTask: StudioTaskView | undefined;
+ let request: AbortController | undefined;
+ const morePages = new IntersectionObserver((entries) => {
+ for (const entry of entries) {
+ const node = entry.target as HTMLElement;
+ const section = node.dataset.moreSection as "tasks" | "artifacts";
+ if (!entry.isIntersecting || request !== undefined || active !== section) continue;
+ morePages.unobserve(node);
+ void refresh(section, node.dataset.before);
+ }
+ }, { rootMargin: "0px 0px 120px 0px" });
+ const continuation = (section: "tasks" | "artifacts", cursor: string): HTMLElement => {
+ const node = document.createElement("div");
+ node.className = "library-continuation";
+ node.dataset.moreSection = section;
+ node.dataset.before = cursor;
+ node.textContent = "Loading more…";
+ return node;
+ };
+ const selectArtifact = (id: string | undefined): void => {
+ selectedArtifact = id;
+ for (const card of Array.from(artifactGrid.querySelectorAll<HTMLElement>("[data-artifact-id]"))) {
+ const selected = card.dataset.artifactId === id;
+ card.classList.toggle("selected", selected);
+ if (selected) card.setAttribute("aria-current", "true");
+ else card.removeAttribute("aria-current");
+ }
+ };
+ const videoPreviews = new IntersectionObserver((entries) => {
+ for (const entry of entries) {
+ if (!entry.isIntersecting) continue;
+ videoPreviews.unobserve(entry.target);
+ if (entry.target instanceof HTMLImageElement) {
+ const image = entry.target;
+ void audioPreview(image.dataset.audioSource!).then((url) => {
+ if (url === undefined || !image.isConnected) return;
+ image.src = url;
+ image.classList.add("is-ready");
+ });
+ continue;
+ }
+ const video = entry.target as HTMLVideoElement;
+ video.preload = "metadata";
+ video.src = video.dataset.previewSource!;
+ }
+ }, { root: artifactGrid });
const renderSources = (): void => {
if (snapshot === undefined) return;
@@ -224,75 +342,140 @@ export function createLibraryPane(code: CodePane): LibraryPane {
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" ? "run" : file.language === "svs" ? "tune" : "code")}</span>`;
- button.setAttribute("aria-label", `${stem(file.path)} ${file.language.toUpperCase()}`);
- button.title = `${file.role} · ${file.path}${file.imports.length === 0 ? "" : `\nimports ${file.imports.join(", ")}`}`;
- button.addEventListener("click", () => {
- selectedSource = file.path;
- renderSources();
+ const button = sidebarItem({
+ label: `${stem(file.path)} ${file.language.toUpperCase()}`,
+ icon: file.language === "svrun" ? "run" : file.language === "svs" ? "tune" : "code",
+ selected: file.path === selectedSource,
+ select: () => { selectedSource = file.path; renderSources(); },
});
+ button.title = `${file.role} · ${file.path}${file.imports.length === 0 ? "" : `\nimports ${file.imports.join(", ")}`}`;
return button;
}));
};
+ const renderTaskContext = (): void => {
+ for (const node of Array.from(element.querySelectorAll<HTMLElement>("[data-task-context]"))) {
+ const title = selectedTask === undefined ? undefined : selectedTask.title ?? stem(selectedTask.run ?? selectedTask.source);
+ if (selectedTask !== undefined && node.dataset.taskId === selectedTask.id
+ && node.querySelector(".task-context-name span")?.textContent === title) continue;
+ node.replaceChildren();
+ node.hidden = selectedTask === undefined;
+ node.dataset.taskId = selectedTask?.id ?? "";
+ if (selectedTask === undefined) continue;
+ const task = selectedTask;
+ const back = document.createElement("button");
+ back.type = "button"; back.className = "task-context-name";
+ back.innerHTML = "<span></span>";
+ back.querySelector("span")!.textContent = task.title ?? stem(task.run ?? task.source);
+ back.title = `${task.title ?? stem(task.run ?? task.source)} · Return to task`;
+ back.addEventListener("click", () => {
+ taskFilter = "all";
+ switchTo("tasks", false);
+ renderTasks();
+ taskList.querySelector<HTMLElement>(`[data-task-id="${CSS.escape(task.id)}"]`)?.scrollIntoView({ block: "nearest" });
+ });
+ const clear = document.createElement("button");
+ clear.type = "button"; clear.className = "task-context-clear";
+ clear.innerHTML = icon("close"); clear.title = "Clear task filter"; clear.setAttribute("aria-label", clear.title);
+ clear.addEventListener("click", () => {
+ selectedTask = undefined; delete libraries.artifacts; renderTaskContext(); renderTasks();
+ if (active === "artifacts") { renderArtifacts(); void refresh("artifacts"); }
+ });
+ node.append(back, clear);
+ }
+ };
+
const renderTasks = (): void => {
+ for (const node of Array.from(taskList.querySelectorAll("[data-more-section]"))) morePages.unobserve(node);
+ const library = libraries.tasks;
const tasks = library?.tasks ?? [];
- const runtime = library?.runtime;
- 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);
- const entries: HTMLElement[] = tasks.map(taskCard);
- if (tasks.length === 0) {
- entries.push(emptyState("tasks",
- 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."));
- }
- if (library?.next !== undefined) entries.push(olderButton(() => void loadOlder()));
+ const filters = [["all", "All tasks", "component"], ["ongoing", "In progress", "when"], ["finished", "Finished", "check"]] as const;
+ const heading = taskPanel.toolbar.querySelector<HTMLElement>("[data-task-heading]")!;
+ heading.textContent = filters.find(([id]) => id === taskFilter)![1];
+ heading.title = library?.runtime === undefined ? "Saved project Results · no Runtime selected" : library.runtime;
+ taskPanel.navigation.replaceChildren(...filters.map(([id, label, mark]) => sidebarItem({
+ label, icon: mark, selected: id === taskFilter,
+ select: () => { taskFilter = id; taskList.scrollTop = 0; renderTasks(); },
+ })));
+ const tasksToShow = tasks.filter((task) => taskFilter === "all" || task.ongoing === (taskFilter === "ongoing"))
+ .sort((left, right) => Number(right.ongoing) - Number(left.ongoing) || right.createdAt - left.createdAt);
+ if (selectedTask !== undefined) selectedTask = tasks.find((task) => task.id === selectedTask!.id) ?? selectedTask;
+ const selectTask = (task: StudioTaskView): void => {
+ const changed = selectedTask?.id !== task.id;
+ selectedTask = task;
+ if (changed) delete libraries.artifacts;
+ renderTaskContext();
+ for (const card of Array.from(taskList.querySelectorAll<HTMLElement>("[data-task-id]"))) {
+ card.classList.toggle("selected", card.dataset.taskId === task.id);
+ }
+ };
+ const entries = tasksToShow.map((task) => taskCard(task, selectedTask?.id === task.id,
+ () => selectTask(task), () => { selectTask(task); switchTo("artifacts"); }));
+ renderTaskContext();
+ if (tasksToShow.length === 0) entries.push(emptyState("tasks",
+ library === undefined && request !== undefined ? "Loading tasks…" : taskFilter === "ongoing" ? "No tasks in progress" : "No tasks here",
+ taskFilter === "ongoing" && library?.runtime === undefined
+ ? "No Runtime is selected. Saved tasks are available under Finished."
+ : "Refresh to read the latest task status."));
+ // Runtime activity is returned in full on the first page. Older pages contain Results only.
+ if (taskFilter !== "ongoing" && library?.next !== undefined) entries.push(continuation("tasks", library.next));
taskList.replaceChildren(...entries);
+ for (const node of Array.from(taskList.querySelectorAll("[data-more-section]"))) morePages.observe(node);
};
const renderArtifacts = (): void => {
+ videoPreviews.disconnect();
+ for (const node of Array.from(artifactGrid.querySelectorAll("[data-more-section]"))) morePages.unobserve(node);
+ const cards = new Map(Array.from(artifactGrid.querySelectorAll<HTMLElement>("[data-artifact-id]"), (card) => [card.dataset.artifactId!, card]));
+ const library = libraries.artifacts;
const artifacts = library?.artifacts ?? [];
- element.querySelector<HTMLElement>("[data-artifact-count]")!.textContent = `${artifacts.length} public file${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
+ const filters = [["all", "All media", "component"], ["video", "Videos", "video"], ["image", "Images", "image"], ["audio", "Audio", "waveform"]] as const;
+ const heading = mediaPanel.toolbar.querySelector<HTMLElement>("[data-media-heading]")!;
+ heading.textContent = filters.find(([id]) => id === artifactFilter)?.[1] ?? "All media";
+ heading.title = "Media category";
+ renderTaskContext();
+ artifactFilters.replaceChildren(...filters.map(([id, label, mark]) => sidebarItem({
+ label, icon: mark, selected: id === artifactFilter,
+ select: () => {
+ artifactFilter = id;
+ delete libraries.artifacts;
+ artifactGrid.scrollTop = 0;
+ void refresh("artifacts");
+ renderArtifacts();
+ },
+ })));
+ const shown = artifactFilter === "all" ? artifacts
: artifacts.filter((artifact) => artifact.mediaType.startsWith(`${artifactFilter}/`));
- const entries: HTMLElement[] = shown.map(artifactCard);
- if (shown.length === 0) {
- entries.push(emptyState("results",
- artifacts.length === 0 ? "No accepted artifacts" : `No ${artifactFilter} artifacts`,
- "Public files appear here when a Build Result contains them."));
+ const entries: HTMLElement[] = shown.map((artifact) => {
+ const held = cards.get(artifact.id);
+ cards.delete(artifact.id);
+ if (held !== undefined && held.dataset.build === artifact.build && held.dataset.output === artifact.output
+ && held.dataset.displayName === (artifact.displayName ?? "") && held.dataset.nameEditable === String(artifact.nameEditable === true)) return held;
+ const previousVideo = held?.querySelector("video");
+ if (previousVideo != null) { previousVideo.removeAttribute("src"); previousVideo.load(); }
+ return artifactCard(artifact, openArtifact, (updated) => {
+ const current = libraries.artifacts;
+ if (current !== undefined) libraries.artifacts = { ...current,
+ artifacts: current.artifacts.map((item) => item.id === updated.id ? { ...item, displayName: updated.displayName! } : item),
+ };
+ renamedArtifact(updated);
+ });
+ });
+ for (const card of cards.values()) {
+ const video = card.querySelector("video");
+ if (video !== null) { video.removeAttribute("src"); video.load(); }
}
- if (library?.next !== undefined) entries.push(olderButton(() => void loadOlder()));
+ if (shown.length === 0) entries.push(emptyState("results",
+ library === undefined && request !== undefined ? "Loading media…" : artifactFilter === "all" ? "No media" : `No ${artifactFilter} files`,
+ "Images, videos and audio published as file Outputs appear here, including those from ongoing Builds."));
+ if (library?.next !== undefined) entries.push(continuation("artifacts", library.next));
artifactGrid.replaceChildren(...entries);
+ selectArtifact(selectedArtifact);
+ for (const preview of Array.from(artifactGrid.querySelectorAll("video:not([src]), [data-audio-source]:not(.is-ready)"))) videoPreviews.observe(preview);
+ for (const node of Array.from(artifactGrid.querySelectorAll("[data-more-section]"))) morePages.observe(node);
};
- const switchTo = (next: LibrarySection): void => {
+ const switchTo = (next: LibrarySection, reload = true): void => {
active = next;
for (const tab of Array.from(element.querySelectorAll<HTMLButtonElement>("[data-library-tab]"))) {
const selected = tab.dataset.libraryTab === next;
@@ -302,77 +485,75 @@ export function createLibraryPane(code: CodePane): LibraryPane {
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();
+ if (next === "artifacts") renderArtifacts();
+ if (next === "tasks") renderTasks();
+ if (next !== "source" && reload) void refresh(next);
+ else request?.abort();
};
- for (const tab of Array.from(element.querySelectorAll<HTMLButtonElement>("[data-library-tab]"))) {
- tab.addEventListener("click", () => switchTo(tab.dataset.libraryTab as LibrarySection));
- }
-
- const mergeLibrary = (value: StudioLibraryView, append: boolean): void => {
- if (library === undefined || (!append && !expanded)) {
- library = value;
- return;
- }
- const tasks = new Map(library.tasks.map((task) => [task.id, task]));
- const artifacts = new Map(library.artifacts.map((artifact) => [artifact.id, artifact]));
- for (const task of value.tasks) tasks.set(task.id, task);
- for (const artifact of value.artifacts) artifacts.set(artifact.id, artifact);
- library = {
- environment: value.environment,
- ...(value.runtime === undefined ? {} : { runtime: value.runtime }),
- ...((append || !expanded ? value.next : library.next) === undefined
- ? {}
- : { next: append || !expanded ? value.next : library.next }),
- tasks: [...tasks.values()].sort((left, right) => right.createdAt - left.createdAt || left.id.localeCompare(right.id)),
- artifacts: [...artifacts.values()].sort((left, right) =>
- Number(right.highlighted) - Number(left.highlighted)
- || right.createdAt - left.createdAt
- || left.output.localeCompare(right.output)
- || left.valuePath.localeCompare(right.valuePath)),
- };
- };
-
- const refresh = async (before?: string): Promise<void> => {
- if (refreshing) return;
- refreshing = true;
+ const refresh = async (section: "tasks" | "artifacts", before?: string): Promise<void> => {
+ if (before !== undefined && request !== undefined) return;
+ request?.abort();
+ const controller = new AbortController();
+ request = controller;
+ const status = element.querySelector<HTMLElement>(`[data-library-status="${section}"]`)!;
+ status.textContent = "Refreshing…";
+ status.hidden = true;
element.classList.add("is-refreshing");
try {
- const query = before === undefined ? "" : `?${new URLSearchParams({ before }).toString()}`;
- const response = await fetch(`/__studio/library${query}`);
+ const query = new URLSearchParams({ section });
+ if (before !== undefined) query.set("before", before);
+ if (section === "artifacts" && artifactFilter !== "all") query.set("media", artifactFilter);
+ if (section === "artifacts" && selectedTask !== undefined) query.set("build", selectedTask.id);
+ const response = await fetch(`/__studio/library?${query.toString()}`, { signal: controller.signal });
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");
- mergeLibrary(value, before !== undefined);
- if (before !== undefined) expanded = true;
- renderTasks();
- renderArtifacts();
+ if (controller.signal.aborted) return;
+ const previous = libraries[section];
+ if (before === undefined || previous === undefined) libraries[section] = value;
+ else {
+ const tasks = new Map(previous.tasks.map((task) => [task.id, task]));
+ for (const task of value.tasks) tasks.set(task.id, task);
+ libraries[section] = {
+ ...value,
+ tasks: [...tasks.values()].sort((left, right) => right.createdAt - left.createdAt || left.id.localeCompare(right.id)),
+ artifacts: mergeStudioArtifacts([...previous.artifacts, ...value.artifacts]),
+ };
+ }
+ if (section === "tasks") renderTasks();
+ else renderArtifacts();
+ status.textContent = `Updated ${new Date().toLocaleTimeString()}`;
} catch (error) {
- const detail = error instanceof Error ? error.message : String(error);
- if (active === "tasks") taskList.replaceChildren(emptyState("tasks", "Build Results unavailable", detail));
- if (active === "artifacts") artifactGrid.replaceChildren(emptyState("results", "Build Results unavailable", detail));
+ if (!controller.signal.aborted) {
+ const detail = error instanceof Error ? error.message : String(error);
+ status.hidden = false;
+ status.textContent = `Refresh failed: ${detail}${libraries[section] === undefined ? "" : " · Previous view retained"}`;
+ }
} finally {
- refreshing = false;
- element.classList.remove("is-refreshing");
+ if (request === controller) {
+ request = undefined;
+ element.classList.remove("is-refreshing");
+ if (controller.signal.aborted) status.textContent = "Refresh interrupted";
+ }
}
};
- const loadOlder = async (): Promise<void> => {
- if (library?.next !== undefined) await refresh(library.next);
- };
-
+ for (const tab of Array.from(element.querySelectorAll<HTMLButtonElement>("[data-library-tab]"))) {
+ tab.addEventListener("click", () => {
+ switchTo(tab.dataset.libraryTab as LibrarySection, tab.dataset.libraryTab !== "tasks" || libraries.tasks === undefined);
+ });
+ }
for (const button of Array.from(element.querySelectorAll<HTMLButtonElement>("[data-library-refresh]"))) {
- button.addEventListener("click", () => void refresh());
+ button.addEventListener("click", () => { if (active !== "source") void refresh(active); });
}
- window.setInterval(() => {
- if (document.visibilityState === "visible" && active !== "source") void refresh();
- }, 3_000);
return {
element,
+ selectArtifact,
show(value) {
snapshot = value;
renderSources();
},
- refresh,
+ refresh: async () => { if (active !== "source") await refresh(active); },
};
}
diff --git a/packages/studio/src/ui/main.ts b/packages/studio/src/ui/main.ts
index 6a77ec44..81beb63b 100644
--- a/packages/studio/src/ui/main.ts
+++ b/packages/studio/src/ui/main.ts
@@ -60,9 +60,9 @@ app.innerHTML = `
const store = createStore();
const code = createCodePane();
-const library = createLibraryPane(code);
+const stage = createStage(store, (id) => library.selectArtifact(id));
+const library = createLibraryPane(code, (artifact) => stage.openArtifact(artifact), (artifact) => stage.renameArtifact(artifact));
const timeline = createTimeline(store);
-const stage = createStage(store);
app.querySelector<HTMLElement>("[data-library]")!.append(library.element);
app.querySelector<HTMLElement>("[data-timeline]")!.append(timeline.element);
app.querySelector<HTMLElement>("[data-stage]")!.append(stage.element);
@@ -72,8 +72,9 @@ app.querySelector<HTMLElement>("[data-stage]")!.append(stage.element);
const shell = app.querySelector<HTMLElement>(".studio-shell")!;
const upperShell = app.querySelector<HTMLElement>(".upper-shell")!;
const workspacePanel = app.querySelector<HTMLElement>(".workspace-panel")!;
+const sidebarMinimum = 320;
const sourceHandle = createHandle({
- axis: "column", initial: Math.round(window.innerWidth * 0.34), minimum: 280,
+ axis: "column", initial: 416, minimum: sidebarMinimum,
maximum: () => Math.max(360, upperShell.clientWidth - 720),
apply: (size) => { upperShell.style.setProperty("--source-width", `${size}px`); },
remember: "hypit-studio.v3.source-width",
@@ -81,7 +82,7 @@ const sourceHandle = createHandle({
sourceHandle.classList.add("source-handle");
upperShell.insertBefore(sourceHandle, app.querySelector<HTMLElement>("[data-stage]")!);
const workspaceHandle = createHandle({
- axis: "column", initial: Math.round(window.innerWidth * 0.22), minimum: 270, invert: true,
+ axis: "column", initial: Math.round(window.innerWidth * 0.22), minimum: sidebarMinimum, invert: true,
maximum: () => Math.max(320, upperShell.clientWidth - 680),
apply: (size) => { upperShell.style.setProperty("--workspace-width", `${size}px`); },
remember: "hypit-studio.v3.workspace-width",
@@ -993,7 +994,6 @@ 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/material-preview.ts b/packages/studio/src/ui/material-preview.ts
index 864b2b99..a6b9b099 100644
--- a/packages/studio/src/ui/material-preview.ts
+++ b/packages/studio/src/ui/material-preview.ts
@@ -129,7 +129,7 @@ async function audioWaveform(url: string): Promise<string | undefined> {
}
}
-function audioPreview(url: string): Promise<string | undefined> {
+export function audioPreview(url: string): Promise<string | undefined> {
const held = generatedAudio.get(url);
if (held !== undefined) return held;
const pending = audioWaveform(url).catch(() => undefined).then((waveform) => {
diff --git a/packages/studio/src/ui/overlay.ts b/packages/studio/src/ui/overlay.ts
index d44eabdf..86d7ed3c 100644
--- a/packages/studio/src/ui/overlay.ts
+++ b/packages/studio/src/ui/overlay.ts
@@ -14,7 +14,7 @@ export type Box = {
readonly widthPx: number; readonly heightPx: number;
};
-export type Measure = (clipId: string) => Box | undefined;
+export type Measure = (clipId: string) => (Box & { readonly stackOrder: number }) | undefined;
export type Overlay = {
readonly element: SVGSVGElement;
@@ -62,21 +62,24 @@ export function createOverlay(store: Store, measure: Measure): Overlay {
element.setAttribute("class", "stage-overlay");
element.setAttribute("preserveAspectRatio", "none");
- let live: readonly Clip[] = [];
+ let entities: readonly Clip[] = [];
let canvas = { width: 1, height: 1 };
- let last: { snapshot: StudioSnapshot; selected: Clip | undefined; frame: number } | undefined;
+ let last: { snapshot: StudioSnapshot; selected: Clip | undefined } | undefined;
/**
* The box is measured off the picture rather than restated from the Source:
* motion moves an element across its span, so only what was drawn knows where
* it ended up. A Present that has not mounted has no box to draw.
*/
- const drawnBox = (clip: Clip): Box | undefined => {
- const ids = clip.presentId === undefined ? clip.renderIds : [clip.presentId];
- const boxes = ids.flatMap((id) => {
+ const drawnParts = (clip: Clip) => {
+ const ids = clip.renderIds.length > 0 ? clip.renderIds : clip.presentId === undefined ? [] : [clip.presentId];
+ return ids.flatMap((id) => {
const found = measure(id);
return found === undefined ? [] : [found];
});
+ };
+ const drawnBox = (clip: Clip): Box | undefined => {
+ const boxes = drawnParts(clip);
if (boxes.length === 0) return undefined;
const left = Math.min(...boxes.map((box) => box.xPx));
const top = Math.min(...boxes.map((box) => box.yPx));
@@ -87,23 +90,23 @@ export function createOverlay(store: Store, measure: Measure): Overlay {
const draw = (): void => {
if (last === undefined) return;
- const { snapshot, selected, frame } = last;
+ const { snapshot, selected } = last;
canvas = { width: snapshot.space.canvasWidth, height: snapshot.space.canvasHeight };
element.setAttribute("viewBox", `0 0 ${canvas.width} ${canvas.height}`);
element.replaceChildren();
- // Only clips actually on screen can be picked out of the picture.
- live = store.clipsAt(frame);
+ // An editing interval can end before its visual representation disappears.
+ // The renderer decides which associated parts are visible at this frame.
+ entities = snapshot.tracks.flatMap((track) => track.clips);
if (selected === undefined) return;
const tones = intentTones(snapshot);
const tone = tones.get(selected.authoredId);
- const onScreen = frame >= selected.startFrame && frame < selected.endFrameExclusive;
const box = drawnBox(selected);
// A Present that is not on screen at this frame was never drawn, so there
// is nothing to put a box around.
if (box === undefined) return;
const group = document.createElementNS(SVG_NS, "g");
- group.setAttribute("class", `box${onScreen ? "" : " box-elsewhere"}${tone === undefined ? "" : ` tone-${tone}`}`);
+ group.setAttribute("class", `box${tone === undefined ? "" : ` tone-${tone}`}`);
group.append(rect(box, "box-content"));
@@ -111,16 +114,15 @@ export function createOverlay(store: Store, measure: Measure): Overlay {
label.setAttribute("x", String(box.xPx + 10));
label.setAttribute("y", String(Math.max(28, box.yPx - 12)));
label.setAttribute("class", "box-label");
- label.textContent = onScreen ? selected.display.title : `${selected.display.title} (not at this frame)`;
+ label.textContent = selected.display.title;
group.append(label);
element.append(group);
};
- store.subscribe(({ snapshot, selection, playhead }) => {
+ store.subscribe(({ snapshot, selection }) => {
last = {
snapshot,
selected: selection.kind === "clip" ? store.clip(selection.clipId) : undefined,
- frame: playhead.frame,
};
draw();
});
@@ -133,12 +135,11 @@ export function createOverlay(store: Store, measure: Measure): Overlay {
if (box.width === 0 || box.height === 0) return undefined;
const x = (clientX - box.left) / box.width * canvas.width;
const y = (clientY - box.top) / box.height * canvas.height;
- // clipsAt already returns topmost first, so the first hit is the one an
- // author would say they clicked on.
- return live.find((clip) => {
- const box = drawnBox(clip);
- return box !== undefined && inside(box, x, y);
- });
+ // Hit individual parts, not the empty space inside a group's union box.
+ return entities.flatMap((clip) => drawnParts(clip)
+ .filter((part) => inside(part, x, y))
+ .map((part) => ({ clip, order: part.stackOrder })))
+ .sort((left, right) => right.order - left.order)[0]?.clip;
},
};
}
diff --git a/packages/studio/src/ui/sidebar-panel.ts b/packages/studio/src/ui/sidebar-panel.ts
new file mode 100644
index 00000000..347f7df0
--- /dev/null
+++ b/packages/studio/src/ui/sidebar-panel.ts
@@ -0,0 +1,31 @@
+import { icon } from "./icons.js";
+
+/** Shared chrome; each view owns its navigation choices, toolbar and content. */
+export function createSidebarPanel(mark: string, navigationLabel: string) {
+ const element = document.createElement("div");
+ element.className = "sidebar-panel";
+ element.innerHTML = `
+ <div class="sidebar-panel-heading"><span class="sidebar-panel-mark" aria-hidden="true">${icon(mark)}</span></div>
+ <div class="sidebar-panel-toolbar"></div>
+ <nav class="sidebar-panel-nav"></nav>
+ <div class="sidebar-panel-content"></div>`;
+ const navigation = element.querySelector<HTMLElement>("nav")!;
+ navigation.setAttribute("aria-label", navigationLabel);
+ return {
+ element, navigation,
+ toolbar: element.querySelector<HTMLElement>(".sidebar-panel-toolbar")!,
+ content: element.querySelector<HTMLElement>(".sidebar-panel-content")!,
+ };
+}
+
+export function sidebarItem(input: { label: string; icon: string; selected: boolean; select(): void }) {
+ const button = document.createElement("button");
+ button.type = "button";
+ button.className = `sidebar-panel-item${input.selected ? " active" : ""}`;
+ button.setAttribute("aria-label", input.label);
+ button.setAttribute("aria-pressed", String(input.selected));
+ button.title = input.label;
+ button.innerHTML = icon(input.icon);
+ button.addEventListener("click", input.select);
+ return button;
+}
diff --git a/packages/studio/src/ui/stage.ts b/packages/studio/src/ui/stage.ts
index 0962d458..fa125be1 100644
--- a/packages/studio/src/ui/stage.ts
+++ b/packages/studio/src/ui/stage.ts
@@ -1,4 +1,5 @@
-import type { StudioSnapshot } from "../shared.js";
+import { createArtifactPreview } from "./artifact-preview.js";
+import type { StudioArtifactView, StudioSnapshot } from "../shared.js";
import { createOverlay } from "./overlay.js";
import { icon, setIcon } from "./icons.js";
import type { State, Store } from "./selection.js";
@@ -7,6 +8,8 @@ export type Stage = {
readonly element: HTMLElement;
/** Start or stop playback, however the request arrived. */
toggle(): void;
+ openArtifact(artifact: StudioArtifactView): void;
+ renameArtifact(artifact: StudioArtifactView): void;
};
/**
@@ -17,19 +20,23 @@ export type Stage = {
* drives frames, not seconds, and lands on exactly the frame the renderer would
* photograph.
*/
-export function createStage(store: Store): Stage {
+export function createStage(store: Store, selectedArtifact: (id: string | undefined) => void): Stage {
const element = document.createElement("section");
element.className = "stage";
element.innerHTML = `
<div class="stage-heading">
<div class="stage-title">${icon("preview")}<strong>Preview</strong></div>
+ <button type="button" class="stage-return" hidden>Back to composition</button>
</div>
<div class="stage-viewport">
<div class="stage-scaler">
<iframe title="Preview" sandbox="allow-scripts allow-same-origin" allow="autoplay"></iframe>
</div>
</div>
+ <input class="stage-scrubber" type="range" min="0" max="0" value="0" step="0.01" aria-label="Media time" hidden>
<div class="stage-bar">
+ <span class="stage-time" hidden></span>
+ <div class="stage-transport">
<button type="button" data-previous aria-label="Previous frame" title="Previous frame">
${icon("previous")}
</button>
@@ -39,6 +46,7 @@ export function createStage(store: Store): Stage {
<button type="button" data-next aria-label="Next frame" title="Next frame">
${icon("next")}
</button>
+ </div>
<button type="button" data-mute aria-label="Mute" class="stage-mute">
<span data-mute-icon>${icon("volume")}</span>
</button>
@@ -57,17 +65,30 @@ export function createStage(store: Store): Stage {
* of its enter and exit, and selecting a clip lands the playhead on exactly
* the frame where that displacement is largest.
*/
- const measure = (clipId: string): { xPx: number; yPx: number; widthPx: number; heightPx: number } | undefined => {
+ const measure = (clipId: string): { xPx: number; yPx: number; widthPx: number; heightPx: number; stackOrder: number } | undefined => {
const document_ = iframe.contentDocument;
if (document_ === null) return undefined;
const present = document_.querySelector(`[data-hypit-present-id="${CSS.escape(clipId)}"]`);
+ if (present === null) return undefined;
+ const current = store.current();
+ if (current === undefined) return undefined;
+ const frameRate = fps(current.snapshot);
+ const start = Number(present.getAttribute("data-start"));
+ const end = start + Number(present.getAttribute("data-duration"));
+ if (current.playhead.frame < Math.round(start * frameRate)
+ || current.playhead.frame >= Math.round(end * frameRate)) return undefined;
// The present spans the whole canvas; the drawn box is its frame element.
const drawn = present?.querySelector(`[data-hypit-element-id="${CSS.escape(`${clipId}:frame`)}"]`)
?? present?.querySelector("[data-hypit-element-id]");
if (drawn === null || drawn === undefined) return undefined;
+ for (let ancestor: Element | null = drawn; ancestor !== null; ancestor = ancestor.parentElement) {
+ const style = document_.defaultView!.getComputedStyle(ancestor);
+ if (style.display === "none" || style.visibility === "hidden" || Number(style.opacity) === 0) return undefined;
+ }
const box = drawn.getBoundingClientRect();
if (box.width === 0 && box.height === 0) return undefined;
- return { xPx: box.left, yPx: box.top, widthPx: box.width, heightPx: box.height };
+ return { xPx: box.left, yPx: box.top, widthPx: box.width, heightPx: box.height,
+ stackOrder: Number(document_.defaultView!.getComputedStyle(present).zIndex) || 0 };
};
// The overlay is a sibling of the iframe inside the scaler, so it inherits the
@@ -152,6 +173,7 @@ export function createStage(store: Store): Stage {
};
const toggle = (): void => {
+ if (artifactPreview.selected !== undefined) { artifactPreview.toggle(); return; }
if (state === undefined) return;
if (playing) { stop(); return; }
playing = true;
@@ -172,21 +194,107 @@ export function createStage(store: Store): Stage {
};
play.addEventListener("click", toggle);
previous.addEventListener("click", () => {
- if (state !== undefined) store.seek(state.playhead.frame - 1, "video");
+ if (artifactPreview.selected !== undefined) artifactPreview.seek((artifactPreview.media?.currentTime ?? 0) - 5);
+ else if (state !== undefined) store.seek(state.playhead.frame - 1, "video");
});
next.addEventListener("click", () => {
- if (state !== undefined) store.seek(state.playhead.frame + 1, "video");
+ if (artifactPreview.selected !== undefined) artifactPreview.seek((artifactPreview.media?.currentTime ?? 0) + 5);
+ else if (state !== undefined) store.seek(state.playhead.frame + 1, "video");
});
const applyMuted = (): void => {
setIcon(muteIcon, muted ? "muted" : "volume");
mute.setAttribute("aria-label", muted ? "Unmute" : "Mute");
+ if (artifactPreview.media !== undefined) artifactPreview.media.muted = muted;
(iframe.contentWindow as SeekWindow | null)?.__hypitSetMuted?.(muted);
};
mute.addEventListener("click", () => { muted = !muted; applyMuted(); });
+ const title = element.querySelector<HTMLElement>(".stage-title strong")!;
+ const back = element.querySelector<HTMLButtonElement>(".stage-return")!;
+ const scrubber = element.querySelector<HTMLInputElement>(".stage-scrubber")!;
+ const time = element.querySelector<HTMLElement>(".stage-time")!;
+ const transport = element.querySelector<HTMLElement>(".stage-transport")!;
+ const clock = (seconds: number): string => {
+ const ticks = Math.max(0, Math.round(seconds * 100));
+ const whole = Math.floor(ticks / 100);
+ return `${Math.floor(whole / 60)}:${String(whole % 60).padStart(2, "0")}.${String(ticks % 100).padStart(2, "0")}`;
+ };
+ const artifactPreview = createArtifactPreview(() => {
+ if (artifactPreview.selected === undefined) return;
+ const media = artifactPreview.media;
+ const timed = media !== undefined;
+ const duration = media !== undefined && Number.isFinite(media.duration) ? media.duration : 0;
+ transport.hidden = !timed;
+ mute.hidden = !timed;
+ scrubber.hidden = !timed;
+ time.hidden = !timed;
+ play.disabled = duration <= 0 || media?.error != null;
+ previous.disabled = next.disabled = play.disabled;
+ scrubber.disabled = duration <= 0;
+ scrubber.step = "0.01";
+ scrubber.setAttribute("aria-label", "Media time");
+ scrubber.max = String(duration);
+ scrubber.value = String(media?.currentTime ?? 0);
+ time.textContent = `${clock(media?.currentTime ?? 0)} / ${clock(duration)}`;
+ setIcon(playIcon, media !== undefined && !media.paused ? "pause" : "play");
+ play.setAttribute("aria-label", media !== undefined && !media.paused ? "Pause" : "Play");
+ });
+ viewport.append(artifactPreview.element);
+ const compositionTime = (): void => {
+ if (state === undefined || artifactPreview.selected !== undefined) return;
+ const rate = fps(state.snapshot);
+ scrubber.hidden = time.hidden = false;
+ scrubber.disabled = !ready;
+ scrubber.step = String(1 / rate);
+ scrubber.max = String(Math.max(0, state.snapshot.space.frameCount - 1) / rate);
+ scrubber.value = String(state.playhead.frame / rate);
+ scrubber.setAttribute("aria-label", "Composition time");
+ time.textContent = `${clock(state.playhead.frame / rate)} / ${clock(state.snapshot.space.frameCount / rate)}`;
+ };
+ scrubber.addEventListener("input", () => {
+ if (artifactPreview.selected !== undefined) artifactPreview.seek(Number(scrubber.value));
+ else if (state !== undefined) store.seek(Math.round(Number(scrubber.value) * fps(state.snapshot)), "video");
+ });
+
+ const returnToComposition = (): void => {
+ artifactPreview.close();
+ selectedArtifact(undefined);
+ scaler.hidden = false;
+ back.hidden = true;
+ compositionTime();
+ transport.hidden = mute.hidden = false;
+ play.disabled = previous.disabled = next.disabled = false;
+ previous.title = "Previous frame";
+ previous.setAttribute("aria-label", previous.title);
+ next.title = "Next frame";
+ next.setAttribute("aria-label", next.title);
+ title.textContent = "Preview";
+ title.removeAttribute("title");
+ setIcon(playIcon, "play");
+ play.setAttribute("aria-label", "Play");
+ fit();
+ if (state !== undefined && ready) seekPicture(state.playhead.frame);
+ };
+ back.addEventListener("click", returnToComposition);
+
+ const openArtifact = (artifact: StudioArtifactView): void => {
+ stop();
+ scaler.hidden = true;
+ back.hidden = false;
+ title.textContent = artifact.displayName ?? artifact.output;
+ title.title = artifact.output;
+ previous.title = "Back 5 seconds";
+ next.title = "Forward 5 seconds";
+ previous.setAttribute("aria-label", previous.title);
+ next.setAttribute("aria-label", next.title);
+ artifactPreview.open(artifact, muted);
+ selectedArtifact(artifact.id);
+ };
+
iframe.addEventListener("load", () => {
ready = true;
+ compositionTime();
if (state !== undefined) seekPicture(state.playhead.frame);
applyMuted();
// The box could not be measured until now.
@@ -197,16 +305,19 @@ export function createStage(store: Store): Stage {
store.subscribe((value) => {
const first = state === undefined;
+ const moved = state !== undefined && (state.playhead.frame !== value.playhead.frame || state.selection !== value.selection);
state = value;
+ if (moved && value.playhead.origin !== "play" && artifactPreview.selected !== undefined) returnToComposition();
if (value.snapshot.revision !== mounted) {
mounted = value.snapshot.revision;
- stop();
+ if (artifactPreview.selected === undefined) stop();
ready = false;
const preview = value.snapshot.preview;
iframe.srcdoc = preview.srcdoc;
fit();
}
if (first) fit();
+ compositionTime();
// Playing and scrubbing are different requests: one lets material run on
// its own clock, the other moves it. Asking a decoder for a fresh seek
@@ -227,5 +338,10 @@ export function createStage(store: Store): Stage {
if (playing) overlay.refresh();
});
- return { element, toggle };
+ return { element, toggle, openArtifact,
+ renameArtifact(artifact) {
+ const selected = artifactPreview.selected;
+ if (selected?.build === artifact.build && selected.output === artifact.output) title.textContent = artifact.displayName ?? artifact.output;
+ },
+ };
}
diff --git a/packages/studio/src/ui/timeline.ts b/packages/studio/src/ui/timeline.ts
index d516a149..3c9a55af 100644
--- a/packages/studio/src/ui/timeline.ts
+++ b/packages/studio/src/ui/timeline.ts
@@ -17,7 +17,6 @@ export type Timeline = {
readonly fit: () => void;
};
-const opened = new Set<string>();
const itemMetrics = {
// Ordinary items fill their rows. Only the semantic lane owns compact word cells.
insetYPx: 1,
@@ -577,18 +576,15 @@ export function createTimeline(store: Store): Timeline {
detail: string,
height: number,
attached = false,
- hasState = false,
): HTMLElement => {
const label = document.createElement("div");
- label.className = `track-label track-${kind}${hasState ? " track-label-has-state" : ""}`;
+ label.className = `track-label track-${kind}`;
if (attached) label.classList.add("track-label-attached");
label.style.height = `${height}px`;
label.title = `${name} · ${detail}`;
label.innerHTML = `${attached
? '<span class="track-attachment-mark" aria-hidden="true"></span>'
- : '<span class="track-icon"></span>'}<span class="track-copy"><strong></strong></span>${hasState
- ? '<span class="track-state"></span>'
- : ""}`;
+ : '<span class="track-icon"></span>'}<span class="track-copy"><strong></strong></span>`;
if (!attached) setIcon(label.querySelector(".track-icon")!, iconName);
label.querySelector("strong")!.textContent = name;
return label;
@@ -604,7 +600,7 @@ export function createTimeline(store: Store): Timeline {
.sort((left, right) => (left.binding.lane.order ?? 0) - (right.binding.lane.order ?? 0));
const buildSemanticLane = (snapshot: StudioSnapshot): void => {
- if (snapshot.semantic === undefined || snapshot.semantic.segments.length === 0) {
+ if (snapshot.semantic === undefined) {
return;
}
const presentation = snapshot.semantic.presentation;
@@ -781,17 +777,6 @@ export function createTimeline(store: Store): Timeline {
attached = false,
): void => {
const tone = track.binding.tone;
- const freeFrom: number[] = [];
- const rowOf = new Map<string, number>();
- for (const clip of [...track.clips].sort((a, b) => b.stackOrder - a.stackOrder || a.startFrame - b.startFrame)) {
- let row = freeFrom.findIndex((free) => free <= clip.startFrame);
- if (row < 0) { row = freeFrom.length; freeFrom.push(0); }
- freeFrom[row] = clip.endFrameExclusive;
- rowOf.set(clip.id, row);
- }
- const depth = Math.max(1, freeFrom.length);
- const folded = depth > 1 && !opened.has(track.id);
- const shownRows = folded ? 1 : depth;
const laneHeight = track.binding.lane.heightPx;
const displayedItems = track.clips.length;
const label = createTrackLabel(
@@ -799,44 +784,26 @@ export function createTimeline(store: Store): Timeline {
tone,
track.binding.icon,
`${displayedItems} item${displayedItems === 1 ? "" : "s"}`,
- shownRows * laneHeight,
+ laneHeight,
attached,
- depth > 1,
);
label.classList.add(`track-facet-${track.binding.facet}`);
- if (depth > 1) {
- const fold = document.createElement("button");
- fold.type = "button";
- fold.className = "track-fold";
- fold.textContent = folded ? `+${depth - 1}` : "−";
- fold.title = folded ? `Show ${depth} rows` : "Collapse rows";
- fold.setAttribute("aria-expanded", String(!folded));
- fold.addEventListener("click", (event) => {
- event.stopPropagation();
- if (opened.has(track.id)) opened.delete(track.id);
- else opened.add(track.id);
- build(snapshot);
- paint();
- });
- label.querySelector(".track-state")!.append(fold);
- }
labels.append(label);
const lane = document.createElement("div");
lane.className = `lane track-tone-${tone} track-facet-${track.binding.facet}${attached ? " lane-attached" : ""}`;
- lane.style.height = `${shownRows * laneHeight}px`;
+ lane.style.height = `${laneHeight}px`;
lane.style.setProperty("--lane-height", `${laneHeight}px`);
const laneWidth = lanes.clientWidth;
const materialMounts: {
readonly target: HTMLElement;
readonly preview: Extract<StudioSnapshot["tracks"][number]["clips"][number]["display"]["layers"][number], { readonly kind: "preview" }>["preview"];
}[] = [];
- for (const clip of track.clips) {
+ // Stable order preserves Companion projection order when stack levels tie.
+ for (const clip of [...track.clips].sort((a, b) => a.stackOrder - b.stackOrder)) {
const from = place(clip.startFrame, snapshot.space.frameCount, zoom.window());
const to = place(clip.endFrameExclusive, snapshot.space.frameCount, zoom.window());
if (to <= 0 || from >= 1) continue;
- const row = rowOf.get(clip.id) ?? 0;
- if (folded && row > 0) continue;
const node = document.createElement("button");
node.type = "button";
node.className = `clip clip-tone-${tone} clip-facet-${track.binding.facet} clip-chrome-${clip.presentation.chrome}`;
@@ -847,7 +814,6 @@ export function createTimeline(store: Store): Timeline {
node.style.width = `max(2px, calc(${Math.max(0, to - from) * 100}% - ${itemMetrics.gapPx}px))`;
const visibleWidthPx = visibleItemWidth(from, to, laneWidth);
node.classList.toggle("clip-preview-wide", visibleWidthPx >= 92);
- node.style.top = `${row * laneHeight}px`;
node.title = `${clip.display.title} · ${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-layers" aria-hidden="true"></span><span class="clip-phases"></span></span><span class="clip-selection" aria-hidden="true"></span>`;
const layers = node.querySelector<HTMLElement>(".clip-layers")!;
@@ -940,8 +906,7 @@ export function createTimeline(store: Store): Timeline {
const attachedTo = track.binding.lane.attachedTo;
if (attachedTo !== undefined) continue;
buildTrack(snapshot, track, nextClipNodes);
- const slot = track.binding.lane.groupId;
- if (slot === undefined) continue;
+ const slot = track.binding.lane.groupId ?? track.binding.groupId;
const attachments = attachedTracks(snapshot, slot, track.binding.groupId);
for (const attachment of attachments) {
buildTrack(snapshot, attachment, nextClipNodes, true);
diff --git a/packages/studio/start.ts b/packages/studio/start.ts
index 032778c2..17153c4e 100644
--- a/packages/studio/start.ts
+++ b/packages/studio/start.ts
@@ -11,9 +11,12 @@ Open a Run in the browser to inspect its composition, Sources and Results.
hypit studio --run <build.svrun> [--runtime <hypit.runtime.json>]
[--port <number>] [--workspace <directory>] [--package-root <directory>]
-Paths are relative to the invoking project. Without --runtime, Studio uses
-that project's selected Runtime Profile. The server prints its browser URL;
-press Ctrl+C to stop it.
+Relative command-line paths start at the current directory; --workspace selects
+the project, without rebasing those paths. Otherwise the nearest package.json
+above the current directory defines the project (or the current directory if none).
+Without --runtime, Studio uses that project's .hypit/runtime selection.
+The server prints its project, Run, Runtime selection and browser URL.
+Press Ctrl+C to stop it.
`);
}
@@ -76,6 +79,15 @@ export async function runStudio(argv: readonly string[], io: Pick<CliIo, "write"
const runtimePath = runtimeArgument === undefined
? selectedRuntime?.profile
: resolve(invokedFrom, runtimeArgument);
+ console.info([
+ ` Project ${workspaceRoot}`,
+ ` Run ${runPath}`,
+ ` Runtime Profile ${runtimePath ?? "not selected"}`,
+ ` Runtime selection ${runtimeArgument !== undefined
+ ? "command argument (this session only)" : selectedRuntime?.selectionFile ?? "none"}`,
+ ...(packageRoot === workspaceRoot ? [] : [` Package root ${packageRoot}`]),
+ "",
+ ].join("\n"));
const port = Number(values.get("port") ?? "5179");
if (!Number.isSafeInteger(port) || port <= 0) invalidArguments("--port must be a positive integer");
diff --git a/packages/studio/test/build-library.test.ts b/packages/studio/test/build-library.test.ts
index 8a38976e..8e40bac5 100644
--- a/packages/studio/test/build-library.test.ts
+++ b/packages/studio/test/build-library.test.ts
@@ -2,18 +2,20 @@ import assert from "node:assert/strict";
import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
+import { pathToFileURL } from "node:url";
import test from "node:test";
-import { buildResultDirectory } from "@hypit/build-result";
+import { buildResultDirectory, FileBuildResultRepository } from "@hypit/build-result";
import type { BuildResultRepository } from "@hypit/build-result";
import type { BuildView } from "@hypit/runtime-host-node";
+import { buildIdCreatedAt } from "@hypit/protocol";
import { openStudioBuildLibrary, readStudioLibrary } from "../src/build-library.js";
function activeBuild(id: string, root: string): BuildView {
return {
id,
- createdAt: 100,
+ createdAt: buildIdCreatedAt(id)!,
activity: "saving-result",
outcome: "complete",
cancellationRequested: false,
@@ -39,6 +41,7 @@ test("Studio library joins this environment's Builds with project Build Result f
outcome: "complete" as const,
outputs: {
"final.video": {
+ displayName: "Final cut",
type: { module: { name: "example", version: "1" }, name: "Video" },
value: { kind: "build-file" as const, path: "files/final.video.mp4", size: 42, mediaType: "video/mp4" },
},
@@ -51,6 +54,7 @@ test("Studio library joins this environment's Builds with project Build Result f
async updatePresentation() { throw new Error("read-only fixture"); },
async read(build) { return manifests.find((item) => item.id === build); },
async browse(request) {
+ if (request?.before !== undefined) return { results: [] };
assert.deepEqual(request, { limit: 25 });
return { results: manifests, next: relevant.id };
},
@@ -69,9 +73,10 @@ test("Studio library joins this environment's Builds with project Build Result f
const value = manifest?.outputs[output as "final.video"];
return value === undefined ? undefined : { build, output, type: value.type, value: value.value };
},
+ async describeFile(_build, file) { return file; },
async openFile() { return undefined; },
};
- const view = await readStudioLibrary({
+ const input = {
profile: "/project/hypit.runtime.json",
workspaceRoot: "/project",
runtime: {
@@ -80,7 +85,8 @@ test("Studio library joins this environment's Builds with project Build Result f
},
},
results,
- });
+ };
+ const view = await readStudioLibrary({ ...input, section: "tasks" });
assert.equal(view.next, relevant.id);
assert.deepEqual(view.tasks.map((task) => ({
@@ -91,21 +97,39 @@ test("Studio library joins this environment's Builds with project Build Result f
targets: task.targets,
})), [{
id: "bld_20260902T130000000Z_0000000001",
- status: "active",
+ status: "saving-result",
source: "author/main.svml",
run: "runs/build.svrun",
targets: ["final.video"],
}]);
- assert.deepEqual(view.artifacts.map((artifact) => ({
+ assert.deepEqual(view.artifacts, []);
+ const media = await readStudioLibrary({ ...input, section: "artifacts" });
+ assert.deepEqual(media.tasks, []);
+ assert.equal(media.artifacts[0]?.displayName, "Final cut");
+ const queried: (string | undefined)[] = [];
+ const images = await readStudioLibrary({ ...input, section: "artifacts", media: "image", results: {
+ ...results,
+ async browse(request) {
+ queried.push(request?.before);
+ if (request?.before === undefined) return { results: [manifests[0]!], next: relevant.id };
+ return { results: [{ ...manifests[0]!, outputs: { "still.image": {
+ ...manifests[0]!.outputs["final.video"],
+ value: { kind: "build-file" as const, path: "files/still.png", size: 20, mediaType: "image/png" },
+ } } }] };
+ },
+ } });
+ assert.deepEqual(queried, [undefined, relevant.id]);
+ assert.deepEqual(images.artifacts.map((item) => item.mediaType), ["image/png"]);
+ assert.equal(images.next, undefined);
+
+ assert.deepEqual(media.artifacts.map((artifact) => ({
build: artifact.build,
output: artifact.output,
- valuePath: artifact.valuePath,
filePath: artifact.filePath,
mediaType: artifact.mediaType,
})), [{
build: "bld_20260902T130000000Z_0000000001",
output: "final.video",
- valuePath: "$",
filePath: "files/final.video.mp4",
mediaType: "video/mp4",
}]);
@@ -137,15 +161,21 @@ test("Studio opens project Build Results without a Runtime or ResourceStore", as
const buildLibrary = await openStudioBuildLibrary(undefined, root, root);
assert(buildLibrary !== undefined);
- const view = await buildLibrary.library();
+ const view = await buildLibrary.library({ section: "tasks" });
assert.equal(view.runtime, undefined);
assert.deepEqual(view.tasks.map((item) => [item.id, item.title, item.status]), [
[build, "First cut", "complete"],
]);
- assert.deepEqual(view.artifacts.map((item) => [item.build, item.output, item.valuePath]), [
- [build, "final.video", "$"],
+ const media = await buildLibrary.library({ section: "artifacts" });
+ assert.deepEqual(media.artifacts.map((item) => [item.build, item.output]), [
+ [build, "final.video"],
]);
- const artifact = await buildLibrary.openArtifact(build, "final.video", "$");
+ await buildLibrary.renameArtifact(build, "final.video", "Renamed final");
+ const renamed = await buildLibrary.library({ section: "artifacts" });
+ assert.equal(renamed.artifacts[0]?.displayName, "Renamed final");
+ assert.equal(renamed.artifacts[0]?.nameEditable, true);
+ assert.equal(renamed.artifacts[0]?.output, "final.video");
+ const artifact = await buildLibrary.openArtifact(build, "final.video");
assert.notEqual(artifact, undefined);
const stream = await artifact!.open({ start: 2, endExclusive: 8 });
assert.notEqual(stream, undefined);
@@ -160,3 +190,111 @@ test("Studio opens project Build Results without a Runtime or ResourceStore", as
await rm(root, { recursive: true, force: true });
}
});
+
+const mediaTypeRef = { module: { name: "example", version: "1" }, name: "Media" };
+
+test("media listing includes active files, follows file references and leaves Composite Outputs unopened", async () => {
+ const owner = "bld_20260902T130000010Z_0000000001";
+ const active = "bld_20260902T130000011Z_0000000001";
+ const image = { type: mediaTypeRef, value: { kind: "build-file" as const, path: "files/portrait.png", mediaType: "image/png", size: 100 } };
+ const manifests: import("@hypit/build-result").BuildResultManifest[] = [{
+ format: "hypit.build-result@1", id: owner, source: { path: "/project/main.svml" },
+ run: { path: "/project/earlier.svrun" }, targets: ["portrait.image"], outcome: "failed", finishedAt: 300,
+ failure: "Rendering failed", highlightedOutputs: ["portrait.image"],
+ outputs: {
+ "portrait.image": image,
+ "data.json": { type: mediaTypeRef, value: { kind: "build-file", path: "files/data.json", mediaType: "application/json", size: 20 } },
+ "normalized.video": { type: mediaTypeRef, value: { kind: "value", path: "values/normalized.json" } },
+ "semantic.take": { type: mediaTypeRef, value: { kind: "value", path: "values/semantic.json" } },
+ },
+ }, {
+ format: "hypit.build-result@1", id: active, source: { path: "/project/main.svml" },
+ run: { path: "/project/current.svrun" }, targets: ["final.video"],
+ outputs: {
+ "reused.image": { type: mediaTypeRef, value: { kind: "build-output", build: owner, output: "portrait.image" } },
+ "voice.audio": { type: mediaTypeRef, value: { kind: "build-file", path: "files/voice.wav", mediaType: "audio/wav", size: 80 } },
+ "reused.take": { type: mediaTypeRef, value: { kind: "build-output", build: owner, output: "semantic.take" } },
+ },
+ }];
+ const described: string[] = [];
+ const resolved: string[] = [];
+ const results: BuildResultRepository = {
+ async create() { throw new Error("read-only"); },
+ async openWriter() { throw new Error("read-only"); },
+ async removeIncomplete() { throw new Error("read-only"); },
+ async updatePresentation() { throw new Error("read-only"); },
+ async read(build) { return manifests.find((item) => item.id === build); },
+ async browse() { return { results: [manifests[0] as import("@hypit/build-result").FinishedBuildResultManifest] }; },
+ async describeOutput(_build, output) {
+ described.push(output);
+ if (output === "reused.take") return { kind: "composite", type: mediaTypeRef };
+ assert.equal(output, "reused.image");
+ return { kind: "resource", type: mediaTypeRef, mediaType: "image/png", size: 100 };
+ },
+ async resolve(_build, output) {
+ resolved.push(output);
+ assert.equal(output, "reused.image", "No Composite value or non-media file should be opened");
+ return { ...image, build: owner, output: "portrait.image" };
+ },
+ async describeFile(_build, file) { return file; },
+ async openFile() { throw new Error("Listing never reads media bytes"); },
+ };
+ const view: BuildView = {
+ ...activeBuild(active, "/project"), source: { path: "/project/main.svml" },
+ run: { path: "/project/current.svrun" }, activity: "running", requests: { total: 4, completed: 2 },
+ };
+ const input = { workspaceRoot: "/project", results, runtime: { async activity() { return { builds: [view], capacity: [] }; } } };
+ const tasks = await readStudioLibrary({ ...input, section: "tasks" });
+ assert.deepEqual(described, []);
+ assert.deepEqual(resolved, []);
+ assert.deepEqual(tasks.artifacts, []);
+ assert.deepEqual(tasks.tasks.map((task) => [task.id, task.ongoing, task.status]), [[active, true, "running"], [owner, false, "failed"]]);
+ assert.equal(tasks.tasks[1]?.detail, "Rendering failed");
+ assert.equal(tasks.tasks[1]?.finishedAt, 300);
+ assert.deepEqual(tasks.tasks[0]?.requests, { total: 4, completed: 2 });
+ assert.equal("acceptedRecords" in tasks.tasks[0]!, false);
+
+ const media = await readStudioLibrary({ ...input, section: "artifacts" });
+ assert.equal(media.artifacts.length, 2);
+ const portrait = media.artifacts.find((item) => item.mediaType === "image/png")!;
+ assert.equal(portrait.ownerBuild, owner);
+ assert.equal(portrait.highlighted, true);
+ assert.deepEqual(portrait.origins.map((origin) => [origin.build, origin.output]), [[owner, "portrait.image"], [active, "reused.image"]]);
+ assert.deepEqual(resolved, ["reused.image"]);
+ assert(media.artifacts.some((item) => item.build === active && item.output === "voice.audio"));
+
+ const scoped = await readStudioLibrary({ ...input, section: "artifacts", run: "current.svrun" });
+ assert.equal(scoped.artifacts.length, 2);
+ assert(scoped.artifacts.every((item) => item.origins.every((origin) => origin.build === active)));
+ const selected = await readStudioLibrary({ ...input, section: "artifacts", build: owner });
+ assert.deepEqual(selected.artifacts.map((item) => item.output), ["portrait.image"]);
+ const outside = await readStudioLibrary({ ...input, section: "artifacts", workspaceRoot: "/different-project", build: owner });
+ assert.deepEqual(outside.artifacts, []);
+});
+
+test("Studio groups repeated external file references and retains both Build uses", async () => {
+ const root = await mkdtemp(join(tmpdir(), "hypit-studio-external-"));
+ try {
+ const imagePath = join(root, "portrait.png");
+ await writeFile(imagePath, new Uint8Array([1, 2]));
+ const results = new FileBuildResultRepository(join(root, "results"));
+ const type = { module: { name: "example", version: "1" }, name: "Image" };
+ for (const id of ["bld_20260902T130000000Z_0000000001", "bld_20260902T130000001Z_0000000001"]) {
+ const writer = await results.create({ id, source: { path: join(root, "main.svml") },
+ targets: ["portrait"], publishedOutputs: [{ name: "portrait", output: "portrait" }],
+ resourceReferences: { res_image: { kind: "external-file", uri: pathToFileURL(imagePath).href,
+ size: 2, mediaType: "image/png" } } });
+ await writer.sync({ state: { status: "complete", records: [{ id: "image", type,
+ value: { kind: "blob", resource: "res_image", size: 2, mediaType: "image/png" } }],
+ plan: { outputBindings: [{ output: "portrait", record: "image", type }] },
+ } as unknown as import("@hypit/protocol").BuildState,
+ resources: { async open() { throw new Error("No bytes should be copied"); } } });
+ await writer.finish({ outcome: "complete" });
+ }
+ const view = await readStudioLibrary({ workspaceRoot: root, results, section: "artifacts" });
+ assert.equal(view.artifacts.length, 1);
+ assert.equal(view.artifacts[0]!.origins.length, 2);
+ assert.equal(view.artifacts[0]!.ownerBuild, undefined);
+ assert.equal(view.artifacts[0]!.filePath, pathToFileURL(imagePath).href);
+ } finally { await rm(root, { recursive: true, force: true }); }
+});
diff --git a/packages/workspace-fs-node/README.md b/packages/workspace-fs-node/README.md
index 466508ef..ddab1a81 100644
--- a/packages/workspace-fs-node/README.md
+++ b/packages/workspace-fs-node/README.md
@@ -4,7 +4,10 @@ Reference Node filesystem implementation of the host-neutral `Workspace` contrac
Every `open()` call creates one isolated compilation session. It canonicalizes real paths, confines
local SourceUnit and Source Asset reads to the configured root, rejects symlink escapes, locks each
-edge to the first bytes observed and returns defensive Resource attachments.
+Source edge to the first bytes observed and returns defensive Resource attachments. File attachments
+also carry their resolved `file:` URI so Result publication can preserve the external reference.
+The Resource's identity and metadata belong to the compilation session; its file remains a live
+dependency rather than becoming a persistent snapshot.
A Host may supply an external Source resolver. One explicit non-relative Source locator can then
open a SourceUnit in a separate canonical root; that Source's relative imports and assets remain
diff --git a/packages/workspace-fs-node/src/workspace.ts b/packages/workspace-fs-node/src/workspace.ts
index 11719cf7..66ac75b0 100644
--- a/packages/workspace-fs-node/src/workspace.ts
+++ b/packages/workspace-fs-node/src/workspace.ts
@@ -1,3 +1,4 @@
+import { pathToFileURL } from "node:url";
import { randomUUID } from "node:crypto";
import { createReadStream } from "node:fs";
import { readFile, realpath, stat } from "node:fs/promises";
@@ -177,6 +178,7 @@ class NodeFilesystemWorkspaceSession implements WorkspaceSession {
if (!this.#attachments.has(attachmentKey)) {
this.#attachments.set(attachmentKey, {
artifact: { ...artifact },
+ location: pathToFileURL(canonical).href,
open: () => createReadStream(canonical),
});
}
@@ -189,7 +191,7 @@ class NodeFilesystemWorkspaceSession implements WorkspaceSession {
const byResource = left.artifact.resource.localeCompare(right.artifact.resource);
return byResource === 0 ? left.artifact.mediaType.localeCompare(right.artifact.mediaType) : byResource;
})
- .map((item) => ({ artifact: { ...item.artifact }, open: item.open }));
+ .map((item) => ({ ...item, artifact: { ...item.artifact } }));
}
}
diff --git a/packages/workspace/src/index.ts b/packages/workspace/src/index.ts
index 987b4b1a..42d99a83 100644
--- a/packages/workspace/src/index.ts
+++ b/packages/workspace/src/index.ts
@@ -9,6 +9,8 @@ import type { BlobRef } from "@hypit/protocol";
/** Repeatably openable transfer bytes admitted by the selected Workspace. */
export type ArtifactAttachment = {
readonly artifact: BlobRef;
+ /** Stable external address, when the Workspace supplies a file by reference. */
+ readonly location?: string;
open(): Awaitable<AsyncIterable<Uint8Array>>;
};
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 28222fec..5087ec67 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -14,6 +14,9 @@ importers:
cmu-pronouncing-dictionary:
specifier: 3.0.0
version: 3.0.0
+ koffi:
+ specifier: 3.2.1
+ version: 3.2.1
puppeteer-core:
specifier: 25.10.0
version: 25.10.0
@@ -463,6 +466,9 @@ importers:
'@hypit/protocol':
specifier: workspace:*
version: link:../protocol
+ koffi:
+ specifier: 3.2.1
+ version: 3.2.1
packages/build-result-fs:
dependencies:
@@ -4591,6 +4597,96 @@ packages:
'@jridgewell/[email protected]':
resolution: {integrity: sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==}
+ '@koromix/[email protected]':
+ resolution: {integrity: sha512-1pJQ4jnZlUJduK9u9DC5CGy3aOgDUPvIXpNb6syV3+Dh5Q/ugezAIGCqvY+w+1mgXsve0pd0NVvJRjdZNHQ6MA==}
+ cpu: [arm64]
+ os: [android]
+
+ '@koromix/[email protected]':
+ resolution: {integrity: sha512-HH40xGh3gVQifjOBnhwT2tECC0lL1lYe+nxHvWNSzxDIyQNcVPXg38ta7vuONRFpD+uIrw7fqGYLzbZIagkVcg==}
+ cpu: [x64]
+ os: [android]
+
+ '@koromix/[email protected]':
+ resolution: {integrity: sha512-Vj4h+xcjc5+Cn0DhPHjgRX4omKAv96Kehtcd+1YgYuY2W7FvQn9vS+3SmzVwhC5Qmg9bIwUZObYQ8T/4hBqQqA==}
+ cpu: [arm64]
+ os: [darwin]
+
+ '@koromix/[email protected]':
+ resolution: {integrity: sha512-gFCWxNBTZIvxo1p+PURWfsy2Ctj5FGnVVs1f03lTLhBvmxEto70pdIiFztdFLDFkAJ1pmtQmruRKapeK+E8YPA==}
+ cpu: [x64]
+ os: [darwin]
+
+ '@koromix/[email protected]':
+ resolution: {integrity: sha512-qj+f1s2e6vULaUG1cdlTcCXmunCq2t+rjxku1+esaMIqVnHpOwj0QzPuInG0AFdXjwBNQhyVR/HpDj8daEwwsQ==}
+ cpu: [arm64]
+ os: [freebsd]
+
+ '@koromix/[email protected]':
+ resolution: {integrity: sha512-6olHb1Qfgai0jjs6ddlDDD0ZfsCxy7SPi8rMRpuYQWH0qhgtyQu82hw5b1p7z+TJ0zZP3ZeQQ6l+U/MlM1ICHQ==}
+ cpu: [ia32]
+ os: [freebsd]
+
+ '@koromix/[email protected]':
+ resolution: {integrity: sha512-Dikhw1ySYNVMkmeFvFVjnU5Wdk6mffNoOjJxm9bTG96vg7OlemylxqdEven47R1YJ3yzNVJn/MlQ207ORWfi2w==}
+ cpu: [x64]
+ os: [freebsd]
+
+ '@koromix/[email protected]':
+ resolution: {integrity: sha512-K+cGUL5iBcDqxmsocrjmlASqDf24gc7artbVW3PewG2c9AqwC63lezgwvB85Nx4lZAQjB6zIFHh9A7t1yGbwhw==}
+ cpu: [arm64]
+ os: [linux]
+
+ '@koromix/[email protected]':
+ resolution: {integrity: sha512-OfwUwZylidq95wQKp6ClInULrfB2giu7dqM6Rhe0zAe6lES5I2SXNw15T9+GnRHk3/9hKT2XZ37OZLaKSyWNLA==}
+ cpu: [arm]
+ os: [linux]
+
+ '@koromix/[email protected]':
+ resolution: {integrity: sha512-rxj6UYjU1qd98gxNQOSCdLpc5cPRi5Giq9rNd3jnGuSNIyMkwa6Dxw4cUjmhIBCYESMJtmNt5NWnJp5u9wTfYQ==}
+ cpu: [ia32]
+ os: [linux]
+
+ '@koromix/[email protected]':
+ resolution: {integrity: sha512-aHhnHzkPRmT/IHDlGvESJ/Bs32m8N6UE6Ab6kMeJzgk74IN8af2m/81/wZJtybR1M2UxCV4NmlVNUYQQvSAO3Q==}
+ cpu: [loong64]
+ os: [linux]
+
+ '@koromix/[email protected]':
+ resolution: {integrity: sha512-qtQBsjbm3LiirLJvajWmKkNb7ARk7fvJVXdftJ7NtAnF3Xw8EbDvrtvmvtNI1yLPlYcBmlzCCD71hwhWYk0SIA==}
+ cpu: [riscv64]
+ os: [linux]
+
+ '@koromix/[email protected]':
+ resolution: {integrity: sha512-c7hw7Qs/r5gnFRTQLcbifBwRU7wiocj+2pVuDQ5Ahb3r36SZmupmgYbTWcLvTW+hul1jd7SKRV0d14ZJq/tvSw==}
+ cpu: [x64]
+ os: [linux]
+
+ '@koromix/[email protected]':
+ resolution: {integrity: sha512-mmY8fY8LQ/CB52+h3yrMYmVyoxzW3x08S0yI6VNfHWdfU6yJtZkKCbhjmQCYMrWbYKC4gMvwZwCywIGPAkLyeA==}
+ cpu: [ia32]
+ os: [openbsd]
+
+ '@koromix/[email protected]':
+ resolution: {integrity: sha512-k4ig6aAPbFSRATOIIOfdf/KtlOGH4SVls6L9fy0QnTxRJYvY2oSltTsQtBDANgEQldlq8Kl5WnpRa1VSibP4Lw==}
+ cpu: [x64]
+ os: [openbsd]
+
+ '@koromix/[email protected]':
+ resolution: {integrity: sha512-cTWBJGK//pDMeKQJE/79Aq9MiOAF4H8QyLZHSQ9IWm8czOfwjG4J1AhsQ9DjI9KFOykH77hhnpmQTGVMIubGig==}
+ cpu: [arm64]
+ os: [win32]
+
+ '@koromix/[email protected]':
+ resolution: {integrity: sha512-Z50EM6TAZ7CFyMmyX6thv8eNpJchqe9eenhibSIy2Eq/FQYF76gU2VK/LEoaF46L8hfC7TpTp9b10MvReHEyFA==}
+ cpu: [ia32]
+ os: [win32]
+
+ '@koromix/[email protected]':
+ resolution: {integrity: sha512-ZmZNiBO6bkOSh3QNzgfvb1cMY0yMobn6ZQrSMqbAce21qyYL8niIbyipz9N/PIRDciGhsV0wUxnZsxIO+yWsHQ==}
+ cpu: [x64]
+ os: [win32]
+
'@napi-rs/[email protected]':
resolution: {integrity: sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ==}
engines: {node: ^22.20 || ^24.12 || >=25}
@@ -5591,6 +5687,9 @@ packages:
resolution: {integrity: sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA==}
+ resolution: {integrity: sha512-0qE3lZ8jllRqPN4Ob6Ajl7c2bJSJDhQWuKLGP5hIEpHLllJWv1ydHFMhHmHc5p/W9GticKVDbYzZd7TBoQ4CZg==}
+
resolution: {integrity: sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==}
engines: {node: '>= 12.0.0'}
@@ -7408,6 +7507,60 @@ snapshots:
'@jridgewell/[email protected]': {}
+ '@koromix/[email protected]':
+ optional: true
+
+ '@koromix/[email protected]':
+ optional: true
+
+ '@koromix/[email protected]':
+ optional: true
+
+ '@koromix/[email protected]':
+ optional: true
+
+ '@koromix/[email protected]':
+ optional: true
+
+ '@koromix/[email protected]':
+ optional: true
+
+ '@koromix/[email protected]':
+ optional: true
+
+ '@koromix/[email protected]':
+ optional: true
+
+ '@koromix/[email protected]':
+ optional: true
+
+ '@koromix/[email protected]':
+ optional: true
+
+ '@koromix/[email protected]':
+ optional: true
+
+ '@koromix/[email protected]':
+ optional: true
+
+ '@koromix/[email protected]':
+ optional: true
+
+ '@koromix/[email protected]':
+ optional: true
+
+ '@koromix/[email protected]':
+ optional: true
+
+ '@koromix/[email protected]':
+ optional: true
+
+ '@koromix/[email protected]':
+ optional: true
+
+ '@koromix/[email protected]':
+ optional: true
+
'@napi-rs/[email protected]':
optional: true
@@ -8406,6 +8559,27 @@ snapshots:
safe-buffer: 5.2.1
optional: true
+ optionalDependencies:
+ '@koromix/koffi-android-arm64': 3.2.1
+ '@koromix/koffi-android-x64': 3.2.1
+ '@koromix/koffi-darwin-arm64': 3.2.1
+ '@koromix/koffi-darwin-x64': 3.2.1
+ '@koromix/koffi-freebsd-arm64': 3.2.1
+ '@koromix/koffi-freebsd-ia32': 3.2.1
+ '@koromix/koffi-freebsd-x64': 3.2.1
+ '@koromix/koffi-linux-arm': 3.2.1
+ '@koromix/koffi-linux-arm64': 3.2.1
+ '@koromix/koffi-linux-ia32': 3.2.1
+ '@koromix/koffi-linux-loong64': 3.2.1
+ '@koromix/koffi-linux-riscv64': 3.2.1
+ '@koromix/koffi-linux-x64': 3.2.1
+ '@koromix/koffi-openbsd-ia32': 3.2.1
+ '@koromix/koffi-openbsd-x64': 3.2.1
+ '@koromix/koffi-win32-arm64': 3.2.1
+ '@koromix/koffi-win32-ia32': 3.2.1
+ '@koromix/koffi-win32-x64': 3.2.1
+
optional: true
diff --git a/skills/hypit/references/creation/project-files.md b/skills/hypit/references/creation/project-files.md
index 402db4d1..551fa6c9 100644
--- a/skills/hypit/references/creation/project-files.md
+++ b/skills/hypit/references/creation/project-files.md
@@ -53,10 +53,21 @@ Sources can live below the root, with file and Source imports relative to the de
| Boundary | When to set it explicitly |
| --- | --- |
-| `--workspace <directory>` | Choose the Source containment root when running from another directory |
+| `--workspace <directory>` | Choose the project root for Sources, Runtime selection, project packages and Results when running from another directory |
| `--asset-root <directory>` | Admit assets stored elsewhere while keeping Source imports in their workspace |
| `--package-root <directory>` | Resolve project packages from another installation location |
+Relative command-line paths start at the shell's current directory. `--workspace` selects the project
+without rebasing the Run, Source or `--runtime` argument. For example, from outside a project:
+
+```bash
+hypit paths --workspace /path/to/video-project
+hypit studio --run /path/to/video-project/build.svrun --workspace /path/to/video-project
+```
+
+`paths` shows the resolved project and where its Runtime selection came from. Source imports and asset
+references inside files remain relative to their declaring file.
+
For example, `hypit check authors/main.svml --asset-root /path/to/shared-media` admits intentionally
referenced shared media. Keep the same relevant boundaries for subsequent commands. An ordinary
project uses its own package installation; reserved `@hypit/*` packages come from the selected
@@ -180,6 +191,12 @@ Results forward an Output to its original owning Build, so copying only the late
can omit media still in use. A custom filesystem or S3 repository needs the corresponding files or
access and an explicit destination selection; changing `hypit.results.json` does not move them.
+External input files remain live dependencies, including when referenced inside structured Outputs.
+The Node workspace records their resolved file addresses. When moving to another machine, provide
+those inputs and update affected references to their new locations. Copying Result directories alone
+does not collect external files; an explicit `hypit get` export does collect the selected Output's
+referenced bytes.
+
The recipient installs the selected Distribution and project dependencies, configures their Runtime,
and inspects the received Results. Planning the intended Run shows whether its reuse choices still
resolve and what new work remains. Active execution stays with the originating Runtime until that
diff --git a/skills/hypit/references/environment/profile.md b/skills/hypit/references/environment/profile.md
index 5cdc5d90..f3c472e3 100644
--- a/skills/hypit/references/environment/profile.md
+++ b/skills/hypit/references/environment/profile.md
@@ -99,6 +99,14 @@ Each authored model needs an Endpoint that supports its exact requested capabili
Runtime selection is project-local. Commands read that project's `.hypit/runtime` pointer and do not
choose a Profile from a familiar filename or from another project above it.
+Use `hypit paths` to see the actual project, Profile, selection source and storage locations.
+`--runtime <profile>` selects a Profile for that invocation; `runtime use <profile>` records the
+project's default. From elsewhere, `hypit paths --workspace /path/to/project` inspects that project.
+The same project option applies to `doctor`, `runtime`, `programs`, `auth` and Build status/control.
+`doctor` without a selected Profile checks project Results only; its Scope line states that boundary.
+The [project boundary](../creation/project-files.md#establish-the-project-boundary) explains how the
+current directory, `package.json` and explicit paths determine which project these commands address.
+
## Keep the owners separate
| Owner | What it decides |
diff --git a/skills/hypit/references/production/authoring.md b/skills/hypit/references/production/authoring.md
index e708dfa4..e8ff0dbd 100644
--- a/skills/hypit/references/production/authoring.md
+++ b/skills/hypit/references/production/authoring.md
@@ -144,7 +144,12 @@ alone does not. Write that exact choice into the Run. Results retain public Outp
was exported into `assets/` or `output/`; inspect them before concluding that material is missing.
A failed or cancelled Build may still contain completed public Outputs worth using. Reuse those
Outputs rather than submitting their generation again to recover a later failure. A later Build
-that forwards an earlier Output does not copy its bytes.
+that forwards an earlier Output does not copy its bytes. New structured Outputs also keep references
+to reused media inside them; wrapping a video in another value does not create another video file.
+
+A `<file>` Candidate refers to the selected file. Replacing that file changes subsequent reads;
+removing it leaves a missing dependency. A new Build records the selected reference without copying
+the file into every Result. A Candidate that generates new media saves its new output normally.
The current Build's generated media normally continues downstream as the material for the commissioned
work. Reusing it explicitly lets Caption, MG, Effects, composition, and final encoding change without
diff --git a/skills/hypit/references/production/studio.md b/skills/hypit/references/production/studio.md
index ab193f33..b013946a 100644
--- a/skills/hypit/references/production/studio.md
+++ b/skills/hypit/references/production/studio.md
@@ -22,6 +22,11 @@ Open the URL actually printed by the process and retain it with the Run it serve
requested port is 5179; `--port` selects another, and an occupied port can cause Vite to choose a
different one. Reuse an existing session when it serves the intended project and Run.
+The startup output identifies the project, absolute Run path, Runtime Profile and selection source.
+An explicit `--runtime` applies to this session; the project's default comes from `.hypit/runtime`.
+When launching from another directory, use `--workspace` to select the project and supply the Run
+path from the current directory, as shown in [project boundaries](../creation/project-files.md#establish-the-project-boundary).
+
Studio watches the Run and its loaded Author/Recipe Sources and recompiles them after changes.
Changing package code, adding a package import, changing Companion activation, or selecting another
Runtime or Result repository requires restarting that Studio session: those implementations and
@@ -49,8 +54,17 @@ include when the user wants to continue editing on another machine.
| Preview | The selected Film composition rendered by HyperFrames in the browser. Play or seek to inspect the actual selected media and graphics. |
| Timeline | Semantic Segments, Selections and Moments, plus the component-projected Track entities and their visible intervals, materials or event lanes. A rectangle may describe occupancy, activation or persistent visibility; read the component's meaning. |
| Inspector | With nothing selected, project, Canvas, time and Run facts. For a selected entity, only its declared adjustable fields, organized under Where, How and When where applicable. |
-| Tasks | Finished project Results and, with a selected Runtime, read-only active Build/Operation information. This is a view of execution, not a replacement Build submission mechanism. |
-| Artifacts | Public media files from project Results, including files inside Composite Outputs. Previewing one does not select it as a Candidate in the Run. |
+| Tasks | One card per Build, grouped into ongoing and finished. Active status and progress come from the selected Runtime; completed, failed and cancelled Builds come from project Results. Cards retain the source Run, times and any failure or attention reason. |
+| Artifacts | Image, video and audio file Outputs from project Results, including those already published by ongoing Builds. Use the sidebar to choose all media, videos, images or audio. View media on a Build opens its Outputs; opening the Artifacts tab returns to project media. Composite Outputs such as normalized media and Semantic Takes stay intact and do not add their internal files to this gallery. Click a card to view it in the central preview; video and audio have playback and a time slider. Back to composition returns to the existing composition position. Previewing a file does not select it as a Candidate in the Run. |
+
+Open either library tab or click Refresh to read its latest state. These lists do not poll.
+Refresh replaces the view; scrolling to the end loads more. Media categories query matching files
+across Result pages, so an intervening Build without that kind of media does not require a separate action. A failed refresh keeps the
+previous view and displays the error. Multiple references to one stored file share a media card;
+its source details retain the originating Builds and Outputs. Highlighted Outputs appear first.
+Names show up to two lines. Double-click a name or press F2 to edit; Enter or leaving the field
+saves, and Escape cancels. Renaming changes the displayed Output name in the finished Result,
+not its reference identifier or media file.
Use [Builds and Results](builds.md) to inspect Output names, export media, finish an incomplete Result,
edit Result presentation metadata or select an earlier Output. Studio reads the same project Result