@devries-cameron20 / t3code-1 / commits / a11ad7424d
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

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 e3e8b78c01a4259d4bbe06e1764e1ddc55c0d1c3. All review threads are resolved. GPT 6.1 Sol via the Codex harness in T3 Code.

Yash Singh committed Nov 10, 2026 at 12:35 UTC a11ad7424d60f6224aef2652727c3e8adc9a4e86
17 files changed +283 -38
apps/server/src/assets/AssetAccess.ts
+2 -2
@@ -15,7 +15,7 @@ import {
15 AssetWorkspaceRootNormalizationError,
16 SOURCE_CONTROL_MEDIA_ASSET,
17 ThreadId,
18 - ToolActivityNativeAppReference,
18 + NativeAppIconReference,
19 TurnItemId,
20 } from "@t3tools/contracts";
21 import {
@@ -152,7 +152,7 @@ const AssetClaimsSchema = Schema.Union([
152 Schema.Struct({
153 version: Schema.Literal(1),
154 kind: Schema.Literal("native-app-icon"),
155 - app: ToolActivityNativeAppReference,
155 + app: NativeAppIconReference,
156 expiresAt: Schema.Number,
157 }),
158 Schema.Struct({
apps/server/src/assets/NativeAppIconResolver.test.ts new
+62
@@ -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
+13 -8
@@ -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";
3 import * as Cache from "effect/Cache";
4 import * as Cause from "effect/Cause";
5 import * as Digest from "effect/crypto/Digest";
@@ -28,16 +29,16 @@ const RESOLUTION_CACHE_MAX_ENTRIES = 256;
29 export class NativeAppIconResolver extends Context.Service<
30 NativeAppIconResolver,
31 {
31 - readonly resolve: (app: ToolActivityNativeAppReference) => Effect.Effect<string | null>;
32 + readonly resolve: (app: NativeAppIconReference) => Effect.Effect<string | null>;
33 }
34 >()("t3/assets/NativeAppIconResolver") {}
35
35 -function appCacheKey(app: ToolActivityNativeAppReference): string {
36 +function appCacheKey(app: NativeAppIconReference): string {
37 return JSON.stringify(app);
38 }
39
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;
42 }
43
44 const existingFile = Effect.fn("NativeAppIconResolver.existingFile")(function* (filePath: string) {
@@ -91,9 +92,13 @@ function containsControlCharacter(value: string): boolean {
92 }
93
94 const resolveApplicationPath = Effect.fn("NativeAppIconResolver.resolveApplicationPath")(function* (
94 - app: ToolActivityNativeAppReference,
95 + app: NativeAppIconReference,
96 ) {
97 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 + }
102 const query =
103 app._tag === "app-id"
104 ? `kMDItemCFBundleIdentifier == '${app.appId}'`
@@ -131,7 +136,7 @@ const resolveApplicationPath = Effect.fn("NativeAppIconResolver.resolveApplicati
136 });
137
138 const resolveNativeAppIconUncached = Effect.fn("NativeAppIconResolver.resolveUncached")(function* (
134 - app: ToolActivityNativeAppReference,
139 + app: NativeAppIconReference,
140 ) {
141 const fileSystem = yield* FileSystem.FileSystem;
142 const path = yield* Path.Path;
@@ -242,7 +247,7 @@ export const make = Effect.gen(function* () {
247 );
248
249 const resolveAttempt = Effect.fn("NativeAppIconResolver.resolve")(function* (
245 - app: ToolActivityNativeAppReference,
250 + app: NativeAppIconReference,
251 ) {
252 if (
253 hostPlatform !== "darwin" ||
apps/server/src/auth/RpcAuthorization.test.ts
+5 -1
@@ -412,10 +412,14 @@ it.effect("separates host file URLs from readable attachment URLs", () =>
412 yield* client[WS_METHODS.assetsCreateUrl]({
413 resource: { _tag: "attachment", attachmentId: "image" },
414 });
415 + yield* client[WS_METHODS.assetsCreateUrl]({
416 + resource: { _tag: "native-app-icon", app: { _tag: "app-id", appId: "com.apple.calculator" } },
417 + });
418 for (const resource of [
419 { _tag: "workspace-file", threadId: ThreadId.make("thread"), path: "file.txt" },
420 { _tag: "media-file", threadId: ThreadId.make("thread"), path: "/repo/image.png" },
421 { _tag: "draft-workspace-file", cwd: "/repo", path: "file.txt" },
422 + { _tag: "native-app-icon", app: { _tag: "app-path", path: "/private/Secret.app" } },
423 ] as const) {
424 expect(
425 yield* client[WS_METHODS.assetsCreateUrl]({ resource }).pipe(Effect.flip),
@@ -424,7 +428,7 @@ it.effect("separates host file URLs from readable attachment URLs", () =>
428 requiredPermission: AuthFilesystemReadScope,
429 });
430 }
427 - expect(handled).toBe(1);
431 + expect(handled).toBe(2);
432 }).pipe(Effect.scoped),
433 );
434
apps/server/src/auth/RpcAuthorization.ts
+2 -1
@@ -265,7 +265,8 @@ const requiredScopesForRpcCall = (
265 return [
266 resource._tag === "workspace-file" ||
267 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")
270 ? AuthFilesystemReadScope
271 : AuthOrchestrationReadScope,
272 ];
apps/server/src/process/externalLauncher.test.ts
+33
@@ -95,6 +95,39 @@ const layerTest = (input: {
95 );
96 };
97
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 +
131 it.effect.skipIf(windowsHost)(
132 "launched browsers and editors do not inherit ELECTRON_RUN_AS_NODE",
133 () =>
apps/server/src/process/externalLauncher.ts
+7 -5
@@ -1,3 +1,4 @@
1 +import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
2 import * as NodePath from "@effect/platform-node/NodePath";
3 import {
4 EDITORS,
@@ -500,21 +501,22 @@ const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* (
501 return yield* new ExternalLauncherUnsupportedEditorError({ editor: input.editor });
502 }
503
504 + const target = expandHomePath(input.cwd, yield* HostProcess.HomeDirectory);
505 if (input.reveal === true) {
504 - return yield* resolveFileManagerRevealLaunch(input.cwd, platform, env, command);
506 + return yield* resolveFileManagerRevealLaunch(target, platform, env, command);
507 }
508
509 return {
510 editor: editorDef.id,
509 - target: input.cwd,
511 + target,
512 command,
513 args:
514 command === "explorer.exe" && env.WSL_DISTRO_NAME !== undefined
513 - ? [resolveWslFileManagerPath(input.cwd, env.WSL_DISTRO_NAME)]
515 + ? [resolveWslFileManagerPath(target, env.WSL_DISTRO_NAME)]
516 : platform === "win32"
517 ? // Explorer interprets / as a switch and silently opens a fallback folder.
516 - [normalizeWindowsFileManagerPath(input.cwd)]
517 - : [input.cwd],
518 + [normalizeWindowsFileManagerPath(target)]
519 + : [target],
520 };
521 });
522
apps/web/src/assets/assetUrls.ts
+2 -1
@@ -106,6 +106,7 @@ function isFileResource(resource: AssetResource): boolean {
106 return (
107 resource._tag === "workspace-file" ||
108 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")
111 );
112 }
apps/web/src/components/ChatMarkdown.browser.test.tsx
+1
@@ -40,6 +40,7 @@ vi.mock(import("../state/server"), async (original) => {
40 const { Atom } = await import("effect/reactivity");
41 const noConfig = Atom.make(null);
42 const modelsConfig = Atom.make({
43 + environment: { platform: { os: "darwin" } },
44 availableEditors: [],
45 settings: { providerInstances: {} },
46 providers: [
apps/web/src/components/ChatMarkdown.tsx
+31 -9
@@ -1,3 +1,4 @@
1 +import { clientHostEnvironmentAtom } from "../state/clientHostEnvironment";
2 import { buildFileLinkParentSuffixByPath, fileLinkLabel } from "@t3tools/shared/fileLinks";
3 import {
4 isWindowsDrivePathHref,
@@ -410,6 +411,7 @@ type MarkdownServerConfigFields = ReturnType<typeof markdownServerConfigFields>;
411 function markdownServerConfigFields(config: ServerConfig | null) {
412 return {
413 pullRequestsEnabled: config !== null,
414 + isMacOS: config?.environment.platform.os === "darwin",
415 availableEditors: config?.availableEditors ?? NO_MARKDOWN_EDITORS,
416 revealInFileManagerLabel:
417 config?.shellRevealInFileManager === true && config.availableEditors.includes("file-manager")
@@ -426,6 +428,7 @@ function markdownServerConfigFieldsEqual(
428 ): boolean {
429 return (
430 previous.pullRequestsEnabled === next.pullRequestsEnabled &&
431 + previous.isMacOS === next.isMacOS &&
432 previous.revealInFileManagerLabel === next.revealInFileManagerLabel &&
433 previous.availableEditors.length === next.availableEditors.length &&
434 previous.availableEditors.every((editor, index) => editor === next.availableEditors[index])
@@ -551,6 +554,7 @@ function useChatMarkdownState({
554 const environmentId = threadRef?.environmentId ?? explicitEnvironmentId ?? null;
555 const canOperateHost = useEnvironmentScope(environmentId, AuthOrchestrationOperateScope);
556 const canOperatePreview = useEnvironmentScope(environmentId, AuthPreviewOperateScope);
557 + const isClientHost = useAtomValue(clientHostEnvironmentAtom(environmentId));
558 const remoteOpen = useRemoteOpenResolution(environmentId);
559 const canUseShellActions =
560 canOperateHost &&
@@ -620,7 +624,7 @@ function useChatMarkdownState({
624 },
625 );
626 };
623 - const { pullRequestsEnabled, availableEditors, revealInFileManagerLabel } = useAtomValue(
627 + const { pullRequestsEnabled, availableEditors, revealInFileManagerLabel, isMacOS } = useAtomValue(
628 markdownServerConfigFieldsAtom(environmentId),
629 );
630 const projects = useProjects();
@@ -811,6 +815,13 @@ function useChatMarkdownState({
815 cwd,
816 findWorkspaceMatch: () => findWorkspaceFileMatch(fileLinkMeta),
817 });
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");
825 const mediaPath = mediaSource ?? fileLinkMeta.filePath;
826 const canPreviewMedia =
827 mediaMimeTypeFromExtension(
@@ -825,9 +836,14 @@ function useChatMarkdownState({
836 environmentId={environmentId}
837 href={fileLinkMeta.targetPath}
838 targetPath={fileLinkMeta.targetPath}
828 - iconPath={fileLinkMeta.filePath}
839 + iconPath={
840 + isAppBundle && cwd
841 + ? resolveWorkspaceFilePath(fileLinkMeta.filePath, cwd)
842 + : fileLinkMeta.filePath
843 + }
844 + isAppBundle={isAppBundle}
845 workspaceRelativePath={fileLinkMeta.workspaceRelativePath}
830 - panelPath={panelPath}
846 + panelPath={isAppBundle ? null : panelPath}
847 line={fileLinkMeta.line}
848 label={fileLinkLabel(
849 {
@@ -841,12 +857,18 @@ function useChatMarkdownState({
857 theme={resolvedTheme}
858 threadRef={threadRef}
859 onOpen={
844 - canUseShellActions
860 + canOpenApp
861 ? 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
872 }
873 resolveCopyPaths={async () =>
874 markdownFileCopyPaths(fileLinkMeta, await resolveHostPath(), cwd)
@@ -857,7 +879,7 @@ function useChatMarkdownState({
879 ? () => openMarkdownMedia(mediaPath, fileLinkMeta.filePath)
880 : undefined
881 }
860 - openInEditorMenuLabel={preferredEditorMenuLabel}
882 + openInEditorMenuLabel={canOpenApp ? "Open app" : preferredEditorMenuLabel}
883 onReveal={
884 canUseShellActions && revealInFileManagerLabel !== undefined
885 ? async () => revealFileInFileManager((await resolveHostPath()).absolutePath)
apps/web/src/components/chat/FileTagChip.tsx
+10 -6
@@ -1,8 +1,10 @@
1 +import type { ReactNode } from "react";
2 import type { EnvironmentId } from "@t3tools/contracts";
3 import { ContextChipLabel } from "../ContextChip";
4 import { WorkspaceEntryIcon } from "./WorkspaceEntryIcon";
5
6 export function FileTagChipContent(props: {
7 + icon?: ReactNode;
8 path: string;
9 label: string;
10 theme: "light" | "dark";
@@ -11,12 +13,14 @@ export function FileTagChipContent(props: {
13 }) {
14 return (
15 <>
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 + )}
24 <ContextChipLabel>{props.label}</ContextChipLabel>
25 </>
26 );
apps/web/src/components/chat/MarkdownFileLink.tsx
+39 -2
@@ -1,3 +1,4 @@
1 +import { useAssetUrlState } from "../../assets/assetUrls";
2 import { formatFilePathForClipboard } from "@t3tools/client-runtime/media-actions";
3 import {
4 isAtomCommandInterrupted,
@@ -5,7 +6,7 @@ import {
6 type AtomCommandResult,
7 } from "@t3tools/client-runtime/state/runtime";
8 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";
10
11 import { readLocalApi } from "../../localApi";
12 import { cn } from "../../lib/utils";
@@ -22,13 +23,14 @@ import {
23 shouldUseMarkdownFileBrowserPrimaryAction,
24 } from "./MarkdownFileLink.logic";
25 import { reportMarkdownActionFailure } from "./markdownActionFailure";
25 -import { WorkspaceEntryTooltip } from "./WorkspaceEntryIcon";
26 +import { WorkspaceEntryIcon, WorkspaceEntryTooltip } from "./WorkspaceEntryIcon";
27
28 interface MarkdownFileLinkProps {
29 environmentId: EnvironmentId | null;
30 href: string;
31 targetPath: string;
32 iconPath: string;
33 + isAppBundle?: boolean;
34 workspaceRelativePath: string | null;
35 panelPath: string | null;
36 line?: number | undefined;
@@ -53,6 +55,7 @@ export const MarkdownFileLink = memo(function MarkdownFileLink({
55 href,
56 targetPath,
57 iconPath,
58 + isAppBundle = false,
59 workspaceRelativePath,
60 panelPath,
61 line,
@@ -350,6 +353,11 @@ export const MarkdownFileLink = memo(function MarkdownFileLink({
353 onContextMenu={handleContextMenu}
354 >
355 <FileTagChipContent
356 + icon={
357 + isAppBundle ? (
358 + <AppBundleIcon environmentId={environmentId} path={iconPath} theme={theme} />
359 + ) : undefined
360 + }
361 path={iconPath}
362 environmentId={environmentId}
363 label={label}
@@ -369,6 +377,11 @@ export const MarkdownFileLink = memo(function MarkdownFileLink({
377 onContextMenu={handleContextMenu}
378 >
379 <FileTagChipContent
380 + icon={
381 + isAppBundle ? (
382 + <AppBundleIcon environmentId={environmentId} path={iconPath} theme={theme} />
383 + ) : undefined
384 + }
385 path={iconPath}
386 environmentId={environmentId}
387 label={label}
@@ -401,6 +414,7 @@ function areMarkdownFileLinkPropsEqual(
414 previous.copyMarkdown === next.copyMarkdown &&
415 previous.theme === next.theme &&
416 previous.threadRef === next.threadRef &&
417 + previous.isAppBundle === next.isAppBundle &&
418 previous.onOpen === next.onOpen &&
419 previous.onOpenInPanel === next.onOpenInPanel &&
420 previous.openInEditorMenuLabel === next.openInEditorMenuLabel &&
@@ -411,3 +425,26 @@ function areMarkdownFileLinkPropsEqual(
425 previous.revealLabel === next.revealLabel
426 );
427 }
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 +}
apps/web/src/state/clientHostEnvironment.ts new
+34
@@ -0,0 +1,34 @@
1 +import type { ConnectionTarget } from "@t3tools/client-runtime/connection";
2 +import type { EnvironmentId } from "@t3tools/contracts";
3 +import { Atom } from "effect/reactivity";
4 +import { isLoopbackHostname } from "../environments/primary/target";
5 +import { environmentPresentations } from "./presentation";
6 +import { hostEnvironmentIdAtom } from "./primaryEnvironment";
7 +
8 +export function isClientHostEnvironment(
9 + environmentId: EnvironmentId,
10 + hostEnvironmentId: string | null,
11 + target: ConnectionTarget | null,
12 + isDesktopRenderer: boolean,
13 +): boolean {
14 + if (isDesktopRenderer && environmentId === hostEnvironmentId) return true;
15 + if (target?._tag !== "PrimaryConnectionTarget") return false;
16 + if (isDesktopRenderer) return true;
17 + try {
18 + return isLoopbackHostname(new URL(target.httpBaseUrl).hostname);
19 + } catch {
20 + return false;
21 + }
22 +}
23 +
24 +export const clientHostEnvironmentAtom = Atom.family((environmentId: EnvironmentId | null) =>
25 + Atom.make((get) => {
26 + if (environmentId === null) return false;
27 + return isClientHostEnvironment(
28 + environmentId,
29 + get(hostEnvironmentIdAtom),
30 + get(environmentPresentations.presentationAtom(environmentId))?.entry.target ?? null,
31 + window.desktopBridge !== undefined,
32 + );
33 + }),
34 +);
apps/web/src/state/primaryEnvironment.test.ts
+30
@@ -1,3 +1,9 @@
1 +import { isClientHostEnvironment } from "./clientHostEnvironment";
2 +import {
3 + PrimaryConnectionTarget,
4 + SshConnectionTarget,
5 + RelayConnectionTarget,
6 +} from "@t3tools/client-runtime/connection";
7 import { EnvironmentId } from "@t3tools/contracts";
8 import { Atom, AtomRegistry } from "effect/reactivity";
9 import { describe, expect, it } from "vite-plus/test";
@@ -39,3 +45,27 @@ describe("themeEnvironmentIdAtom", () => {
45 expect(themeEnvironmentId({ primary: null, host: null, catalog: [REMOTE] })).toBeNull();
46 });
47 });
48 +
49 +it("recognizes the desktop host service and direct browser loopback, excluding remote primaries", () => {
50 + const target = (httpBaseUrl: string) =>
51 + new PrimaryConnectionTarget({
52 + environmentId: PRIMARY,
53 + label: "Local",
54 + httpBaseUrl,
55 + wsBaseUrl: "ws://localhost/ws",
56 + });
57 + expect(isClientHostEnvironment(SERVICE, "service", null, true)).toBe(true);
58 + expect(isClientHostEnvironment(REMOTE, "service", target("https://remote.example"), false)).toBe(
59 + false,
60 + );
61 + expect(isClientHostEnvironment(PRIMARY, null, target("http://localhost:3000"), false)).toBe(true);
62 + expect(isClientHostEnvironment(PRIMARY, null, target("http://127.0.0.1:3000"), false)).toBe(true);
63 + expect(isClientHostEnvironment(PRIMARY, null, target("https://remote.example"), true)).toBe(true);
64 + expect(isClientHostEnvironment(REMOTE, null, null, true)).toBe(false);
65 + for (const target of [
66 + new SshConnectionTarget({ environmentId: REMOTE, label: "SSH", connectionId: "ssh-1" }),
67 + new RelayConnectionTarget({ environmentId: REMOTE, label: "Relay" }),
68 + ]) {
69 + expect(isClientHostEnvironment(REMOTE, "service", target, true)).toBe(false);
70 + }
71 +});
apps/web/src/state/primaryEnvironment.ts
+1 -1
@@ -13,7 +13,7 @@ export const primaryEnvironmentIdAtom = Atom.make((get) => {
13 return null;
14 }).pipe(Atom.withLabel("web-primary-environment-id"));
15
16 -const hostEnvironmentIdAtom = Atom.make<string | null>(null).pipe(
16 +export const hostEnvironmentIdAtom = Atom.make<string | null>(null).pipe(
17 Atom.keepAlive,
18 Atom.withLabel("web-host-environment-id"),
19 );
packages/client-runtime/src/state/assets.ts
+2 -1
@@ -101,7 +101,8 @@ export function blockedAssetUrlState(
101 fileAccess.canReadFiles ||
102 (resource._tag !== "workspace-file" &&
103 resource._tag !== "media-file" &&
104 - resource._tag !== "draft-workspace-file")
104 + resource._tag !== "draft-workspace-file" &&
105 + !(resource._tag === "native-app-icon" && resource.app._tag === "app-path"))
106 ) {
107 return null;
108 }
packages/contracts/src/assets.ts
+9 -1
@@ -17,6 +17,14 @@ const ASSET_PATH_MAX_LENGTH = 1024;
17 */
18 export const SOURCE_CONTROL_MEDIA_ASSET = "github-media" as const;
19
20 +export const NativeAppIconReference = Schema.Union([
21 + ToolActivityNativeAppReference,
22 + Schema.TaggedStruct("app-path", {
23 + path: TrimmedNonEmptyString.check(Schema.isMaxLength(ASSET_PATH_MAX_LENGTH)),
24 + }),
25 +]);
26 +export type NativeAppIconReference = typeof NativeAppIconReference.Type;
27 +
28 export const AssetResource = Schema.Union([
29 Schema.TaggedStruct("workspace-file", {
30 threadId: ThreadId,
@@ -50,7 +58,7 @@ export const AssetResource = Schema.Union([
58 path: Schema.optional(ProjectFaviconPath),
59 }),
60 Schema.TaggedStruct("native-app-icon", {
53 - app: ToolActivityNativeAppReference,
61 + app: NativeAppIconReference,
62 }),
63 // Media a change request body points at on its host. A private repository serves these only
64 // to a request that carries a credential, which the client has none of, so the server fetches