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
Diff view
93 changes: 93 additions & 0 deletions apps/desktop/src/preview/Manager.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import * as NodeFileSystem from "@effect/platform-node/NodeFileSystem";
import * as NodeVM from "node:vm";
import * as Schema from "effect/Schema";
import { it as effectIt } from "@effect/vitest";
Expand Down Expand Up @@ -34,6 +35,98 @@ import * as PreviewManager from "./Manager.ts";
const encodePreviewManagerError = Schema.encodeSync(PreviewManager.PreviewManagerError);
import * as PreviewPasskeys from "./Passkeys.ts";

describe("copyToDownloads", () => {
effectIt.effect("preserves concurrent downloads with the same filename", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const directory = yield* fs.makeTempDirectoryScoped();
const downloads = directory + "/downloads";
yield* fs.makeDirectory(downloads);
const first = directory + "/first.csv";
const second = directory + "/second.csv";
yield* fs.writeFileString(first, "first export");
yield* fs.writeFileString(second, "second export");
const checked = yield* Deferred.make<void>();
let checks = 0;
const concurrentFs = FileSystem.FileSystem.of({
...fs,
exists: (target) =>
target === downloads + "/export.csv"
? Effect.gen(function* () {
checks += 1;
if (checks === 2) yield* Deferred.succeed(checked, undefined);
yield* Deferred.await(checked);
return false;
})
: fs.exists(target),
});
const targets = yield* Effect.all(
[
PreviewManager.copyToDownloads(downloads, first, "export.csv"),
PreviewManager.copyToDownloads(downloads, second, "export.csv"),
],
{ concurrency: "unbounded" },
).pipe(Effect.provideService(FileSystem.FileSystem, concurrentFs));
expect((yield* fs.readDirectory(downloads)).sort()).toEqual(["export (1).csv", "export.csv"]);
const contents = yield* Effect.all([
fs.readFileString(downloads + "/export.csv"),
fs.readFileString(downloads + "/export (1).csv"),
]);
expect(contents.sort()).toEqual(["first export", "second export"]);
expect(new Set(targets).size).toBe(2);
}).pipe(Effect.provide(Layer.merge(NodeFileSystem.layer, Path.layer)), Effect.scoped),
);
effectIt.effect("leaves existing downloads intact when all 100 names are occupied", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const directory = yield* fs.makeTempDirectoryScoped();
const downloads = directory + "/downloads";
yield* fs.makeDirectory(downloads);
const source = directory + "/source.csv";
yield* fs.writeFileString(source, "new export");
yield* Effect.forEach(
Array.from({ length: 100 }, (_, attempt) => attempt),
(attempt) =>
fs.writeFileString(
downloads + (attempt === 0 ? "/export.csv" : "/export (" + attempt + ").csv"),
"existing export",
),
);
const exit = yield* Effect.exit(
PreviewManager.copyToDownloads(downloads, source, "export.csv"),
);
expect(Exit.isFailure(exit)).toBe(true);
if (Exit.isFailure(exit)) {
expect(Option.getOrThrow(Cause.findErrorOption(exit.cause))).toMatchObject({
cause: { code: "EEXIST" },
});
}
expect(yield* fs.readDirectory(downloads)).toHaveLength(100);
const contents = yield* Effect.forEach(yield* fs.readDirectory(downloads), (name) =>
fs.readFileString(downloads + "/" + name),
);
expect(new Set(contents)).toEqual(new Set(["existing export"]));
}).pipe(Effect.provide(Layer.merge(NodeFileSystem.layer, Path.layer)), Effect.scoped),
);

effectIt.effect("preserves non-collision copy errors without creating a download", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const directory = yield* fs.makeTempDirectoryScoped();
const exit = yield* Effect.exit(
PreviewManager.copyToDownloads(directory, directory + "/missing.csv", "export.csv"),
);
expect(Exit.isFailure(exit)).toBe(true);
if (Exit.isFailure(exit)) {
expect(Option.getOrThrow(Cause.findErrorOption(exit.cause))).toMatchObject({
cause: { code: "ENOENT" },
});
}
expect(yield* fs.readDirectory(directory)).toEqual([]);
}).pipe(Effect.provide(Layer.merge(NodeFileSystem.layer, Path.layer)), Effect.scoped),
);
});

describe("fitPictureInPictureContentSize", () => {
it("preserves the PiP content area across aspect-ratio changes", () => {
expect(PreviewManager.fitPictureInPictureContentSize([480, 320], 16 / 9)).toEqual([523, 294]);
Expand Down
58 changes: 37 additions & 21 deletions apps/desktop/src/preview/Manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@
* elements live in the renderer; we only attach listeners and forward state
* here). Single layer-scoped browser session partition.
*/
// @effect-diagnostics-next-line nodeBuiltinImport:off -- FileSystem.copyFile has no exclusive-copy flag.
import * as NodeFS from "node:fs";
// @effect-diagnostics-next-line nodeBuiltinImport:off -- COPYFILE_EXCL atomically prevents replacement by concurrent writers.
import * as NodeFSP from "node:fs/promises";
import {
DesktopPreviewRecordingInputSchema,
DESKTOP_PREVIEW_RECORDING_CAPTURE_TRIGGER,
Expand Down Expand Up @@ -501,6 +505,7 @@ interface ExpectedAgentInput {
readonly expiresAt: number;
}
type OpenLinkListener = (event: DesktopPreviewOpenLinkEvent) => Effect.Effect<void>;

/**
* Protocols a preview page may open in a real popup window.
*
Expand Down Expand Up @@ -3717,26 +3722,6 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
// a page put a modal over the whole app. Downloads from a page the agent drove
// last go to the artifact directory instead. Downloads the human starts keep
// the Save dialog.
/** Puts a copy in Downloads under a name that never replaces a file already there. */
const copyToDownloads = Effect.fn("PreviewManager.copyToDownloads")(function* (
source: string,
fileName: string,
) {
const directory = app.getPath("downloads");
const extension = path.extname(fileName);
const stem = path.basename(fileName, extension) || "download";
for (let attempt = 0; attempt < 100; attempt += 1) {
const target = path.join(
directory,
attempt === 0 ? `${stem}${extension}` : `${stem} (${attempt})${extension}`,
);
if (yield* fileSystem.exists(target)) continue;
yield* fileSystem.copyFile(source, target);
shell.showItemInFolder(target);
return;
}
});

const installDownloadHandler = (session: Session) => {
if (downloadHandlerSessions.has(session)) return;
downloadHandlerSessions.add(session);
Expand All @@ -3749,7 +3734,9 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
item.once("done", (_doneEvent, state) => {
if (state !== "completed") return;
runFork(
copyToDownloads(item.getSavePath(), item.getFilename()).pipe(
copyToDownloads(app.getPath("downloads"), item.getSavePath(), item.getFilename()).pipe(
Effect.provideService(Path.Path, path),
Effect.tap((target) => Effect.sync(() => shell.showItemInFolder(target))),
Effect.catch((error) =>
Effect.logWarning("preview download copy failed", { cause: error }),
),
Expand Down Expand Up @@ -5538,6 +5525,35 @@ export class PreviewManager extends Context.Service<
}
>()("@t3tools/desktop/preview/Manager/PreviewManager") {}

/** Puts a copy in Downloads under a name that never replaces a file already there. */
export const copyToDownloads = Effect.fn("PreviewManager.copyToDownloads")(function* (
directory: string,
source: string,
fileName: string,
) {
const path = yield* Path.Path;
const extension = path.extname(fileName);
const stem = path.basename(fileName, extension) || "download";
for (let attempt = 0; ; attempt += 1) {
const target = path.join(
directory,
attempt === 0 ? `${stem}${extension}` : `${stem} (${attempt})${extension}`,
);
const copied = yield* Effect.tryPromise(() =>
NodeFSP.copyFile(source, target, NodeFS.constants.COPYFILE_EXCL),
).pipe(
Effect.as(true),
Effect.catch((error) => {
const cause = error.cause;
return attempt < 99 && cause instanceof Error && "code" in cause && cause.code === "EEXIST"
? Effect.succeed(false)
: Effect.fail(error);
}),
);
if (copied) return target;
}
});

/** @public Service construction is part of the canonical Effect module API. */
export const make = Effect.gen(function* PreviewManagerMake() {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
Expand Down
73 changes: 45 additions & 28 deletions apps/mobile/src/features/browser/BrowserCloneRouteScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ export function BrowserCloneRouteScreen({ route }: Props) {
useEffect(() => {
if (AsyncResult.isSuccess(event) && event.value.threadId === threadId) refreshList();
}, [event, threadId, refreshList]);
const canOperate = useAtomValue(previewEnvironment.cloneInvoke.permissionAtom(environmentId));
const invoke = useAtomCommand(previewEnvironment.cloneInvoke, { reportFailure: false });
const [selectedTab, setSelectedTab] = useState<string | null>(null);
const [frame, setFrame] = useState<PreviewAutomationFrame | null>(null);
Expand All @@ -58,7 +59,7 @@ export function BrowserCloneRouteScreen({ route }: Props) {
setFrame(null);
setError(null);
failedRef.current = false;
if (!tabId || !active || !focused) return;
if (!tabId || !active || !focused || !canOperate) return;
const session = createBrowserCloneSession(
{
environmentId,
Expand Down Expand Up @@ -95,7 +96,7 @@ export function BrowserCloneRouteScreen({ route }: Props) {
session.dispose();
if (sessionRef.current === session) sessionRef.current = null;
};
}, [active, focused, environmentId, threadId, tabId, generation, invoke]);
}, [active, focused, environmentId, threadId, tabId, generation, invoke, canOperate]);
const failed = useCallback((session: ReturnType<typeof createBrowserCloneSession>) => {
if (sessionRef.current === session) {
failedRef.current = true;
Expand Down Expand Up @@ -155,31 +156,33 @@ export function BrowserCloneRouteScreen({ route }: Props) {
}}
>
<StatusBar barStyle="light-content" />
<View className="shrink-0 border-b border-white/10">
<ScrollView
horizontal
style={{ flexGrow: 0 }}
showsHorizontalScrollIndicator={false}
contentContainerStyle={{ padding: 8, gap: 8 }}
>
{tabs.map((tab) => (
<Pressable
key={tab.tabId}
accessibilityRole="tab"
accessibilityState={{ selected: tab.tabId === tabId }}
onPress={() => setSelectedTab(tab.tabId)}
className={`max-w-64 border px-3 py-2 ${tab.tabId === tabId ? "border-white/50 bg-white/10" : "border-white/10"}`}
>
<AppText numberOfLines={1} className="text-white">
{tab.navStatus._tag === "Idle"
? "New tab"
: tab.navStatus.title || tab.navStatus.url}
</AppText>
</Pressable>
))}
</ScrollView>
</View>
{tab?.runtime === "server" && (
{canOperate && (
<View className="shrink-0 border-b border-white/10">
<ScrollView
horizontal
style={{ flexGrow: 0 }}
showsHorizontalScrollIndicator={false}
contentContainerStyle={{ padding: 8, gap: 8 }}
>
{tabs.map((tab) => (
<Pressable
key={tab.tabId}
accessibilityRole="tab"
accessibilityState={{ selected: tab.tabId === tabId }}
onPress={() => setSelectedTab(tab.tabId)}
className={`max-w-64 border px-3 py-2 ${tab.tabId === tabId ? "border-white/50 bg-white/10" : "border-white/10"}`}
>
<AppText numberOfLines={1} className="text-white">
{tab.navStatus._tag === "Idle"
? "New tab"
: tab.navStatus.title || tab.navStatus.url}
</AppText>
</Pressable>
))}
</ScrollView>
</View>
)}
{canOperate && tab?.runtime === "server" && (
<Pressable
accessibilityRole="button"
onPress={() =>
Expand All @@ -194,7 +197,21 @@ export function BrowserCloneRouteScreen({ route }: Props) {
<AppText className="text-center text-white">Open server browser</AppText>
</Pressable>
)}
{!tabId || error || AsyncResult.isFailure(list) ? (
{!canOperate ? (
<View className="flex-1 items-center justify-center gap-4 bg-screen px-8">
<AppText className="text-center text-base text-foreground">
Browser access is not permitted. Ask the environment owner to grant browser control, or
pair again with a link that allows it.
</AppText>
<Pressable
accessibilityRole="button"
onPress={() => navigation.goBack()}
className="px-5 py-3"
>
<AppText className="text-foreground">Done</AppText>
</Pressable>
</View>
) : !tabId || error || AsyncResult.isFailure(list) ? (
<View className="flex-1 items-center justify-center gap-4 bg-screen px-8">
<AppText className="text-center text-base text-foreground">
{AsyncResult.isFailure(list)
Expand Down
Loading
Loading