diff --git a/apps/desktop/src/electron/ElectronShell.test.ts b/apps/desktop/src/electron/ElectronShell.test.ts index c82f3542c3..f5c85769ce 100644 --- a/apps/desktop/src/electron/ElectronShell.test.ts +++ b/apps/desktop/src/electron/ElectronShell.test.ts @@ -1,25 +1,15 @@ -import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, describe, it } from "@effect/vitest"; -import * as Clock from "effect/Clock"; -import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; -import * as FileSystem from "effect/FileSystem"; -import * as Layer from "effect/Layer"; -import * as Path from "effect/Path"; -import * as TestClock from "effect/testing/TestClock"; -import { FetchHttpClient } from "effect/unstable/http"; -import { afterEach, beforeEach, expect, vi } from "vite-plus/test"; +import { beforeEach, vi } from "vite-plus/test"; -const { openExternalMock, showItemInFolderMock, writeTextMock } = vi.hoisted(() => ({ +const { openExternalMock, writeTextMock } = vi.hoisted(() => ({ openExternalMock: vi.fn(), - showItemInFolderMock: vi.fn(), writeTextMock: vi.fn(), })); vi.mock("electron", () => ({ shell: { openExternal: openExternalMock, - showItemInFolder: showItemInFolderMock, }, clipboard: { writeText: writeTextMock, @@ -28,27 +18,12 @@ vi.mock("electron", () => ({ import * as ElectronShell from "./ElectronShell.ts"; -const testLayer = Layer.unwrap( - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const temporaryDirectory = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3code-electron-shell-test-", - }); - return ElectronShell.layer({ temporaryDirectory }); - }), -).pipe(Layer.provideMerge(NodeServices.layer), Layer.provideMerge(FetchHttpClient.layer)); - describe("ElectronShell", () => { beforeEach(() => { openExternalMock.mockReset(); - showItemInFolderMock.mockReset(); writeTextMock.mockReset(); }); - afterEach(() => { - vi.unstubAllGlobals(); - }); - it.effect("opens safe external URLs", () => Effect.gen(function* () { openExternalMock.mockResolvedValue(undefined); @@ -58,7 +33,7 @@ describe("ElectronShell", () => { assert.equal(result, true); assert.deepEqual(openExternalMock.mock.calls, [["https://example.com/path"]]); - }).pipe(Effect.provide(testLayer)), + }).pipe(Effect.provide(ElectronShell.layer)), ); it.effect("does not open unsafe external URLs", () => @@ -68,7 +43,7 @@ describe("ElectronShell", () => { assert.equal(result, false); assert.equal(openExternalMock.mock.calls.length, 0); - }).pipe(Effect.provide(testLayer)), + }).pipe(Effect.provide(ElectronShell.layer)), ); it.effect("returns false when Electron rejects openExternal", () => @@ -79,74 +54,6 @@ describe("ElectronShell", () => { const result = yield* electronShell.openExternal("https://example.com/path"); assert.equal(result, false); - }).pipe(Effect.provide(testLayer)), - ); - - it.effect("downloads files with spaces and unicode names before revealing them", () => - Effect.gen(function* () { - vi.stubGlobal( - "fetch", - vi.fn(async () => new Response("remote contents", { status: 200 })), - ); - - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const electronShell = yield* ElectronShell.ElectronShell; - const filePath = yield* electronShell.downloadAndReveal( - "https://example.com/signed-asset", - String.raw`C:\Users\TestUser\notes 😀 with spaces.txt`, - ); - - expect(path.basename(filePath)).toBe("notes 😀 with spaces.txt"); - expect(yield* fileSystem.readFileString(filePath)).toBe("remote contents"); - expect(showItemInFolderMock).toHaveBeenCalledExactlyOnceWith(filePath); - yield* fileSystem.remove(path.dirname(filePath), { recursive: true, force: true }); - }).pipe(Effect.provide(testLayer)), - ); - - it.effect("rejects unsafe download URLs", () => - Effect.gen(function* () { - const electronShell = yield* ElectronShell.ElectronShell; - const result = yield* Effect.exit( - electronShell.downloadAndReveal("file:///etc/passwd", "passwd"), - ); - - expect(result._tag).toBe("Failure"); - expect(showItemInFolderMock).not.toHaveBeenCalled(); - }).pipe(Effect.provide(testLayer)), - ); - - it.effect("removes only remote-file download directories older than three days", () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const temporaryDirectory = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3code-electron-shell-cleanup-test-", - }); - const staleDirectory = path.join(temporaryDirectory, "t3code-remote-file-stale"); - const freshDirectory = path.join(temporaryDirectory, "t3code-remote-file-fresh"); - const unrelatedDirectory = path.join(temporaryDirectory, "other-app-stale"); - yield* Effect.forEach( - [staleDirectory, freshDirectory, unrelatedDirectory], - (directory) => fileSystem.makeDirectory(directory), - { discard: true }, - ); - - yield* TestClock.adjust(ElectronShell.REMOTE_FILE_RETENTION_MS * 2); - const nowMillis = yield* Clock.currentTimeMillis; - const staleTimestamp = nowMillis - ElectronShell.REMOTE_FILE_RETENTION_MS - 1; - const freshTimestamp = nowMillis - ElectronShell.REMOTE_FILE_RETENTION_MS + 1_000; - const staleDate = DateTime.toDateUtc(DateTime.makeUnsafe(staleTimestamp)); - const freshDate = DateTime.toDateUtc(DateTime.makeUnsafe(freshTimestamp)); - yield* fileSystem.utimes(staleDirectory, staleDate, staleDate); - yield* fileSystem.utimes(freshDirectory, freshDate, freshDate); - yield* fileSystem.utimes(unrelatedDirectory, staleDate, staleDate); - - yield* ElectronShell.cleanupStaleRemoteFileDownloads(temporaryDirectory, nowMillis); - - expect(yield* fileSystem.exists(staleDirectory)).toBe(false); - expect(yield* fileSystem.exists(freshDirectory)).toBe(true); - expect(yield* fileSystem.exists(unrelatedDirectory)).toBe(true); - }).pipe(Effect.provide(NodeServices.layer)), + }).pipe(Effect.provide(ElectronShell.layer)), ); }); diff --git a/apps/desktop/src/electron/ElectronShell.ts b/apps/desktop/src/electron/ElectronShell.ts index 510403494a..316d3138bf 100644 --- a/apps/desktop/src/electron/ElectronShell.ts +++ b/apps/desktop/src/electron/ElectronShell.ts @@ -1,19 +1,11 @@ -import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; -import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; -import * as Path from "effect/Path"; -import * as Schema from "effect/Schema"; -import * as Stream from "effect/Stream"; -import { HttpClient } from "effect/unstable/http"; import * as Electron from "electron"; const SAFE_EXTERNAL_PROTOCOLS = new Set(["http:", "https:"]); -const REMOTE_FILE_DIRECTORY_PREFIX = "t3code-remote-file-"; -export const REMOTE_FILE_RETENTION_MS = 3 * 24 * 60 * 60 * 1000; export function parseSafeExternalUrl(rawUrl: unknown): Option.Option { if (typeof rawUrl !== "string") { @@ -28,183 +20,30 @@ export function parseSafeExternalUrl(rawUrl: unknown): Option.Option { } } -export function sanitizeDownloadFileName(rawFileName: string): string { - const baseName = (rawFileName.split(/[\\/]/).pop() ?? "").trim(); - const sanitized = Array.from(baseName, (character) => { - const codePoint = character.codePointAt(0) ?? 0; - return codePoint <= 31 || codePoint === 127 || character === ":" ? "_" : character; - }).join(""); - if (sanitized === "" || sanitized === "." || sanitized === "..") { - return "download"; - } - return Array.from(sanitized).slice(0, 200).join(""); -} - -const ElectronShellDownloadOperation = Schema.Literals([ - "validate-url", - "create-temp-directory", - "download", - "reveal", -]); - -export class ElectronShellDownloadError extends Schema.TaggedErrorClass()( - "ElectronShellDownloadError", - { - operation: ElectronShellDownloadOperation, - cause: Schema.Defect(), - }, -) { - override get message(): string { - switch (this.operation) { - case "validate-url": - return "The download URL is invalid."; - case "create-temp-directory": - return "Unable to create a temporary download folder."; - case "download": - return "Unable to download the remote file."; - case "reveal": - return "The file was downloaded, but Finder could not reveal it."; - } - } -} - -const isElectronShellDownloadError = Schema.is(ElectronShellDownloadError); - -export const cleanupStaleRemoteFileDownloads = Effect.fn( - "ElectronShell.cleanupStaleRemoteFileDownloads", -)(function* (temporaryDirectory: string, nowMillis: number) { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const entries = yield* fileSystem.readDirectory(temporaryDirectory); - - yield* Effect.forEach( - entries, - (entry) => { - if (!entry.startsWith(REMOTE_FILE_DIRECTORY_PREFIX)) { - return Effect.void; - } - const candidate = path.join(temporaryDirectory, entry); - return fileSystem.stat(candidate).pipe( - Effect.flatMap((info) => { - if (info.type !== "Directory" || Option.isNone(info.mtime)) { - return Effect.void; - } - const ageMillis = nowMillis - info.mtime.value.getTime(); - return ageMillis > REMOTE_FILE_RETENTION_MS - ? fileSystem.remove(candidate, { recursive: true, force: true }) - : Effect.void; - }), - Effect.catch((cause) => - Effect.logWarning("Failed to inspect or remove a stale remote-file download.", { - candidate, - cause, - }), - ), - ); - }, - { concurrency: 4, discard: true }, - ); -}); - export class ElectronShell extends Context.Service< ElectronShell, { readonly openExternal: (rawUrl: unknown) => Effect.Effect; - readonly downloadAndReveal: ( - rawUrl: unknown, - fileName: string, - ) => Effect.Effect; readonly copyText: (text: string) => Effect.Effect; } >()("@t3tools/desktop/electron/ElectronShell") {} -export const layer = (options: { readonly temporaryDirectory: string }) => - Layer.effect( - ElectronShell, - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const httpClient = (yield* HttpClient.HttpClient).pipe(HttpClient.filterStatusOk); - const nowMillis = yield* Clock.currentTimeMillis; - - yield* cleanupStaleRemoteFileDownloads(options.temporaryDirectory, nowMillis).pipe( - Effect.catch((cause) => - Effect.logWarning("Failed to clean stale remote-file downloads.", { cause }), +export const make = ElectronShell.of({ + openExternal: (rawUrl) => + Option.match(parseSafeExternalUrl(rawUrl), { + onNone: () => Effect.succeed(false), + onSome: (externalUrl) => + Effect.promise(() => + Electron.shell.openExternal(externalUrl).then( + () => true, + () => false, + ), ), - ); - - const downloadAndReveal = Effect.fn("ElectronShell.downloadAndReveal")(function* ( - rawUrl: unknown, - rawFileName: string, - ) { - const url = Option.getOrElse(parseSafeExternalUrl(rawUrl), () => ""); - if (url === "") { - return yield* new ElectronShellDownloadError({ - operation: "validate-url", - cause: rawUrl, - }); - } - - const directory = yield* fileSystem - .makeTempDirectory({ - directory: options.temporaryDirectory, - prefix: REMOTE_FILE_DIRECTORY_PREFIX, - }) - .pipe( - Effect.mapError( - (cause) => - new ElectronShellDownloadError({ - operation: "create-temp-directory", - cause, - }), - ), - ); - const filePath = path.join(directory, sanitizeDownloadFileName(rawFileName)); - - return yield* Effect.gen(function* () { - const response = yield* httpClient.get(url); - yield* Stream.run(response.stream, fileSystem.sink(filePath, { flag: "wx" })); - yield* Effect.try({ - try: () => Electron.shell.showItemInFolder(filePath), - catch: (cause) => - new ElectronShellDownloadError({ - operation: "reveal", - cause, - }), - }); - return filePath; - }).pipe( - Effect.mapError((cause) => - isElectronShellDownloadError(cause) - ? cause - : new ElectronShellDownloadError({ - operation: "download", - cause, - }), - ), - Effect.tapError(() => - fileSystem.remove(directory, { recursive: true, force: true }).pipe(Effect.ignore), - ), - ); - }); - - return ElectronShell.of({ - openExternal: (rawUrl) => - Option.match(parseSafeExternalUrl(rawUrl), { - onNone: () => Effect.succeed(false), - onSome: (externalUrl) => - Effect.promise(() => - Electron.shell.openExternal(externalUrl).then( - () => true, - () => false, - ), - ), - }), - downloadAndReveal, - copyText: (text) => - Effect.sync(() => { - Electron.clipboard.writeText(text); - }), - }); }), - ); + copyText: (text) => + Effect.sync(() => { + Electron.clipboard.writeText(text); + }), +}); + +export const layer = Layer.succeed(ElectronShell, make); diff --git a/apps/desktop/src/ipc/DesktopIpcHandlers.ts b/apps/desktop/src/ipc/DesktopIpcHandlers.ts index a88a495ebd..e478d0c6ef 100644 --- a/apps/desktop/src/ipc/DesktopIpcHandlers.ts +++ b/apps/desktop/src/ipc/DesktopIpcHandlers.ts @@ -32,7 +32,6 @@ import { } from "./methods/updates.ts"; import { confirm, - downloadAndReveal, getAppBranding, getLocalEnvironmentBootstraps, getLocalEnvironmentBearerToken, @@ -84,7 +83,6 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers" yield* ipc.handle(setTheme); yield* ipc.handle(showContextMenu); yield* ipc.handle(openExternal); - yield* ipc.handle(downloadAndReveal); yield* ipc.handle(getUpdateState); yield* ipc.handle(setUpdateChannel); yield* ipc.handle(downloadUpdate); diff --git a/apps/desktop/src/ipc/channels.ts b/apps/desktop/src/ipc/channels.ts index 6fd0a551e1..0d5c79cf55 100644 --- a/apps/desktop/src/ipc/channels.ts +++ b/apps/desktop/src/ipc/channels.ts @@ -3,7 +3,6 @@ export const CONFIRM_CHANNEL = "desktop:confirm"; export const SET_THEME_CHANNEL = "desktop:set-theme"; export const CONTEXT_MENU_CHANNEL = "desktop:context-menu"; export const OPEN_EXTERNAL_CHANNEL = "desktop:open-external"; -export const DOWNLOAD_AND_REVEAL_CHANNEL = "desktop:download-and-reveal"; export const MENU_ACTION_CHANNEL = "desktop:menu-action"; export const GET_WINDOW_FULLSCREEN_STATE_CHANNEL = "desktop:get-window-fullscreen-state"; export const WINDOW_FULLSCREEN_STATE_CHANNEL = "desktop:window-fullscreen-state"; diff --git a/apps/desktop/src/ipc/methods/window.ts b/apps/desktop/src/ipc/methods/window.ts index cdd4a92688..a4e98aaaba 100644 --- a/apps/desktop/src/ipc/methods/window.ts +++ b/apps/desktop/src/ipc/methods/window.ts @@ -1,7 +1,6 @@ import { ContextMenuItemSchema, DesktopAppBrandingSchema, - DesktopDownloadAndRevealInputSchema, DesktopEnvironmentBootstrapSchema, DesktopThemeSchema, PickFolderOptionsSchema, @@ -269,13 +268,3 @@ export const openExternal = DesktopIpc.makeIpcMethod({ return yield* shell.openExternal(url); }), }); - -export const downloadAndReveal = DesktopIpc.makeIpcMethod({ - channel: IpcChannels.DOWNLOAD_AND_REVEAL_CHANNEL, - payload: DesktopDownloadAndRevealInputSchema, - result: Schema.String, - handler: Effect.fn("desktop.ipc.window.downloadAndReveal")(function* ({ url, fileName }) { - const shell = yield* ElectronShell.ElectronShell; - return yield* shell.downloadAndReveal(url, fileName); - }), -}); diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts index c8cbb261d9..7a51700e0f 100644 --- a/apps/desktop/src/main.ts +++ b/apps/desktop/src/main.ts @@ -109,10 +109,7 @@ const electronLayer = Layer.mergeAll( ElectronMenu.layer, ElectronProtocol.layer, ElectronSafeStorage.layer, - ElectronShell.layer({ temporaryDirectory: NodeOS.tmpdir() }).pipe( - Layer.provideMerge(NodeServices.layer), - Layer.provideMerge(NodeHttpClient.layerUndici), - ), + ElectronShell.layer, ElectronTheme.layer, ElectronUpdater.layer, ElectronWindow.layer, diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts index 952eaf56a3..9f92cfcf2f 100644 --- a/apps/desktop/src/preload.ts +++ b/apps/desktop/src/preload.ts @@ -105,7 +105,6 @@ contextBridge.exposeInMainWorld("desktopBridge", { ...(position === undefined ? {} : { position }), }), openExternal: (url: string) => ipcRenderer.invoke(IpcChannels.OPEN_EXTERNAL_CHANNEL, url), - downloadAndReveal: (input) => ipcRenderer.invoke(IpcChannels.DOWNLOAD_AND_REVEAL_CHANNEL, input), onMenuAction: (listener) => { const wrappedListener = (_event: Electron.IpcRendererEvent, action: unknown) => { if (typeof action !== "string") return; diff --git a/apps/desktop/src/window/DesktopWindow.test.ts b/apps/desktop/src/window/DesktopWindow.test.ts index 6fdb2c26ae..587da8d443 100644 --- a/apps/desktop/src/window/DesktopWindow.test.ts +++ b/apps/desktop/src/window/DesktopWindow.test.ts @@ -255,7 +255,6 @@ function makeTestLayer(input: { input.openedExternalUrls?.push(url); return true; }), - downloadAndReveal: () => Effect.die("not implemented"), copyText: () => Effect.void, } satisfies ElectronShell.ElectronShell["Service"]), electronThemeLayer, @@ -349,7 +348,6 @@ const makeSplashScenario = (createOutcomes: readonly (Electron.BrowserWindow | n electronMenuLayer, Layer.succeed(ElectronShell.ElectronShell, { openExternal: () => Effect.succeed(true), - downloadAndReveal: () => Effect.die("not implemented"), copyText: () => Effect.void, } satisfies ElectronShell.ElectronShell["Service"]), electronThemeLayer, diff --git a/apps/server/src/assets/AssetAccess.test.ts b/apps/server/src/assets/AssetAccess.test.ts index fb636a8b24..06a22754e5 100644 --- a/apps/server/src/assets/AssetAccess.test.ts +++ b/apps/server/src/assets/AssetAccess.test.ts @@ -25,38 +25,6 @@ const testLayer = Layer.mergeAll( ).pipe(Layer.provideMerge(NodeServices.layer)); describe("AssetAccess", () => { - it.effect("issues exact download URLs for non-preview workspace files", () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const root = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-asset-download-workspace-", - }); - const textPath = path.join(root, "notes with spaces.txt"); - yield* fileSystem.writeFileString(textPath, "download me"); - const canonicalTextPath = yield* fileSystem.realPath(textPath); - - const result = yield* issueAssetUrl({ - resource: { - _tag: "workspace-file-download", - threadId: ThreadId.make("thread-1"), - path: textPath, - }, - workspaceRoot: root, - }); - const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length); - const separatorIndex = suffix.indexOf("/"); - - expect( - yield* resolveAsset(suffix.slice(0, separatorIndex), suffix.slice(separatorIndex + 1)), - ).toEqual({ - kind: "file", - path: canonicalTextPath, - }); - expect(result.relativeUrl.endsWith("/notes%20with%20spaces.txt")).toBe(true); - }).pipe(Effect.provide(testLayer)), - ); - it.effect("issues workspace URLs that resolve the entry file and sibling assets", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; diff --git a/apps/server/src/assets/AssetAccess.ts b/apps/server/src/assets/AssetAccess.ts index f454e31aa0..b469e0e315 100644 --- a/apps/server/src/assets/AssetAccess.ts +++ b/apps/server/src/assets/AssetAccess.ts @@ -174,7 +174,6 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i let fileName: string; switch (input.resource._tag) { - case "workspace-file-download": case "workspace-file": { if (!input.workspaceRoot) { return yield* new AssetWorkspaceContextNotFoundError({ @@ -204,10 +203,7 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i }), ), ); - if ( - input.resource._tag === "workspace-file" && - !isWorkspacePreviewEntryPath(resolved.relativePath) - ) { + if (!isWorkspacePreviewEntryPath(resolved.relativePath)) { return yield* new AssetPreviewTypeValidationError({ resource: input.resource, }); @@ -238,23 +234,21 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i }), ), ); - claims = - input.resource._tag === "workspace-file-download" || - isWorkspaceImagePreviewPath(resolved.relativePath) - ? { - version: 1, - kind: "workspace-file-exact", - workspaceRoot: canonicalWorkspaceRoot, - relativePath: resolved.relativePath, - expiresAt, - } - : { - version: 1, - kind: "workspace-file", - workspaceRoot: canonicalWorkspaceRoot, - baseRelativePath: path.dirname(resolved.relativePath), - expiresAt, - }; + claims = isWorkspaceImagePreviewPath(resolved.relativePath) + ? { + version: 1, + kind: "workspace-file-exact", + workspaceRoot: canonicalWorkspaceRoot, + relativePath: resolved.relativePath, + expiresAt, + } + : { + version: 1, + kind: "workspace-file", + workspaceRoot: canonicalWorkspaceRoot, + baseRelativePath: path.dirname(resolved.relativePath), + expiresAt, + }; fileName = path.basename(resolved.relativePath); break; } diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 93caedd569..ce91052fb8 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -1701,10 +1701,7 @@ const makeWsRpcLayer = ( observeRpcEffect( WS_METHODS.assetsCreateUrl, Effect.gen(function* () { - if ( - input.resource._tag !== "workspace-file" && - input.resource._tag !== "workspace-file-download" - ) { + if (input.resource._tag !== "workspace-file") { return yield* issueAssetUrl({ resource: input.resource }); } const thread = yield* projectionSnapshotQuery diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx index 4c824435e0..c0a9219859 100644 --- a/apps/web/src/components/ChatMarkdown.tsx +++ b/apps/web/src/components/ChatMarkdown.tsx @@ -9,7 +9,11 @@ import { Minimize2Icon, WrapTextIcon, } from "lucide-react"; -import type { ScopedThreadRef, ServerProviderSkill } from "@t3tools/contracts"; +import type { + ExecutionEnvironmentPlatformOs, + ScopedThreadRef, + ServerProviderSkill, +} from "@t3tools/contracts"; import { isAtomCommandInterrupted, squashAtomCommandFailure, @@ -45,15 +49,6 @@ import { PierreEntryIcon } from "./chat/PierreEntryIcon"; import { hasSpecificPierreIconForFileName, syntheticFileNameForLanguageId } from "../pierre-icons"; import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; import { Button } from "./ui/button"; -import { - AlertDialog, - AlertDialogClose, - AlertDialogDescription, - AlertDialogFooter, - AlertDialogHeader, - AlertDialogPopup, - AlertDialogTitle, -} from "./ui/alert-dialog"; import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "./ui/collapsible"; import { ScrollArea } from "./ui/scroll-area"; import { Menu, MenuItem, MenuPopup, MenuTrigger } from "./ui/menu"; @@ -81,8 +76,6 @@ import { useRightPanelStore } from "../rightPanelStore"; import { useActiveEnvironmentId } from "../state/entities"; import { serverEnvironment } from "../state/server"; import { assetEnvironment } from "../state/assets"; -import { resolveAssetUrl } from "../assets/assetUrls"; -import { useEnvironment } from "../state/environments"; import { usePreparedConnection } from "../state/session"; import { previewEnvironment } from "../state/preview"; import { shellEnvironment } from "../state/shell"; @@ -756,9 +749,7 @@ interface MarkdownFileLinkProps { threadRef?: ScopedThreadRef | undefined; onOpen: (targetPath: string) => Promise>; onShowInFinder: (targetPath: string) => Promise>; - fileManagerAction: "native" | "download" | "disabled"; fileManagerLabel: string; - onDownloadAndShowInFinder?: ((targetPath: string) => Promise) | undefined; onOpenInBrowser?: (() => Promise>) | undefined; className?: string | undefined; } @@ -767,6 +758,12 @@ const MARKDOWN_LINK_HREF_PATTERN = /\[[^\]]*]\(([^)\s]+)(?:\s+["'][^"']*["'])?\) const MARKDOWN_FILE_LINK_CLASS_NAME = "chat-markdown-file-link cursor-pointer transition-colors hover:bg-accent/70"; +function fileManagerLabelForPlatform(platform: ExecutionEnvironmentPlatformOs | undefined): string { + if (platform === "darwin") return "Show in Finder"; + if (platform === "windows") return "Show in File Explorer"; + return "Show in Files"; +} + function pathParentSegments(path: string): string[] { const normalized = path.replaceAll("\\", "/"); const segments = normalized.split("/").filter((segment) => segment.length > 0); @@ -1039,14 +1036,10 @@ const MarkdownFileLink = memo(function MarkdownFileLink({ threadRef, onOpen, onShowInFinder, - fileManagerAction, fileManagerLabel, - onDownloadAndShowInFinder, onOpenInBrowser, className, }: MarkdownFileLinkProps) { - const [downloadDialogOpen, setDownloadDialogOpen] = useState(false); - const [isDownloading, setIsDownloading] = useState(false); const handleOpenInEditor = useCallback(() => { void (async () => { try { @@ -1122,31 +1115,6 @@ const MarkdownFileLink = memo(function MarkdownFileLink({ })(); }, [fileManagerLabel, iconPath, onShowInFinder]); - const handleDownloadAndShowInFinder = useCallback(() => { - if (!onDownloadAndShowInFinder) return; - void (async () => { - setIsDownloading(true); - try { - await onDownloadAndShowInFinder(iconPath); - setDownloadDialogOpen(false); - } catch (cause) { - reportMarkdownActionFailure( - { operation: "download-file-and-show-in-finder", target: iconPath }, - cause, - ); - toastManager.add( - stackedThreadToast({ - type: "error", - title: "Unable to download file", - description: cause instanceof Error ? cause.message : "An error occurred.", - }), - ); - } finally { - setIsDownloading(false); - } - })(); - }, [iconPath, onDownloadAndShowInFinder]); - const handleOpenInBrowser = useCallback(() => { if (!onOpenInBrowser) { return; @@ -1244,7 +1212,6 @@ const MarkdownFileLink = memo(function MarkdownFileLink({ { id: "show-in-finder", label: fileManagerLabel, - disabled: fileManagerAction === "disabled", }, ] as const, { x: event.clientX, y: event.clientY }, @@ -1267,10 +1234,6 @@ const MarkdownFileLink = memo(function MarkdownFileLink({ return; } if (clicked === "show-in-finder") { - if (fileManagerAction === "download") { - setDownloadDialogOpen(true); - return; - } handleShowInFinder(); } } catch (cause) { @@ -1286,7 +1249,6 @@ const MarkdownFileLink = memo(function MarkdownFileLink({ handleOpenInBrowser, handleOpenInEditor, handleShowInFinder, - fileManagerAction, fileManagerLabel, onOpenInBrowser, targetPath, @@ -1294,70 +1256,37 @@ const MarkdownFileLink = memo(function MarkdownFileLink({ ); return ( - <> - - { - event.preventDefault(); - event.stopPropagation(); - if (onOpenInBrowser) { - handleOpenInBrowser(); - return; - } - handleOpenInFilePreview(); - }} - onContextMenu={handleContextMenu} - > - - - } - /> - -
- {displayPath} -
-
-
- { - if (!isDownloading) setDownloadDialogOpen(open); - }} + + { + event.preventDefault(); + event.stopPropagation(); + if (onOpenInBrowser) { + handleOpenInBrowser(); + return; + } + handleOpenInFilePreview(); + }} + onContextMenu={handleContextMenu} + > + + + } + /> + - - - Download this remote file? - - T3 Code will download a temporary copy of{" "} - - {iconPath.replaceAll("\\", "/").split("/").pop() ?? iconPath} - {" "} - to this Mac and show it in Finder. - - - - }> - Cancel - - - - - - +
+ {displayPath} +
+ + ); }, areMarkdownFileLinkPropsEqual); @@ -1378,9 +1307,7 @@ function areMarkdownFileLinkPropsEqual( previous.threadRef === next.threadRef && previous.onOpen === next.onOpen && previous.onShowInFinder === next.onShowInFinder && - previous.fileManagerAction === next.fileManagerAction && previous.fileManagerLabel === next.fileManagerLabel && - previous.onDownloadAndShowInFinder === next.onDownloadAndShowInFinder && previous.onOpenInBrowser === next.onOpenInBrowser && previous.className === next.className ); @@ -1409,10 +1336,9 @@ function ChatMarkdown({ const preparedConnection = usePreparedConnection(threadRef?.environmentId ?? null); const environmentId = useActiveEnvironmentId(); const fileEnvironmentId = threadRef?.environmentId ?? environmentId; - const fileEnvironment = useEnvironment(fileEnvironmentId); - const serverConfig = useAtomValue(serverEnvironment.configValueAtom(environmentId)); + const serverConfig = useAtomValue(serverEnvironment.configValueAtom(fileEnvironmentId)); const openInPreferredEditor = useOpenInPreferredEditor( - environmentId, + fileEnvironmentId, serverConfig?.availableEditors ?? [], ); const showFileInFinder = useCallback( @@ -1431,49 +1357,7 @@ function ChatMarkdown({ }, [fileEnvironmentId, revealInFileManager], ); - const localPlatform = typeof navigator === "undefined" ? "" : navigator.platform.toLowerCase(); - const isDesktopHosted = typeof window !== "undefined" && window.desktopBridge !== undefined; - const fileManagerLabel = localPlatform.includes("mac") - ? "Show in Finder" - : localPlatform.includes("win") - ? "Show in File Explorer" - : "Show in Files"; - const fileManagerAction = - isDesktopHosted && fileEnvironment?.entry.target._tag === "PrimaryConnectionTarget" - ? "native" - : isDesktopHosted && localPlatform.includes("mac") - ? "download" - : "disabled"; - const downloadAndShowInFinder = useCallback( - async (targetPath: string) => { - if (!threadRef || preparedConnection._tag === "None") { - throw new Error("The remote environment is not connected."); - } - const result = await createAssetUrl({ - environmentId: threadRef.environmentId, - input: { - resource: { - _tag: "workspace-file-download", - threadId: threadRef.threadId, - path: targetPath, - }, - }, - }); - if (result._tag === "Failure") { - throw squashAtomCommandFailure(result); - } - const url = resolveAssetUrl(preparedConnection.value.httpBaseUrl, result.value.relativeUrl); - if (url === null) { - throw new Error("The remote environment returned an invalid download URL."); - } - const api = readLocalApi(); - if (!api) { - throw new Error("The local desktop API is unavailable."); - } - await api.shell.downloadAndReveal({ url, fileName: targetPath }); - }, - [createAssetUrl, preparedConnection, threadRef], - ); + const fileManagerLabel = fileManagerLabelForPlatform(serverConfig?.environment.platform.os); const diffThemeName = resolveDiffThemeName(resolvedTheme); const markdownFileLinkMetaByHref = useMemo(() => { const metaByHref = new Map< @@ -1696,11 +1580,7 @@ function ChatMarkdown({ threadRef={threadRef} onOpen={openInPreferredEditor} onShowInFinder={showFileInFinder} - fileManagerAction={fileManagerAction} fileManagerLabel={fileManagerLabel} - onDownloadAndShowInFinder={ - fileManagerAction === "download" ? downloadAndShowInFinder : undefined - } onOpenInBrowser={ threadRef && isPreviewSupportedInRuntime() && @@ -1756,8 +1636,6 @@ function ChatMarkdown({ openInPreferredEditor, openExternalLinkInPreview, openMarkdownFileInPreview, - downloadAndShowInFinder, - fileManagerAction, fileManagerLabel, resolvedTheme, showFileInFinder, diff --git a/apps/web/src/localApi.test.ts b/apps/web/src/localApi.test.ts index c02a63fd5d..3379f5ed98 100644 --- a/apps/web/src/localApi.test.ts +++ b/apps/web/src/localApi.test.ts @@ -87,13 +87,11 @@ describe("LocalApi", () => { const pickFolder = vi.fn().mockResolvedValue("/tmp/project"); const getClientSettings = vi.fn().mockResolvedValue(DEFAULT_CLIENT_SETTINGS); const setClientSettings = vi.fn().mockResolvedValue(undefined); - const downloadAndReveal = vi.fn().mockResolvedValue("/tmp/download/readme.txt"); testWindow().desktopBridge = { showContextMenu, pickFolder, getClientSettings, setClientSettings, - downloadAndReveal, } as unknown as DesktopBridge; const { createLocalApi } = await import("./localApi"); @@ -104,21 +102,11 @@ describe("LocalApi", () => { await expect(api.dialogs.pickFolder({ initialPath: "/tmp" })).resolves.toBe("/tmp/project"); await expect(api.persistence.getClientSettings()).resolves.toEqual(DEFAULT_CLIENT_SETTINGS); await api.persistence.setClientSettings(DEFAULT_CLIENT_SETTINGS); - await expect( - api.shell.downloadAndReveal({ - url: "https://example.com/readme.txt", - fileName: String.raw`C:\workspace\readme.txt`, - }), - ).resolves.toBe("/tmp/download/readme.txt"); expect(showContextMenu).toHaveBeenCalledWith(items, undefined); expect(pickFolder).toHaveBeenCalledWith({ initialPath: "/tmp" }); expect(getClientSettings).toHaveBeenCalledTimes(1); expect(setClientSettings).toHaveBeenCalledWith(DEFAULT_CLIENT_SETTINGS); - expect(downloadAndReveal).toHaveBeenCalledWith({ - url: "https://example.com/readme.txt", - fileName: String.raw`C:\workspace\readme.txt`, - }); }); it("persists client settings in browser storage", async () => { diff --git a/apps/web/src/localApi.ts b/apps/web/src/localApi.ts index d308e5e637..2fbf183f91 100644 --- a/apps/web/src/localApi.ts +++ b/apps/web/src/localApi.ts @@ -37,12 +37,6 @@ function createBrowserLocalApi(): LocalApi { window.open(url, "_blank", "noopener,noreferrer"); }, - downloadAndReveal: async (input) => { - if (!window.desktopBridge) { - throw new Error("Downloading and revealing files requires the desktop app."); - } - return window.desktopBridge.downloadAndReveal(input); - }, }, contextMenu: { show: async ( diff --git a/packages/contracts/src/assets.ts b/packages/contracts/src/assets.ts index dffefab5f6..0dbe7d9fa2 100644 --- a/packages/contracts/src/assets.ts +++ b/packages/contracts/src/assets.ts @@ -9,10 +9,6 @@ export const AssetResource = Schema.Union([ threadId: ThreadId, path: TrimmedNonEmptyString.check(Schema.isMaxLength(ASSET_PATH_MAX_LENGTH)), }), - Schema.TaggedStruct("workspace-file-download", { - threadId: ThreadId, - path: TrimmedNonEmptyString.check(Schema.isMaxLength(ASSET_PATH_MAX_LENGTH)), - }), Schema.TaggedStruct("attachment", { attachmentId: TrimmedNonEmptyString.check(Schema.isMaxLength(256)), }), diff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.ts index 463265df00..6c853ca163 100644 --- a/packages/contracts/src/ipc.ts +++ b/packages/contracts/src/ipc.ts @@ -926,12 +926,6 @@ export const DesktopPreviewRecordingSaveInputSchema = Schema.Struct({ data: Schema.Uint8Array, }); -export const DesktopDownloadAndRevealInputSchema = Schema.Struct({ - url: Schema.String.check(Schema.isTrimmed()).check(Schema.isNonEmpty()), - fileName: Schema.String.check(Schema.isNonEmpty()), -}); -export type DesktopDownloadAndRevealInput = typeof DesktopDownloadAndRevealInputSchema.Type; - export const DesktopPreviewAutomationClickInputSchema = Schema.Struct({ tabId: DesktopPreviewTabIdSchema, input: PreviewAutomationClickInput, @@ -1011,7 +1005,6 @@ export interface DesktopBridge { position?: { x: number; y: number }, ) => Promise; openExternal: (url: string) => Promise; - downloadAndReveal: (input: DesktopDownloadAndRevealInput) => Promise; onMenuAction: (listener: (action: string) => void) => () => void; getWindowFullscreenState: () => boolean; onWindowFullscreenStateChange: (listener: (fullscreen: boolean) => void) => () => void; @@ -1108,7 +1101,6 @@ export interface LocalApi { shell: { openInEditor: (cwd: string, editor: EditorId) => Promise; openExternal: (url: string) => Promise; - downloadAndReveal: (input: DesktopDownloadAndRevealInput) => Promise; }; contextMenu: { show: (