Skip to content
Open
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
Diff view
368 changes: 368 additions & 0 deletions apps/app/test/files-stories.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,368 @@
// @vitest-environment happy-dom
import { Effect, Option } from "effect";
import { afterEach, describe, expect, it, vi } from "vitest";
import { Machine as Browser } from "../gen/app__files.effect.vibe";
import { Machine as Correction, canBegin, canCancel, inv as correctionInv } from "../gen/app__files__correction.effect.vibe";
import * as Destination from "../gen/app__files__destination.effect.vibe";
import {
Machine as Shown,
canAnswered,
canLost,
canSelectAgain,
inv as previewInv,
showing,
usable,
} from "../gen/app__files__preview.effect.vibe";
import {
Machine as Scan,
canDiscardDraft,
canExportPdf,
canKeepPhoto,
canRecognize,
editText,
exporting,
inv as scanInv,
lawAPagePickedBehindItsPickerIsAdded,
lawTheScanStaysOpenOnlyBehindItsOwnPicker,
pageOf,
recognize,
recognized,
} from "../gen/app__files__scan.effect.vibe";
import * as ScanDraft from "../gen/app__files__scanDraft.effect.vibe";
import * as ScanText from "../gen/app__files__scanText.effect.vibe";
import * as FileSearch from "../gen/app__files__search.effect.vibe";
import { Machine as Bin, canAskToErase, canFinished, inv as trashInv, keptUntil, lawDaysLeftCountDownFromThirty } from "../gen/app__files__trash.effect.vibe";
import { Machine as Shell } from "../gen/app__shell.effect.vibe";
import { agentFilter } from "../src/files/agent.vibe";
import {
childrenOf,
filterTimeOf,
folderLocation,
kindOf,
scanNoteLimit,
validFileName,
validStoragePath,
} from "../src/files/entries.vibe";
import { selectListedFile, showPlace } from "../src/files/files.vibe";
import { Handles } from "../src/files/handles.vibe";
import files from "../src/files/index.tsx";
import { filesPlaces, parseFilesPlace } from "../src/files/places.vibe";
import { kindOf as previewKindOf, pictureFits } from "../src/files/preview.vibe";
import { scanPanel, scanPrimary, scanQuiet } from "../src/files/scan-dialog.ts";
import { ScanAssets, noteContent, searchWords, setScanOutline, startScan } from "../src/files/scan.vibe";
import { ScanEntry } from "../src/files/scanEntry.vibe";
import { TrashFacts } from "../src/files/trashFacts.vibe";
import * as From from "../src/runtime/senders.auth.vibe";
import { closeAll, drawn, goHome, hardware, only, open, press, underAct, until } from "./alpha.tsx";
import { memoryIndexedDB } from "./fakes/indexeddb.ts";
import { type Scene, scene } from "./fakes/scene.ts";

underAct();
afterEach(async () => {
await closeAll();
vi.unstubAllGlobals();
});

const SAMPLE_SCAN_BLOB = new Blob([new Uint8Array([137, 80, 78, 71])], { type: "image/png" });

async function mountFiles(world: Scene = { ...scene(), phone: true }) {
const running = await open(world, only("home", "view:Files", "notice"));
await drawn(() => running.alpha.runtime.runPromise(Effect.gen(function* () {
const shell = yield* Shell;
if ((yield* shell.get()).trail.at(-1) !== "Files") yield* shell.send({ type: "openView", view: "Files" });
})));
const runtime = files.runtime(running.alpha);
await until(running.alpha, runtime, Browser, (state) => state.open && state.storage.status === "Loaded");
return { ...running, world, runtime };
}

async function openDownloadsFolder(world?: Scene) {
const mounted = await mountFiles(world);
await press("Internal storage");
await press("Download");
await until(mounted.alpha, mounted.runtime, Browser, (state) => state.listing.status === "Loaded" && state.items.length === 2);
return mounted;
}

async function openScannerWithPage(world?: Scene) {
const mounted = await mountFiles(world);
await drawn(() => mounted.alpha.runtime.runPromise(startScan()));
await until(mounted.alpha, mounted.runtime, Scan, (state) => state.open && state.keeping.loading.status === "Loaded");
await drawn(() => mounted.runtime.runPromise(Effect.gen(function* () {
const held = yield* ScanAssets;
yield* held.hold(1, { blob: SAMPLE_SCAN_BLOB, width: 100, height: 140 });
const scan = yield* Scan;
yield* scan.send({ type: "add", frame: 1, replacing: 0, camera: true }, From.phone);
})));
await until(mounted.alpha, mounted.runtime, Scan, (state) => state.pages.length === 1);
return mounted;
}

describe("Files story specifications", () => {
// spec/app/files/correction.md, "Story: Correct a page's edges"
it("detects page edges on open, requires an updated outline after corner drag, and reports draw failure", async () => {
const { alpha, runtime } = await openScannerWithPage();

const idle = await runtime.runPromise(Effect.flatMap(Correction, (c) => c.get()));
expect(canBegin(idle, 1, "Phone")).toBe(false);
expect(canBegin(idle, 1, "Owner")).toBe(true);

await drawn(() => runtime.runPromise(Effect.flatMap(Correction, (c) => c.send({ type: "begin", image: 1 }, From.owner))));
await until(alpha, runtime, Correction, (state) => state.image === 1 && (state.failed || state.edges.showing));

const afterBegin = await runtime.runPromise(Effect.flatMap(Correction, (c) => c.get()));
if (!afterBegin.failed) {
await drawn(() => runtime.runPromise(setScanOutline(1, {
corners: [{ x: 0.1, y: 0.1 }, { x: 0.9, y: 0.1 }, { x: 0.9, y: 0.9 }, { x: 0.1, y: 0.9 }],
turns: 1,
})));
}
expect(canCancel(await runtime.runPromise(Effect.flatMap(Correction, (c) => c.get())), "Owner")).toBe(true);

await hardware("back");
await until(alpha, runtime, Correction, (state) => state.image === 0);
const closed = await runtime.runPromise(Effect.flatMap(Correction, (c) => c.get()));
expect(correctionInv(closed)).toBe(true);
});

it('tracks destination folder trail, loading/failure/empty states, and reviewed target place (spec/app/files/destination.md, "Story: Choose a destination")', async () => {
const { alpha, runtime } = await openDownloadsFolder();

const firstFile = await runtime.runPromise(Effect.flatMap(Browser, (b) => Effect.map(b.get(), (state) => state.items[0]?.id)));
expect(firstFile).toBeDefined();
if (firstFile !== undefined) {
await drawn(() => runtime.runPromise(selectListedFile(firstFile)));
await until(alpha, runtime, Browser, (state) => state.picked.includes(firstFile));
}

await drawn(() => runtime.runPromise(Effect.flatMap(Browser, (b) => b.send({ type: "openMoveTo", action: "Move" }, From.owner))));
await until(alpha, runtime, Browser, (state) => state.sheet.open && state.sheet.reading.status === "Loaded");

const sheet = await runtime.runPromise(Effect.flatMap(Browser, (b) => Effect.map(b.get(), (state) => state.sheet)));
expect(Destination.ready(sheet)).toBe(true);
expect(Destination.here(sheet)).toBeGreaterThan(0);
expect(Destination.place(sheet).names.length).toBeGreaterThan(0);

const folderLabel = await runtime.runPromise(Effect.flatMap(Handles, (handles) => handles.label(Destination.here(sheet))));
expect(Option.isSome(folderLabel)).toBe(true);
expect(folderLocation("Internal storage", "Download/Receipts")).toBe("Internal storage \u203a Download \u203a Receipts");

await hardware("back");
await until(alpha, runtime, Browser, (state) => !state.sheet.open);
expect(Destination.inv(await runtime.runPromise(Effect.flatMap(Browser, (b) => Effect.map(b.get(), (state) => state.sheet))))).toBe(true);
});

it('reports lost file access, clears stale preview content, and offers re-selection to the owner (spec/app/files/preview.md, "Story: Get a file back when access was lost")', async () => {
expect(previewKindOf("image/jpeg")).toBe("Photo");
expect(previewKindOf("application/pdf")).toBe("Pdf");
expect(pictureFits(undefined)).toBe(false);

const { alpha, runtime } = await openDownloadsFolder();
await press("beach.jpg");
await until(alpha, runtime, Shown, (state) => state.content.status === "Loaded");

const loaded = await runtime.runPromise(Effect.flatMap(Shown, (s) => s.get()));
expect(usable(loaded)).toBe(true);
expect(canLost(loaded, "Owner")).toBe(false);
expect(canLost(loaded, "Phone")).toBe(true);

await drawn(() => runtime.runPromise(Effect.flatMap(Shown, (s) => s.send({ type: "lost" }, From.phone))));
await until(alpha, runtime, Shown, (state) => !state.reachable);

const lost = await runtime.runPromise(Effect.flatMap(Shown, (s) => s.get()));
expect(canSelectAgain(lost, "Owner")).toBe(true);
expect(previewInv(lost)).toBe(true);
});

it('closes an open preview cleanly on restart and blocks late email handoff answers (spec/app/files/preview.md, "Story: Come back to a preview after a restart")', async () => {
const world: Scene = { ...scene(), phone: true };
const first = await openDownloadsFolder(world);
await press("lease.pdf");
await until(first.alpha, first.runtime, Shown, (state) => showing(state) && state.kind === "Pdf");
await first.close();

const second = await mountFiles(world);
const restarted = await second.runtime.runPromise(Effect.flatMap(Shown, (s) => s.get()));
expect(showing(restarted)).toBe(false);
expect(restarted.viewer).toBe(0);
expect(canAnswered(restarted, 1, "Phone")).toBe(false);
expect(previewInv(restarted)).toBe(true);
});

it('recognizes page text on device, supports text edits, copy, link review, and event suggestion (spec/app/files/scan.md, "Story: Read and correct the text on a page")', async () => {
const { runtime } = await openScannerWithPage();

const ready = await runtime.runPromise(Effect.flatMap(Scan, (s) => s.get()));
expect(canRecognize(ready, 1, "Phone")).toBe(false);
expect(canRecognize(ready, 1, "Owner")).toBe(true);
expect(scanNoteLimit).toBe(20_241);

const wordedPage: ScanDraft.Page = { image: 1, camera: true, text: 1, blank: false, edits: 0, links: 1 };
await drawn(() => runtime.runPromise(Effect.flatMap(ScanAssets, (held) => held.holdWords(1, 0, {
text: "Meeting tomorrow at 10am https://alpha.example",
lines: [],
links: ["https://alpha.example"],
}))));

const words = await runtime.runPromise(noteContent([wordedPage]));
expect(words).toContain("Meeting tomorrow at 10am");

const reading = recognize(ready, 1, "Owner");
const read = recognized(reading.state, reading.state.text.reading.ticket, true, false, 2, "Phone");
const edited = editText(read, 1, 1, "Owner");
expect(pageOf(edited, 1).edits).toBe(1);
expect(scanInv(edited)).toBe(true);
});

it('saves scan drafts continuously and deletes them only when explicitly discarded by the owner (spec/app/files/scan.md, "Story: Keep the scan as I work")', async () => {
vi.stubGlobal("indexedDB", memoryIndexedDB());
const { alpha, runtime } = await openScannerWithPage();

const stored = await runtime.runPromise(Effect.flatMap(ScanAssets, (held) => held.read(1)));
expect(stored?.width).toBe(100);

await until(alpha, runtime, Scan, (state) => state.keeping.stored && canDiscardDraft(state, "Owner"));
const saving = await runtime.runPromise(Effect.flatMap(Scan, (s) => s.get()));
expect(canDiscardDraft(saving, "Phone")).toBe(false);
expect(canDiscardDraft(saving, "Owner")).toBe(true);

await drawn(() => runtime.runPromise(Effect.flatMap(Scan, (s) => s.send({ type: "discardDraft" }, From.owner))));
await until(alpha, runtime, Scan, (state) => state.pages.length === 0);
const discarded = await runtime.runPromise(Effect.flatMap(Scan, (s) => s.get()));
expect(scanInv(discarded)).toBe(true);
});

it('exports a scan PDF once, surfaces size errors, and saves camera photos to Photos once (spec/app/files/scan.md, "Story: Make the PDF, and keep the photo")', async () => {
expect(scanPanel).toContain("rounded-panel");
expect(scanPrimary).toContain("bg-alpha");
expect(scanQuiet).toContain("bg-transparent");

const { alpha, runtime } = await openScannerWithPage({ ...scene(), phone: true });

const ready = await runtime.runPromise(Effect.flatMap(Scan, (s) => s.get()));
expect(canKeepPhoto(ready, 1, "Owner")).toBe(true);
expect(canExportPdf(ready, "Owner")).toBe(true);

await drawn(() => runtime.runPromise(Effect.flatMap(Scan, (s) => s.send({ type: "exportPdf" }, From.owner))));
await until(alpha, runtime, Scan, (state) => !exporting(state) && (state.pdf.outcome === "Confirmed" || state.pdf.outcome === "Refused" || state.problem !== "NoProblem"));
const afterExport = await runtime.runPromise(Effect.flatMap(Scan, (s) => s.get()));
expect(scanInv(afterExport)).toBe(true);
});

it('stays open behind its own picker, closes when hidden otherwise, and clears in-flight work on restart (spec/app/files/scan.md, "Story: Leave the scan and come back")', async () => {
expect(lawTheScanStaysOpenOnlyBehindItsOwnPicker(true, false)).toBe(true);
expect(lawTheScanStaysOpenOnlyBehindItsOwnPicker(false, false)).toBe(true);
expect(lawAPagePickedBehindItsPickerIsAdded(2, true)).toBe(true);

const world: Scene = { ...scene(), phone: true };
const first = await openScannerWithPage(world);

await drawn(() => first.runtime.runPromise(Effect.flatMap(Scan, (s) => s.send({ type: "hidden", picking: true }, From.phone))));
const behindPicker = await first.runtime.runPromise(Effect.flatMap(Scan, (s) => s.get()));
expect(behindPicker.open).toBe(true);

await goHome(first.alpha);
await until(first.alpha, first.runtime, Scan, (state) => !state.open);

await first.close();
const second = await mountFiles(world);
const restarted = await second.runtime.runPromise(Effect.flatMap(Scan, (s) => s.get()));
expect(restarted.open).toBe(false);
expect(scanInv(restarted)).toBe(true);
});

it('tracks scan text reading, link review, calendar suggestion, and one-time note creation (spec/app/files/scanText.md, "Story: Use the text on my pages")', async () => {
const { alpha, runtime } = await openScannerWithPage();

const wordedPage: ScanDraft.Page = { image: 1, camera: true, text: 1, blank: false, edits: 0, links: 1 };
expect(ScanText.worded(ScanDraft.noPage)).toBe(false);
expect(ScanText.worded(wordedPage)).toBe(true);

await drawn(() => runtime.runPromise(Effect.flatMap(ScanAssets, (held) => held.holdWords(1, 0, { text: "Flight 42", lines: [], links: [] }))));
expect(await runtime.runPromise(searchWords(1, wordedPage))).toEqual({ text: "Flight 42", lines: [], links: [] });
expect(await runtime.runPromise(noteContent([wordedPage]))).toBe("Flight 42");

const draft = {
day: 1,
fields: { title: "Flight 42", place: "", notes: "", begin: 1_795_400_000_000, end: 1_795_403_600_000, allDay: false, people: "" },
disclosures: [],
};
const takenEvent = await alpha.runtime.runPromise(Effect.gen(function* () {
const entry = yield* ScanEntry;
yield* entry.calendar(draft);
return yield* entry.takeEvent();
}));
expect(takenEvent?.fields.title).toBe("Flight 42");

const reviewed = ScanText.reviewLinks(ScanText.initial, wordedPage);
const opening = ScanText.openLink(reviewed, 1);
const opened = ScanText.linkOpened(opening, opening.opening.id, true);
const suggested = ScanText.suggested(ScanText.suggest(opened, wordedPage), 1, true, true);
const noted = ScanText.noted(ScanText.makeNote(suggested, [wordedPage]), 1, true, true);
expect(noted.note.outcome).toBe("Confirmed");
expect(ScanText.canMakeNote(noted, [wordedPage])).toBe(false);
expect(ScanText.inv(noted)).toBe(true);
});

it('reports looking, found, empty, unfinished, and trouble filter states while following folder navigation (spec/app/files/search.md, "Story: Filter what I see")', async () => {
expect(kindOf({ directory: false, mimeType: "image/jpeg" })).toBe("Image");
expect(childrenOf({ directory: true, children: 3 })).toBe(3);
expect(validFileName("receipt.pdf")).toBe("receipt.pdf");
expect(validStoragePath("Download/receipt.pdf")).toBe("Download/receipt.pdf");
expect(filterTimeOf("2026-12-04")).toBeGreaterThan(0);
expect(filesPlaces.get("downloads")).toBe("Downloads");
expect(Option.isSome(parseFilesPlace("Documents"))).toBe(true);

const { alpha, runtime } = await openDownloadsFolder();
const imageFilter: FileSearch.Filter = { ...FileSearch.everything, kind: "Image", anyKind: false };

const reply = await runtime.runPromise(agentFilter(1, imageFilter, false));
expect(reply.ok).toBe(true);
await until(alpha, runtime, Browser, (state) => FileSearch.finding(state.search) === "Found");
const found = await runtime.runPromise(Effect.flatMap(Browser, (b) => Effect.map(b.get(), (state) => state.search)));
expect(found.hits.map((item) => item.name)).toContain("beach.jpg");

await drawn(() => runtime.runPromise(Effect.flatMap(Browser, (b) => b.send({ type: "clearFilter" }, From.owner))));
await until(alpha, runtime, Browser, (state) => FileSearch.finding(state.search) === "NoFilter");
expect(FileSearch.inv(await runtime.runPromise(Effect.flatMap(Browser, (b) => Effect.map(b.get(), (state) => state.search))))).toBe(true);
});

it('clears Trash dialogs and in-flight jobs on restart so nothing repeats or accepts stale answers (spec/app/files/trash.md, "Story: Come back to the Trash after a restart")', async () => {
expect(lawDaysLeftCountDownFromThirty(1_000, 1_000)).toBe(true);
expect(keptUntil(1_000)).toBeGreaterThan(1_000);

const world: Scene = { ...scene(), phone: true };
world.files.trash.push({
id: "trash-1",
was: { volume: "primary", path: "Download/old.txt", directory: false, mimeType: "text/plain", size: 42, modified: 10 },
deletedAt: 1_000,
});

const first = await mountFiles(world);
const openedTrash = await first.runtime.runPromise(showPlace("Trash", Effect.succeed(true)));
expect(openedTrash).toBe(true);
await until(first.alpha, first.runtime, Bin, (state) => state.open && state.listing.status === "Loaded" && state.entries.length === 1);

const [listed, facts] = await first.runtime.runPromise(Effect.gen(function* () {
const bin = yield* (yield* Bin).get();
const rows = yield* (yield* TrashFacts).rows();
return [bin, rows] as const;
}));
const entry = listed.entries[0];
expect(entry).toBeDefined();
expect(facts.size).toBe(1);
if (entry !== undefined) {
expect(canAskToErase(listed, entry, "Owner")).toBe(true);
await drawn(() => first.runtime.runPromise(Effect.flatMap(Bin, (b) => b.send({ type: "askToErase", entry }, From.owner))));
await until(first.alpha, first.runtime, Bin, (state) => state.erasing.showing);
}

await first.close();
const second = await mountFiles(world);
const restarted = await second.runtime.runPromise(Effect.flatMap(Bin, (b) => b.get()));
expect(restarted.open).toBe(false);
expect(restarted.erasing.showing).toBe(false);
expect(canFinished(restarted, 1, 5_000, "Phone")).toBe(false);
expect(trashInv(restarted)).toBe(true);
});
});
Loading
Loading