Skip to content

Commit a11ad74

Browse files
authored
fix(web): show app bundle icons and open apps from markdown links
macOS app-bundle links now display their native icons and offer Open app on eligible local hosts. Reuse the desktop host environment identity and direct loopback detection to keep launches local. Resolve icons from the exact bundle path, expand home-relative icon and file-manager paths on the server, and require filesystem-read permission for path-selected icons. Validated with focused regressions, a real Calculator icon and app launch, and green CI and automated reviews on e3e8b78. All review threads are resolved. GPT 6.1 Sol via the Codex harness in T3 Code.
1 parent 283fa1f commit a11ad74

17 files changed

Lines changed: 283 additions & 38 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: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
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(yield* resolver.resolve({ _tag: "app-path", path: "~/Build Output/My App.app" })).toBe(
45+
icon,
46+
);
47+
expect(commands.filter((command) => command === "/usr/bin/sips")).toHaveLength(1);
48+
expect(commands).not.toContain("/usr/bin/mdfind");
49+
expect(yield* resolver.resolve({ _tag: "app-path", path: "relative.app" })).toBeNull();
50+
expect(yield* resolver.resolve({ _tag: "app-path", path: root })).toBeNull();
51+
}).pipe(
52+
Effect.provide(
53+
Layer.mergeAll(
54+
spawner,
55+
ServerConfig.ServerConfig.layerTest(root, { prefix: "t3-native-icon-config-" }),
56+
),
57+
),
58+
Effect.provideService(HostProcess.Platform, "darwin"),
59+
Effect.provideService(HostProcess.HomeDirectory, root),
60+
);
61+
}).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
62+
);

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

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
import type { ToolActivityNativeAppReference } from "@t3tools/contracts";
1+
import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
2+
import type { NativeAppIconReference } from "@t3tools/contracts";
23
import * as Cache from "effect/Cache";
34
import * as Cause from "effect/Cause";
45
import * as Digest from "effect/crypto/Digest";
@@ -28,16 +29,16 @@ const RESOLUTION_CACHE_MAX_ENTRIES = 256;
2829
export class NativeAppIconResolver extends Context.Service<
2930
NativeAppIconResolver,
3031
{
31-
readonly resolve: (app: ToolActivityNativeAppReference) => Effect.Effect<string | null>;
32+
readonly resolve: (app: NativeAppIconReference) => Effect.Effect<string | null>;
3233
}
3334
>()("t3/assets/NativeAppIconResolver") {}
3435

35-
function appCacheKey(app: ToolActivityNativeAppReference): string {
36+
function appCacheKey(app: NativeAppIconReference): string {
3637
return JSON.stringify(app);
3738
}
3839

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

4344
const existingFile = Effect.fn("NativeAppIconResolver.existingFile")(function* (filePath: string) {
@@ -91,9 +92,13 @@ function containsControlCharacter(value: string): boolean {
9192
}
9293

9394
const resolveApplicationPath = Effect.fn("NativeAppIconResolver.resolveApplicationPath")(function* (
94-
app: ToolActivityNativeAppReference,
95+
app: NativeAppIconReference,
9596
) {
9697
const path = yield* Path.Path;
98+
if (app._tag === "app-path") {
99+
const appPath = expandHomePath(app.path, yield* HostProcess.HomeDirectory);
100+
return path.isAbsolute(appPath) && appPath.endsWith(".app") ? appPath : null;
101+
}
97102
const query =
98103
app._tag === "app-id"
99104
? `kMDItemCFBundleIdentifier == '${app.appId}'`
@@ -131,7 +136,7 @@ const resolveApplicationPath = Effect.fn("NativeAppIconResolver.resolveApplicati
131136
});
132137

133138
const resolveNativeAppIconUncached = Effect.fn("NativeAppIconResolver.resolveUncached")(function* (
134-
app: ToolActivityNativeAppReference,
139+
app: NativeAppIconReference,
135140
) {
136141
const fileSystem = yield* FileSystem.FileSystem;
137142
const path = yield* Path.Path;
@@ -242,7 +247,7 @@ export const make = Effect.gen(function* () {
242247
);
243248

244249
const resolveAttempt = Effect.fn("NativeAppIconResolver.resolve")(function* (
245-
app: ToolActivityNativeAppReference,
250+
app: NativeAppIconReference,
246251
) {
247252
if (
248253
hostPlatform !== "darwin" ||

‎apps/server/src/auth/RpcAuthorization.test.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -412,10 +412,14 @@ it.effect("separates host file URLs from readable attachment URLs", () =>
412412
yield* client[WS_METHODS.assetsCreateUrl]({
413413
resource: { _tag: "attachment", attachmentId: "image" },
414414
});
415+
yield* client[WS_METHODS.assetsCreateUrl]({
416+
resource: { _tag: "native-app-icon", app: { _tag: "app-id", appId: "com.apple.calculator" } },
417+
});
415418
for (const resource of [
416419
{ _tag: "workspace-file", threadId: ThreadId.make("thread"), path: "file.txt" },
417420
{ _tag: "media-file", threadId: ThreadId.make("thread"), path: "/repo/image.png" },
418421
{ _tag: "draft-workspace-file", cwd: "/repo", path: "file.txt" },
422+
{ _tag: "native-app-icon", app: { _tag: "app-path", path: "/private/Secret.app" } },
419423
] as const) {
420424
expect(
421425
yield* client[WS_METHODS.assetsCreateUrl]({ resource }).pipe(Effect.flip),
@@ -424,7 +428,7 @@ it.effect("separates host file URLs from readable attachment URLs", () =>
424428
requiredPermission: AuthFilesystemReadScope,
425429
});
426430
}
427-
expect(handled).toBe(1);
431+
expect(handled).toBe(2);
428432
}).pipe(Effect.scoped),
429433
);
430434

‎apps/server/src/auth/RpcAuthorization.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -265,7 +265,8 @@ const requiredScopesForRpcCall = (
265265
return [
266266
resource._tag === "workspace-file" ||
267267
resource._tag === "media-file" ||
268-
resource._tag === "draft-workspace-file"
268+
resource._tag === "draft-workspace-file" ||
269+
(resource._tag === "native-app-icon" && resource.app._tag === "app-path")
269270
? AuthFilesystemReadScope
270271
: AuthOrchestrationReadScope,
271272
];

‎apps/server/src/process/externalLauncher.test.ts‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,39 @@ const layerTest = (input: {
9595
);
9696
};
9797

98+
// macOS command lookup cannot search a Windows drive-letter PATH.
99+
it.effect.skipIf(windowsHost)(
100+
"opens home-relative app bundles using the server home directory",
101+
() =>
102+
Effect.gen(function* () {
103+
const fs = yield* FileSystem.FileSystem;
104+
const path = yield* Path.Path;
105+
const bin = yield* fs.makeTempDirectoryScoped({ prefix: "t3-app-open-" });
106+
yield* fs.writeFileString(path.join(bin, "open"), "#!/bin/sh\n");
107+
yield* fs.chmod(path.join(bin, "open"), 0o755);
108+
const spawned: ChildProcess.StandardCommand[] = [];
109+
yield* Effect.gen(function* () {
110+
const launcher = yield* ExternalLauncher.ExternalLauncher;
111+
for (const cwd of ["~/Applications/My App.app", "/Applications/My App.app"]) {
112+
yield* launcher.launchEditor({ editor: "file-manager", cwd });
113+
}
114+
}).pipe(
115+
Effect.provide(
116+
layerTest({
117+
platform: "darwin",
118+
env: { PATH: bin },
119+
onSpawn: (command) => spawned.push(command),
120+
}),
121+
),
122+
Effect.provideService(HostProcess.HomeDirectory, "/Users/server"),
123+
);
124+
assert.deepEqual(
125+
spawned.map((command) => command.args),
126+
[["/Users/server/Applications/My App.app"], ["/Applications/My App.app"]],
127+
);
128+
}).pipe(Effect.provide(NodeServices.layer)),
129+
);
130+
98131
it.effect.skipIf(windowsHost)(
99132
"launched browsers and editors do not inherit ELECTRON_RUN_AS_NODE",
100133
() =>

‎apps/server/src/process/externalLauncher.ts‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
12
import * as NodePath from "@effect/platform-node/NodePath";
23
import {
34
EDITORS,
@@ -500,21 +501,22 @@ const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* (
500501
return yield* new ExternalLauncherUnsupportedEditorError({ editor: input.editor });
501502
}
502503

504+
const target = expandHomePath(input.cwd, yield* HostProcess.HomeDirectory);
503505
if (input.reveal === true) {
504-
return yield* resolveFileManagerRevealLaunch(input.cwd, platform, env, command);
506+
return yield* resolveFileManagerRevealLaunch(target, platform, env, command);
505507
}
506508

507509
return {
508510
editor: editorDef.id,
509-
target: input.cwd,
511+
target,
510512
command,
511513
args:
512514
command === "explorer.exe" && env.WSL_DISTRO_NAME !== undefined
513-
? [resolveWslFileManagerPath(input.cwd, env.WSL_DISTRO_NAME)]
515+
? [resolveWslFileManagerPath(target, env.WSL_DISTRO_NAME)]
514516
: platform === "win32"
515517
? // Explorer interprets / as a switch and silently opens a fallback folder.
516-
[normalizeWindowsFileManagerPath(input.cwd)]
517-
: [input.cwd],
518+
[normalizeWindowsFileManagerPath(target)]
519+
: [target],
518520
};
519521
});
520522

‎apps/web/src/assets/assetUrls.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,7 @@ function isFileResource(resource: AssetResource): boolean {
106106
return (
107107
resource._tag === "workspace-file" ||
108108
resource._tag === "media-file" ||
109-
resource._tag === "draft-workspace-file"
109+
resource._tag === "draft-workspace-file" ||
110+
(resource._tag === "native-app-icon" && resource.app._tag === "app-path")
110111
);
111112
}

‎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,
@@ -410,6 +411,7 @@ type MarkdownServerConfigFields = ReturnType<typeof markdownServerConfigFields>;
410411
function markdownServerConfigFields(config: ServerConfig | null) {
411412
return {
412413
pullRequestsEnabled: config !== null,
414+
isMacOS: config?.environment.platform.os === "darwin",
413415
availableEditors: config?.availableEditors ?? NO_MARKDOWN_EDITORS,
414416
revealInFileManagerLabel:
415417
config?.shellRevealInFileManager === true && config.availableEditors.includes("file-manager")
@@ -426,6 +428,7 @@ function markdownServerConfigFieldsEqual(
426428
): boolean {
427429
return (
428430
previous.pullRequestsEnabled === next.pullRequestsEnabled &&
431+
previous.isMacOS === next.isMacOS &&
429432
previous.revealInFileManagerLabel === next.revealInFileManagerLabel &&
430433
previous.availableEditors.length === next.availableEditors.length &&
431434
previous.availableEditors.every((editor, index) => editor === next.availableEditors[index])
@@ -551,6 +554,7 @@ function useChatMarkdownState({
551554
const environmentId = threadRef?.environmentId ?? explicitEnvironmentId ?? null;
552555
const canOperateHost = useEnvironmentScope(environmentId, AuthOrchestrationOperateScope);
553556
const canOperatePreview = useEnvironmentScope(environmentId, AuthPreviewOperateScope);
557+
const isClientHost = useAtomValue(clientHostEnvironmentAtom(environmentId));
554558
const remoteOpen = useRemoteOpenResolution(environmentId);
555559
const canUseShellActions =
556560
canOperateHost &&
@@ -620,7 +624,7 @@ function useChatMarkdownState({
620624
},
621625
);
622626
};
623-
const { pullRequestsEnabled, availableEditors, revealInFileManagerLabel } = useAtomValue(
627+
const { pullRequestsEnabled, availableEditors, revealInFileManagerLabel, isMacOS } = useAtomValue(
624628
markdownServerConfigFieldsAtom(environmentId),
625629
);
626630
const projects = useProjects();
@@ -811,6 +815,13 @@ function useChatMarkdownState({
811815
cwd,
812816
findWorkspaceMatch: () => findWorkspaceFileMatch(fileLinkMeta),
813817
});
818+
const isAppBundle = isMacOS && fileLinkMeta.filePath.endsWith(".app");
819+
const canOpenApp =
820+
environmentId !== null &&
821+
isAppBundle &&
822+
isClientHost &&
823+
canOperateHost &&
824+
availableEditors.includes("file-manager");
814825
const mediaPath = mediaSource ?? fileLinkMeta.filePath;
815826
const canPreviewMedia =
816827
mediaMimeTypeFromExtension(
@@ -825,9 +836,14 @@ function useChatMarkdownState({
825836
environmentId={environmentId}
826837
href={fileLinkMeta.targetPath}
827838
targetPath={fileLinkMeta.targetPath}
828-
iconPath={fileLinkMeta.filePath}
839+
iconPath={
840+
isAppBundle && cwd
841+
? resolveWorkspaceFilePath(fileLinkMeta.filePath, cwd)
842+
: fileLinkMeta.filePath
843+
}
844+
isAppBundle={isAppBundle}
829845
workspaceRelativePath={fileLinkMeta.workspaceRelativePath}
830-
panelPath={panelPath}
846+
panelPath={isAppBundle ? null : panelPath}
831847
line={fileLinkMeta.line}
832848
label={fileLinkLabel(
833849
{
@@ -841,12 +857,18 @@ function useChatMarkdownState({
841857
theme={resolvedTheme}
842858
threadRef={threadRef}
843859
onOpen={
844-
canUseShellActions
860+
canOpenApp
845861
? async () =>
846-
openInPreferredEditor(
847-
markdownFileEditorTarget(fileLinkMeta, await resolveHostPath()),
848-
)
849-
: undefined
862+
openInEditor({
863+
environmentId,
864+
input: { cwd: (await resolveHostPath()).absolutePath, editor: "file-manager" },
865+
})
866+
: canUseShellActions
867+
? async () =>
868+
openInPreferredEditor(
869+
markdownFileEditorTarget(fileLinkMeta, await resolveHostPath()),
870+
)
871+
: undefined
850872
}
851873
resolveCopyPaths={async () =>
852874
markdownFileCopyPaths(fileLinkMeta, await resolveHostPath(), cwd)
@@ -857,7 +879,7 @@ function useChatMarkdownState({
857879
? () => openMarkdownMedia(mediaPath, fileLinkMeta.filePath)
858880
: undefined
859881
}
860-
openInEditorMenuLabel={preferredEditorMenuLabel}
882+
openInEditorMenuLabel={canOpenApp ? "Open app" : preferredEditorMenuLabel}
861883
onReveal={
862884
canUseShellActions && revealInFileManagerLabel !== undefined
863885
? async () => revealFileInFileManager((await resolveHostPath()).absolutePath)

0 commit comments

Comments
 (0)