From a69c8a54b91e66bb3bd89aa8e6420c128e0cedaf Mon Sep 17 00:00:00 2001 From: Tim Smart Date: Tue, 21 Jul 2026 12:10:03 +1200 Subject: [PATCH 01/13] Add desktop open-with application support - Let users pick macOS .app bundles with system icons - Add open-with IPC, launch resolution, and settings plumbing - Cover bundle parsing, availability, and launch behavior with tests --- .../src/electron/ElectronDialog.test.ts | 69 +- apps/desktop/src/electron/ElectronDialog.ts | 82 ++ .../src/electron/MacApplicationIcon.ts | 63 ++ apps/desktop/src/ipc/DesktopIpcHandlers.ts | 8 + apps/desktop/src/ipc/channels.ts | 3 + apps/desktop/src/ipc/methods/openWith.test.ts | 43 + apps/desktop/src/ipc/methods/openWith.ts | 47 + apps/desktop/src/main.ts | 2 + apps/desktop/src/preload.ts | 4 + .../settings/DesktopClientSettings.test.ts | 13 +- .../desktop/src/shell/DesktopOpenWith.test.ts | 218 ++++ apps/desktop/src/shell/DesktopOpenWith.ts | 332 ++++++ .../src/window/DesktopApplicationMenu.test.ts | 1 + apps/web/src/components/ChatView.tsx | 3 +- .../src/components/chat/ChatHeader.test.ts | 8 +- apps/web/src/components/chat/ChatHeader.tsx | 8 +- apps/web/src/components/chat/OpenInPicker.tsx | 998 +++++++++++++----- .../KeybindingsSettings.logic.test.ts | 1 + .../settings/KeybindingsSettings.logic.ts | 1 + apps/web/src/editorPreferences.ts | 6 +- apps/web/src/localApi.test.ts | 30 + apps/web/src/localApi.ts | 12 + apps/web/src/openWith.test.ts | 98 ++ apps/web/src/openWith.ts | 101 ++ packages/contracts/src/index.ts | 1 + packages/contracts/src/ipc.ts | 11 + packages/contracts/src/openWith.test.ts | 77 ++ packages/contracts/src/openWith.ts | 179 ++++ packages/contracts/src/settings.test.ts | 6 + packages/contracts/src/settings.ts | 7 + 30 files changed, 2171 insertions(+), 261 deletions(-) create mode 100644 apps/desktop/src/electron/MacApplicationIcon.ts create mode 100644 apps/desktop/src/ipc/methods/openWith.test.ts create mode 100644 apps/desktop/src/ipc/methods/openWith.ts create mode 100644 apps/desktop/src/shell/DesktopOpenWith.test.ts create mode 100644 apps/desktop/src/shell/DesktopOpenWith.ts create mode 100644 apps/web/src/openWith.test.ts create mode 100644 apps/web/src/openWith.ts create mode 100644 packages/contracts/src/openWith.test.ts create mode 100644 packages/contracts/src/openWith.ts diff --git a/apps/desktop/src/electron/ElectronDialog.test.ts b/apps/desktop/src/electron/ElectronDialog.test.ts index 388b3fd2c15..72b6c15a465 100644 --- a/apps/desktop/src/electron/ElectronDialog.test.ts +++ b/apps/desktop/src/electron/ElectronDialog.test.ts @@ -7,13 +7,17 @@ import { beforeEach, vi } from "vite-plus/test"; import * as ElectronDialog from "./ElectronDialog.ts"; -const { showMessageBoxMock, showOpenDialogMock, showErrorBoxMock } = vi.hoisted(() => ({ - showMessageBoxMock: vi.fn(), - showOpenDialogMock: vi.fn(), - showErrorBoxMock: vi.fn(), -})); +const { showMessageBoxMock, showOpenDialogMock, showErrorBoxMock, getFileIconMock } = vi.hoisted( + () => ({ + showMessageBoxMock: vi.fn(), + showOpenDialogMock: vi.fn(), + showErrorBoxMock: vi.fn(), + getFileIconMock: vi.fn(), + }), +); vi.mock("electron", () => ({ + app: { getFileIcon: getFileIconMock }, dialog: { showMessageBox: showMessageBoxMock, showOpenDialog: showOpenDialogMock, @@ -26,8 +30,63 @@ describe("ElectronDialog", () => { showMessageBoxMock.mockReset(); showOpenDialogMock.mockReset(); showErrorBoxMock.mockReset(); + getFileIconMock.mockReset(); }); + it.effect("selects a macOS application and resolves its system icon", () => + Effect.gen(function* () { + const owner = { id: 12 } as BrowserWindow; + showOpenDialogMock.mockResolvedValue({ + canceled: false, + filePaths: ["/Applications/Terminal.app"], + }); + getFileIconMock.mockResolvedValue({ toDataURL: () => "data:image/png;base64,icon" }); + const dialog = yield* ElectronDialog.ElectronDialog; + + const result = yield* dialog.pickApplication({ owner: Option.some(owner) }); + + assert.deepEqual(Option.getOrNull(result), { + applicationPath: "/Applications/Terminal.app", + suggestedName: "Terminal", + iconDataUrl: "data:image/png;base64,icon", + }); + assert.deepEqual(showOpenDialogMock.mock.calls[0], [ + owner, + { + defaultPath: "/Applications", + properties: ["openFile"], + filters: [{ name: "Applications", extensions: ["app"] }], + }, + ]); + }).pipe(Effect.provide(ElectronDialog.layer)), + ); + + it.effect("returns none when application selection is cancelled", () => + Effect.gen(function* () { + showOpenDialogMock.mockResolvedValue({ canceled: true, filePaths: [] }); + const dialog = yield* ElectronDialog.ElectronDialog; + assert.isTrue(Option.isNone(yield* dialog.pickApplication({ owner: Option.none() }))); + assert.equal(getFileIconMock.mock.calls.length, 0); + }).pipe(Effect.provide(ElectronDialog.layer)), + ); + + it.effect("keeps a valid selection when icon extraction fails", () => + Effect.gen(function* () { + showOpenDialogMock.mockResolvedValue({ + canceled: false, + filePaths: ["/Users/test/Applications/My Tool.app"], + }); + getFileIconMock.mockRejectedValue(new Error("icon unavailable")); + const dialog = yield* ElectronDialog.ElectronDialog; + + assert.deepEqual(Option.getOrNull(yield* dialog.pickApplication({ owner: Option.none() })), { + applicationPath: "/Users/test/Applications/My Tool.app", + suggestedName: "My Tool", + iconDataUrl: null, + }); + }).pipe(Effect.provide(ElectronDialog.layer)), + ); + it.effect("returns false without opening a confirm dialog for empty messages", () => Effect.gen(function* () { const dialog = yield* ElectronDialog.ElectronDialog; diff --git a/apps/desktop/src/electron/ElectronDialog.ts b/apps/desktop/src/electron/ElectronDialog.ts index be633971bea..8318fd6cab7 100644 --- a/apps/desktop/src/electron/ElectronDialog.ts +++ b/apps/desktop/src/electron/ElectronDialog.ts @@ -1,10 +1,15 @@ +// @effect-diagnostics nodeBuiltinImport:off - Electron's native picker returns host paths. import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; +import * as NodePath from "node:path"; import * as Electron from "electron"; +import type { DesktopApplicationSelection } from "@t3tools/contracts"; + +import { resolveMacApplicationIconDataUrl } from "./MacApplicationIcon.ts"; const CONFIRM_BUTTON_INDEX = 1; @@ -23,6 +28,19 @@ export class ElectronDialogPickFolderError extends Schema.TaggedErrorClass()( + "ElectronDialogPickApplicationError", + { + ownerWindowId: Schema.NullOr(Schema.Number), + selectedPath: Schema.NullOr(Schema.String), + cause: Schema.Defect(), + }, +) { + override get message(): string { + return "Failed to select a macOS application."; + } +} + export class ElectronDialogConfirmError extends Schema.TaggedErrorClass()( "ElectronDialogConfirmError", { @@ -69,6 +87,7 @@ export class ElectronDialogShowErrorBoxError extends Schema.TaggedErrorClass; } +export interface ElectronDialogPickApplicationInput { + readonly owner: Option.Option; +} + export interface ElectronDialogConfirmInput { readonly owner: Option.Option; readonly message: string; @@ -92,6 +115,12 @@ export class ElectronDialog extends Context.Service< readonly pickFolder: ( input: ElectronDialogPickFolderInput, ) => Effect.Effect, ElectronDialogPickFolderError>; + readonly pickApplication: ( + input: ElectronDialogPickApplicationInput, + ) => Effect.Effect< + Option.Option, + ElectronDialogPickApplicationError + >; readonly confirm: ( input: ElectronDialogConfirmInput, ) => Effect.Effect; @@ -137,6 +166,59 @@ export const make = ElectronDialog.of({ } return Option.fromNullishOr(result.filePaths[0]); }), + pickApplication: Effect.fn("desktop.electron.dialog.pickApplication")(function* (input) { + const ownerWindowId = Option.match(input.owner, { + onNone: () => null, + onSome: (owner) => owner.id, + }); + const options: Electron.OpenDialogOptions = { + defaultPath: "/Applications", + properties: ["openFile"], + filters: [{ name: "Applications", extensions: ["app"] }], + }; + const result = yield* Effect.tryPromise({ + try: () => + Option.match(input.owner, { + onNone: () => Electron.dialog.showOpenDialog(options), + onSome: (owner) => Electron.dialog.showOpenDialog(owner, options), + }), + catch: (cause) => + new ElectronDialogPickApplicationError({ + ownerWindowId, + selectedPath: null, + cause, + }), + }); + if (result.canceled) return Option.none(); + + const applicationPath = result.filePaths[0]; + if ( + applicationPath === undefined || + !NodePath.isAbsolute(applicationPath) || + !applicationPath.toLowerCase().endsWith(".app") + ) { + return yield* new ElectronDialogPickApplicationError({ + ownerWindowId, + selectedPath: applicationPath ?? null, + cause: new Error("The selected path is not an absolute .app bundle."), + }); + } + + const iconDataUrl = yield* Effect.tryPromise({ + try: () => resolveMacApplicationIconDataUrl(applicationPath), + catch: (cause) => + new ElectronDialogPickApplicationError({ + ownerWindowId, + selectedPath: applicationPath, + cause, + }), + }).pipe(Effect.orElseSucceed(() => null)); + return Option.some({ + applicationPath, + suggestedName: NodePath.basename(applicationPath, NodePath.extname(applicationPath)), + iconDataUrl, + }); + }), confirm: Effect.fn("desktop.electron.dialog.confirm")(function* (input) { const normalizedMessage = input.message.trim(); if (normalizedMessage.length === 0) { diff --git a/apps/desktop/src/electron/MacApplicationIcon.ts b/apps/desktop/src/electron/MacApplicationIcon.ts new file mode 100644 index 00000000000..8809f857504 --- /dev/null +++ b/apps/desktop/src/electron/MacApplicationIcon.ts @@ -0,0 +1,63 @@ +// @effect-diagnostics nodeBuiltinImport:off - macOS bundle paths use the host path grammar. +import * as NodeChildProcess from "node:child_process"; +import * as NodeFSP from "node:fs/promises"; +import * as NodeOS from "node:os"; +import * as NodePath from "node:path"; +import * as NodeUtil from "node:util"; + +import * as Electron from "electron"; + +const execFile = NodeUtil.promisify(NodeChildProcess.execFile); + +async function resolveBundleIconPath(applicationPath: string): Promise { + const infoPlistPath = NodePath.join(applicationPath, "Contents", "Info.plist"); + const { stdout } = await execFile( + "/usr/bin/plutil", + ["-extract", "CFBundleIconFile", "raw", infoPlistPath], + { encoding: "utf8" }, + ); + const configuredName = stdout.trim(); + if ( + configuredName.length === 0 || + NodePath.basename(configuredName) !== configuredName || + configuredName === "." || + configuredName === ".." + ) { + return null; + } + const iconName = NodePath.extname(configuredName) ? configuredName : `${configuredName}.icns`; + const iconPath = NodePath.join(applicationPath, "Contents", "Resources", iconName); + const stat = await NodeFSP.stat(iconPath); + return stat.isFile() ? iconPath : null; +} + +async function convertIcnsToDataUrl(iconPath: string): Promise { + const temporaryDirectory = await NodeFSP.mkdtemp( + NodePath.join(NodeOS.tmpdir(), "t3code-open-with-icon-"), + ); + const pngPath = NodePath.join(temporaryDirectory, "icon.png"); + try { + await execFile("/usr/bin/sips", ["-s", "format", "png", iconPath, "--out", pngPath]); + const png = await NodeFSP.readFile(pngPath); + const image = Electron.nativeImage.createFromBuffer(png); + if (image.isEmpty()) throw new Error("The converted application icon is empty."); + return image.toDataURL(); + } finally { + await NodeFSP.rm(temporaryDirectory, { recursive: true, force: true }); + } +} + +/** + * Electron's macOS file-icon lookup can return the generic application-bundle icon for a + * `.app` directory. Prefer the bundle's declared ICNS asset when it can be read, then use + * Electron's system lookup for asset-catalog apps and all failure cases. + */ +export async function resolveMacApplicationIconDataUrl(applicationPath: string): Promise { + try { + const iconPath = await resolveBundleIconPath(applicationPath); + if (iconPath !== null) return await convertIcnsToDataUrl(iconPath); + } catch { + // Fall through to Electron's system icon lookup. + } + return (await Electron.app.getFileIcon(applicationPath, { size: "large" })).toDataURL(); +} diff --git a/apps/desktop/src/ipc/DesktopIpcHandlers.ts b/apps/desktop/src/ipc/DesktopIpcHandlers.ts index e478d0c6eff..402e9d75a23 100644 --- a/apps/desktop/src/ipc/DesktopIpcHandlers.ts +++ b/apps/desktop/src/ipc/DesktopIpcHandlers.ts @@ -42,6 +42,11 @@ import { showContextMenu, } from "./methods/window.ts"; import * as PreviewIpc from "./methods/preview.ts"; +import { + openWith, + pickOpenWithApplication, + resolveOpenWithPresentations, +} from "./methods/openWith.ts"; import { getWslState, setWslBackendEnabled, setWslDistro, setWslOnly } from "./methods/wsl.ts"; export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers")(function* () { @@ -83,6 +88,9 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers" yield* ipc.handle(setTheme); yield* ipc.handle(showContextMenu); yield* ipc.handle(openExternal); + yield* ipc.handle(pickOpenWithApplication); + yield* ipc.handle(resolveOpenWithPresentations); + yield* ipc.handle(openWith); 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 95c725130e5..459fd1982ce 100644 --- a/apps/desktop/src/ipc/channels.ts +++ b/apps/desktop/src/ipc/channels.ts @@ -3,6 +3,9 @@ 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 PICK_OPEN_WITH_APPLICATION_CHANNEL = "desktop:pick-open-with-application"; +export const RESOLVE_OPEN_WITH_PRESENTATIONS_CHANNEL = "desktop:resolve-open-with-presentations"; +export const OPEN_WITH_CHANNEL = "desktop:open-with"; 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/openWith.test.ts b/apps/desktop/src/ipc/methods/openWith.test.ts new file mode 100644 index 00000000000..9e606199ebd --- /dev/null +++ b/apps/desktop/src/ipc/methods/openWith.test.ts @@ -0,0 +1,43 @@ +import { assert, describe, it } from "@effect/vitest"; +import { OpenWithEntryId } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Ref from "effect/Ref"; + +import * as DesktopOpenWith from "../../shell/DesktopOpenWith.ts"; +import { openWith, resolveOpenWithPresentations } from "./openWith.ts"; + +describe("Open With IPC methods", () => { + it.effect("encodes presentations and delegates launch inputs", () => + Effect.gen(function* () { + const opened = yield* Ref.make(null); + const entryId = OpenWithEntryId.make("terminal"); + const layer = Layer.succeed( + DesktopOpenWith.DesktopOpenWith, + DesktopOpenWith.DesktopOpenWith.of({ + resolvePresentations: Effect.succeed([ + { entryId, available: true, iconDataUrl: "data:image/png;base64,abc" }, + ]), + open: (input) => Ref.set(opened, input), + }), + ); + + assert.deepEqual( + yield* resolveOpenWithPresentations.handler(undefined).pipe(Effect.provide(layer)), + [{ entryId: "terminal", available: true, iconDataUrl: "data:image/png;base64,abc" }], + ); + yield* openWith + .handler({ + environmentId: "primary", + entryId: "terminal", + directory: "/tmp/project", + }) + .pipe(Effect.provide(layer)); + assert.deepEqual(yield* Ref.get(opened), { + environmentId: "primary", + entryId: "terminal", + directory: "/tmp/project", + }); + }), + ); +}); diff --git a/apps/desktop/src/ipc/methods/openWith.ts b/apps/desktop/src/ipc/methods/openWith.ts new file mode 100644 index 00000000000..eb19e0ec7e3 --- /dev/null +++ b/apps/desktop/src/ipc/methods/openWith.ts @@ -0,0 +1,47 @@ +import { + DesktopApplicationSelection, + DesktopOpenWithInput, + OpenWithEntryPresentation, +} from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; + +import * as ElectronDialog from "../../electron/ElectronDialog.ts"; +import * as ElectronWindow from "../../electron/ElectronWindow.ts"; +import * as DesktopOpenWith from "../../shell/DesktopOpenWith.ts"; +import * as IpcChannels from "../channels.ts"; +import * as DesktopIpc from "../DesktopIpc.ts"; + +export const pickOpenWithApplication = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.PICK_OPEN_WITH_APPLICATION_CHANNEL, + payload: Schema.Void, + result: Schema.NullOr(DesktopApplicationSelection), + handler: Effect.fn("desktop.ipc.openWith.pickApplication")(function* () { + const dialog = yield* ElectronDialog.ElectronDialog; + const electronWindow = yield* ElectronWindow.ElectronWindow; + return Option.getOrNull( + yield* dialog.pickApplication({ owner: yield* electronWindow.focusedMainOrFirst }), + ); + }), +}); + +export const resolveOpenWithPresentations = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.RESOLVE_OPEN_WITH_PRESENTATIONS_CHANNEL, + payload: Schema.Void, + result: Schema.Array(OpenWithEntryPresentation), + handler: Effect.fn("desktop.ipc.openWith.resolvePresentations")(function* () { + const openWith = yield* DesktopOpenWith.DesktopOpenWith; + return yield* openWith.resolvePresentations; + }), +}); + +export const openWith = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.OPEN_WITH_CHANNEL, + payload: DesktopOpenWithInput, + result: Schema.Void, + handler: Effect.fn("desktop.ipc.openWith.open")(function* (input) { + const openWith = yield* DesktopOpenWith.DesktopOpenWith; + yield* openWith.open(input); + }), +}); diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts index 9795f04e8ae..8f85581b24b 100644 --- a/apps/desktop/src/main.ts +++ b/apps/desktop/src/main.ts @@ -49,6 +49,7 @@ import * as DesktopClientSettings from "./settings/DesktopClientSettings.ts"; import * as DesktopSavedEnvironments from "./settings/DesktopSavedEnvironments.ts"; import * as DesktopAppSettings from "./settings/DesktopAppSettings.ts"; import * as DesktopShellEnvironment from "./shell/DesktopShellEnvironment.ts"; +import * as DesktopOpenWith from "./shell/DesktopOpenWith.ts"; import * as DesktopSshEnvironment from "./ssh/DesktopSshEnvironment.ts"; import * as DesktopSshPasswordPrompts from "./ssh/DesktopSshPasswordPrompts.ts"; import * as DesktopState from "./app/DesktopState.ts"; @@ -178,6 +179,7 @@ const desktopApplicationLayer = Layer.mergeAll( DesktopLifecycle.layer, DesktopApplicationMenu.layer, DesktopShellEnvironment.layer, + DesktopOpenWith.layer, desktopSshLayer, ).pipe( Layer.provideMerge(DesktopUpdates.layer), diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts index 228114fd1d1..3a12ae1f39e 100644 --- a/apps/desktop/src/preload.ts +++ b/apps/desktop/src/preload.ts @@ -105,6 +105,10 @@ contextBridge.exposeInMainWorld("desktopBridge", { ...(position === undefined ? {} : { position }), }), openExternal: (url: string) => ipcRenderer.invoke(IpcChannels.OPEN_EXTERNAL_CHANNEL, url), + pickOpenWithApplication: () => ipcRenderer.invoke(IpcChannels.PICK_OPEN_WITH_APPLICATION_CHANNEL), + resolveOpenWithPresentations: () => + ipcRenderer.invoke(IpcChannels.RESOLVE_OPEN_WITH_PRESENTATIONS_CHANNEL), + openWith: (input) => ipcRenderer.invoke(IpcChannels.OPEN_WITH_CHANNEL, input), onMenuAction: (listener) => { const wrappedListener = (_event: Electron.IpcRendererEvent, action: unknown) => { if (typeof action !== "string") return; diff --git a/apps/desktop/src/settings/DesktopClientSettings.test.ts b/apps/desktop/src/settings/DesktopClientSettings.test.ts index 8f50aa8f882..bc1a06e7c34 100644 --- a/apps/desktop/src/settings/DesktopClientSettings.test.ts +++ b/apps/desktop/src/settings/DesktopClientSettings.test.ts @@ -1,6 +1,6 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, describe, it } from "@effect/vitest"; -import { ClientSettingsSchema, type ClientSettings } from "@t3tools/contracts"; +import { ClientSettingsSchema, OpenWithEntryId, type ClientSettings } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; @@ -20,6 +20,17 @@ const clientSettings: ClientSettings = { diffIgnoreWhitespace: true, favorites: [], glassOpacity: 80, + openWithEntries: [ + { + id: OpenWithEntryId.make("terminal"), + name: "Terminal", + kind: "terminal", + invocation: { type: "mac-application", applicationPath: "/Applications/Terminal.app" }, + directoryMode: "open-target", + arguments: [], + }, + ], + preferredOpenWith: { type: "custom", id: OpenWithEntryId.make("terminal") }, providerModelPreferences: {}, sidebarAutoSettleAfterDays: 3, sidebarProjectGroupingMode: "repository_path", diff --git a/apps/desktop/src/shell/DesktopOpenWith.test.ts b/apps/desktop/src/shell/DesktopOpenWith.test.ts new file mode 100644 index 00000000000..7709fd58616 --- /dev/null +++ b/apps/desktop/src/shell/DesktopOpenWith.test.ts @@ -0,0 +1,218 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, describe, it } from "@effect/vitest"; +import { + DEFAULT_CLIENT_SETTINGS, + EnvironmentId, + OpenWithEntry, + OpenWithEntryId, + PRIMARY_LOCAL_ENVIRONMENT_ID, +} from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; +import * as Schema from "effect/Schema"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; + +import * as DesktopConfig from "../app/DesktopConfig.ts"; +import * as DesktopEnvironment from "../app/DesktopEnvironment.ts"; +import * as DesktopClientSettings from "../settings/DesktopClientSettings.ts"; +import * as DesktopOpenWith from "./DesktopOpenWith.ts"; + +const decodeEntry = Schema.decodeUnknownSync(OpenWithEntry); + +const configuredEntries = [ + decodeEntry({ + id: "echo", + name: "Echo", + kind: "other", + invocation: { type: "command", executable: "/bin/echo" }, + directoryMode: "open-target", + arguments: [], + }), + decodeEntry({ + id: "missing", + name: "Missing", + kind: "other", + invocation: { type: "command", executable: "/definitely/missing/t3-open-with" }, + directoryMode: "open-target", + arguments: [], + }), +] as const; + +const environmentLayer = DesktopEnvironment.layer({ + dirname: "/repo/apps/desktop/src", + homeDirectory: "/tmp", + platform: "darwin", + processArch: "arm64", + appVersion: "1.0.0", + appPath: "/repo", + isPackaged: true, + resourcesPath: "/repo/resources", + runningUnderArm64Translation: false, +}).pipe( + Layer.provide( + Layer.mergeAll( + NodeServices.layer, + DesktopConfig.layerTest({ T3CODE_HOME: "/tmp/t3-open-with" }), + ), + ), +); + +const openWithLayer = DesktopOpenWith.layer.pipe( + Layer.provideMerge( + DesktopClientSettings.layerTest( + Option.some({ + ...DEFAULT_CLIENT_SETTINGS, + openWithEntries: configuredEntries, + }), + ), + ), + Layer.provideMerge(environmentLayer), + Layer.provideMerge(NodeServices.layer), +); + +describe("DesktopOpenWith launch resolution", () => { + it.effect("appends the directory for open-target command entries", () => + Effect.gen(function* () { + const launch = yield* DesktopOpenWith.resolveOpenWithLaunch( + decodeEntry({ + id: "echo", + name: "Echo", + kind: "other", + invocation: { type: "command", executable: "/bin/echo" }, + directoryMode: "open-target", + arguments: ["--flag"], + }), + "/tmp/work tree", + "darwin", + ); + assert.deepEqual(launch, { + command: "/bin/echo", + args: ["--flag", "/tmp/work tree"], + shell: false, + cwd: null, + }); + }).pipe(Effect.provide(NodeServices.layer)), + ); + + it.effect("sets cwd without adding a directory argument in working-directory mode", () => + Effect.gen(function* () { + const launch = yield* DesktopOpenWith.resolveOpenWithLaunch( + decodeEntry({ + id: "echo", + name: "Echo", + kind: "other", + invocation: { type: "command", executable: "/bin/echo" }, + directoryMode: "working-directory", + arguments: ["one argument"], + }), + "/tmp/work tree", + "darwin", + ); + assert.deepEqual(launch, { + command: "/bin/echo", + args: ["one argument"], + shell: false, + cwd: "/tmp/work tree", + }); + }).pipe(Effect.provide(NodeServices.layer)), + ); + + it.effect("expands placeholders within independent argument rows without shell parsing", () => + Effect.gen(function* () { + const launch = yield* DesktopOpenWith.resolveOpenWithLaunch( + decodeEntry({ + id: "echo", + name: "Echo", + kind: "other", + invocation: { type: "command", executable: "/bin/echo" }, + directoryMode: "custom-arguments", + arguments: ["prefix={directory}=suffix", "literal value"], + }), + "/tmp/work tree", + "darwin", + ); + assert.deepEqual(launch.args, ["prefix=/tmp/work tree=suffix", "literal value"]); + assert.isFalse(launch.shell ?? false); + }).pipe(Effect.provide(NodeServices.layer)), + ); + + it.effect("resolves CFBundleExecutable and reports missing bundle executables", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const base = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-open-with-test-" }); + const applicationPath = path.join(base, "Fixture.app"); + const contentsPath = path.join(applicationPath, "Contents"); + const executableDirectory = path.join(contentsPath, "MacOS"); + yield* fileSystem.makeDirectory(executableDirectory, { recursive: true }); + yield* fileSystem.writeFileString( + path.join(contentsPath, "Info.plist"), + ` + CFBundleExecutableFixture`, + ); + const executablePath = path.join(executableDirectory, "Fixture"); + yield* fileSystem.writeFileString(executablePath, "#!/bin/sh\n"); + + assert.equal( + yield* DesktopOpenWith.resolveMacBundleExecutable(applicationPath), + executablePath, + ); + yield* fileSystem.remove(executablePath); + const error = yield* Effect.flip(DesktopOpenWith.resolveMacBundleExecutable(applicationPath)); + assert.equal(error.reason, "missing-executable"); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), + ); + + it.effect("reports available and missing command presentations", () => + Effect.gen(function* () { + const openWith = yield* DesktopOpenWith.DesktopOpenWith; + const presentations = yield* openWith.resolvePresentations; + assert.deepEqual(presentations, [ + { entryId: configuredEntries[0].id, available: true, iconDataUrl: null }, + { + entryId: configuredEntries[1].id, + available: false, + iconDataUrl: null, + unavailableReason: "Executable not found: /definitely/missing/t3-open-with", + }, + ]); + }).pipe(Effect.provide(openWithLayer)), + ); + + it.effect("rejects secondary environments, invalid targets, and unknown entry ids", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-open-target-" }); + const openWith = yield* DesktopOpenWith.DesktopOpenWith; + + const remoteError = yield* Effect.flip( + openWith.open({ + environmentId: EnvironmentId.make("ssh:test"), + entryId: configuredEntries[0].id, + directory, + }), + ); + assert.equal(remoteError._tag, "OpenWithEnvironmentError"); + + const relativeError = yield* Effect.flip( + openWith.open({ + environmentId: EnvironmentId.make(PRIMARY_LOCAL_ENVIRONMENT_ID), + entryId: configuredEntries[0].id, + directory: "relative/path", + }), + ); + assert.equal(relativeError._tag, "OpenWithInvalidTargetError"); + + const unknownError = yield* Effect.flip( + openWith.open({ + environmentId: EnvironmentId.make(PRIMARY_LOCAL_ENVIRONMENT_ID), + entryId: OpenWithEntryId.make("unknown"), + directory, + }), + ); + assert.equal(unknownError._tag, "OpenWithMissingEntryError"); + }).pipe(Effect.provide(openWithLayer), Effect.scoped), + ); +}); diff --git a/apps/desktop/src/shell/DesktopOpenWith.ts b/apps/desktop/src/shell/DesktopOpenWith.ts new file mode 100644 index 00000000000..ee996a07145 --- /dev/null +++ b/apps/desktop/src/shell/DesktopOpenWith.ts @@ -0,0 +1,332 @@ +// @effect-diagnostics nodeBuiltinImport:off - macOS bundle paths use the host path grammar. +import { + OpenWithBundleResolutionError, + OpenWithEnvironmentError, + OpenWithInvalidTargetError, + OpenWithMissingEntryError, + OpenWithSpawnError, + OpenWithUnavailableApplicationError, + PRIMARY_LOCAL_ENVIRONMENT_ID, + type DesktopOpenWithInput, + type OpenWithEntry, + type OpenWithEntryPresentation, + type OpenWithLaunchError, +} from "@t3tools/contracts"; +import { resolveCommandPath, resolveSpawnCommand } from "@t3tools/shared/shell"; +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 NodePath from "node:path"; +import * as ChildProcess from "effect/unstable/process/ChildProcess"; +import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner"; + +import * as DesktopEnvironment from "../app/DesktopEnvironment.ts"; +import { resolveMacApplicationIconDataUrl } from "../electron/MacApplicationIcon.ts"; +import * as DesktopClientSettings from "../settings/DesktopClientSettings.ts"; + +interface ResolvedLaunch { + readonly command: string; + readonly args: readonly string[]; + readonly cwd: string | null; + readonly shell?: boolean; +} + +const statPath = (path: string) => + FileSystem.FileSystem.pipe( + Effect.flatMap((fileSystem) => fileSystem.stat(path)), + Effect.map(Option.some), + Effect.orElseSucceed(() => Option.none()), + ); + +const applicationUnavailableReason = (entry: OpenWithEntry): string => + entry.invocation.type === "mac-application" + ? `Application not found: ${entry.invocation.applicationPath}` + : `Executable not found: ${entry.invocation.executable}`; + +const isMacApplicationPath = (value: string): boolean => + NodePath.isAbsolute(value) && value.toLowerCase().endsWith(".app"); + +const commandExists = Effect.fn("desktop.openWith.commandExists")(function* (command: string) { + return yield* resolveCommandPath(command).pipe( + Effect.as(true), + Effect.catchTag("CommandResolutionError", () => Effect.succeed(false)), + ); +}); + +const entryIsAvailable = Effect.fn("desktop.openWith.entryIsAvailable")(function* ( + entry: OpenWithEntry, + platform: NodeJS.Platform, +) { + if (entry.invocation.type === "command") { + return yield* commandExists(entry.invocation.executable); + } + if (platform !== "darwin" || !isMacApplicationPath(entry.invocation.applicationPath)) { + return false; + } + const stat = yield* statPath(entry.invocation.applicationPath); + return Option.isSome(stat) && stat.value.type === "Directory"; +}); + +const resolveIconDataUrl = (applicationPath: string) => + Effect.tryPromise({ + try: () => resolveMacApplicationIconDataUrl(applicationPath), + catch: (cause) => new OpenWithIconResolutionError({ applicationPath, cause }), + }).pipe(Effect.orElseSucceed(() => null)); + +class OpenWithIconResolutionError extends Schema.TaggedErrorClass()( + "OpenWithIconResolutionError", + { applicationPath: Schema.String, cause: Schema.Defect() }, +) {} + +export const resolveMacBundleExecutable = Effect.fn("desktop.openWith.resolveMacBundleExecutable")( + function* (applicationPath: string) { + if (!isMacApplicationPath(applicationPath)) { + return yield* new OpenWithBundleResolutionError({ + applicationPath, + reason: "invalid-application-path", + }); + } + const infoPlistPath = NodePath.join(applicationPath, "Contents", "Info.plist"); + const plistStat = yield* statPath(infoPlistPath); + if (Option.isNone(plistStat) || plistStat.value.type !== "File") { + return yield* new OpenWithBundleResolutionError({ + applicationPath, + reason: "missing-info-plist", + }); + } + + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const executableName = yield* spawner + .string( + ChildProcess.make( + "/usr/bin/plutil", + ["-extract", "CFBundleExecutable", "raw", "-o", "-", infoPlistPath], + { stdin: "ignore", stdout: "pipe", stderr: "pipe" }, + ), + ) + .pipe( + Effect.map((output) => output.trim()), + Effect.mapError( + (cause) => + new OpenWithBundleResolutionError({ + applicationPath, + reason: "malformed-info-plist", + cause, + }), + ), + ); + if ( + executableName.length === 0 || + executableName.includes("/") || + executableName.includes("\\") + ) { + return yield* new OpenWithBundleResolutionError({ + applicationPath, + reason: "malformed-info-plist", + }); + } + const executablePath = NodePath.join(applicationPath, "Contents", "MacOS", executableName); + const executableStat = yield* statPath(executablePath); + if (Option.isNone(executableStat) || executableStat.value.type !== "File") { + return yield* new OpenWithBundleResolutionError({ + applicationPath, + reason: "missing-executable", + }); + } + return executablePath; + }, +); + +const expandDirectoryArguments = (args: readonly string[], directory: string): string[] => + args.map((argument) => argument.replaceAll("{directory}", directory)); + +export const resolveOpenWithLaunch = Effect.fn("desktop.openWith.resolveLaunch")(function* ( + entry: OpenWithEntry, + directory: string, + platform: NodeJS.Platform, +): Effect.fn.Return< + ResolvedLaunch, + OpenWithLaunchError, + FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner +> { + if (!(yield* entryIsAvailable(entry, platform))) { + return yield* new OpenWithUnavailableApplicationError({ + entryId: entry.id, + executable: + entry.invocation.type === "mac-application" + ? entry.invocation.applicationPath + : entry.invocation.executable, + }); + } + + if (entry.directoryMode === "open-target") { + if (entry.invocation.type === "mac-application") { + return { + command: "/usr/bin/open", + args: ["-a", entry.invocation.applicationPath, directory], + cwd: null, + }; + } + const command = yield* resolveSpawnCommand(entry.invocation.executable, [ + ...entry.arguments, + directory, + ]); + return { ...command, cwd: null }; + } + + if (entry.directoryMode === "working-directory") { + if (entry.invocation.type === "mac-application") { + return { + command: yield* resolveMacBundleExecutable(entry.invocation.applicationPath), + args: [...entry.arguments], + cwd: directory, + }; + } + const command = yield* resolveSpawnCommand(entry.invocation.executable, entry.arguments); + return { ...command, cwd: directory }; + } + + if (!entry.arguments.some((argument) => argument.includes("{directory}"))) { + return yield* new OpenWithUnavailableApplicationError({ + entryId: entry.id, + executable: "Custom arguments must include {directory}", + }); + } + const args = expandDirectoryArguments(entry.arguments, directory); + if (entry.invocation.type === "mac-application") { + return { + command: yield* resolveMacBundleExecutable(entry.invocation.applicationPath), + args, + cwd: null, + }; + } + const command = yield* resolveSpawnCommand(entry.invocation.executable, args); + return { ...command, cwd: null }; +}); + +const spawnDetached = ( + entry: OpenWithEntry, + launch: ResolvedLaunch & { readonly shell?: boolean }, +) => + ChildProcessSpawner.ChildProcessSpawner.pipe( + Effect.flatMap((spawner) => + spawner.spawn( + ChildProcess.make(launch.command, launch.args, { + ...(launch.cwd === null ? {} : { cwd: launch.cwd }), + detached: true, + shell: launch.shell ?? false, + stdin: "ignore", + stdout: "ignore", + stderr: "ignore", + }), + ), + ), + Effect.flatMap((handle) => handle.unref), + Effect.asVoid, + Effect.scoped, + Effect.mapError( + (cause) => + new OpenWithSpawnError({ + entryId: entry.id, + command: launch.command, + args: [...launch.args], + cwd: launch.cwd, + cause, + }), + ), + ); + +export class DesktopOpenWith extends Context.Service< + DesktopOpenWith, + { + readonly resolvePresentations: Effect.Effect; + readonly open: (input: DesktopOpenWithInput) => Effect.Effect; + } +>()("@t3tools/desktop/shell/DesktopOpenWith") {} + +export const make = Effect.gen(function* () { + const clientSettings = yield* DesktopClientSettings.DesktopClientSettings; + const environment = yield* DesktopEnvironment.DesktopEnvironment; + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + + const providePlatformServices = ( + effect: Effect.Effect< + A, + E, + FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner + >, + ): Effect.Effect => + effect.pipe( + Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.provideService(Path.Path, path), + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + ); + + const resolvePresentations = Effect.gen(function* () { + const settings = yield* clientSettings.get; + if (Option.isNone(settings)) return []; + return yield* Effect.forEach(settings.value.openWithEntries, (entry) => + Effect.gen(function* () { + const available = yield* providePlatformServices( + entryIsAvailable(entry, environment.platform), + ); + const iconDataUrl = + available && entry.invocation.type === "mac-application" + ? yield* resolveIconDataUrl(entry.invocation.applicationPath) + : null; + return { + entryId: entry.id, + available, + iconDataUrl, + ...(available ? {} : { unavailableReason: applicationUnavailableReason(entry) }), + } satisfies OpenWithEntryPresentation; + }), + ); + }).pipe(Effect.withSpan("desktop.openWith.resolvePresentations")); + + const open = Effect.fn("desktop.openWith.open")(function* (input: DesktopOpenWithInput) { + if (input.environmentId !== PRIMARY_LOCAL_ENVIRONMENT_ID) { + return yield* new OpenWithEnvironmentError({ environmentId: input.environmentId }); + } + if (!NodePath.isAbsolute(input.directory)) { + return yield* new OpenWithInvalidTargetError({ + directory: input.directory, + reason: "relative", + }); + } + const targetStat = yield* providePlatformServices(statPath(input.directory)); + if (Option.isNone(targetStat)) { + return yield* new OpenWithInvalidTargetError({ + directory: input.directory, + reason: "missing", + }); + } + if (targetStat.value.type !== "Directory") { + return yield* new OpenWithInvalidTargetError({ + directory: input.directory, + reason: "not-directory", + }); + } + const settings = yield* clientSettings.get; + const entry = Option.isSome(settings) + ? settings.value.openWithEntries.find((candidate) => candidate.id === input.entryId) + : undefined; + if (entry === undefined) { + return yield* new OpenWithMissingEntryError({ entryId: input.entryId }); + } + const launch = yield* providePlatformServices( + resolveOpenWithLaunch(entry, input.directory, environment.platform), + ); + yield* providePlatformServices(spawnDetached(entry, launch)); + }); + + return DesktopOpenWith.of({ resolvePresentations, open }); +}); + +export const layer = Layer.effect(DesktopOpenWith, make); diff --git a/apps/desktop/src/window/DesktopApplicationMenu.test.ts b/apps/desktop/src/window/DesktopApplicationMenu.test.ts index 168846466ed..149caa79747 100644 --- a/apps/desktop/src/window/DesktopApplicationMenu.test.ts +++ b/apps/desktop/src/window/DesktopApplicationMenu.test.ts @@ -50,6 +50,7 @@ const electronAppLayer = Layer.succeed(ElectronApp.ElectronApp, { const electronDialogLayer = Layer.succeed(ElectronDialog.ElectronDialog, { pickFolder: () => Effect.succeed(Option.none()), + pickApplication: () => Effect.succeed(Option.none()), confirm: () => Effect.succeed(false), showMessageBox: () => Effect.succeed({ response: 0, checkboxChecked: false }), showErrorBox: () => Effect.void, diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 63750e91041..8804b45de9c 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -2330,7 +2330,8 @@ function ChatViewContent(props: ChatViewProps) { }), ); const keybindings = useAtomValue(primaryServerKeybindingsAtom); - const availableEditors = useAtomValue(primaryServerAvailableEditorsAtom); + const activeServerConfig = useAtomValue(serverEnvironment.configValueAtom(environmentId)); + const availableEditors = activeServerConfig?.availableEditors ?? []; // Prefer an instance-id match so a custom Codex instance (e.g. // `codex_personal`) surfaces its own status/message in the banner rather // than the default Codex's. Falls back to first-match-by-kind when no diff --git a/apps/web/src/components/chat/ChatHeader.test.ts b/apps/web/src/components/chat/ChatHeader.test.ts index d716092fc3e..36508296203 100644 --- a/apps/web/src/components/chat/ChatHeader.test.ts +++ b/apps/web/src/components/chat/ChatHeader.test.ts @@ -16,24 +16,24 @@ describe("shouldShowOpenInPicker", () => { ).toBe(true); }); - it("hides the picker when hosted static mode has no primary environment", () => { + it("keeps built-in applications visible when hosted static mode has no primary environment", () => { expect( shouldShowOpenInPicker({ activeProjectName: "codething-mvp", activeThreadEnvironmentId: EnvironmentId.make("environment-remote"), primaryEnvironmentId: null, }), - ).toBe(false); + ).toBe(true); }); - it("hides the picker for remote environments", () => { + it("keeps built-in applications visible for remote environments", () => { expect( shouldShowOpenInPicker({ activeProjectName: "codething-mvp", activeThreadEnvironmentId: EnvironmentId.make("environment-remote"), primaryEnvironmentId, }), - ).toBe(false); + ).toBe(true); }); it("hides the picker when there is no active project", () => { diff --git a/apps/web/src/components/chat/ChatHeader.tsx b/apps/web/src/components/chat/ChatHeader.tsx index 3a7d57859a8..c0bb8417e54 100644 --- a/apps/web/src/components/chat/ChatHeader.tsx +++ b/apps/web/src/components/chat/ChatHeader.tsx @@ -48,11 +48,7 @@ export function shouldShowOpenInPicker(input: { readonly activeThreadEnvironmentId: EnvironmentId; readonly primaryEnvironmentId: EnvironmentId | null; }): boolean { - return ( - Boolean(input.activeProjectName) && - input.primaryEnvironmentId !== null && - input.activeThreadEnvironmentId === input.primaryEnvironmentId - ); + return Boolean(input.activeProjectName); } export const ChatHeader = memo(function ChatHeader({ @@ -82,7 +78,7 @@ export const ChatHeader = memo(function ChatHeader({ const showOpenInPicker = shouldShowOpenInPicker({ activeProjectName, activeThreadEnvironmentId, - primaryEnvironmentId, + primaryEnvironmentId: null, }); return (
diff --git a/apps/web/src/components/chat/OpenInPicker.tsx b/apps/web/src/components/chat/OpenInPicker.tsx index de5a2f7cfff..11b2a1c510e 100644 --- a/apps/web/src/components/chat/OpenInPicker.tsx +++ b/apps/web/src/components/chat/OpenInPicker.tsx @@ -1,11 +1,68 @@ -import { EditorId, type EnvironmentId, type ResolvedKeybindingsConfig } from "@t3tools/contracts"; -import { memo, useCallback, useEffect, useMemo } from "react"; +import { + EditorId, + EnvironmentId, + OpenWithEntry as OpenWithEntrySchema, + PRIMARY_LOCAL_ENVIRONMENT_ID, + type OpenWithDirectoryMode, + type OpenWithEntry, + type OpenWithEntryKind, + type OpenWithEntryPresentation, + type OpenWithEntryRef, + type ResolvedKeybindingsConfig, +} from "@t3tools/contracts"; +import * as Schema from "effect/Schema"; +import { + AppWindowIcon, + ChevronDownIcon, + Code2Icon, + FolderClosedIcon, + PlusIcon, + SettingsIcon, + SquareTerminalIcon, + Trash2Icon, + TriangleAlertIcon, +} from "lucide-react"; +import { memo, useCallback, useEffect, useId, useMemo, useState, type FormEvent } from "react"; + +import { readLegacyPreferredEditor } from "../../editorPreferences"; import { isOpenFavoriteEditorShortcut, shortcutLabelForCommand } from "../../keybindings"; -import { usePreferredEditor } from "../../editorPreferences"; -import { ChevronDownIcon, FolderClosedIcon } from "lucide-react"; +import { + mergeOpenWithOptions, + nextOpenWithEntryId, + refForOpenWithOption, + resolveEffectiveOpenWith, + type OpenWithOption, +} from "../../openWith"; +import { useClientSettings, useUpdateClientSettings } from "../../hooks/useSettings"; +import { ensureLocalApi } from "../../localApi"; +import { usePrimaryEnvironmentId } from "../../state/environments"; +import { shellEnvironment } from "../../state/shell"; +import { useAtomCommand } from "../../state/use-atom-command"; +import { + AlertDialog, + AlertDialogClose, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogPopup, + AlertDialogTitle, +} from "../ui/alert-dialog"; import { Button } from "../ui/button"; +import { + Dialog, + DialogDescription, + DialogFooter, + DialogHeader, + DialogPanel, + DialogPopup, + DialogTitle, +} from "../ui/dialog"; import { Group, GroupSeparator } from "../ui/group"; -import { Menu, MenuItem, MenuPopup, MenuShortcut, MenuTrigger } from "../ui/menu"; +import { Input } from "../ui/input"; +import { Label } from "../ui/label"; +import { Menu, MenuItem, MenuPopup, MenuSeparator, MenuShortcut, MenuTrigger } from "../ui/menu"; +import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select"; +import { stackedThreadToast, toastManager } from "../ui/toast"; import { AntigravityIcon, CursorIcon, @@ -31,156 +88,137 @@ import { RustRoverIcon, WebStormIcon, } from "../JetBrainsIcons"; -import { cn, isMacPlatform, isWindowsPlatform } from "~/lib/utils"; -import { shellEnvironment } from "~/state/shell"; -import { useAtomCommand } from "~/state/use-atom-command"; - -type OpenInOption = { - label: string; - Icon: Icon; - value: EditorId; - kind: "brand" | "generic"; +import { cn, isMacPlatform, isWindowsPlatform, randomUUID } from "~/lib/utils"; + +type BuiltinPresentation = { + readonly label: string; + readonly Icon: Icon; + readonly value: EditorId; + readonly kind: "brand" | "generic"; }; -const resolveOptions = (platform: string, availableEditors: ReadonlyArray) => { - const baseOptions: ReadonlyArray = [ - { - label: "Cursor", - Icon: CursorIcon, - value: "cursor", - kind: "brand", - }, - { - label: "Trae", - Icon: TraeIcon, - value: "trae", - kind: "brand", - }, - { - label: "Kiro", - Icon: KiroIcon, - value: "kiro", - kind: "brand", - }, - { - label: "VS Code", - Icon: VisualStudioCode, - value: "vscode", - kind: "brand", - }, - { - label: "VS Code Insiders", - Icon: VisualStudioCodeInsiders, - value: "vscode-insiders", - kind: "brand", - }, - { - label: "VSCodium", - Icon: VSCodium, - value: "vscodium", - kind: "brand", - }, - { - label: "Zed", - Icon: Zed, - value: "zed", - kind: "brand", - }, - { - label: "Antigravity", - Icon: AntigravityIcon, - value: "antigravity", - kind: "brand", - }, - { - label: "IntelliJ IDEA", - Icon: IntelliJIdeaIcon, - value: "idea", - kind: "brand", - }, - { - label: "Aqua", - Icon: AquaIcon, - value: "aqua", - kind: "brand", - }, - { - label: "CLion", - Icon: CLionIcon, - value: "clion", - kind: "brand", - }, - { - label: "DataGrip", - Icon: DataGripIcon, - value: "datagrip", - kind: "brand", - }, - { - label: "DataSpell", - Icon: DataSpellIcon, - value: "dataspell", - kind: "brand", - }, - { - label: "GoLand", - Icon: GoLandIcon, - value: "goland", - kind: "brand", - }, - { - label: "PhpStorm", - Icon: PhpStormIcon, - value: "phpstorm", - kind: "brand", - }, - { - label: "PyCharm", - Icon: PyCharmIcon, - value: "pycharm", - kind: "brand", - }, - { - label: "Rider", - Icon: RiderIcon, - value: "rider", - kind: "brand", - }, - { - label: "RubyMine", - Icon: RubyMineIcon, - value: "rubymine", - kind: "brand", - }, - { - label: "RustRover", - Icon: RustRoverIcon, - value: "rustrover", - kind: "brand", - }, - { - label: "WebStorm", - Icon: WebStormIcon, - value: "webstorm", - kind: "brand", - }, - { - label: isMacPlatform(platform) - ? "Finder" - : isWindowsPlatform(platform) - ? "Explorer" - : "Files", - Icon: FolderClosedIcon, - value: "file-manager", - kind: "generic", - }, - ]; - const availableEditorSet = new Set(availableEditors); - return baseOptions.filter((option) => availableEditorSet.has(option.value)); +const BUILTIN_PRESENTATIONS: readonly BuiltinPresentation[] = [ + { label: "Cursor", Icon: CursorIcon, value: "cursor", kind: "brand" }, + { label: "Trae", Icon: TraeIcon, value: "trae", kind: "brand" }, + { label: "Kiro", Icon: KiroIcon, value: "kiro", kind: "brand" }, + { label: "VS Code", Icon: VisualStudioCode, value: "vscode", kind: "brand" }, + { + label: "VS Code Insiders", + Icon: VisualStudioCodeInsiders, + value: "vscode-insiders", + kind: "brand", + }, + { label: "VSCodium", Icon: VSCodium, value: "vscodium", kind: "brand" }, + { label: "Zed", Icon: Zed, value: "zed", kind: "brand" }, + { label: "Antigravity", Icon: AntigravityIcon, value: "antigravity", kind: "brand" }, + { label: "IntelliJ IDEA", Icon: IntelliJIdeaIcon, value: "idea", kind: "brand" }, + { label: "Aqua", Icon: AquaIcon, value: "aqua", kind: "brand" }, + { label: "CLion", Icon: CLionIcon, value: "clion", kind: "brand" }, + { label: "DataGrip", Icon: DataGripIcon, value: "datagrip", kind: "brand" }, + { label: "DataSpell", Icon: DataSpellIcon, value: "dataspell", kind: "brand" }, + { label: "GoLand", Icon: GoLandIcon, value: "goland", kind: "brand" }, + { label: "PhpStorm", Icon: PhpStormIcon, value: "phpstorm", kind: "brand" }, + { label: "PyCharm", Icon: PyCharmIcon, value: "pycharm", kind: "brand" }, + { label: "Rider", Icon: RiderIcon, value: "rider", kind: "brand" }, + { label: "RubyMine", Icon: RubyMineIcon, value: "rubymine", kind: "brand" }, + { label: "RustRover", Icon: RustRoverIcon, value: "rustrover", kind: "brand" }, + { label: "WebStorm", Icon: WebStormIcon, value: "webstorm", kind: "brand" }, + { label: "File Manager", Icon: FolderClosedIcon, value: "file-manager", kind: "generic" }, +]; + +const DESKTOP_PRIMARY_ENVIRONMENT_ID = EnvironmentId.make(PRIMARY_LOCAL_ENVIRONMENT_ID); + +const builtinPresentationById = new Map(BUILTIN_PRESENTATIONS.map((entry) => [entry.value, entry])); +const decodeOpenWithEntry = Schema.decodeUnknownSync(OpenWithEntrySchema); + +type ArgumentRow = { readonly id: string; readonly value: string }; +const makeArgumentRow = (value = ""): ArgumentRow => ({ id: randomUUID(), value }); + +const OPEN_WITH_KIND_LABELS: Record = { + editor: "Editor", + terminal: "Terminal", + "file-manager": "File manager", + other: "Other", +}; + +const DIRECTORY_MODE_LABELS: Record = { + "open-target": "Open target", + "working-directory": "Working directory", + "custom-arguments": "Custom arguments", }; -function getOpenInIconClass(kind: OpenInOption["kind"]) { - return cn(kind === "brand" ? "text-foreground opacity-100" : "text-muted-foreground"); +function categoryIcon(kind: OpenWithEntryKind): Icon { + if (kind === "editor") return Code2Icon; + if (kind === "terminal") return SquareTerminalIcon; + if (kind === "file-manager") return FolderClosedIcon; + return AppWindowIcon; +} + +function CustomIcon({ + entry, + presentation, + className, +}: { + entry: OpenWithEntry; + presentation: OpenWithEntryPresentation | null; + className?: string; +}) { + if (presentation?.iconDataUrl) { + return ; + } + const FallbackIcon = categoryIcon(entry.kind); + return