Merge remote-tracking branch 'origin/codex/unified-cli-share' into prerelease/cli-share

This commit is contained in:
Miguel Ángel
2026-11-10 13:33:42 -05:00
15 changed files with 225 additions and 21 deletions
+10 -2
View File
@@ -3069,8 +3069,12 @@ Adding versions uses the same project. Turning off its link does not free a slot
remove a project in web management or upgrade when the workspace is full.
The server enforces the limit even when clients create projects simultaneously.
Running `share` again returns the existing link without uploading edits. Use
`--update` to publish a new rendered version. The previous ready version remains
Running `share` again returns the existing link without uploading edits. An explicit
audience flag (for example, `share --public`) changes an existing share’s audience
without uploading a version, just like Studio’s audience selector. Without an
audience flag, access stays unchanged. Use
`--update` to publish a new rendered version. If nothing changed, the command says
“Already up to date” (`upToDate: true` in JSON). The previous ready version remains
visible while an update processes. Interrupted first uploads can resume when
the source is unchanged; if it changed, explicitly use `--update`. If the
project's review or audience changes while rendering, check the current share
@@ -3094,6 +3098,10 @@ failed update; `url` remains null. Use `--update` to explicitly retry with the
current project. Signing into a different account while a share is running
stops that operation; start it again after sign-in.
When another account owns the review, JSON errors use the fixed code
`owner_signed_out` with the owner email in `error.owner`. The human-readable
message also identifies the account to sign into.
The standard production CLI includes exact trusted storage origins for review
videos and editable project sources; no upload configuration is required.
Development environments, custom API/OAuth endpoints or clients, and custom
+1 -1
View File
@@ -37,7 +37,7 @@ export class AuthError extends Error {
export const ErrNotConfigured = () =>
new AuthError(
"NOT_CONFIGURED",
"No HeyGen credentials found",
"No HeyGen credentials found.",
"Run `hyperframes auth login` to sign in.",
);
+37
View File
@@ -1,3 +1,4 @@
import { ReviewFailed } from "@hyperframes/share";
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { runCommand } from "citty";
import { consumeCommandResult } from "../utils/commandResult.js";
@@ -96,3 +97,39 @@ it("deduplicates progress and terminates each message before the friendly error"
]);
expect(friendly).toHaveBeenCalledWith("Sharing blocked.");
});
it.each(["owner@example.com", "another@example.com"])(
"keeps the owner error code stable for %s",
async (owner) => {
mocks.run.mockRejectedValue(new ReviewFailed(403, `owner_signed_out:${owner}`));
const out = vi.spyOn(console, "log").mockImplementation(() => {});
await runCommand(command, { rawArgs: ["--status", "--json"] });
expect(consumeCommandResult().exitCode).toBe(1);
expect(out).toHaveBeenCalledOnce();
expect(JSON.parse(String(out.mock.calls[0]?.[0]))).toEqual({
ok: false,
error: {
code: "owner_signed_out",
owner,
message: `This review belongs to ${owner}. Switch to that account to manage it.`,
},
});
},
);
it("reports an unchanged update in human and JSON output", async () => {
mocks.run.mockResolvedValue({
state: "ready",
ready: true,
upToDate: true,
source: { at: "ready" },
});
const out = vi.spyOn(console, "log").mockImplementation(() => {});
await runCommand(command, { rawArgs: ["--update"] });
expect(out).toHaveBeenCalledWith("Already up to date.");
await runCommand(command, { rawArgs: ["--update", "--json"] });
expect(JSON.parse(String(out.mock.calls.at(-1)?.[0]))).toMatchObject({
ok: true,
upToDate: true,
});
});
+7 -3
View File
@@ -73,7 +73,10 @@ export default defineCommand({
await presentResult(result, input, Boolean(args.json));
} catch (error) {
const failure = shareError(error);
if (args.json) console.log(JSON.stringify(jsonFailure(failure.code, failure.message)));
if (args.json)
console.log(
JSON.stringify({ ...jsonFailure(failure.code, failure.message), error: failure }),
);
else console.error(failure.message);
setCommandExitCode(error instanceof CliUsageError ? 2 : 1);
}
@@ -114,7 +117,7 @@ function validateActionOptions(
) {
if (action !== "share" && audience)
throw new CliUsageError(
"Audience flags are only valid for a first share. Use --manage to change access.",
"Use audience flags with hyperframes share, without --update, --status or --manage.",
);
if ((action === "status" || action === "manage") && (args.space || args["video-only"]))
throw new CliUsageError("--space and --video-only cannot be used with --status or --manage.");
@@ -126,7 +129,7 @@ function requestedAudience(args: ShareArgs) {
if (args.team) audiences.push("team");
if (args["invite-only"]) audiences.push("invite");
if (args.private) audiences.push("private");
if (audiences.length > 1) throw new CliUsageError("Choose one first-share audience.");
if (audiences.length > 1) throw new CliUsageError("Choose one audience.");
return audiences[0];
}
@@ -172,6 +175,7 @@ async function presentResult(result: ShareState, input: ShareAction, json: boole
async function presentSuccessfulResult(result: ShareState, input: ShareAction, json: boolean) {
if (json) console.log(JSON.stringify({ ok: true, ...result }));
else if (result.upToDate) console.log("Already up to date.");
else if (input.action === "manage") {
console.log(result.manageUrl);
if (!isUnattended()) await (await import("open")).default(result.manageUrl);
@@ -10,6 +10,7 @@ afterEach(() => {
for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
});
const state: ShareState = {
upToDate: false,
share: {
projectId: "project",
url: "https://hyperframes.dev/r/test",
@@ -8,6 +8,7 @@ export function presentShare(value: ShareState): LocalShareState {
value.share?.takedown ||
value.share?.sharingState?.state === "subscription_required";
return {
upToDate: value.upToDate,
state: presentedState(value, Boolean(held)),
url: held ? null : (value.url ?? value.previousUrl),
failure: value.state === "failed" ? value.version.failure : null,
@@ -7,6 +7,7 @@ import { AuthError } from "../auth/errors.js";
import { createShareCsrf, localShareRequestAllowed } from "./shareBoundary.js";
const state: ShareState = {
upToDate: false,
source: { at: "not_checked" },
share: null,
version: { last: null, source: "none", exporting: null, failure: null },
+6 -3
View File
@@ -1,4 +1,4 @@
import { ReviewFailed, reviewSentence } from "@hyperframes/share";
import { ownerOf, ReviewFailed, reviewSentence } from "@hyperframes/share";
import { ShareSourceError } from "./sources.js";
import { isAuthError } from "../auth/errors.js";
import { CliUsageError } from "../utils/commandResult.js";
@@ -19,7 +19,7 @@ const HINTS: Record<string, string> = {
not_shared:
"This project has no shared review yet. Run hyperframes share with an explicit audience.",
};
export function shareError(error: unknown): { code: string; message: string } {
export function shareError(error: unknown): { code: string; message: string; owner?: string } {
if (error instanceof CliUsageError) return { code: error.code, message: error.message };
if (error instanceof ShareSourceError)
return { code: "source_unavailable", message: error.message };
@@ -28,11 +28,14 @@ export function shareError(error: unknown): { code: string; message: string } {
code: error.code.toLowerCase(),
message: `${error.message} ${error.hint ?? ""}`.trim(),
};
if (error instanceof ReviewFailed)
if (error instanceof ReviewFailed) {
const owner = error.status === 401 ? null : ownerOf(error.reason);
if (owner !== null) return { code: "owner_signed_out", owner, message: reviewSentence(error) };
return {
code: error.status === 401 ? "login_expired" : error.reason || "share_failed",
message: HINTS[error.reason] ?? reviewSentence(error),
};
}
return {
code: "share_failed",
message: error instanceof Error ? error.message : "Sharing failed. Try again.",
+44 -5
View File
@@ -13,6 +13,7 @@ const mocks = vi.hoisted(() => ({
refresh: vi.fn(),
event: vi.fn(),
access: vi.fn(),
setAccess: vi.fn(),
}));
vi.mock("@hyperframes/share", () => ({
reviewClient: () => ({ project: mocks.project, spaces: mocks.spaces, reviewFlags: mocks.flags }),
@@ -23,7 +24,7 @@ vi.mock("@hyperframes/share", () => ({
addVersion: mocks.add,
pendingReviewExport: mocks.pending,
refreshReviewExport: mocks.refresh,
setReviewAccess: vi.fn(),
setReviewAccess: mocks.setAccess,
turnOffReviewLink: vi.fn(),
ReviewFailed: class extends Error {
constructor(
@@ -104,15 +105,20 @@ describe("share operation consent and identity", () => {
).rejects.toMatchObject({ reason: "review_project_limit_reached" });
expect(mocks.render).not.toHaveBeenCalled();
});
it("preserves existing workspace and audience", async () => {
it("preserves existing workspace and changes an explicitly requested audience", async () => {
mocks.status.mockResolvedValue(shared);
const service = createShareService("/project");
await expect(service.run({ action: "update", space: "other" })).rejects.toMatchObject({
reason: "workspace_mismatch",
});
await expect(service.run({ action: "share", audience: "private" })).rejects.toMatchObject({
reason: "manage_existing_audience",
});
mocks.setAccess.mockImplementation(async () =>
mocks.status.mockResolvedValue({ ...shared, access: "private" }),
);
await service.run({ action: "share", audience: "private" });
expect(mocks.setAccess).toHaveBeenCalledWith(
expect.objectContaining({ change: { access: "private" } }),
);
expect(mocks.add).not.toHaveBeenCalled();
expect(mocks.render).not.toHaveBeenCalled();
});
it("refuses a public share opened while a private first share was rendering", async () => {
@@ -423,3 +429,36 @@ it("retries an uncreated first version after refusal even when local files chang
expect(mocks.add).toHaveBeenCalledOnce();
expect(mocks.create).not.toHaveBeenCalled();
});
it("reports an unchanged completed update without claiming a new version", async () => {
mocks.status.mockResolvedValue(shared);
mocks.version.mockResolvedValue({ last: { current: true }, source: "ready" });
mocks.add.mockResolvedValue(null);
const result = await createShareService("/project").run({ action: "update" });
expect(result.upToDate).toBe(true);
});
it("propagates a refused audience change without rendering", async () => {
mocks.status.mockResolvedValue(shared);
mocks.setAccess.mockRejectedValue(new Error("Restricted sharing requires a subscription"));
await expect(
createShareService("/project").run({ action: "share", audience: "team" }),
).rejects.toThrow("subscription");
expect(mocks.render).not.toHaveBeenCalled();
});
it("does not label a newly published version as already up to date", async () => {
mocks.status.mockResolvedValue(shared);
mocks.version.mockResolvedValue({ last: { current: true }, source: "ready" });
mocks.add.mockImplementation(async ({ onAdded }) => {
onAdded();
return null;
});
expect((await createShareService("/project").run({ action: "update" })).upToDate).toBe(false);
});
it("does not label a still-processing update as already up to date", async () => {
mocks.status.mockResolvedValue(shared);
mocks.version.mockResolvedValue({ last: { current: true }, source: "ready" });
mocks.pending.mockResolvedValue({ projectId: "project" });
mocks.add.mockResolvedValue(null);
expect((await createShareService("/project").run({ action: "update" })).upToDate).toBe(false);
});
+24 -2
View File
@@ -64,6 +64,7 @@ async function readStatus(
const failed = hasFailedVersion(version);
const ready = Boolean(activeUrl && latest && !processing && !failed);
return {
upToDate: false,
share,
version,
pending,
@@ -216,7 +217,10 @@ export function createShareService(
return { ...result, state: "processing", ready: false, url: null };
}
attempt.complete(result.ready, added);
return result;
return {
...result,
upToDate: isUnchangedUpdate(input, added, result),
};
};
const uploadTarget = async (current: ReviewShare | null, input: ShareAction, space?: string) => {
const share = current
@@ -250,7 +254,16 @@ export function createShareService(
const mutate = async (input: ShareAction, attempt: ShareAttempt) => {
await auth.access();
attempt.authenticated();
const current = await readStatus(dir, client, undefined, attempt.recover);
let current = await readStatus(dir, client, undefined, attempt.recover);
if (current.share && changesAudience(input, current.share)) {
assertExistingIntent(current.share, { ...input, audience: undefined });
const projectId = current.share.projectId;
await setReviewAccess({ projectPath: dir, client, change: { access: input.audience } });
current = await readStatus(dir, client, projectId);
assertExistingIntent(current.share, input);
attempt.retrieved();
return current;
}
assertExistingIntent(current.share, input);
if (retrievesExisting(current, input)) {
attempt.retrieved();
@@ -304,3 +317,12 @@ export type ShareState = Awaited<ReturnType<typeof readStatus>>;
function hasFailedVersion(version: Awaited<ReturnType<typeof reviewVersion>>): boolean {
return Boolean(version.failure && !version.held);
}
function changesAudience(input: ShareAction, share: ReviewShare) {
return input.action === "share" && Boolean(input.audience) && share.access !== input.audience;
}
function isUnchangedUpdate(input: ShareAction, added: boolean, result: ShareState) {
return (
input.action === "update" && !added && Boolean(result.version.last?.current) && !result.pending
);
}
+1
View File
@@ -11,6 +11,7 @@ export interface LocalShareSpace {
limit: number | null;
}
export interface LocalShareState {
upToDate?: boolean;
state: "not_shared" | "link_off" | "ready" | "processing" | "failed" | "unavailable";
url: string | null;
manageUrl: string;
@@ -497,7 +497,9 @@ it("refuses an upgrade destination outside the public pricing flow", async () =>
snapshot.spaces[0]!.plan = "free";
snapshot.spaces[0]!.upgradeUrl = "https://example.com/checkout";
await mount();
expect(host.textContent).not.toContain("Upgrade to Pro");
expect(
[...host.querySelectorAll("a")].some((link) => link.textContent?.includes("Upgrade to Pro")),
).toBe(false);
});
it.each([false, true])(
@@ -546,3 +548,38 @@ it("bootstraps sharing when the CLI advertises its bridge", async () => {
marker.remove();
}
});
it("acknowledges an unchanged update", async () => {
snapshot.share = {
...snapshot.share,
state: "ready",
url: "https://hyperframes.dev/r/test",
audience: "public",
spaceId: "team1",
};
job = { ...job, state: "done", result: { ...snapshot.share, upToDate: true } };
await act(async () => root.render(<QuickShareContent token={token} />));
await act(async () => button("Update shared version")?.click());
expect(host.textContent).toContain("Already up to date.");
});
it("resets the copied acknowledgement after two seconds", async () => {
vi.useFakeTimers();
Object.defineProperty(navigator, "clipboard", {
configurable: true,
value: { writeText: vi.fn().mockResolvedValue(undefined) },
});
snapshot.share = {
...snapshot.share,
state: "ready",
url: "https://hyperframes.dev/r/test",
audience: "public",
spaceId: "team1",
};
await act(async () => root.render(<QuickShareContent token={token} />));
await act(async () => button("Copy link")?.click());
expect(button("Copied")).toBeDefined();
await act(async () => vi.advanceTimersByTime(2000));
expect(button("Copied")).toBeUndefined();
expect(button("Copy link")).toBeDefined();
vi.useRealTimers();
});
@@ -69,6 +69,7 @@ export function QuickShareContent({
{progress ? (
<p role="status">{progress} You can close this panel; keep Studio running.</p>
) : null}
{model.notice ? <p role="status">{model.notice}</p> : null}
<ShareLogin model={model} />
{error ? (
<p role="alert" className="text-step-11 text-text-2">
@@ -61,6 +61,7 @@ export function ShareAudience({
{choices.map((value) => {
const option = AUDIENCES[value];
const OptionIcon = option.icon;
const needsPro = requiresPro(space, value, snapshot.share.audience);
return (
<MenuRadioItem
key={value}
@@ -77,9 +78,16 @@ export function ShareAudience({
<OptionIcon size={15} aria-hidden="true" />
</span>
<span className="min-w-0 leading-snug">
<span className="block font-semibold">{option.label}</span>
<span className="flex items-center gap-2 font-semibold">
{option.label}
{needsPro ? (
<span className="rounded bg-press px-1.5 py-0.5 text-step-10 font-semibold">
Pro
</span>
) : null}
</span>
<span className="block whitespace-normal text-step-11 text-text-3">
{option.detail}
{needsPro ? "Upgrade to Pro to use this option" : option.detail}
</span>
</span>
</span>
@@ -87,6 +95,26 @@ export function ShareAudience({
);
})}
</MenuRadioGroup>
{space?.plan === "free" &&
(!space.audiences.includes("team") || !space.audiences.includes("invite")) ? (
<p className="mx-2 mt-1 border-t border-border px-1 py-2 text-step-11 text-text-2">
Free includes anyone-with-the-link sharing. Upgrade to Pro for workspace and invite-only
sharing.
</p>
) : null}
</Menu>
);
}
function requiresPro(
space: LocalShareSnapshot["spaces"][number] | undefined,
value: LocalShareAudience,
current: LocalShareAudience | null,
) {
return (
space?.plan === "free" &&
!space.audiences.includes(value) &&
value !== current &&
(value === "team" || value === "invite")
);
}
@@ -29,7 +29,8 @@ export function useQuickShare(token: string, beforeShare?: () => Promise<void>)
const reconnectOnReturn = useRef(false);
const [error, setError] = useState<string | null>(null);
const [errorCode, setErrorCode] = useState<string | null>(null);
const [copied, setCopied] = useState(false);
const { copied, setCopied, acknowledgeCopy } = useCopyAcknowledgement();
const [notice, setNotice] = useState("");
const opened = useRef(false);
const lifetime = useRef<AbortController | null>(null);
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
@@ -59,6 +60,7 @@ export function useQuickShare(token: string, beforeShare?: () => Promise<void>)
const result = job.result;
if (result) setSnapshot((prior) => (prior ? { ...prior, share: result, job } : prior));
await refresh(signal, job.state === "failed");
if (!signal.aborted) setNotice(completionNotice(job));
}
async function refresh(signal: AbortSignal, preserveSelection = false) {
setError(null);
@@ -108,6 +110,7 @@ export function useQuickShare(token: string, beforeShare?: () => Promise<void>)
setError(null);
setErrorCode(null);
setCopied(false);
setNotice("");
setProgress("Preparing share…");
try {
if (["share", "update"].includes(action.action)) await beforeShare?.();
@@ -166,7 +169,8 @@ export function useQuickShare(token: string, beforeShare?: () => Promise<void>)
async function copy(url: string) {
try {
await navigator.clipboard.writeText(url);
setCopied(true);
if (lifetime.current?.signal.aborted) return;
acknowledgeCopy();
shareInteraction(token, { event: "share_link_copied", via: "copy" });
} catch {
setError("Couldn’t copy. Open the shared page and copy its address.");
@@ -181,9 +185,26 @@ export function useQuickShare(token: string, beforeShare?: () => Promise<void>)
error,
errorCode,
copied,
notice,
progress,
run,
copy,
};
}
export type QuickShareModel = ReturnType<typeof useQuickShare>;
function completionNotice(job: LocalShareJob) {
return job.state === "done" && job.result?.upToDate ? "Already up to date." : "";
}
function useCopyAcknowledgement() {
const [copied, setCopied] = useState(false);
const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
useMountEffect(() => () => clearTimeout(timer.current));
function acknowledgeCopy() {
clearTimeout(timer.current);
setCopied(true);
timer.current = setTimeout(() => setCopied(false), 2000);
}
return { copied, setCopied, acknowledgeCopy };
}