8000 Streaming media pipeline + native file handles for multi-GB sources by johannboehme · Pull Request #24 · johannboehme/tk-1 · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
8000
Diff view
566 changes: 566 additions & 0 deletions frontend/bun.lock

Large diffs are not rendered by default.

7 changes: 4 additions & 3 deletions frontend/src/App.tsx
Original file line number Diff line number Diff line change
10BC8 Expand Up @@ -11,6 +11,7 @@ import { RecMark } from "./editor/components/RuleStrip";
import { Footer } from "./components/Footer";
import { Datenschutz } from "./pages/Datenschutz";
import Editor from "./pages/Editor";
import { JobPermissionRoute } from "./components/JobPermissionRoute";
import History from "./pages/History";
import { Impressum } from "./pages/Impressum";
import JobPage from "./pages/JobPage";
Expand Down Expand Up @@ -77,9 +78,9 @@ export default function App() {
<Routes>
<Route path="/" element={<Upload />} />
<Route path="/jobs" element={<History />} />
<Route path="/job/:id" element={<JobPage />} />
<Route path="/job/:id/edit" element={<Editor />} />
<Route path="/job/:id/render" element={<RenderScreen />} />
<Route path="/job/:id" element={<JobPermissionRoute><JobPage /></JobPermissionRoute>} />
<Route path="/job/:id/edit" element={<JobPermissionRoute><Editor /></JobPermissionRoute>} />
<Route path="/job/:id/render" element={<JobPermissionRoute><RenderScreen /></JobPermissionRoute>} />
<Route path="/settings" element={<Settings caps={caps} />} />
<Route path="/impressum" element={<Impressum />} />
<Route path="/datenschutz" element={<Datenschutz />} />
Expand Down
65 changes: 65 additions & 0 deletions frontend/src/components/JobPermissionRoute.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
/**
* Route wrapper that ensures all of a job's `FileSystemFileHandle`-
* backed assets have read permission before rendering the wrapped
* page (Editor / JobPage / RenderScreen). When a handle's permission
* has lapsed (typical after a page reload), shows a single-click
* "Allow access" prompt — the browser only grants
* `requestPermission()` from within a user gesture.
*
* No-op for v2 / OPFS-backed jobs: `checkReadPermission` returns
* "n/a" / "granted" for OPFS sources, the gate flips to ready
* immediately.
*/

import { useEffect, useMemo, useState } from "react";
import { useParams } from "react-router-dom";
import { jobsDb } from "../storage/jobs-db";
import {
PermissionGate,
type AssetWithName,
} from "./PermissionGate";

export function JobPermissionRoute({ children }: { children: React.ReactNode }) {
const { id = "" } = useParams<{ id: string }>();
const [assets, setAssets] = useState<AssetWithName[] | null>(null);
const [missing, setMissing] = useState(false);

useEffect(() => {
let cancelled = false;
(async () => {
const job = await jobsDb.getJob(id);
if (cancelled) return;
if (!job) {
setMissing(true);
return;
}
const list: AssetWithName[] = [];
if (job.audioSource) {
list.push({ source: job.audioSource, name: job.audioFilename });
}
for (const v of job.videos ?? []) {
if (v.source) list.push({ source: v.source, name: v.filename });
}
setAssets(list);
})();
return () => {
cancelled = true;
};
}, [id]);

// Memoise so PermissionGate's `useEffect` dep doesn't re-trigger on
// every parent render once we've resolved the list.
const memoised = useMemo(() => assets ?? [], [assets]);

if (missing) {
return (
<main className="flex-1 flex items-center justify-center px-6 py-10">
<div className="border-l-2 border-danger pl-3 py-2 text-sm text-danger font-mono">
Job not found.
</div>
</main>
);
}
if (assets === null) return null; // initial load, no flash
return <PermissionGate assets={memoised}>{children}</PermissionGate>;
}
166 changes: 166 additions & 0 deletions frontend/src/components/PermissionGate.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
/**
* Re-grant overlay for `FileSystemFileHandle`-backed jobs.
*
* When a user reopens a project after a page reload, the browser may
* have lost the read permission for their original media files (the
* permission state goes from `granted` → `prompt` once the
* tab/handle ages out). The browser only allows
* `handle.requestPermission()` from within a user gesture, so we
* gate the editor / job page on a click that fires the prompt.
*
* The gate is a no-op for v2 / OPFS-backed jobs (everything resolves
* to `granted`).
*/

import { useEffect, useState } from "react";
import {
type AssetSource,
checkReadPermission,
requestReadPermission,
} from "../local/asset-source";

export interface AssetWithName {
source: AssetSource;
name: string;
}

export interface PermissionGateProps {
/** All assets the page wants to read. The gate will check each and
* prompt for any that aren't granted. */
assets: AssetWithName[];
/** Rendered once every asset is granted. */
children: React.ReactNode;
}

type GateState =
| { kind: "checking" }
| { kind: "ready" }
| { kind: "needs-grant"; pending: AssetWithName[] }
| { kind: "denied"; denied: AssetWithName[] };

export function PermissionGate({ assets, children }: PermissionGateProps) {
const [state, setState] = useState<GateState>({ kind: "checking" });

useEffect(() => {
let cancelled = false;
(async () => {
const pending: AssetWithName[] = [];
for (const a of assets) {
const p = await checkReadPermission(a.source);
if (p === "prompt") pending.push(a);
else if (p === "denied") {
if (!cancelled) setState({ kind: "denied", denied: [a] });
return;
}
}
if (cancelled) return;
setState(pending.length === 0 ? { kind: "ready" } : { kind: "needs-grant", pending });
})();
return () => {
cancelled = true;
};
}, [assets]);

if (state.kind === "checking") return null;
if (state.kind === "ready") return <>{children}</>;
if (state.kind === "denied") {
return (
<DeniedView
denied={state.denied}
=> setState({ kind: "checking" })}
/>
);
}
return (
<NeedsGrantView
pending={state.pending}
=> setState({ kind: "ready" })}
=> setState({ kind: "denied", denied: d })}
/>
);
}

function NeedsGrantView({
pending,
onGranted,
onDenied,
}: {
pending: AssetWithName[];
onGranted: () => void;
onDenied: (denied: AssetWithName[]) => void;
}) {
const [busy, setBusy] = useState(false);
const grantAll = async () => {
setBusy(true);
const denied: AssetWithName[] = [];
for (const a of pending) {
const p = await requestReadPermission(a.source);
if (p !== "granted") denied.push(a);
}
setBusy(false);
if (denied.length > 0) onDenied(denied);
else onGranted();
};
return (
<main className="flex-1 flex items-center justify-center px-6 py-10">
<div className="max-w-md w-full bg-paper-hi border border-rule rounded-lg p-6 flex flex-col gap-4">
<h1 className="font-display text-2xl text-ink">Re-grant file access</h1>
<p className="text-sm text-ink-2 leading-relaxed">
Your browser doesn't keep file permissions across reloads.
Click below to re-allow this project to read its media files
from your disk — the bytes never leave your machine.
</p>
<ul className="flex flex-col gap-1 text-xs text-ink-2 font-mono">
{pending.map((a) => (
<li
key={a.name}
className="px-3 h-9 flex items-center bg-paper-deep border border-rule rounded"
>
{a.name}
</li>
))}
</ul>
<button
type="button"
>
disabled={busy}
className="h-11 rounded-md bg-hot text-paper font-display tracking-label uppercase text-sm hover:opacity-90 disabled:opacity-60"
>
{busy ? "…" : `Allow access (${pending.length})`}
</button>
</div>
</main>
);
}

function DeniedView({
denied,
onRetry,
}: {
denied: AssetWithName[];
onRetry: () => void;
}) {
return (
<main className="flex-1 flex items-center justify-center px-6 py-10">
<div className="max-w-md w-full bg-paper-hi border-l-2 border-danger pl-4 py-4 flex flex-col gap-3">
<h1 className="font-display text-xl text-ink">File access denied</h1>
<p className="text-sm text-ink-2 leading-relaxed">
Without read access we can't open this project. Files we
need:
</p>
<ul className="text-xs text-ink-2 font-mono">
{denied.map((d) => (
<li key={d.name}>· {d.name}</li>
))}
</ul>
<button
type="button"
>
className="self-start font-mono text-xs text-cobalt hover:underline tracking-label uppercase"
>
Try again
</button>
</div>
</main>
);
}
72 changes: 46 additions & 26 deletions frontend/src/editor/components/AddMediaButton.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,22 @@ vi.mock("../../local/jobs", () => ({
addImageToJob: vi.fn(async () => "cam-3"),
}));

vi.mock("../../local/file-picker", () => ({
pickVideoOrImageFiles: vi.fn(async () => []),
}));

import { addImageToJob, addVideoToJob } from "../../local/jobs";
import { pickVideoOrImageFiles } from "../../local/file-picker";

const mockedPick = vi.mocked(pickVideoOrImageFiles);

function file(name: string, type: string): File {
return new File(["dummy"], name, { type });
}

function pick(f: File) {
return { file: f, handle: null as null };
}

describe("AddMediaButton", () => {
beforeEach(() => {
Expand All @@ -22,70 +37,75 @@ describe("AddMediaButton", () => {
expect(screen.getByTestId("add-media-match-toggle")).toBeInTheDocument();
});

it("routes a video file through addVideoToJob with the toggle's setting (default ON)", async () => {
it("routes a video pick through addVideoToJob with the toggle's setting (default ON)", async () => {
const f = file("shot.mp4", "vi 10BC8 deo/mp4");
mockedPick.mockResolvedValueOnce([pick(f)]);
render(<AddMediaButton jobId="job-x" />);
const file = new File(["dummy"], "shot.mp4", { type: "video/mp4" });
const input = screen.getByTestId("add-media-input") as HTMLInputElement;
Object.defineProperty(input, "files", { value: [file], configurable: true });
fireEvent.change(input);
fireEvent.click(screen.getByTestId("add-media-button"));

await new Promise((r) => setTimeout(r, 0));
expect(addVideoToJob).toHaveBeenCalledWith("job-x", file, {
expect(addVideoToJob).toHaveBeenCalledWith("job-x", pick(f), {
skipSync: false,
});
});

it("toggling MATCH off causes videos to skip sync", async () => {
const f = file("broll.mp4", "video/mp4");
mockedPick.mockResolvedValueOnce([pick(f)]);
render(<AddMediaButton jobId="job-x" />);
fireEvent.click(screen.getByTestId("add-media-match-toggle"));
expect(
screen.getByTestId("add-media-match-toggle").getAttribute("aria-checked"),
).toBe("false");

const file = new File(["dummy"], "broll.mp4", { type: "video/mp4" });
const input = screen.getByTestId("add-media-input") as HTMLInputElement;
Object.defineProperty(input, "files", { value: [file], configurable: true });
fireEvent.change(input);
fireEvent.click(screen.getByTestId("add-media-button"));

await new Promise((r) => setTimeout(r, 0));
expect(addVideoToJob).toHaveBeenCalledWith("job-x", file, {
expect(addVideoToJob).toHaveBeenCalledWith("job-x", pick(f), {
skipSync: true,
});
});

it("routes an image file through addImageToJob (toggle is irrelevant)", async () => {
it("routes an image pick through addImageToJob (toggle is irrelevant)", async () => {
const f = file("still.png", "image/png");
mockedPick.mockResolvedValueOnce([pick(f)]);
render(<AddMediaButton jobId="job-x" />);
const file = new File(["dummy"], "still.png", { type: "image/png" });
const input = screen.getByTestId("add-media-input") as HTMLInputElement;
Object.defineProperty(input, "files", { value: [file], configurable: true });
fireEvent.change(input);
fireEvent.click(screen.getByTestId("add-media-button"));

await new Promise((r) => setTimeout(r, 0));
expect(addImageToJob).toHaveBeenCalledWith("job-x", file);
expect(addImageToJob).toHaveBeenCalledWith("job-x", pick(f));
expect(addVideoToJob).not.toHaveBeenCalled();
});

it("a mixed selection dispatches to the correct entry per file", async () => {
const v = file("a.mp4", "video/mp4");
const i = file("b.png", "image/png");
mockedPick.mockResolvedValueOnce([pick(v), pick(i)]);
render(<AddMediaButton jobId="job-x" />);
const v = new File(["v"], "a.mp4", { type: "video/mp4" });
const i = new File(["i"], "b.png", { type: "image/png" });
const input = screen.getByTestId("add-media-input") as HTMLInputElement;
Object.defineProperty(input, "files", { value: [v, i], configurable: true });
fireEvent.change(input);
fireEvent.click(screen.getByTestId("add-media-button"));

await new Promise((r) => setTimeout(r, 5));
expect(addVideoToJob).toHaveBeenCalledTimes(1);
expect(addImageToJob).toHaveBeenCalledTimes(1);
});

it("posts a notice on success summarising what was added", async () => {
const f = file("shot.mp4", "video/mp4");
mockedPick.mockResolvedValueOnce([pick(f)]);
render(<AddMediaButton jobId="job-x" />);
const file = new File(["dummy"], "shot.mp4", { type: "video/mp4" });
const input = screen.getByTestId("add-media-input") as HTMLInputElement;
Object.defineProperty(input, "files", { value: [file], configurable: true });
fireEvent.change(input);
fireEvent.click(screen.getByTestId("add-media-button"));

await new Promise((r) => setTimeout(r, 0));
expect(useEditorStore.getState().notice?.message).toMatch(/added/i);
});

it("user-cancelled pick (empty array) is a silent no-op", async () => {
mockedPick.mockResolvedValueOnce([]);
render(<AddMediaButton jobId="job-x" />);
fireEvent.click(screen.getByTestId("add-media-button"));
await new Promise((r) => setTimeout(r, 0));
expect(addVideoToJob).not.toHaveBeenCalled();
expect(addImageToJob).not.toHaveBeenCalled();
expect(useEditorStore.getState().notice).toBeFalsy();
});
});
Loading
Loading
0