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.

fix(studio): stabilize script edits and rejected parameter values

kashorin08589cafa872
diff --git a/packages/script/README.md b/packages/script/README.md
index ea7b6bf7..2efc304c 100644
--- a/packages/script/README.md
+++ b/packages/script/README.md
@@ -141,8 +141,18 @@ The media consumer still decides playback and visual coverage inside those proje
`adjustScriptSelection` and `adjustScriptMoment` accept explicit anchor identities. A Selection's
two endpoints are written together. Script owns their legal source sites: token punctuation and
postfix attributes stay attached, Segment boundaries stay structural, and coincident markers are
-ordered together. Equivalent horizontal marker spacing is normalized on edit; empty self-closing
-Segments expand when needed to make their distinct boundaries writable.
+ordered together. Writeback reads the current source, removes the markers, normalizes ordinary
+same-line prose, and places the markers at their requested anchors. Repeated spaces and tabs in
+prose become necessary separators; punctuation uses the same attachment rules as Script's text
+projection. Newlines, blank lines and each line's leading spaces/tabs remain intact. A marker at
+the start of a line is placed after its indentation; whitespace after that marker is prose, not
+additional indentation. Marker-only lines remain blank when the marker leaves. Comments, tags,
+Dual Text and display attributes retain their own syntax and are not passed through prose cleanup.
+
+Normalization keeps lexical units unchanged and does not restore earlier whitespace spellings.
+It has no persistent formatting state: the same text structure and anchor relationships produce
+the same spelling on repeated edits. Empty self-closing Segments expand when needed to make their
+distinct boundaries writable.
Writeback reparses the result to retain the intended identities and unchanged narrative/caption
content. These checks concern authored order, not frame order. A consumer's temporal projection
diff --git a/packages/script/src/edit.ts b/packages/script/src/edit.ts
index 29b67e54..7fb4842f 100644
--- a/packages/script/src/edit.ts
+++ b/packages/script/src/edit.ts
@@ -3,6 +3,7 @@ import type { SourceRange } from "@hypit/protocol";
import { canonicalStringify } from "@hypit/protocol";
import { captionDocument, narrativeValue } from "./narrative.js";
import { parseScript } from "./parser.js";
+import { cleanHorizontalProse } from "./lexical.js";
import type { Affinity, ParsedNarrative, SemanticAnchor } from "./types.js";
export type ScriptAnchorEditSite = {
@@ -99,6 +100,34 @@ type AdjustmentInput = {
type NamedAnchor = { readonly id: string; readonly edge: "open" | "close" | "moment"; readonly anchorId: string };
+/** Normalize only parser-owned prose. Indentation is read from this edit's input, never stored. */
+function normalizedProse(source: string, parsed: ParsedNarrative, original: string): string {
+ const bodyStarts = new Set(parsed.segments.flatMap(segment => [segment.contentRange.start,
+ ...segment.atoms.filter(atom => atom.kind === "role").map(atom => atom.range.end)]));
+ const bodyEnds = new Set(parsed.segments.map(segment => segment.contentRange.end));
+ const indentation = original.split(/\r\n|\r|\n/u).map(line => /^[ \t]*/u.exec(line)![0].length);
+ const lines: Array<{ start: number; end: number; indentEnd: number }> = [];
+ let offset = 0;
+ const parts = source.split(/(\r\n|\r|\n)/u);
+ for (let index = 0; index < parts.length; index += 2) {
+ const text = parts[index]!;
+ lines.push({ start: offset, end: offset + text.length, indentEnd: offset + indentation[index / 2]! });
+ offset += text.length + (parts[index + 1]?.length ?? 0);
+ }
+ const edits: Edit[] = [];
+ for (const range of parsed.proseRanges) for (const line of lines) {
+ const start = Math.max(range.start, line.indentEnd);
+ const end = Math.min(range.end, line.end);
+ if (start >= end) continue;
+ let text = cleanHorizontalProse(source.slice(start, end));
+ const outside = !parsed.segments.some(segment => range.start >= segment.contentRange.start && range.end <= segment.contentRange.end);
+ if (start === line.indentEnd || bodyStarts.has(start) || outside) text = text.replace(/^[ \t]+/u, "");
+ if (end === line.end || bodyEnds.has(end) || outside) text = text.replace(/[ \t]+$/u, "");
+ edits.push({ range: { start, end }, replacement: text });
+ }
+ return applyEdits(source, edits);
+}
+
/** One canonical boundary spelling, independent of the order of previous gestures. */
function rewrite(input: AdjustmentInput, markers: readonly NamedAnchor[]): string {
const ranges = [
@@ -106,28 +135,12 @@ function rewrite(input: AdjustmentInput, markers: readonly NamedAnchor[]): strin
...input.parsed.selections.flatMap((item) => [item.open.range, item.close.range]),
].map((range) => ({ start: range.start - input.parsed.sourceRange.start, end: range.end - input.parsed.sourceRange.start }))
.sort((a, b) => a.start - b.start);
- const removals: Edit[] = [];
- for (const range of ranges) {
- let start = range.start;
- let end = range.end;
- while (start > 0 && /[ \t]/u.test(input.source[start - 1]!)) start -= 1;
- while (end < input.source.length && /[ \t]/u.test(input.source[end]!)) end += 1;
- const previous = removals.at(-1);
- if (previous && start <= previous.range.end) {
- removals[removals.length - 1] = { range: { start: previous.range.start, end }, replacement: "" };
- } else removals.push({ range: { start, end }, replacement: "" });
- }
- const edits = removals.map(({ range }): Edit => {
- const original = input.source.slice(range.start, range.end);
- // Keep line indentation; elsewhere all horizontal spellings of this gap are one space.
- const indentation = range.start === 0 || /[\r\n]/u.test(input.source[range.start - 1]!);
- const gap = indentation ? /^[ \t]*/u.exec(original)![0] : /[ \t]/u.test(original) ? " " : "";
- return { range, replacement: gap };
- });
+ const edits: Edit[] = ranges.map(range => ({ range, replacement: "" }));
for (const segment of input.parsed.segments) {
if (segment.selfClosing) edits.push({ range: { start: segment.range.start - input.parsed.sourceRange.start, end: segment.range.end - input.parsed.sourceRange.start }, replacement: `<${segment.id}></${segment.id}>` });
}
- const base = applyEdits(input.source, edits);
+ const unmarked = applyEdits(input.source, edits);
+ const base = normalizedProse(unmarked, parseScript(input.sourceName, unmarked), input.source);
const parsed = parseScript(input.sourceName, base);
const sites = new Map(scriptAnchorEditSites(parsed).map((site, order) => [site.anchorId, { ...site, order }]));
const groups = new Map<number, Array<NamedAnchor & { affinity: Affinity; order: number }>>();
@@ -135,6 +148,9 @@ function rewrite(input: AdjustmentInput, markers: readonly NamedAnchor[]): strin
const site = sites.get(value.anchorId);
if (!site) throw new Error(`Semantic Anchor ${value.anchorId} does not exist.`);
let offset = site.offset;
+ const lineStart = Math.max(base.lastIndexOf("\n", offset - 1), base.lastIndexOf("\r", offset - 1)) + 1;
+ const indentEnd = lineStart + /^[ \t]*/u.exec(base.slice(lineStart))![0].length;
+ if (offset < indentEnd) offset = indentEnd;
// Reuse horizontal separators without moving a word marker ahead of line indentation.
let gapStart = offset;
while (gapStart > 0 && /[ \t]/u.test(base[gapStart - 1]!)) gapStart -= 1;
@@ -193,7 +209,6 @@ export function adjustScriptSelection(input: AdjustmentInput & { readonly adjust
const start = order.indexOf(adjustment.startAnchorId);
const end = order.indexOf(adjustment.endAnchorId);
if (start < 0 || end < start) throw new Error("Selection endpoints must follow Script anchor order.");
- if (selection.startAnchorId === adjustment.startAnchorId && selection.endAnchorId === adjustment.endAnchorId) return input.source;
return rewrite(input, namedAnchors(parsed).map((item) => item.id !== adjustment.id ? item : {
...item, anchorId: item.edge === "open" ? adjustment.startAnchorId : adjustment.endAnchorId,
}));
@@ -203,7 +218,6 @@ export function adjustScriptSelection(input: AdjustmentInput & { readonly adjust
export function adjustScriptMoment(input: AdjustmentInput & { readonly adjustment: ScriptMomentAdjustment }): string {
const moment = input.parsed.moments.find((item) => item.id === input.adjustment.id);
if (!moment) throw new Error(`Script Moment ${input.adjustment.id} does not exist.`);
- if (moment.anchorId === input.adjustment.anchorId) return input.source;
return rewrite(input, namedAnchors(input.parsed).map((item) => item.id !== input.adjustment.id ? item : {
...item, anchorId: input.adjustment.anchorId,
}));
diff --git a/packages/script/src/lexical.ts b/packages/script/src/lexical.ts
index 82e08eff..8db9b99d 100644
--- a/packages/script/src/lexical.ts
+++ b/packages/script/src/lexical.ts
@@ -72,16 +72,29 @@ export function lexicalEditRanges(value: string): readonly { start: number; end:
}
/** Canonical prose spacing; punctuation remains display/speech information, never a timing token. */
-export function cleanProjection(value: string): string {
+function attachProseSpacing(value: string): string {
return value
- .replace(/\s+/gu, " ")
- .replace(/\s+([,.;:!?%…,。!?;:、%‰)】》」』〕〉}\]])/gu, "$1")
- .replace(/([([{(【《「『〔〈“‘])\s+/gu, "$1")
+ .replace(/ +([,.;:!?%…,。!?;:、%‰)】》」』〕〉}\]])/gu, "$1")
+ .replace(/([([{(【《「『〔〈“‘]) +/gu, "$1")
// Do not erase a cross-script space: `here 你好` must remain two semantic regions.
// Only collapse explicit spaces inside one CJK run; the lexical tokenizer already keeps
// adjacent Latin and CJK runs separate when no space was authored.
- .replace(/([\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}])\s+(?=[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}])/gu, "$1")
- .trim();
+ .replace(/([\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]) +(?=[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}])/gu, "$1");
+}
+
+export function cleanProjection(value: string): string {
+ return attachProseSpacing(value.replace(/\s+/gu, " ")).trim();
+}
+
+/** Source formatting keeps line breaks and lexical boundaries, including spaced decimal-like prose. */
+export function cleanHorizontalProse(value: string): string {
+ const collapsed = value.replace(/[ \t]+/gu, " ");
+ const attached = attachProseSpacing(collapsed);
+ const words = (text: string) => lexicalUnits(text).map(unit => unit.text);
+ // A separator in `3 .14` cannot be erased into the different token `3.14`.
+ const before = words(collapsed);
+ const after = words(attached);
+ return before.length === after.length && before.every((word, index) => word === after[index]) ? attached : collapsed;
}
/** Structural markers split atoms but must not invent prose whitespace when those atoms rejoin. */
diff --git a/packages/script/src/parser.ts b/packages/script/src/parser.ts
index 95e2fa71..839ef74c 100644
--- a/packages/script/src/parser.ts
+++ b/packages/script/src/parser.ts
@@ -142,6 +142,7 @@ export function parseScript(
const segments: ParsedSegment[] = [];
const tokens: ParsedToken[] = [];
+ const proseRanges: Array<{ start: number; end: number }> = [];
const captionRegions: ParsedCaptionRegion[] = [];
const selections = new Map<string, RawSelection>();
const moments = new Map<string, RawMoment>();
@@ -238,12 +239,13 @@ export function parseScript(
raw: string,
absoluteStart: number,
dual = false,
- ): Array<{ readonly value: string; readonly start: number; readonly end: number }> => {
- const pieces: Array<{ value: string; start: number; end: number }> = [];
+ ): Array<{ readonly value: string; readonly start: number; readonly end: number; readonly positions: readonly number[] }> => {
+ const pieces: Array<{ value: string; start: number; end: number; positions: readonly number[] }> = [];
let buffer = "";
let bufferStart = 0;
+ const positions = [absoluteStart];
const flush = (end: number): void => {
- if (buffer) pieces.push({ value: buffer, start: absoluteStart + bufferStart, end: absoluteStart + end });
+ if (buffer) pieces.push({ value: buffer, start: absoluteStart + bufferStart, end: absoluteStart + end, positions });
buffer = "";
bufferStart = end;
};
@@ -256,10 +258,12 @@ export function parseScript(
?? fail("SCRIPT_ESCAPE", `Unknown Script escape "${raw.slice(index, index + 2)}".`, absoluteStart + index);
buffer += escape.value;
index += escape.length;
+ positions.push(absoluteStart + index);
continue;
}
buffer += raw[index];
index += 1;
+ positions.push(absoluteStart + index);
}
flush(raw.length);
return pieces;
@@ -425,6 +429,7 @@ export function parseScript(
start: number,
end: number,
captureCaptionRegion = true,
+ sourcePositions?: readonly number[],
): void => {
if (!current) {
if (speech.trim() || caption.trim()) {
@@ -436,12 +441,14 @@ export function parseScript(
const tokenStart = tokens.length;
const editRanges = lexicalEditRanges(speech);
const units = lexicalUnits(speech);
+ // Decoded characters may occupy more than one source character (for example \@).
+ const position = (index: number): number => sourceOffset + (sourcePositions?.[index] ?? start + index);
// A punctuation-only piece can follow a display attribute or escaped source piece.
const preceding = tokens.at(-1);
const closing = splitLeadingClosingPunctuation(speech).previous;
if (preceding?.segmentId === current.id && preceding.editRange.end === sourceOffset + start && closing && speech.startsWith(closing)) {
tokens[tokens.length - 1] = { ...preceding, editRange: {
- start: preceding.editRange.start, end: sourceOffset + start + closing.length,
+ start: preceding.editRange.start, end: position(closing.length),
} };
}
for (const [unitIndex, match] of units.entries()) {
@@ -460,12 +467,12 @@ export function parseScript(
text: match.text,
normalized,
range: {
- start: sourceOffset + start + match.index,
- end: sourceOffset + start + match.index + match.text.length,
+ start: position(match.index),
+ end: position(match.index + match.text.length),
},
editRange: {
- start: sourceOffset + start + editRanges[unitIndex]!.start,
- end: sourceOffset + start + editRanges[unitIndex]!.end,
+ start: position(editRanges[unitIndex]!.start),
+ end: position(editRanges[unitIndex]!.end),
},
});
}
@@ -501,7 +508,7 @@ export function parseScript(
let emittedCaption = false;
const addLiteral = (part: string, start: number): void => {
for (const piece of literalPieces(part, start, true)) {
- addText(piece.value, emittedCaption ? "" : caption, piece.start, piece.end, false);
+ addText(piece.value, emittedCaption ? "" : caption, piece.start, piece.end, false, piece.positions);
emittedCaption = true;
}
};
@@ -669,7 +676,8 @@ export function parseScript(
offset += 1;
}
const raw = source.slice(textStart, offset);
- for (const piece of literalPieces(raw, textStart)) addText(piece.value, piece.value, piece.start, piece.end);
+ if (raw) proseRanges.push({ start: sourceOffset + textStart, end: sourceOffset + offset });
+ for (const piece of literalPieces(raw, textStart)) addText(piece.value, piece.value, piece.start, piece.end, true, piece.positions);
if (source[offset] === "{") {
const block = parseAttributeBlock(source.slice(offset), offset);
if (!raw || /\s$/u.test(raw)) {
@@ -834,6 +842,7 @@ export function parseScript(
return {
sourceRange: { start: sourceOffset, end: sourceOffset + source.length },
+ proseRanges,
segments,
tokens,
turns,
diff --git a/packages/script/src/types.ts b/packages/script/src/types.ts
index 6c8262a7..254e195f 100644
--- a/packages/script/src/types.ts
+++ b/packages/script/src/types.ts
@@ -81,6 +81,8 @@ export type ParsedNarrative = Omit<
> & {
/** Exact Script body range, used only for source-preserving Program-boundary edits. */
readonly sourceRange: SourceRange;
+ /** Ordinary source prose/whitespace; excludes tags, Dual Text, attributes and comments. */
+ readonly proseRanges: readonly SourceRange[];
readonly segments: readonly ParsedSegment[];
readonly tokens: readonly ParsedToken[];
readonly turns: readonly ParsedTurn[];
diff --git a/packages/script/test/edit.test.ts b/packages/script/test/edit.test.ts
index 3ea925a1..9be4ac54 100644
--- a/packages/script/test/edit.test.ts
+++ b/packages/script/test/edit.test.ts
@@ -1,6 +1,7 @@
import assert from "node:assert/strict";
import test from "node:test";
import { adjustScriptMoment, adjustScriptSelection, captionDocument, narrativeValue, parseScript } from "@hypit/script";
+import { cleanHorizontalProse } from "../src/lexical.js";
const fixtures = [
'<one><HOST>“Hello,” world{emphasis}! @beat!</one>',
@@ -8,8 +9,20 @@ const fixtures = [
'<one><HOST>用<Hypit|Hai Pit>做视频 || 很好。@beat!</one>',
'<one/>\r\n<two><HOST>Hello. @beat!</two>',
'<one> <HOST>first @beat! second.\n <GUEST>Third.</one><two></two>',
+ '<one>A\n\t ~@beat! B .</one>',
+ '\t <one>\r\n\t <HOST>We are\r\n\t @beat! talking about Instagram .\r\n\t </one>\r\n',
+ '<one>\n @beat! \n <HOST>你 好 ,世 界 !\n</one>',
+ '<one><!-- keep this\n\t comment --> <HOST>用<Hypit|Hai Pit> 做 视频{emphasis} 。@beat!</one>',
+ '<one>Find \\@hypit now. @beat!</one>',
+ '<one>Use \\{braces\\} here. @beat!</one>',
+ '<one><Hypit|Hai \\@ Pit> works. @beat!</one>',
];
+test("horizontal formatting preserves lexical distinctions and line breaks", () => {
+ assert.equal(cleanHorizontalProse("3 .14"), "3 .14");
+ assert.equal(cleanHorizontalProse("Instagram .\n你 好 ,"), "Instagram.\n你好,");
+});
+
for (const source of fixtures) test(`Moment round trips through structural and lexical anchors: ${source}`, () => {
const original = parseScript("edit", source);
const move = (text: string, anchorId: string) => adjustScriptMoment({
@@ -25,6 +38,38 @@ for (const source of fixtures) test(`Moment round trips through structural and l
}
});
+test("normalization retains line indentation and removes marker residue without remembering its origin", () => {
+ const source = '<one>\r\n\t <HOST>We are\r\n\t @beat! on Instagram . \r\n\t </one>';
+ const original = parseScript("edit", source);
+ const originalAnchor = original.moments[0]!.anchorId;
+ const end = original.tokens.at(-1)!.endAnchorId;
+ const move = (text: string, anchorId: string) => adjustScriptMoment({
+ sourceName: "edit", source: text, parsed: parseScript("edit", text), adjustment: { id: "beat", anchorId },
+ });
+ const atEnd = move(source, end);
+ assert.equal(atEnd, '<one>\r\n\t <HOST>We are\r\n\t on Instagram.~@beat!\r\n\t </one>');
+ let current = atEnd;
+ for (let index = 0; index < 30; index++) {
+ current = move(move(current, originalAnchor), end);
+ assert.equal(current, atEnd);
+ }
+ assert.equal(move(atEnd, end), atEnd);
+});
+
+test("equivalent inline whitespace converges to the same marker spelling", () => {
+ const sources = [
+ '<one><HOST>@social on Instagram @/social .</one>',
+ '<one><HOST>@social on Instagram.@/social</one>',
+ ];
+ const normalized = sources.map(source => {
+ const parsed = parseScript("edit", source);
+ const selection = parsed.selections[0]!;
+ return adjustScriptSelection({ sourceName: "edit", source, parsed, adjustment: selection });
+ });
+ assert.equal(normalized[0], normalized[1]);
+ assert.match(normalized[0]!, /on Instagram\.@\/social/u);
+});
+
test("Selection endpoints sharing a source position are written together in semantic order", () => {
const source = '<one><HOST>@range hello @/range world.</one><empty/>';
const original = parseScript("edit", source);
@@ -38,6 +83,29 @@ test("Selection endpoints sharing a source position are written together in sema
}
});
+for (const source of [
+ '<one>A @s B . @/s</one>',
+ '<one>A ~@s B . @/s</one>',
+ '<one>@s A @/s B .</one>',
+ '<one>@s A @/s~ B .</one>',
+]) test(`Selection affinity survives every structural round trip: ${source}`, () => {
+ const original = parseScript("edit", source);
+ const selection = original.selections[0]!;
+ const move = (text: string, startAnchorId: string, endAnchorId: string) => adjustScriptSelection({
+ sourceName: "edit", source: text, parsed: parseScript("edit", text),
+ adjustment: { id: selection.id, startAnchorId, endAnchorId },
+ });
+ const expected = move(source, selection.startAnchorId, selection.endAnchorId);
+ const anchors = original.semanticIndex.anchors;
+ for (let start = 0; start < anchors.length; start++) for (let end = start; end < anchors.length; end++) {
+ const moved = move(expected, anchors[start]!.id, anchors[end]!.id);
+ const actual = parseScript("edit", moved).selections[0]!;
+ assert.equal(actual.startAnchorId, anchors[start]!.id);
+ assert.equal(actual.endAnchorId, anchors[end]!.id);
+ assert.equal(move(moved, selection.startAnchorId, selection.endAnchorId), expected);
+ }
+});
+
test("Moving one relationship preserves crossing selections, cues and other moments", () => {
const source = '<one><HOST>@a One @b two @/a || three @/b. @beat! ~@other!</one>';
const parsed = parseScript("edit", source);
diff --git a/packages/studio/src/ui/main.ts b/packages/studio/src/ui/main.ts
index 76bc1790..6b7572cf 100644
--- a/packages/studio/src/ui/main.ts
+++ b/packages/studio/src/ui/main.ts
@@ -194,11 +194,19 @@ function textValue(value: CanonicalValue): string {
return typeof value === "string" ? value : value === null ? "" : String(value);
}
+function restoreParameterControls(entityId: string): void {
+ const current = store.current();
+ if (current?.selection.kind === "clip" && current.selection.clipId === entityId) {
+ renderInspector(current.snapshot, entityId);
+ }
+}
+
function commitControl(entityId: string, parameter: Clip["inspector"][number], replacement: CanonicalValue): void {
try {
if (sameValue(parameterAuthorValue(parameter, replacement), parameter.value)) return;
void writeParameter(entityId, parameter, replacement);
} catch (error) {
+ restoreParameterControls(entityId);
status.textContent = "Invalid value"; status.className = "status error";
status.title = error instanceof Error ? error.message : String(error);
}
@@ -728,6 +736,7 @@ async function writeParameter(entityId: string, parameter: Clip["inspector"][num
const state = store.current();
if (state === undefined) return;
parameterWriteState = "Saving";
+ status.title = "";
status.textContent = parameterWriteState;
status.className = "status saving";
try {
@@ -742,6 +751,9 @@ async function writeParameter(entityId: string, parameter: Clip["inspector"][num
status.textContent = parameterWriteState;
status.className = "status saved";
} catch (error) {
+ // Validation and stale-revision rejections do not publish a new snapshot.
+ // Restore the accepted value just as a rejected compilation does.
+ restoreParameterControls(entityId);
parameterWriteState = "Failed";
status.textContent = error instanceof Error ? "Save failed" : parameterWriteState;
status.className = "status error";
@@ -1076,6 +1088,7 @@ window.addEventListener("keydown", (event) => {
function applySnapshot(snapshot: StudioSnapshot): void {
failureView.textContent = "";
status.className = "status";
+ status.title = "";
status.textContent = "";
renderMeta(snapshot);
library.show(snapshot);