fix(share): ask before sharing from Studio and bind each action to the confirmed review (#8268)

* fix(share): ask before sharing from Studio, naming the review it changes

A composition's script runs on Studio's origin by default, and a received
folder's .hyperframes/review.json can point Studio at an existing review.
Every share action except sign-in now asks the person first, naming the
review (its link), who can open it, the workspace and whether project files
are uploaded. The request carries the manage link of the review that was
shown, and the server refuses it with share_target_changed when the
project's review no longer matches, so nothing is shared or changed.

* fix(share): bind each Studio share action to the review id the person confirmed

Studio now gets the id and title of the review an action reaches, including a folder
whose record names a review it never opened (a received folder can ship one). The
confirmation names that review, its workspace and who can open it, and says plainly
when a folder arrives already linked. Actions carry the confirmed id; a missing one is
refused as confirmation_required and a different one as share_target_changed, and
after that refusal Studio drops the earlier choice. The docs describe the
confirmation and that project files are included only when chosen.

* fix(share): show the review title on one quoted line in the confirmation

* fix(share): say a linked share also sets who can open it, and check the new state fields

* fix(share): separate the question from the details and say when a title is unknown

* docs(share): name the review record without a path the citation check reads as a file
This commit is contained in:
Ular Kimsanov
2026-11-20 06:02:05 +00:00
committed by GitHub
parent ce0932e047
commit 2c3427089c
14 changed files with 389 additions and 22 deletions
+7 -1
View File
@@ -192,7 +192,13 @@ project. The five free shared-project allowance is the same allowance used by
Desktop and the CLI. The workspace meter comes from the server; retries of an
existing registration do not need an extra slot.
Project files are included when available for the workspace. The panel reports
Before Studio creates a link, uploads a version, or changes who can open a review or
whether its link is on, it asks you to confirm and names the review and who can open
it. A project folder remembers its review in `.hyperframes/review.json`,
so a folder someone sent you can arrive already linked to their review. If the
confirmation names a review you didn't share, cancel.
Project files are included only when you choose **Include editable project files**. The panel reports
whether the last Studio upload included files or was video only. If attaching
files fails, retry the upload or explicitly choose **Retry with video only**.
@@ -37,6 +37,8 @@ const state: ShareState = {
url: "https://hyperframes.dev/r/test",
previousUrl: null,
manageUrl: "https://hyperframes.dev/shares",
reviewId: "project",
reviewTitle: null,
};
it.each([".media/voice.mp3", ".hyperframes/studio-manual-edits.json"])(
"detects %s edits even while the Desktop watcher still says current",
@@ -15,6 +15,8 @@ export function presentShare(value: ShareState): LocalShareState {
failure: value.state === "failed" ? value.version.failure : null,
hasReadyVersion: value.ready || Boolean(value.previousUrl),
manageUrl: value.manageUrl,
reviewId: value.reviewId,
reviewTitle: value.reviewTitle,
// Desktop's watcher does not cover every portable render input.
changed: knownChanges(value),
audience: value.share?.access ?? null,
@@ -17,6 +17,8 @@ const state: ShareState = {
url: null,
previousUrl: null,
manageUrl: "https://hyperframes.dev/shares",
reviewId: null,
reviewTitle: null,
};
function fixture() {
const service: ShareService = {
@@ -55,7 +57,14 @@ async function token(app: Hono) {
throw new Error("missing token");
return body.csrf;
}
// What Studio sends after the person confirms: the id of the review the popover named, null for none.
function confirmed(body: unknown) {
if (!body || typeof body !== "object" || !("action" in body) || body.action === "login")
return body;
return "confirmedReview" in body ? body : { ...body, confirmedReview: state.reviewId };
}
function request(app: Hono, path: string, csrf: string, body?: unknown) {
body = path === "actions" ? confirmed(body) : body;
return app.request(
`/api/share/${path}`,
{
@@ -458,3 +467,77 @@ it.each([undefined, true])("forwards only explicit source consent (%s)", async (
await new Promise((resolve) => setTimeout(resolve, 0));
expect(service.run).toHaveBeenCalledWith(expect.objectContaining({ includeSource }));
});
describe("share actions need the review the person confirmed", () => {
const existing = "existing-project";
it.each([
["share", { action: "share", audience: "public" }],
["update", { action: "update" }],
["access", { action: "access", audience: "public" }],
["off", { action: "off" }],
["on", { action: "on" }],
])("refuses %s without a confirmed review and changes nothing", async (_, body) => {
const { app, service } = fixture();
const csrf = await token(app);
const response = await request(app, "actions", csrf, { ...body, confirmedReview: undefined });
expect(response.status).toBe(400);
expect(await response.json()).toMatchObject({ code: "confirmation_required" });
for (const mutation of [service.run, service.setAccess, service.linkOff, service.linkOn])
expect(mutation).not.toHaveBeenCalled();
});
it("refuses a first share when the folder's record already names a review the person was not shown", async () => {
const { app, service } = fixture();
vi.mocked(service.status).mockResolvedValue({ ...state, reviewId: existing });
const csrf = await token(app);
const response = await request(app, "actions", csrf, {
action: "share",
audience: "public",
confirmedReview: null,
});
expect(response.status).toBe(409);
expect(await response.json()).toMatchObject({ code: "share_target_changed" });
expect(service.run).not.toHaveBeenCalled();
const snapshot = await (await request(app, "snapshot", csrf)).json();
expect(snapshot.job).toBeNull();
});
it("refuses when the project now points to a different review than the one confirmed", async () => {
const { app, service } = fixture();
vi.mocked(service.status).mockResolvedValue({ ...state, reviewId: "another-project" });
const csrf = await token(app);
const response = await request(app, "actions", csrf, {
action: "access",
audience: "public",
confirmedReview: existing,
});
expect(response.status).toBe(409);
expect(service.setAccess).not.toHaveBeenCalled();
});
it("refuses a confirmation that is not a review id", async () => {
const { app, service } = fixture();
const csrf = await token(app);
const response = await request(app, "actions", csrf, {
action: "off",
confirmedReview: "https://hyperframes.studio/shares",
});
expect(response.status).toBe(400);
expect(service.linkOff).not.toHaveBeenCalled();
});
it("runs the action when the confirmed review is still the project's review", async () => {
const { app, service } = fixture();
vi.mocked(service.status).mockResolvedValue({ ...state, reviewId: existing });
const csrf = await token(app);
const response = await request(app, "actions", csrf, {
action: "access",
audience: "public",
confirmedReview: existing,
});
expect(response.status).toBe(202);
await vi.waitFor(() => expect(service.setAccess).toHaveBeenCalledWith("public"));
});
it("still signs in without a confirmed review", async () => {
const { app, login } = fixture();
const csrf = await token(app);
expect((await request(app, "actions", csrf, { action: "login" })).status).toBe(202);
await vi.waitFor(() => expect(login).toHaveBeenCalled());
});
});
+36 -8
View File
@@ -26,22 +26,26 @@ function actionInput(value: unknown): LocalShareAction | null {
const record = Object.fromEntries(Object.entries(value));
if (
Object.keys(record).some(
(key) => !["action", "audience", "space", "videoOnly", "includeSource"].includes(key),
(key) =>
!["action", "audience", "space", "videoOnly", "includeSource", "confirmedReview"].includes(
key,
),
)
)
return null;
const { action, audience, space, videoOnly, includeSource } = record;
const { action, audience, space, videoOnly, includeSource, confirmedReview } = record;
if (!isAction(action)) return null;
const chosen = AUDIENCES.find((mode) => mode === audience);
if (audience !== undefined && !chosen) return null;
const options = actionOptions(space, videoOnly, includeSource);
if (!options) return null;
if (["share", "access"].includes(action) && !chosen) return null;
return {
action,
audience: chosen,
...options,
};
return withConfirmedReview({ action, audience: chosen, ...options }, confirmedReview);
}
function withConfirmedReview(input: LocalShareAction, review: unknown): LocalShareAction | null {
if (input.action === "login" || review === undefined) return input;
return review === null || validId(review) ? { ...input, confirmedReview: review } : null;
}
function isRecord(value: unknown): value is Record<string, unknown> {
@@ -69,7 +73,10 @@ function optionalBoolean(value: unknown): boolean {
return value === undefined || typeof value === "boolean";
}
function validSpace(value: unknown): boolean {
return value === undefined || (typeof value === "string" && /^[A-Za-z0-9_-]{1,128}$/.test(value));
return value === undefined || validId(value);
}
function validId(value: unknown): value is string {
return typeof value === "string" && /^[A-Za-z0-9_-]{1,128}$/.test(value);
}
type CreateService = (
@@ -192,6 +199,8 @@ export function mountShareRoutes(
if (input.action !== "login") {
try {
owner = await sessionOwner(session);
const refused = await targetRefusal(session, input.confirmedReview);
if (refused) return c.json(refused.body, refused.status);
} catch (error) {
return c.json(await presentError(error, c.req.header("x-hyperframes-share-csrf")!), 400);
}
@@ -264,6 +273,25 @@ function executeAction(sharing: ShareService, input: LocalShareAction) {
});
}
async function targetRefusal(
session: { get: () => Promise<ShareService> },
confirmed?: string | null,
) {
if (confirmed === undefined)
return {
status: 400 as const,
body: { code: "confirmation_required", message: "Confirm this sharing change in Studio." },
};
if ((await (await session.get()).status()).reviewId === confirmed) return null;
return {
status: 409 as const,
body: {
code: "share_target_changed",
message: "This project now points to a different shared review. Check it and try again.",
},
};
}
function actionStep(input: LocalShareAction) {
return input.action === "login" ? "signing_in" : "preparing";
}
+18
View File
@@ -88,6 +88,24 @@ beforeEach(() => {
},
]);
});
describe("the review a share action reaches", () => {
it("names the review a folder's record points at even before it was ever opened", async () => {
mocks.record.mockResolvedValue({ projectId: "linked", opened: false, studioProjectId: "s" });
mocks.project.mockResolvedValue({ title: "Someone's review", latest_ready_version_id: null });
const status = await createShareService("/project").status();
expect(status).toMatchObject({ reviewId: "linked", reviewTitle: "Someone's review" });
expect(mocks.project).toHaveBeenCalledWith("linked");
});
it("names the shared review, and no review for a folder that was never shared", async () => {
expect(await createShareService("/project").status()).toMatchObject({ reviewId: null });
mocks.status.mockResolvedValue(shared);
mocks.project.mockResolvedValue({ title: "Mine", latest_ready_version_id: "version-id" });
expect(await createShareService("/project").status()).toMatchObject({
reviewId: "project",
reviewTitle: "Mine",
});
});
});
describe("share operation consent and identity", () => {
it("reads an existing link without rendering or creating a version", async () => {
mocks.status.mockResolvedValue(shared);
+15
View File
@@ -78,8 +78,23 @@ async function readStatus(
ready,
source: uncheckedSource(),
...statusLinks(activeUrl, ready, processing || failed, project),
...(await reviewTarget(dir, client, share, project)),
};
}
async function reviewTarget(
dir: string,
client: ReviewClient,
share: ReviewShare | null,
project: Awaited<ReturnType<typeof readProject>>,
) {
const reviewId = share?.projectId ?? (await recordedReview(dir));
const linked = project ?? (reviewId ? await client.project(reviewId).catch(() => null) : null);
return { reviewId, reviewTitle: linked?.title ?? null };
}
async function recordedReview(dir: string) {
const record = await reviewRecord(dir);
return record && !record.removed ? record.projectId : null;
}
async function readProject(share: ReviewShare | null, client: ReviewClient) {
return share?.projectId ? client.project(share.projectId) : null;
}
+3
View File
@@ -16,6 +16,8 @@ export interface LocalShareState {
state: "not_shared" | "link_off" | "ready" | "processing" | "failed" | "unavailable";
url: string | null;
manageUrl: string;
reviewId: string | null;
reviewTitle: string | null;
changed: boolean | null;
hasReadyVersion?: boolean;
failure?: string | null;
@@ -42,6 +44,7 @@ export type LocalShareAction = {
space?: string;
videoOnly?: boolean;
includeSource?: boolean;
confirmedReview?: string | null;
};
export type LocalShareInteraction =
| { event: "share_opened"; link: "none" | "live" | "changed" }
@@ -44,11 +44,15 @@ let root: Root;
let host: HTMLDivElement;
let snapshot: LocalShareSnapshot;
let calls: unknown[];
let confirmedReviews: unknown[];
let confirm: ReturnType<typeof vi.fn<(message?: string) => boolean>>;
let job: LocalShareJob;
const token = "a".repeat(43);
beforeEach(() => {
interaction.mockReset();
calls = [];
confirmedReviews = [];
confirm = vi.fn(() => true);
snapshot = {
versionSharing: true,
share: {
@@ -56,6 +60,8 @@ beforeEach(() => {
state: "not_shared",
url: null,
manageUrl: "https://hyperframes.dev/shares",
reviewId: null,
reviewTitle: null,
changed: false,
audience: null,
spaceId: null,
@@ -83,12 +89,15 @@ beforeEach(() => {
expect(new Headers(init?.headers).get("X-Hyperframes-Share-CSRF")).toBe(token);
if (url.endsWith("/snapshot")) return Response.json(snapshot);
if (url.endsWith("/actions")) {
calls.push(JSON.parse(String(init?.body)));
const { confirmedReview, ...body } = JSON.parse(String(init?.body));
calls.push(body);
confirmedReviews.push(confirmedReview);
return Response.json(job, { status: 202 });
}
return Response.json(job);
}),
);
vi.stubGlobal("confirm", confirm);
});
afterEach(() => {
act(() => root.unmount());
@@ -675,3 +684,113 @@ it("counts explicit audience, source and manage interactions without sending pro
[token, { event: "share_navigation_clicked", destination: "manage" }],
]);
});
it("sends nothing when the person cancels the confirmation", async () => {
confirm.mockReturnValue(false);
await mount();
await choose("public");
await act(async () => button("Create share link")?.click());
expect(confirm).toHaveBeenCalledOnce();
expect(calls).toEqual([]);
});
it("names the review and who can open it before changing access, and sends that review", async () => {
snapshot.share = {
...snapshot.share,
state: "ready",
url: "https://hyperframes.dev/s/existing",
manageUrl: "https://hyperframes.studio/reviews/existing",
reviewId: "existing",
reviewTitle: "Launch film",
audience: "invite",
spaceId: "team1",
};
await mount();
await choose("public");
await act(async () => button("Save access")?.click());
const message = confirm.mock.calls[0]?.[0] ?? "";
expect(message).toContain('Review: "Launch film"');
expect(message).toContain("Link: https://hyperframes.dev/s/existing");
expect(message).toContain("Workspace: Design team");
expect(message).toContain("Now: Only invited people");
expect(message).toContain("After: Anyone with the link");
expect(calls).toEqual([{ action: "access", audience: "public" }]);
expect(confirmedReviews).toEqual(["existing"]);
});
it("says a folder is already linked to a review before a first share reaches it", async () => {
snapshot.share = {
...snapshot.share,
reviewId: "linked",
reviewTitle: "Someone's review\nWho can open it: Only you",
};
await mount();
await choose("public");
await act(async () => button("Create share link")?.click());
const message = confirm.mock.calls[0]?.[0] ?? "";
expect(message).toContain("already linked to an existing review");
expect(message).toContain(`Review: "Someone's review Who can open it: Only you"`);
expect(message).not.toContain("\nWho can open it: Only you");
expect(message).not.toContain("Workspace:");
expect(confirmedReviews).toEqual(["linked"]);
});
it("confirms a first share as reaching no existing review", async () => {
await mount();
await choose("public");
await act(async () => button("Create share link")?.click());
expect(confirm.mock.calls[0]?.[0]).toContain("Create a share link for this project?");
expect(confirmedReviews).toEqual([null]);
});
it("drops the earlier choice when the project now points to a different review", async () => {
snapshot.share = {
...snapshot.share,
state: "ready",
url: "https://hyperframes.dev/s/existing",
reviewId: "existing",
audience: "invite",
};
vi.mocked(fetch).mockImplementation(async (url, init) => {
if (String(url).endsWith("/actions")) {
calls.push(JSON.parse(String(init?.body)));
snapshot.share = { ...snapshot.share, reviewId: "other", audience: "private" };
return Response.json(
{
code: "share_target_changed",
message: "This project now points to a different shared review.",
},
{ status: 409 },
);
}
return Response.json(snapshot);
});
await mount();
await choose("public");
await act(async () => button("Save access")?.click());
expect(calls).toHaveLength(1);
expect(host.textContent).toContain("different shared review");
expect(button("Save access")).toBeUndefined();
});
it("says when editable project files are included before uploading them", async () => {
await mount();
await choose("public");
await act(async () => {
const box = host.querySelector<HTMLInputElement>('input[type="checkbox"]');
box?.click();
});
await act(async () => button("Create share link")?.click());
expect(confirm.mock.calls[0]?.[0]).toContain("Includes editable project files");
expect(confirm.mock.calls[0]?.[0]).toContain("Workspace: Design team");
});
it("signs in without asking for a confirmation", async () => {
vi.mocked(fetch).mockImplementation(async (url, init) => {
if (String(url).endsWith("/snapshot"))
return Response.json({ code: "unauthenticated", message: "Sign in" }, { status: 400 });
if (String(url).endsWith("/actions")) {
calls.push(JSON.parse(String(init?.body)));
return Response.json({ ...job, step: "signing_in" }, { status: 202 });
}
return Response.json(job);
});
await mount();
await act(async () => button("Sign in")?.click());
expect(confirm).not.toHaveBeenCalled();
expect(calls).toEqual([{ action: "login" }]);
});
@@ -145,14 +145,7 @@ function ManageShare({ model, snapshot, url }: Props & { url: string | null }) {
variant="ghost"
className="h-8 rounded-full text-step-13"
disabled={model.busy}
onClick={() => {
if (
window.confirm(
"Turn off this link? Everyone using the link loses access. Comments are kept.",
)
)
void model.run({ action: "off" });
}}
onClick={() => void model.run({ action: "off" })}
>
Turn link off
</Button>
@@ -18,6 +18,7 @@ const AUDIENCES = {
},
private: { label: "Only you", detail: "Only you can access this share", icon: Lock },
};
export const audienceLabel = (audience: LocalShareAudience) => AUDIENCES[audience].label;
export function ShareAudience({
model,
@@ -19,6 +19,14 @@ const nullableNumber = (value: unknown): value is number | null =>
value === null || (typeof value === "number" && Number.isFinite(value));
export const isAudience = (value: unknown): value is LocalShareAudience =>
audiences.some((mode) => mode === value);
function isReviewNamed(value: Record<string, unknown>) {
return (
nullableText(value.url) &&
text(value.manageUrl) &&
nullableText(value.reviewId) &&
nullableText(value.reviewTitle)
);
}
function isState(value: unknown): value is LocalShareState {
return (
record(value) &&
@@ -26,8 +34,7 @@ function isState(value: unknown): value is LocalShareState {
String(value.state),
) &&
optionalFailure(value.failure) &&
nullableText(value.url) &&
text(value.manageUrl) &&
isReviewNamed(value) &&
nullableBoolean(value.changed) &&
nullableAudience(value.audience) &&
nullableText(value.spaceId) &&
@@ -0,0 +1,79 @@
import type { LocalShareAction, LocalShareSnapshot } from "@hyperframes/studio-server";
import { audienceLabel } from "./ShareAudience";
/**
* What the person agrees to before Studio shares anything: which review it touches and who can open it. A project's
* own review record can point at an existing review, so the review is always named.
*/
export function shareConfirmMessage(
action: LocalShareAction,
snapshot: LocalShareSnapshot,
spaceId: string,
): string {
const { share } = snapshot;
const linked = action.action === "share" && share.reviewId !== null;
const space = snapshot.spaces.find(
(item) => item.id === (share.spaceId ?? (linked ? null : spaceId)),
);
const lines = (...parts: string[]) => parts.filter(Boolean).join("\n");
const ask = (question: string, body: string) => (body ? `${question}\n\n${body}` : question);
const details = (...parts: string[]) =>
lines(
share.reviewId
? `Review: ${share.reviewTitle ? quoted(share.reviewTitle) : "(title not available)"}`
: "",
share.url ? `Link: ${share.url}` : "",
space ? `Workspace: ${space.name}` : "",
...parts,
);
const who = (audience?: LocalShareAudience) =>
audience ? `Who can open it: ${audienceLabel(audience)}` : "";
const files =
action.includeSource && !action.videoOnly
? "Includes editable project files, unused and Git-ignored files too."
: "";
switch (action.action) {
case "share":
return ask(
linked
? "This folder is already linked to an existing review. Sharing adds this video to it and sets who can open it. If you didn't share this project before, cancel: it may have come with a folder someone sent you."
: "Create a share link for this project?",
details(who(action.audience), files),
);
case "update":
return ask(
firstUpload(snapshot)
? "Create the share link for this review?"
: "Upload this project as a new version of this shared review?",
details(who(share.audience ?? undefined), files),
);
case "access":
return ask(
"Change who can open this shared review?",
details(
share.audience ? `Now: ${audienceLabel(share.audience)}` : "",
action.audience ? `After: ${audienceLabel(action.audience)}` : "",
),
);
case "on":
return ask("Turn this review's link back on?", details(who(share.audience ?? undefined)));
case "off":
return ask(
"Turn off this link? Everyone using the link loses access. Comments are kept.",
details(),
);
case "login":
return "";
}
}
type LocalShareAudience = NonNullable<LocalShareAction["audience"]>;
function quoted(title: string) {
const line = title.replace(/[\p{C}\p{Z}\s]+/gu, " ").trim();
return `"${line.length > 80 ? `${line.slice(0, 79)}…` : line}"`;
}
function firstUpload({ share, job }: LocalShareSnapshot) {
return (job?.state === "failed" || share.state === "failed") && share.hasReadyVersion === false;
}
@@ -9,6 +9,7 @@ import type {
import { useMountEffect } from "../../hooks/useMountEffect";
import { LocalShareError, shareAction, shareJob, shareSnapshot } from "./localShareClient";
import { shareInteraction } from "./localShareTelemetry";
import { shareConfirmMessage } from "./shareConfirm";
const STEP_LABELS: Record<string, string> = {
preparing: "Preparing your video…",
signing_in: "Finish signing in in your browser…",
@@ -104,7 +105,11 @@ export function useQuickShare(token: string, beforeShare?: () => Promise<void>)
if (timer.current) clearTimeout(timer.current);
};
});
async function run(action: LocalShareAction) {
async function run(request: LocalShareAction) {
const action = working.current ? null : confirmAction(request);
if (action) await start(action);
}
async function start(action: LocalShareAction) {
const signal = lifetime.current?.signal;
if (!signal || signal.aborted || working.current) return;
track({ event: "share_action_clicked", action: action.action });
@@ -121,6 +126,11 @@ export function useQuickShare(token: string, beforeShare?: () => Promise<void>)
await recoverActionFailure(cause, signal);
}
}
function confirmAction(request: LocalShareAction): LocalShareAction | null {
if (request.action === "login") return request;
if (!snapshot || !window.confirm(shareConfirmMessage(request, snapshot, spaceId))) return null;
return { ...request, confirmedReview: snapshot.share.reviewId };
}
async function recoverActionFailure(cause: unknown, signal: AbortSignal) {
if (
cause instanceof LocalShareError &&
@@ -136,7 +146,8 @@ export function useQuickShare(token: string, beforeShare?: () => Promise<void>)
return;
}
setProgress("");
const recovered = await refresh(signal, true);
const moved = cause instanceof LocalShareError && cause.code === "share_target_changed";
const recovered = await refresh(signal, !moved);
if (recovered && !signal.aborted) {
setError(failure(cause));
setErrorCode(cause instanceof LocalShareError ? cause.code : null);