Skip to content

Commit ead18b1

Browse files
committed
fix(web): show app bundle icons and open apps from markdown links
1 parent 934c7f8 commit ead18b1

11 files changed

Lines changed: 226 additions & 29 deletions

‎apps/server/src/assets/AssetAccess.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ import {
1515
AssetWorkspaceRootNormalizationError,
1616
SOURCE_CONTROL_MEDIA_ASSET,
1717
ThreadId,
18-
ToolActivityNativeAppReference,
18+
NativeAppIconReference,
1919
TurnItemId,
2020
} from "@t3tools/contracts";
2121
import {
@@ -152,7 +152,7 @@ const AssetClaimsSchema = Schema.Union([
152152
Schema.Struct({
153153
version: Schema.Literal(1),
154154
kind: Schema.Literal("native-app-icon"),
155-
app: ToolActivityNativeAppReference,
155+
app: NativeAppIconReference,
156156
expiresAt: Schema.Number,
157157
}),
158158
Schema.Struct({
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2+
import * as NodeServices from "@effect/platform-node/NodeServices";
3+
import { expect, it } from "@effect/vitest";
4+
import * as Effect from "effect/Effect";
5+
import * as FileSystem from "effect/FileSystem";
6+
import * as Layer from "effect/Layer";
7+
import * as Path from "effect/Path";
8+
import { ChildProcessSpawner } from "effect/process";
9+
import * as HostProcess from "@t3tools/shared/HostProcess";
10+
11+
import * as ServerConfig from "../config.ts";
12+
import * as NativeAppIconResolver from "./NativeAppIconResolver.ts";
13+
14+
it.effect("resolves the exact bundle path without Spotlight and caches the converted icon", () =>
15+
Effect.gen(function* () {
16+
const fs = yield* FileSystem.FileSystem;
17+
const path = yield* Path.Path;
18+
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-bundle-icon-" });
19+
const bundle = path.join(root, "Build Output", "My App.app");
20+
const resources = path.join(bundle, "Contents", "Resources");
21+
yield* fs.makeDirectory(resources, { recursive: true });
22+
yield* fs.writeFileString(path.join(resources, "AppIcon.icns"), "icon");
23+
const commands: string[] = [];
24+
const spawner = Layer.mock(ChildProcessSpawner.ChildProcessSpawner)({
25+
string: (command) =>
26+
Effect.gen(function* () {
27+
if (command._tag !== "StandardCommand") return "";
28+
commands.push(command.command);
29+
if (command.command === "/usr/bin/plutil") return "AppIcon";
30+
if (command.command === "/usr/bin/sips") {
31+
yield* fs.writeFileString(String(command.args.at(-1)), "converted icon");
32+
}
33+
return "";
34+
}),
35+
});
36+
yield* Effect.gen(function* () {
37+
const resolver = yield* NativeAppIconResolver.make;
38+
const reference = { _tag: "app-path" as const, path: bundle };
39+
const icon = yield* resolver.resolve(reference);
40+
expect(icon).not.toBeNull();
41+
if (icon === null) return;
42+
expect(yield* fs.readFileString(icon)).toBe("converted icon");
43+
expect(yield* resolver.resolve(reference)).toBe(icon);
44+
expect(commands.filter((command) => command === "/usr/bin/sips")).toHaveLength(1);
45+
expect(commands).not.toContain("/usr/bin/mdfind");
46+
expect(yield* resolver.resolve({ _tag: "app-path", path: "relative.app" })).toBeNull();
47+
expect(yield* resolver.resolve({ _tag: "app-path", path: root })).toBeNull();
48+
}).pipe(
49+
Effect.provide(
50+
Layer.mergeAll(
51+
spawner,
52+
ServerConfig.ServerConfig.layerTest(root, { prefix: "t3-native-icon-config-" }),
53+
),
54+
),
55+
Effect.provideService(HostProcess.Platform, "darwin"),
56+
);
57+
}).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
58+
);

‎apps/server/src/assets/NativeAppIconResolver.ts‎

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import type { ToolActivityNativeAppReference } from "@t3tools/contracts";
1+
import type { NativeAppIconReference } from "@t3tools/contracts";
22
import * as Cache from "effect/Cache";
33
import * as Cause from "effect/Cause";
44
import * as Digest from "effect/crypto/Digest";
@@ -28,16 +28,16 @@ const RESOLUTION_CACHE_MAX_ENTRIES = 256;
2828
export class NativeAppIconResolver extends Context.Service<
2929
NativeAppIconResolver,
3030
{
31-
readonly resolve: (app: ToolActivityNativeAppReference) => Effect.Effect<string | null>;
31+
readonly resolve: (app: NativeAppIconReference) => Effect.Effect<string | null>;
3232
}
3333
>()("t3/assets/NativeAppIconResolver") {}
3434

35-
function appCacheKey(app: ToolActivityNativeAppReference): string {
35+
function appCacheKey(app: NativeAppIconReference): string {
3636
return JSON.stringify(app);
3737
}
3838

39-
function appFromCacheKey(key: string): ToolActivityNativeAppReference {
40-
return JSON.parse(key) as ToolActivityNativeAppReference;
39+
function appFromCacheKey(key: string): NativeAppIconReference {
40+
return JSON.parse(key) as NativeAppIconReference;
4141
}
4242

4343
const existingFile = Effect.fn("NativeAppIconResolver.existingFile")(function* (filePath: string) {
@@ -91,9 +91,12 @@ function containsControlCharacter(value: string): boolean {
9191
}
9292

9393
const resolveApplicationPath = Effect.fn("NativeAppIconResolver.resolveApplicationPath")(function* (
94-
app: ToolActivityNativeAppReference,
94+
app: NativeAppIconReference,
9595
) {
9696
const path = yield* Path.Path;
97+
if (app._tag === "app-path") {
98+
return path.isAbsolute(app.path) && app.path.endsWith(".app") ? app.path : null;
99+
}
97100
const query =
98101
app._tag === "app-id"
99102
? `kMDItemCFBundleIdentifier == '${app.appId}'`
@@ -131,7 +134,7 @@ const resolveApplicationPath = Effect.fn("NativeAppIconResolver.resolveApplicati
131134
});
132135

133136
const resolveNativeAppIconUncached = Effect.fn("NativeAppIconResolver.resolveUncached")(function* (
134-
app: ToolActivityNativeAppReference,
137+
app: NativeAppIconReference,
135138
) {
136139
const fileSystem = yield* FileSystem.FileSystem;
137140
const path = yield* Path.Path;
@@ -242,7 +245,7 @@ export const make = Effect.gen(function* () {
242245
);
243246

244247
const resolveAttempt = Effect.fn("NativeAppIconResolver.resolve")(function* (
245-
app: ToolActivityNativeAppReference,
248+
app: NativeAppIconReference,
246249
) {
247250
if (
248251
hostPlatform !== "darwin" ||

‎apps/web/src/components/ChatMarkdown.browser.test.tsx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ vi.mock(import("../state/server"), async (original) => {
4040
const { Atom } = await import("effect/reactivity");
4141
const noConfig = Atom.make(null);
4242
const modelsConfig = Atom.make({
43+
environment: { platform: { os: "darwin" } },
4344
availableEditors: [],
4445
settings: { providerInstances: {} },
4546
providers: [

‎apps/web/src/components/ChatMarkdown.tsx‎

Lines changed: 31 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { clientHostEnvironmentAtom } from "../state/clientHostEnvironment";
12
import { buildFileLinkParentSuffixByPath, fileLinkLabel } from "@t3tools/shared/fileLinks";
23
import {
34
isWindowsDrivePathHref,
@@ -411,6 +412,7 @@ type MarkdownServerConfigFields = ReturnType<typeof markdownServerConfigFields>;
411412
function markdownServerConfigFields(config: ServerConfig | null) {
412413
return {
413414
pullRequestsEnabled: config !== null,
415+
isMacOS: config?.environment.platform.os === "darwin",
414416
availableEditors: config?.availableEditors ?? NO_MARKDOWN_EDITORS,
415417
revealInFileManagerLabel:
416418
config?.shellRevealInFileManager === true && config.availableEditors.includes("file-manager")
@@ -427,6 +429,7 @@ function markdownServerConfigFieldsEqual(
427429
): boolean {
428430
return (
429431
previous.pullRequestsEnabled === next.pullRequestsEnabled &&
432+
previous.isMacOS === next.isMacOS &&
430433
previous.revealInFileManagerLabel === next.revealInFileManagerLabel &&
431434
previous.availableEditors.length === next.availableEditors.length &&
432435
previous.availableEditors.every((editor, index) => editor === next.availableEditors[index])
@@ -552,6 +555,7 @@ function useChatMarkdownState({
552555
const environmentId = threadRef?.environmentId ?? explicitEnvironmentId ?? null;
553556
const canOperateHost = useEnvironmentScope(environmentId, AuthOrchestrationOperateScope);
554557
const canOperatePreview = useEnvironmentScope(environmentId, AuthPreviewOperateScope);
558+
const isClientHost = useAtomValue(clientHostEnvironmentAtom(environmentId));
555559
const remoteOpen = useRemoteOpenResolution(environmentId);
556560
const canUseShellActions =
557561
canOperateHost &&
@@ -621,7 +625,7 @@ function useChatMarkdownState({
621625
},
622626
);
623627
};
624-
const { pullRequestsEnabled, availableEditors, revealInFileManagerLabel } = useAtomValue(
628+
const { pullRequestsEnabled, availableEditors, revealInFileManagerLabel, isMacOS } = useAtomValue(
625629
markdownServerConfigFieldsAtom(environmentId),
626630
);
627631
const projects = useProjects();
@@ -822,6 +826,13 @@ function useChatMarkdownState({
822826
cwd,
823827
findWorkspaceMatch: () => findWorkspaceFileMatch(fileLinkMeta),
824828
});
829+
const isAppBundle = isMacOS && fileLinkMeta.filePath.endsWith(".app");
830+
const canOpenApp =
831+
environmentId !== null &&
832+
isAppBundle &&
833+
isClientHost &&
834+
canOperateHost &&
835+
availableEditors.includes("file-manager");
825836
const mediaPath = mediaSource ?? fileLinkMeta.filePath;
826837
const canPreviewMedia =
827838
mediaMimeTypeFromExtension(
@@ -836,9 +847,14 @@ function useChatMarkdownState({
836847
environmentId={environmentId}
837848
href={fileLinkMeta.targetPath}
838849
targetPath={fileLinkMeta.targetPath}
839-
iconPath={fileLinkMeta.filePath}
850+
iconPath={
851+
isAppBundle && cwd
852+
? resolveWorkspaceFilePath(fileLinkMeta.filePath, cwd)
853+
: fileLinkMeta.filePath
854+
}
855+
isAppBundle={isAppBundle}
840856
workspaceRelativePath={fileLinkMeta.workspaceRelativePath}
841-
panelPath={panelPath}
857+
panelPath={isAppBundle ? null : panelPath}
842858
line={fileLinkMeta.line}
843859
label={fileLinkLabel(
844860
{
@@ -852,12 +868,18 @@ function useChatMarkdownState({
852868
theme={resolvedTheme}
853869
threadRef={threadRef}
854870
onOpen={
855-
canUseShellActions
871+
canOpenApp
856872
? async () =>
857-
openInPreferredEditor(
858-
markdownFileEditorTarget(fileLinkMeta, await resolveHostPath()),
859-
)
860-
: undefined
873+
openInEditor({
874+
environmentId,
875+
input: { cwd: (await resolveHostPath()).absolutePath, editor: "file-manager" },
876+
})
877+
: canUseShellActions
878+
? async () =>
879+
openInPreferredEditor(
880+
markdownFileEditorTarget(fileLinkMeta, await resolveHostPath()),
881+
)
882+
: undefined
861883
}
862884
resolveCopyPaths={async () =>
863885
markdownFileCopyPaths(fileLinkMeta, await resolveHostPath(), cwd)
@@ -868,7 +890,7 @@ function useChatMarkdownState({
868890
? () => openMarkdownMedia(mediaPath, fileLinkMeta.filePath)
869891
: undefined
870892
}
871-
openInEditorMenuLabel={preferredEditorMenuLabel}
893+
openInEditorMenuLabel={canOpenApp ? "Open app" : preferredEditorMenuLabel}
872894
onReveal={
873895
canUseShellActions && revealInFileManagerLabel !== undefined
874896
? async () => revealFileInFileManager((await resolveHostPath()).absolutePath)

‎apps/web/src/components/chat/FileTagChip.tsx‎

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
1+
import type { ReactNode } from "react";
12
import type { EnvironmentId } from "@t3tools/contracts";
23
import { ContextChipLabel } from "../ContextChip";
34
import { WorkspaceEntryIcon } from "./WorkspaceEntryIcon";
45

56
export function FileTagChipContent(props: {
7+
icon?: ReactNode;
68
path: string;
79
label: string;
810
theme: "light" | "dark";
@@ -11,12 +13,14 @@ export function FileTagChipContent(props: {
1113
}) {
1214
return (
1315
<>
14-
<WorkspaceEntryIcon
15-
path={props.path}
16-
environmentId={props.environmentId}
17-
cwd={props.cwd}
18-
theme={props.theme}
19-
/>
16+
{props.icon ?? (
17+
<WorkspaceEntryIcon
18+
path={props.path}
19+
environmentId={props.environmentId}
20+
cwd={props.cwd}
21+
theme={props.theme}
22+
/>
23+
)}
2024
<ContextChipLabel>{props.label}</ContextChipLabel>
2125
</>
2226
);

‎apps/web/src/components/chat/MarkdownFileLink.tsx‎

Lines changed: 39 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
1+
import { useAssetUrlState } from "../../assets/assetUrls";
12
import { formatFilePathForClipboard } from "@t3tools/client-runtime/media-actions";
23
import {
34
isAtomCommandInterrupted,
45
squashAtomCommandFailure,
56
type AtomCommandResult,
67
} from "@t3tools/client-runtime/state/runtime";
78
import type { EnvironmentId, ScopedThreadRef } from "@t3tools/contracts";
8-
import { memo, type MouseEvent as ReactMouseEvent } from "react";
9+
import { memo, useState, type MouseEvent as ReactMouseEvent } from "react";
910

1011
import { readLocalApi } from "../../localApi";
1112
import { cn } from "../../lib/utils";
@@ -22,13 +23,14 @@ import {
2223
shouldUseMarkdownFileBrowserPrimaryAction,
2324
} from "./MarkdownFileLink.logic";
2425
import { reportMarkdownActionFailure } from "./markdownActionFailure";
25-
import { WorkspaceEntryTooltip } from "./WorkspaceEntryIcon";
26+
import { WorkspaceEntryIcon, WorkspaceEntryTooltip } from "./WorkspaceEntryIcon";
2627

2728
interface MarkdownFileLinkProps {
2829
environmentId: EnvironmentId | null;
2930
href: string;
3031
targetPath: string;
3132
iconPath: string;
33+
isAppBundle?: boolean;
3234
workspaceRelativePath: string | null;
3335
panelPath: string | null;
3436
line?: number | undefined;
@@ -53,6 +55,7 @@ export const MarkdownFileLink = memo(function MarkdownFileLink({
5355
href,
5456
targetPath,
5557
iconPath,
58+
isAppBundle = false,
5659
workspaceRelativePath,
5760
panelPath,
5861
line,
@@ -350,6 +353,11 @@ export const MarkdownFileLink = memo(function MarkdownFileLink({
350353
onContextMenu={handleContextMenu}
351354
>
352355
<FileTagChipContent
356+
icon={
357+
isAppBundle ? (
358+
<AppBundleIcon environmentId={environmentId} path={iconPath} theme={theme} />
359+
) : undefined
360+
}
353361
path={iconPath}
354362
environmentId={environmentId}
355363
label={label}
@@ -369,6 +377,11 @@ export const MarkdownFileLink = memo(function MarkdownFileLink({
369377
onContextMenu={handleContextMenu}
370378
>
371379
<FileTagChipContent
380+
icon={
381+
isAppBundle ? (
382+
<AppBundleIcon environmentId={environmentId} path={iconPath} theme={theme} />
383+
) : undefined
384+
}
372385
path={iconPath}
373386
environmentId={environmentId}
374387
label={label}
@@ -401,6 +414,7 @@ function areMarkdownFileLinkPropsEqual(
401414
previous.copyMarkdown === next.copyMarkdown &&
402415
previous.theme === next.theme &&
403416
previous.threadRef === next.threadRef &&
417+
previous.isAppBundle === next.isAppBundle &&
404418
previous.onOpen === next.onOpen &&
405419
previous.onOpenInPanel === next.onOpenInPanel &&
406420
previous.openInEditorMenuLabel === next.openInEditorMenuLabel &&
@@ -411,3 +425,26 @@ function areMarkdownFileLinkPropsEqual(
411425
previous.revealLabel === next.revealLabel
412426
);
413427
}
428+
429+
function AppBundleIcon(props: {
430+
environmentId: EnvironmentId | null;
431+
path: string;
432+
theme: "light" | "dark";
433+
}) {
434+
const asset = useAssetUrlState(props.environmentId, {
435+
_tag: "native-app-icon",
436+
app: { _tag: "app-path", path: props.path },
437+
});
438+
const [failedUrl, setFailedUrl] = useState<string | null>(null);
439+
if (asset._tag !== "Success" || asset.url === failedUrl) {
440+
return <WorkspaceEntryIcon {...props} />;
441+
}
442+
return (
443+
<img
444+
src={asset.url}
445+
alt=""
446+
className="size-4 shrink-0 object-contain"
447+
onError={() => setFailedUrl(asset.url)}
448+
/>
449+
);
450+
}

0 commit comments

Comments
 (0)