mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-11-18 16:08:56 +00:00
fix(cli): history turn ids from the project folder are checked and sent encoded (#7883)
* fix(cli): history turn ids from the project folder are checked and sent encoded * test(cli): history turn fixtures use the id shape the CLI mints * fix(cli): a turn's label and agent name are kept as written; only ids are checked * style(cli): format the turn reader * refactor(cli): the turn reader checks a marker through small predicates
This commit is contained in:
@@ -215,6 +215,18 @@ describe.each(["direct", "preview"])("hyperframes history (%s)", (mode) => {
|
||||
expect(files()).toEqual(["A", "N2"]);
|
||||
});
|
||||
|
||||
it("a turn with a long label and agent name still ends and undoes as that agent's", async () => {
|
||||
const { write, json, hf, files } = await setup();
|
||||
const name = "agent-".repeat(40);
|
||||
await hf("begin", "--who", name, "--label", "x".repeat(201));
|
||||
write("index.html", "A2");
|
||||
|
||||
const ended = await json("end");
|
||||
expect(ended.entry).toMatchObject({ who: { kind: "agent", name }, files: ["index.html"] });
|
||||
expect((await hf("undo", "--who", name)).code).toBe(0);
|
||||
expect(files()[0]).toBe("A");
|
||||
});
|
||||
|
||||
it("undo by one agent leaves another agent's open turn open", async () => {
|
||||
const { write, read, json, hf, turn } = await setup();
|
||||
await turn("gemini", "Notes", "notes.html", "N2");
|
||||
@@ -358,7 +370,7 @@ describe("hyperframes history, one owner", () => {
|
||||
await hf();
|
||||
const turn = {
|
||||
via: "preview",
|
||||
id: "turn-1",
|
||||
id: "7f3c2a1e-0b4d-4c8e-9a6f-2d1b3c4e5f60",
|
||||
who: { kind: "agent", name: "claude" },
|
||||
label: "Retitle",
|
||||
startedAt: 1,
|
||||
@@ -368,7 +380,7 @@ describe("hyperframes history, one owner", () => {
|
||||
write("index.html", "A2");
|
||||
|
||||
expect((await json("end")).entry).toMatchObject({
|
||||
id: "turn-1",
|
||||
id: "7f3c2a1e-0b4d-4c8e-9a6f-2d1b3c4e5f60",
|
||||
who: turn.who,
|
||||
files: ["index.html"],
|
||||
});
|
||||
@@ -475,7 +487,8 @@ describe("hyperframes history, one owner", () => {
|
||||
const { dir, write, json, hf } = project();
|
||||
await hf();
|
||||
const who = { kind: "agent", name: "claude" };
|
||||
const marker = { via: "direct", id: "turn-1", who, label: "Retitle", startedAt: 1 };
|
||||
const id = "7f3c2a1e-0b4d-4c8e-9a6f-2d1b3c4e5f61";
|
||||
const marker = { via: "direct", id, who, label: "Retitle", startedAt: 1 };
|
||||
writeFileSync(join(dir, ".hyperframes", "history-turn.json"), JSON.stringify(marker));
|
||||
write("index.html", "A2");
|
||||
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { createServer as createHttpServer } from "node:http";
|
||||
import type { AddressInfo } from "node:net";
|
||||
import { createServer, type Server } from "node:net";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, describe, expect, it, onTestFinished, vi } from "vitest";
|
||||
import { MAX_PORT_SCAN } from "../server/portUtils.js";
|
||||
import { historyDeps, withOwner } from "./historyOwner.js";
|
||||
import { endTurn, historyDeps, withOwner, type Turn } from "./historyOwner.js";
|
||||
|
||||
function tempDir(prefix: string): string {
|
||||
const dir = mkdtempSync(join(tmpdir(), prefix));
|
||||
@@ -60,3 +62,66 @@ describe("preview discovery for history", () => {
|
||||
expect(listener.connections()).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
async function recordingPreview(): Promise<{ port: number; paths: string[] }> {
|
||||
const paths: string[] = [];
|
||||
const server = createHttpServer((request, response) => {
|
||||
paths.push(request.url ?? "");
|
||||
response.setHeader("content-type", "application/json");
|
||||
response.end(JSON.stringify({ entries: [], entry: null }));
|
||||
});
|
||||
await new Promise<void>((listening) => server.listen(0, "127.0.0.1", () => listening()));
|
||||
onTestFinished(() => new Promise<void>((done) => server.close(() => done())));
|
||||
return { port: (server.address() as AddressInfo).port, paths };
|
||||
}
|
||||
|
||||
function projectWithMarker(id: string): string {
|
||||
const dir = tempDir("hf-history-marker-");
|
||||
writeFileSync(join(dir, "index.html"), "A");
|
||||
mkdirSync(join(dir, ".hyperframes"), { recursive: true });
|
||||
const marker = { via: "preview", id, who: { kind: "agent", name: "Agent" }, label: "Edit" };
|
||||
writeFileSync(
|
||||
join(dir, ".hyperframes", "history-turn.json"),
|
||||
JSON.stringify({ ...marker, startedAt: 1, lastWriteAt: 2, parts: [] }),
|
||||
);
|
||||
return dir;
|
||||
}
|
||||
|
||||
describe("history turn markers from the project folder", () => {
|
||||
const original = historyDeps.findServer;
|
||||
afterEach(() => {
|
||||
historyDeps.findServer = original;
|
||||
});
|
||||
|
||||
it.each(["../../files/index.html", "%2e%2e/%2e%2e/files", "x?y", "x#y"])(
|
||||
"refuses a marker whose id is %s",
|
||||
async (id) => {
|
||||
const preview = await recordingPreview();
|
||||
historyDeps.findServer = async () => ({ port: preview.port, projectName: "p" }) as never;
|
||||
|
||||
expect(await withOwner(projectWithMarker(id), async (_owner, turn) => turn)).toBeNull();
|
||||
},
|
||||
);
|
||||
|
||||
it("sends a turn id only as one encoded path segment of its own close route", async () => {
|
||||
const preview = await recordingPreview();
|
||||
historyDeps.findServer = async () => ({ port: preview.port, projectName: "p" }) as never;
|
||||
const dir = projectWithMarker("not-read");
|
||||
const turn: Turn = {
|
||||
via: "preview",
|
||||
id: "../../files/x?y#z",
|
||||
who: { kind: "agent", name: "Agent" },
|
||||
label: "Edit",
|
||||
startedAt: 1,
|
||||
lastWriteAt: 2,
|
||||
parts: [],
|
||||
};
|
||||
|
||||
await withOwner(dir, (owner) => endTurn(owner, turn, dir));
|
||||
|
||||
expect(preview.paths).toContain(
|
||||
"/api/projects/p/history/window/..%2F..%2Ffiles%2Fx%3Fy%23z/close",
|
||||
);
|
||||
expect(preview.paths.every((path) => path.startsWith("/api/projects/p/history"))).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
type HistoryResult,
|
||||
type HistoryWho,
|
||||
type UndoMode,
|
||||
isHistoryId,
|
||||
} from "@hyperframes/studio-server/history";
|
||||
|
||||
import { resolveProject } from "./project.js";
|
||||
@@ -78,11 +79,38 @@ export class Refusal extends Error {}
|
||||
|
||||
const turnFile = (dir: string) => join(dir, ".hyperframes", "history-turn.json");
|
||||
|
||||
const WHO_KINDS: readonly unknown[] = ["person", "agent", "outside"] satisfies HistoryWho["kind"][];
|
||||
const isId = (value: unknown): value is string => typeof value === "string" && isHistoryId(value);
|
||||
const isIds = (value: unknown): value is string[] => Array.isArray(value) && value.every(isId);
|
||||
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
||||
!!value && typeof value === "object";
|
||||
const isVia = (value: unknown): value is Turn["via"] => value === "preview" || value === "direct";
|
||||
|
||||
function whoOf(value: unknown): HistoryWho | null {
|
||||
if (!isRecord(value) || !WHO_KINDS.includes(value.kind) || typeof value.name !== "string")
|
||||
return null;
|
||||
return { kind: value.kind as HistoryWho["kind"], name: value.name };
|
||||
}
|
||||
|
||||
const isTurnHead = (value: Record<string, unknown>) => isVia(value.via) && isId(value.id);
|
||||
const hasTurnFields = (value: Record<string, unknown>) =>
|
||||
typeof value.label === "string" &&
|
||||
typeof value.startedAt === "number" &&
|
||||
typeof value.lastWriteAt === "number";
|
||||
|
||||
function parseTurn(value: unknown): Turn | null {
|
||||
if (!isRecord(value) || !isTurnHead(value) || !hasTurnFields(value)) return null;
|
||||
const who = whoOf(value.who);
|
||||
const parts = value.parts ?? [];
|
||||
if (!who || !isIds(parts)) return null;
|
||||
const { via, id, label, startedAt, lastWriteAt } = value as Omit<Turn, "who" | "parts">;
|
||||
return { via, id, who, label, startedAt, lastWriteAt, parts };
|
||||
}
|
||||
|
||||
/** The open turn, or null; a marker with no last write time cannot say when the turn ended, so it has. */
|
||||
function readTurn(dir: string): Turn | null {
|
||||
try {
|
||||
const turn = JSON.parse(readFileSync(turnFile(dir), "utf-8")) as Turn;
|
||||
return typeof turn.lastWriteAt === "number" ? { ...turn, parts: turn.parts ?? [] } : null;
|
||||
return parseTurn(JSON.parse(readFileSync(turnFile(dir), "utf-8")));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
@@ -100,7 +128,8 @@ const lastTurnsFile = (dir: string) => join(dir, ".hyperframes", "history-turns.
|
||||
function readLastTurns(dir: string): Record<string, string[]> {
|
||||
try {
|
||||
const turns: unknown = JSON.parse(readFileSync(lastTurnsFile(dir), "utf-8"));
|
||||
return turns && typeof turns === "object" ? (turns as Record<string, string[]>) : {};
|
||||
if (!turns || typeof turns !== "object") return {};
|
||||
return Object.fromEntries(Object.entries(turns).filter(([, parts]) => isIds(parts)));
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
@@ -160,7 +189,8 @@ function previewOwner(route: (path: string) => string): Owner {
|
||||
via: "preview",
|
||||
list,
|
||||
peek: async (point) => (await json(`/peek/${encodeURIComponent(point)}`)).files,
|
||||
blob: async (hash) => Buffer.from(await (await call(`/blob/${hash}`)).arrayBuffer()),
|
||||
blob: async (hash) =>
|
||||
Buffer.from(await (await call(`/blob/${encodeURIComponent(hash)}`)).arrayBuffer()),
|
||||
undo: (id, who, mode) => json("/undo", { entryId: id, who, mode }),
|
||||
restore: (point, who) => json("/restore", { point, who }),
|
||||
pin: async (id, pinned) => void (await json("/pin", { entryId: id, pinned })),
|
||||
@@ -175,7 +205,7 @@ function previewOwner(route: (path: string) => string): Owner {
|
||||
},
|
||||
// A preview restarted since begin committed the window on its way down.
|
||||
end: (id) =>
|
||||
json(`/window/${id}/close`, {})
|
||||
json(`/window/${encodeURIComponent(id)}/close`, {})
|
||||
.then((closed) => closed.entry as HistoryEntry | null)
|
||||
.catch(async () => (await list()).find((entry) => entry.id === id) ?? null),
|
||||
checkpoint: async () => void (await json("/checkpoint", {}, AbortSignal.timeout(5_000))),
|
||||
|
||||
@@ -19,7 +19,7 @@ export { reclaimUncopiedBlobs, type ReclaimedHistory } from "./reclaimUncopied.j
|
||||
export { isUncopiedMedia } from "./uncopied.js";
|
||||
export { HistoryBusyError } from "./ownerLock.js";
|
||||
export { onRestoredInPlace, type InPlaceOutcome } from "./blobStore.js";
|
||||
export { HistoryIdError } from "./historyId.js";
|
||||
export { HistoryIdError, isHistoryId } from "./historyId.js";
|
||||
export { historyCache } from "./historyCache.js";
|
||||
export {
|
||||
listProjectHistories,
|
||||
|
||||
Reference in New Issue
Block a user