From 39fa5ae9d27c7d3a8a3425cadea73a4306174dc5 Mon Sep 17 00:00:00 2001 From: Michael Wang Date: Fri, 20 Nov 2026 20:38:03 +0000 Subject: [PATCH] fix(cli): share confirms an existing review before changing it in a received folder (#8315) * fix(cli): share confirms an existing review before changing it in a received folder * fix(cli): share asks before changing a review while a share is still in progress --- docs/packages/cli.mdx | 16 ++- packages/cli/src/commands/share.test.ts | 143 +++++++++++++++++++++++- packages/cli/src/commands/share.ts | 82 +++++++++++++- packages/cli/src/share/service.ts | 11 ++ 4 files changed, 245 insertions(+), 7 deletions(-) diff --git a/docs/packages/cli.mdx b/docs/packages/cli.mdx index 5f83dd8c52..c1377eca9a 100644 --- a/docs/packages/cli.mdx +++ b/docs/packages/cli.mdx @@ -134,7 +134,7 @@ when no login or API key is saved (see [`auth`](#hyperframes-auth)). **Flags, not prompts.** A missing required flag fails immediately with a usage example rather than waiting for input. These commands can ask questions on a TTY: `init` prompts for a project name and example unless you pass -`--non-interactive`, `catalog --human-friendly` opens a picker, and `share` asks for a first-share audience. Nothing else +`--non-interactive`, `catalog --human-friendly` opens a picker, and `share` asks for a first-share audience and, in a folder that came from someone else, confirms the existing review it would change. Nothing else prompts, apart from confirmations you can skip with `--yes` or `--no-confirm`. **Unattended runs never prompt.** A run is unattended when stdin or stdout is not @@ -3417,6 +3417,20 @@ the source is unchanged; if it changed, explicitly use `--update`. If the project's review or audience changes while rendering, check the current share with `--status` before retrying. +A folder that came from someone else can carry a review record that names their +existing review. When the project's received-files record, or one above or inside +it, marks the folder as received, `share` confirms that review before it changes +who can open it, its link or its versions. This covers an audience flag, +`--update`, and a share that would add a version or finish setting up the link. In an attended terminal it shows +the review's title, id and link and asks first; declining changes nothing. An +unattended run (`--yes`, `--json`, CI or no terminal) is refused with +`review_confirmation_required` unless `--review ` names that same +review; a `--review` that names another review is refused with `review_mismatch`. +A folder whose received-files records cannot all be read counts as received. +Reading the existing link, a first share with no existing review, and folders +not marked as received are unchanged. To share a received folder as a new review +instead, remove the review record in its `.hyperframes` folder. + Completed renders accumulate in `.hyperframes/share-renders/`. To reclaim that space, wait for uploads to finish and close any running share commands, then remove that directory and `.hyperframes/share-render.json`. The next share or diff --git a/packages/cli/src/commands/share.test.ts b/packages/cli/src/commands/share.test.ts index 0307c03b13..1070a67142 100644 --- a/packages/cli/src/commands/share.test.ts +++ b/packages/cli/src/commands/share.test.ts @@ -1,22 +1,43 @@ import { SourceIgnoreError, ReviewFailed } from "@hyperframes/share"; -import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { runCommand } from "citty"; import { consumeCommandResult } from "../utils/commandResult.js"; const mocks = vi.hoisted(() => ({ run: vi.fn(), + status: vi.fn(), + confirm: vi.fn(), + received: null as null | "unchecked" | { path: string; listed: string[]; hashes: string[] }, + unattended: true, progress: undefined as undefined | ((value: { step: string; slow?: boolean } | null) => void), })); vi.mock("../utils/project.js", () => ({ resolveProjectOrThrow: () => ({ dir: "/project" }) })); -vi.mock("../share/service.js", () => ({ +vi.mock("../utils/privateProjectFile.js", () => ({ + receivedRecordStatus: () => mocks.received, +})); +vi.mock("../utils/attendedTerminal.js", async (importOriginal) => ({ + ...(await importOriginal()), + isUnattended: () => mocks.unattended, +})); +vi.mock("../ui/prompts.js", () => ({ + confirm: mocks.confirm, + select: vi.fn(), + isCancel: (value: unknown) => typeof value === "symbol", +})); +vi.mock("../share/service.js", async (importOriginal) => ({ + ...(await importOriginal()), createShareService: (_dir: string, progress: typeof mocks.progress) => { mocks.progress = progress; - return { run: mocks.run }; + return { run: mocks.run, status: mocks.status }; }, })); import command from "./share.js"; beforeEach(() => { consumeCommandResult(); mocks.run.mockReset(); + mocks.status.mockReset(); + mocks.confirm.mockReset(); + mocks.received = null; + mocks.unattended = true; mocks.run.mockResolvedValue({ state: "failed", ready: false, @@ -164,3 +185,119 @@ it("accepts explicit source inclusion and rejects conflicting choices", async () expect(consumeCommandResult().exitCode).toBe(2); expect(mocks.run).not.toHaveBeenCalled(); }); + +describe("a received folder whose record names an existing review", () => { + const linked = { + reviewId: "rev_theirs", + reviewTitle: "Their \u001b[31mreview", + share: { projectId: "rev_theirs", access: "private", url: "https://hyperframes.dev/r/theirs" }, + state: "ready", + ready: true, + url: "https://hyperframes.dev/r/theirs", + version: { last: { current: true } }, + }; + beforeEach(() => { + mocks.received = { path: "/project/.hyperframes/received-files.json", listed: [], hashes: [] }; + mocks.status.mockResolvedValue(linked); + mocks.run.mockResolvedValue({ state: "ready", ready: true, url: linked.url, source: {} }); + }); + + it("shows the review and changes nothing when the person declines", async () => { + mocks.unattended = false; + mocks.confirm.mockResolvedValue(false); + const out = vi.spyOn(console, "log").mockImplementation(() => {}); + const err = vi.spyOn(console, "error").mockImplementation(() => {}); + await runCommand(command, { rawArgs: ["--public"] }); + expect(mocks.confirm).toHaveBeenCalledWith( + expect.objectContaining({ message: "Share to this review?" }), + ); + const shown = out.mock.calls.flat().join("\n"); + expect(shown).toContain('Review: "Their \\x1b[31mreview" (rev_theirs)'); + expect(shown).toContain("Link: https://hyperframes.dev/r/theirs"); + expect(err).toHaveBeenCalledWith("Sharing cancelled."); + expect(consumeCommandResult().exitCode).toBe(2); + expect(mocks.run).not.toHaveBeenCalled(); + }); + + it("shares to the review the person confirmed", async () => { + mocks.unattended = false; + mocks.confirm.mockResolvedValue(true); + vi.spyOn(console, "log").mockImplementation(() => {}); + await runCommand(command, { rawArgs: ["--update"] }); + expect(mocks.run).toHaveBeenCalledWith( + expect.objectContaining({ action: "update", confirmedReview: "rev_theirs" }), + ); + }); + + it.each([[["--yes"]], [["--json"]], [[]]])( + "refuses to change it unattended without --review %j", + async (flags: string[]) => { + const out = vi.spyOn(console, "log").mockImplementation(() => {}); + vi.spyOn(console, "error").mockImplementation(() => {}); + await runCommand(command, { rawArgs: ["--update", ...flags] }); + expect(consumeCommandResult().exitCode).toBe(2); + expect(mocks.confirm).not.toHaveBeenCalled(); + expect(mocks.run).not.toHaveBeenCalled(); + if (flags[0] === "--json") + expect(JSON.parse(String(out.mock.calls[0]?.[0]))).toMatchObject({ + error: { code: "review_confirmation_required" }, + }); + }, + ); + + it("shares unattended to the review --review names", async () => { + vi.spyOn(console, "log").mockImplementation(() => {}); + await runCommand(command, { rawArgs: ["--public", "--review", "rev_theirs", "--json"] }); + expect(mocks.run).toHaveBeenCalledWith( + expect.objectContaining({ audience: "public", confirmedReview: "rev_theirs" }), + ); + }); + + it("refuses a --review that names another review", async () => { + const out = vi.spyOn(console, "log").mockImplementation(() => {}); + await runCommand(command, { rawArgs: ["--update", "--review", "rev_mine", "--json"] }); + expect(consumeCommandResult().exitCode).toBe(2); + expect(JSON.parse(String(out.mock.calls[0]?.[0]))).toMatchObject({ + error: { code: "review_mismatch" }, + }); + expect(mocks.run).not.toHaveBeenCalled(); + }); + + it("counts a folder whose received-files records cannot be read as received", async () => { + mocks.received = "unchecked"; + vi.spyOn(console, "log").mockImplementation(() => {}); + await runCommand(command, { rawArgs: ["--update", "--json"] }); + expect(mocks.run).not.toHaveBeenCalled(); + }); + + it("returns the existing link without asking when nothing would change", async () => { + vi.spyOn(console, "log").mockImplementation(() => {}); + await runCommand(command, { rawArgs: ["--json"] }); + expect(mocks.run).toHaveBeenCalledWith( + expect.not.objectContaining({ confirmedReview: expect.anything() }), + ); + }); + + it.each([ + ["a share still in progress", { ...linked, activity: { step: "uploading" }, ready: false }], + ["an unopened record with no share yet", { ...linked, share: null, ready: false, url: null }], + ])("refuses unattended without --review for %s", async (_label, state) => { + mocks.status.mockResolvedValue(state); + vi.spyOn(console, "log").mockImplementation(() => {}); + await runCommand(command, { rawArgs: ["--json"] }); + expect(consumeCommandResult().exitCode).toBe(2); + expect(mocks.run).not.toHaveBeenCalled(); + }); + + it("asks nothing in a folder that is not received", async () => { + mocks.received = null; + mocks.unattended = false; + vi.spyOn(console, "log").mockImplementation(() => {}); + await runCommand(command, { rawArgs: ["--update"] }); + expect(mocks.status).not.toHaveBeenCalled(); + expect(mocks.confirm).not.toHaveBeenCalled(); + expect(mocks.run).toHaveBeenCalledWith( + expect.not.objectContaining({ confirmedReview: expect.anything() }), + ); + }); +}); diff --git a/packages/cli/src/commands/share.ts b/packages/cli/src/commands/share.ts index 060c11c644..17d6027d02 100644 --- a/packages/cli/src/commands/share.ts +++ b/packages/cli/src/commands/share.ts @@ -3,7 +3,11 @@ import { resolveProjectOrThrow } from "../utils/project.js"; import { CliUsageError, setCommandExitCode } from "../utils/commandResult.js"; import { isUnattended } from "../utils/attendedTerminal.js"; import * as prompts from "../ui/prompts.js"; +import { c } from "../ui/colors.js"; +import { terminalText } from "@hyperframes/core"; +import { receivedRecordStatus } from "../utils/privateProjectFile.js"; import { + changesNamedReview, createShareService, type ShareAction, type ShareState, @@ -50,6 +54,11 @@ export default defineCommand({ status: { type: "boolean", description: "Read status without rendering or uploading" }, manage: { type: "boolean", description: "Open this share's web management page" }, space: { type: "string", description: "Owning workspace for a new share" }, + review: { + type: "string", + description: + "The review id this run may change; needed without a prompt in a folder that came from someone else", + }, "wait-seconds": { type: "string", description: "Wait for processing (1–1800 seconds)", @@ -73,6 +82,7 @@ export default defineCommand({ if (message !== lastProgress) process.stderr.write(`${message}\n`); lastProgress = message; }); + await confirmNamedReview(input, args, service, project.dir); await chooseAudience(input, args, service); const result = await service.run(input); await presentResult(result, input, Boolean(args.json)); @@ -100,6 +110,7 @@ interface ShareArgs { json?: boolean; "wait-seconds"?: string; space?: string; + review?: string; "video-only"?: boolean; "include-source"?: boolean; } @@ -134,10 +145,10 @@ function validateActionOptions( ); if ( (action === "status" || action === "manage") && - (args.space || args["video-only"] || args["include-source"]) + (args.space || args["video-only"] || args["include-source"] || args.review !== undefined) ) throw new CliUsageError( - "--space, --include-source and --video-only cannot be used with --status or --manage.", + "--space, --include-source, --video-only and --review cannot be used with --status or --manage.", ); } @@ -156,8 +167,73 @@ function requestedAudience(args: ShareArgs) { return audiences[0]; } +function canAsk(args: ShareArgs) { + return !args.yes && !args.json && !isUnattended(); +} + function shouldPrompt(input: ShareAction, args: ShareArgs) { - return input.action === "share" && !input.audience && !args.yes && !args.json && !isUnattended(); + return input.action === "share" && !input.audience && canAsk(args); +} + +async function confirmNamedReview( + input: ShareAction, + args: ShareArgs, + service: ShareService, + dir: string, +) { + if (input.action !== "share" && input.action !== "update") return; + if (args.review === undefined && receivedRecordStatus(dir) === null) return; + const current = await service.status(); + if (args.review !== undefined) { + if (current.reviewId !== args.review) throw reviewMismatch(args.review, current.reviewId); + input.confirmedReview = args.review; + return; + } + if (!changesNamedReview(current, input)) return; + if (!canAsk(args)) throw reviewConfirmationRequired(current); + await askToChangeReview(current); + input.confirmedReview = current.reviewId; +} + +function namedReview(current: ShareState) { + const title = current.reviewTitle + ? `"${terminalText(current.reviewTitle)}"` + : "(title not available)"; + return `${title} (${terminalText(current.reviewId ?? "")})`; +} + +async function askToChangeReview(current: ShareState) { + console.log(); + console.log( + ` ${c.bold("This folder came from someone else, and its review record names an existing review.")}`, + ); + console.log( + ` ${c.bold("Sharing changes that review under your account: who can open it, its link or its versions.")}`, + ); + console.log(` ${c.dim(`Review: ${namedReview(current)}`)}`); + if (current.share?.url) console.log(` ${c.dim(`Link: ${terminalText(current.share.url)}`)}`); + console.log(` ${c.dim("If you did not share this review before, cancel.")}`); + console.log(); + const approved = await prompts.confirm({ message: "Share to this review?", initialValue: false }); + if (prompts.isCancel(approved) || approved !== true) + throw new CliUsageError("Sharing cancelled."); +} + +function reviewConfirmationRequired(current: ShareState) { + const id = terminalText(current.reviewId ?? ""); + return new CliUsageError( + `This folder came from someone else, and its review record names an existing review, ${namedReview(current)}. ` + + `This run cannot ask you to confirm it, so nothing was changed. Pass --review ${id} to share to that review, ` + + "or remove the review record in this folder's .hyperframes folder to share it as a new review.", + { code: "review_confirmation_required" }, + ); +} + +function reviewMismatch(given: string, named: string | null) { + return new CliUsageError( + `--review ${terminalText(given)} is not the review this folder's record names (${named ? terminalText(named) : "none"}). Nothing was changed.`, + { code: "review_mismatch" }, + ); } async function chooseAudience(input: ShareAction, args: ShareArgs, service: ShareService) { diff --git a/packages/cli/src/share/service.ts b/packages/cli/src/share/service.ts index ffbbbd688b..b24ecdedbf 100644 --- a/packages/cli/src/share/service.ts +++ b/packages/cli/src/share/service.ts @@ -375,6 +375,17 @@ function hasFailedVersion(version: Awaited>): b return Boolean(version.failure && !version.held); } +export function changesNamedReview(current: ShareState, input: ShareAction): boolean { + if (!current.reviewId) return false; + if (input.action === "update" || shareStillInProgress(current)) return true; + if (input.action !== "share") return false; + if (current.share && changesAudience(input, current.share)) return true; + return !retrievesExisting(current, input); +} + +function shareStillInProgress(current: ShareState) { + return Boolean(current.activity); +} function changesAudience(input: ShareAction, share: ReviewShare) { return input.action === "share" && Boolean(input.audience) && share.access !== input.audience; }