Skip to content
TypeScript

fix(web): name the remote host and checked path when media is not found (#19677)

Scott Norteman826ef55b749b
diff --git a/apps/server/src/assets/AssetAccess.test.ts b/apps/server/src/assets/AssetAccess.test.ts
index ed8ba831146..b5aa3c1d667 100644
--- a/apps/server/src/assets/AssetAccess.test.ts
+++ b/apps/server/src/assets/AssetAccess.test.ts
@@ -387,6 +387,41 @@ describe("AssetAccess", () => {
}).pipe(Effect.provide(layerTest)),
);
+ it.effect.each([
+ { form: "absolute", requestedPath: undefined, checked: ["absolute.mp4"] },
+ {
+ form: "workspace-relative",
+ requestedPath: "clips/relative.mp4",
+ checked: ["workspace", "clips", "relative.mp4"],
+ },
+ {
+ form: "home-relative",
+ requestedPath: "~/Downloads/home.mp4",
+ checked: ["home", "Downloads", "home.mp4"],
+ },
+ ])("reports the absolute path it checked for a missing $form media path", (scenario) =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-missing-" });
+ const root = path.join(directory, "workspace");
+ yield* fs.makeDirectory(root);
+ const checkedPath = path.join(directory, ...scenario.checked);
+ const error = yield* issueAssetUrl({
+ resource: {
+ _tag: "media-file",
+ threadId: ThreadId.make("thread-1"),
+ path: scenario.requestedPath ?? checkedPath,
+ },
+ workspaceRoot: root,
+ }).pipe(
+ Effect.flip,
+ Effect.provideService(HostProcess.HomeDirectory, path.join(directory, "home")),
+ );
+ expect(error).toMatchObject({ _tag: "AssetWorkspaceAssetNotFoundError", checkedPath });
+ }).pipe(Effect.provide(layerTest)),
+ );
+
it.effect.skipIf(!symlinksSupported)(
"rejects non-previewable files, disguised targets, and directories",
() =>
diff --git a/apps/server/src/assets/AssetAccess.ts b/apps/server/src/assets/AssetAccess.ts
index 24224bdd7a7..32f806c1e66 100644
--- a/apps/server/src/assets/AssetAccess.ts
+++ b/apps/server/src/assets/AssetAccess.ts
@@ -359,7 +359,10 @@ const finalizeAbsoluteMediaFileAsset = Effect.fn("AssetAccess.finalizeAbsoluteMe
),
);
if (!canonicalFile) {
- return yield* new AssetWorkspaceAssetNotFoundError({ resource: input.resource });
+ return yield* new AssetWorkspaceAssetNotFoundError({
+ resource: input.resource,
+ checkedPath: input.requestedPath,
+ });
}
if (hostPreviewMimeTypeFromExtension(path.extname(canonicalFile)) === null) {
return yield* new AssetPreviewTypeValidationError({ resource: input.resource });
@@ -385,7 +388,10 @@ const finalizeAbsoluteMediaFileAsset = Effect.fn("AssetAccess.finalizeAbsoluteMe
),
);
if (!opened) {
- return yield* new AssetWorkspaceAssetNotFoundError({ resource: input.resource });
+ return yield* new AssetWorkspaceAssetNotFoundError({
+ resource: input.resource,
+ checkedPath: input.requestedPath,
+ });
}
return {
claims: {
diff --git a/apps/web/src/components/ChatMarkdown.assets.browser.test.tsx b/apps/web/src/components/ChatMarkdown.assets.browser.test.tsx
index ef33e24e210..f1d33074272 100644
--- a/apps/web/src/components/ChatMarkdown.assets.browser.test.tsx
+++ b/apps/web/src/components/ChatMarkdown.assets.browser.test.tsx
@@ -1,12 +1,28 @@
+import { PrimaryConnectionTarget } from "@t3tools/client-runtime/connection";
import { RegistryContext } from "@effect/atom-react";
-import { type AssetCreateUrlResult, EnvironmentId, ThreadId } from "@t3tools/contracts";
+import {
+ AssetAccessError,
+ AssetWorkspaceAssetNotFoundError,
+ AssetPreviewTypeValidationError,
+ type AssetCreateUrlResult,
+ EnvironmentId,
+ ThreadId,
+} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
+import * as Cause from "effect/Cause";
+import * as Schema from "effect/Schema";
import { AtomRegistry } from "effect/reactivity";
import { act, type ReactNode } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
const mint = vi.hoisted(() => vi.fn<() => Promise<AssetCreateUrlResult>>());
+const remoteOpen = vi.hoisted(() => ({
+ state: { mode: "local-exec" as "local-exec" | "remote-unavailable" },
+ isResolved: true,
+ label: "media-host",
+ httpBaseUrl: "https://host.test",
+}));
// Atoms derived from the server config run in the real registry over a missing config.
vi.mock(import("../state/server"), async (original) => {
const actual = await original();
@@ -21,8 +37,14 @@ vi.mock(import("../state/server"), async (original) => {
vi.mock(import("../state/assets"), async (original) => {
const actual = await original();
const { Atom } = await import("effect/reactivity");
+ const isAssetError = Schema.is(AssetAccessError);
const family = Atom.family((_key: string) =>
- Atom.make(Effect.tryPromise(() => mint())).pipe(Atom.keepAlive),
+ Atom.make(
+ Effect.tryPromise({
+ try: () => mint(),
+ catch: (error) => (isAssetError(error) ? error : new Cause.UnknownError(error)),
+ }),
+ ).pipe(Atom.keepAlive),
);
return {
...actual,
@@ -40,14 +62,30 @@ vi.mock(import("../state/session"), async (original) => ({
...(await original()),
readEnvironmentScope: () => false,
useEnvironmentScope: () => false,
- readPreparedConnection: (() => ({ httpBaseUrl: "https://host.test" })) as never,
+ readPreparedConnection: (() => ({
+ httpBaseUrl: "https://host.test",
+ target: remoteOpen.isResolved
+ ? new PrimaryConnectionTarget({
+ environmentId: EnvironmentId.make("media-environment"),
+ label: remoteOpen.label,
+ httpBaseUrl: remoteOpen.httpBaseUrl,
+ wsBaseUrl: "wss://host.test",
+ })
+ : undefined,
+ })) as never,
usePreparedConnection: (() => ({
_tag: "Some",
value: { httpBaseUrl: "https://host.test" },
})) as never,
}));
+vi.mock(import("../remoteOpen"), async (original) => ({
+ ...(await original()),
+ useRemoteOpenResolution: () => remoteOpen,
+}));
+
import ChatMarkdown from "./ChatMarkdown";
+import { toastManager } from "./ui/toast";
const roots: Root[] = [];
let registry: AtomRegistry.AtomRegistry;
@@ -68,9 +106,24 @@ afterEach(async () => {
for (const root of roots.splice(0)) await act(async () => root.unmount());
registry.dispose();
document.body.replaceChildren();
+ remoteOpen.isResolved = true;
+ remoteOpen.state.mode = "local-exec";
+ remoteOpen.label = "media-host";
+ remoteOpen.httpBaseUrl = "https://host.test";
+ vi.restoreAllMocks();
vi.unstubAllGlobals();
});
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ let reject!: (error: unknown) => void;
+ const promise = new Promise<T>((resolvePromise, rejectPromise) => {
+ resolve = resolvePromise;
+ reject = rejectPromise;
+ });
+ return { promise, resolve, reject };
+}
+
function createTestRoot() {
const container = document.body.appendChild(document.createElement("div"));
const root = createRoot(container);
@@ -88,7 +141,8 @@ function createTestRoot() {
it("opens host media through server authorization before the client grant loads", async () => {
mint.mockResolvedValue({ relativeUrl: "/api/assets/image.png", expiresAt: 1 });
- const onImageExpand = vi.fn();
+ const expanded = deferred<unknown>();
+ const onImageExpand = vi.fn(expanded.resolve);
const { container, render } = createTestRoot();
await render(
<ChatMarkdown
@@ -104,13 +158,9 @@ it("opens host media through server authorization before the client grant loads"
const link = container.querySelector<HTMLAnchorElement>('a[href="/tmp/image.png"]');
expect(link).not.toBeNull();
await act(async () => link!.click());
- await vi.waitFor(() =>
- expect(onImageExpand).toHaveBeenCalledWith(
- expect.objectContaining({
- images: [expect.objectContaining({ src: "https://host.test/api/assets/image.png" })],
- }),
- ),
- );
+ expect(await expanded.promise).toMatchObject({
+ images: [expect.objectContaining({ src: "https://host.test/api/assets/image.png" })],
+ });
});
const threadRef = {
@@ -118,6 +168,79 @@ const threadRef = {
threadId: ThreadId.make("media-thread"),
};
+it.each([
+ {
+ name: "a remote lookup whose host resolves while it is pending",
+ checkedPath: "/home/remote/Downloads/image.png",
+ description: "The file was not found on settled-host at /home/remote/Downloads/image.png.",
+ },
+ {
+ name: "an older remote server without a checked path",
+ description: "The file was not found on settled-host at ~/Downloads/image.png.",
+ },
+ {
+ name: "a missing file on this device",
+ local: true,
+ checkedPath: "/home/local/Downloads/image.png",
+ description: "Media file was not found.",
+ },
+ {
+ name: "a different remote failure",
+ unsupported: true,
+ description: "Only images, videos, audio, HTML, and PDF files can be previewed.",
+ },
+])("reports the media failure for $name", async (scenario) => {
+ const lookup = deferred<AssetCreateUrlResult>();
+ const started = deferred<void>();
+ const reported = deferred<Parameters<typeof toastManager.add>[0]>();
+ mint.mockImplementation(() => {
+ started.resolve();
+ return lookup.promise;
+ });
+ vi.spyOn(toastManager, "add").mockImplementation((toast) => {
+ reported.resolve(toast);
+ return "media-toast";
+ });
+ remoteOpen.isResolved = false;
+ const { container, render } = createTestRoot();
+ const content = (
+ <ChatMarkdown cwd="/repo" threadRef={threadRef} text="[Open image](~/Downloads/image.png)" />
+ );
+ await render(content);
+ const link = container.querySelector<HTMLAnchorElement>('a[href="~/Downloads/image.png"]');
+ expect(link).not.toBeNull();
+ await act(async () => {
+ link!.click();
+ await started.promise;
+ });
+
+ remoteOpen.isResolved = true;
+ remoteOpen.state.mode = scenario.local ? "local-exec" : "remote-unavailable";
+ remoteOpen.httpBaseUrl = scenario.local ? "http://localhost:3773" : "https://host.test";
+ remoteOpen.label = "settled-host";
+ await render(content);
+ const resource = {
+ _tag: "media-file" as const,
+ path: "~/Downloads/image.png",
+ threadId: threadRef.threadId,
+ };
+ await act(async () => {
+ lookup.reject(
+ scenario.unsupported
+ ? new AssetPreviewTypeValidationError({ resource })
+ : new AssetWorkspaceAssetNotFoundError({
+ resource,
+ ...(scenario.checkedPath ? { checkedPath: scenario.checkedPath } : {}),
+ }),
+ );
+ await reported.promise;
+ });
+ expect(await reported.promise).toMatchObject({
+ title: "Media unavailable",
+ description: scenario.description,
+ });
+});
+
function markdown(workspaceMutationId?: string | null) {
return (
<ChatMarkdown
diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx
index e8461925b36..a377301d8d1 100644
--- a/apps/web/src/components/ChatMarkdown.tsx
+++ b/apps/web/src/components/ChatMarkdown.tsx
@@ -48,6 +48,7 @@ import {
} from "lucide-react";
import { Check, Copy, Maximize2, Minimize2 } from "lucide";
import {
+ AssetWorkspaceAssetNotFoundError,
AuthPreviewOperateScope,
type AssetResource,
type EditorId,
@@ -78,6 +79,7 @@ import { MISSING_FILE_ACCESS_MESSAGE } from "@t3tools/client-runtime/state/asset
import { mediaKindFromPath, mediaMimeTypeFromExtension } from "@t3tools/shared/filePreview";
import * as Cause from "effect/Cause";
import * as Option from "effect/Option";
+import * as Schema from "effect/Schema";
import { AsyncResult, Atom } from "effect/reactivity";
import React, {
Children,
@@ -183,7 +185,11 @@ import { isElectron } from "../env";
import { readLocalApi } from "../localApi";
import { useAssetUrlRefresh, useAssetUrlState } from "../assets/assetUrls";
import { cn } from "../lib/utils";
-import { useRemoteOpenResolution, type RemoteOpenMode } from "../remoteOpen";
+import {
+ resolveRemoteOpenState,
+ useRemoteOpenResolution,
+ type RemoteOpenMode,
+} from "../remoteOpen";
import { useRightPanelStore } from "../rightPanelStore";
import { readThreadShell, useProjects } from "../state/entities";
import { serverEnvironment } from "../state/server";
@@ -228,6 +234,8 @@ import {
import { resolveLinkTarget } from "../browser/browserLinkTarget";
import { PullRequestLinkPreview } from "./pullRequest/PullRequestLinkPreview";
+const isAssetNotFoundError = Schema.is(AssetWorkspaceAssetNotFoundError);
+
interface ChatMarkdownProps {
/** Compact markdown transforms remove blocks before rendering inside a label. */
inline?: boolean;
@@ -2466,14 +2474,34 @@ function useChatMarkdownState({
},
(error: unknown) => {
if (mediaRequestId.current !== requestId) return;
+ let description =
+ error instanceof Error
+ ? error.message
+ : "The file could not be loaded. It may have been moved or deleted.";
+ if (
+ isAssetNotFoundError(error) &&
+ error.resource._tag === "media-file" &&
+ environmentId !== null
+ ) {
+ // The connection may resolve while the media lookup is pending.
+ const target = readPreparedConnection(environmentId)?.target ?? null;
+ if (
+ target !== null &&
+ resolveRemoteOpenState({
+ target,
+ sshAlias: null,
+ remoteOpenTargets: undefined,
+ isDesktopRenderer: window.desktopBridge !== undefined,
+ }).mode !== "local-exec"
+ ) {
+ description = `The file was not found on ${target.label} at ${error.checkedPath ?? error.resource.path}.`;
+ }
+ }
toastManager.add(
stackedThreadToast({
type: "error",
title: "Media unavailable",
- description:
- error instanceof Error
- ? error.message
- : "The file could not be loaded. It may have been moved or deleted.",
+ description,
}),
);
},
diff --git a/packages/client-runtime/src/state/assets.test.ts b/packages/client-runtime/src/state/assets.test.ts
index fd665263254..09ddb3cb21f 100644
--- a/packages/client-runtime/src/state/assets.test.ts
+++ b/packages/client-runtime/src/state/assets.test.ts
@@ -12,6 +12,7 @@ import {
WS_METHODS,
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
+import * as Result from "effect/Result";
import * as Effect from "effect/Effect";
import * as Stream from "effect/Stream";
import * as SubscriptionRef from "effect/SubscriptionRef";
@@ -66,6 +67,13 @@ describe("createAssetEnvironmentAtoms", () => {
{ name: "windows path", path: "C:\\Users\\demo\\clip.mp4", fallback: true },
{ name: "inspection failure", path: "/tmp/clip.mp4", error: "inspection", fallback: true },
{ name: "foreign thread", path: "/tmp/clip.mp4", error: "context", fallback: true },
+ { name: "missing on both hosts", path: "/tmp/clip.mp4", localFails: true },
+ {
+ name: "a defect in the local retry",
+ path: "/tmp/clip.mp4",
+ localFails: true,
+ localDefect: true,
+ },
{ name: "remote success", path: "/tmp/clip.mp4", success: true },
{ name: "relative path", path: "clip.mp4" },
{ name: "no primary", path: "/tmp/clip.mp4", primary: "none" },
@@ -92,7 +100,7 @@ describe("createAssetEnvironmentAtoms", () => {
? new AssetWorkspaceAssetInspectionError({ resource, cause: new Error("unreadable") })
: scenario.error === "context"
? new AssetWorkspaceContextNotFoundError({ resource })
- : new AssetWorkspaceAssetNotFoundError({ resource });
+ : new AssetWorkspaceAssetNotFoundError({ resource, checkedPath: "/tmp/clip.mp4" });
const calls: EnvironmentId[] = [];
const supervisors = new Map<
EnvironmentId,
@@ -102,6 +110,14 @@ describe("createAssetEnvironmentAtoms", () => {
const client = {
[WS_METHODS.assetsCreateUrl]: () => {
calls.push(environmentId);
+ if (environmentId === localId && scenario.localFails) {
+ const localError = Effect.fail(
+ new AssetWorkspaceAssetNotFoundError({ resource, checkedPath: "/local/clip.mp4" }),
+ );
+ return scenario.localDefect
+ ? localError.pipe(Effect.ensuring(Effect.die("cleanup failed")))
+ : localError;
+ }
return environmentId === remoteId && !scenario.success
? Effect.fail(error)
: Effect.succeed({
@@ -167,10 +183,16 @@ describe("createAssetEnvironmentAtoms", () => {
? "https://local.test/api/assets/local/media"
: "/api/assets/remote/media",
);
+ } else if (scenario.localDefect) {
+ const cause = yield* Effect.sandbox(result).pipe(Effect.flip);
+ expect(Cause.findErrorOption(cause)).toEqual(Option.some(error));
+ expect(Cause.findDefect(cause)).toEqual(Result.succeed("cleanup failed"));
} else {
expect(yield* Effect.flip(result)).toEqual(error);
}
- expect(calls).toEqual(scenario.fallback ? [remoteId, localId] : [remoteId]);
+ expect(calls).toEqual(
+ scenario.fallback || scenario.localFails ? [remoteId, localId] : [remoteId],
+ );
if (scenario.primary === "reconnecting") {
registry.set(localEnvironment, localTarget);
expect((yield* result).relativeUrl).toBe("https://local.test/api/assets/local/media");
diff --git a/packages/client-runtime/src/state/assets.ts b/packages/client-runtime/src/state/assets.ts
index 2ecd01adc50..8eca5b4f2d1 100644
--- a/packages/client-runtime/src/state/assets.ts
+++ b/packages/client-runtime/src/state/assets.ts
@@ -13,6 +13,7 @@ import {
getProjectFaviconResourceKey,
isProjectFaviconFallbackUrl,
} from "@t3tools/shared/projectFavicon";
+import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Result from "effect/Result";
@@ -156,10 +157,10 @@ export function createAssetEnvironmentAtoms<R, E>(
)
return yield* error;
const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
- const asset = yield* registry.run(
- local.environmentId,
- request(WS_METHODS.assetsCreateUrl, input),
- );
+ // Map the full cause so retry defects and interruption survive.
+ const asset = yield* registry
+ .run(local.environmentId, request(WS_METHODS.assetsCreateUrl, input))
+ .pipe(Effect.catchCause((cause) => Effect.failCause(Cause.map(cause, () => error))));
return { ...asset, relativeUrl: new URL(asset.relativeUrl, local.httpBaseUrl).href };
});
const createUrl = createEnvironmentQueryAtomFamily(runtime, {
diff --git a/packages/contracts/src/assets.test.ts b/packages/contracts/src/assets.test.ts
index 9e4ba486b48..8719fc034aa 100644
--- a/packages/contracts/src/assets.test.ts
+++ b/packages/contracts/src/assets.test.ts
@@ -1,13 +1,20 @@
import * as Schema from "effect/Schema";
import { describe, expect, it } from "vite-plus/test";
-import { AttachmentCreateUploadUrlInput } from "./assets.ts";
+import {
+ AssetAccessError,
+ AssetWorkspaceAssetNotFoundError,
+ AttachmentCreateUploadUrlInput,
+} from "./assets.ts";
+import { ThreadId } from "./baseSchemas.ts";
import {
PROVIDER_SEND_TURN_MAX_FILE_BYTES,
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
} from "./chatAttachment.ts";
const isUploadInput = Schema.is(AttachmentCreateUploadUrlInput);
+const encodeAccessError = Schema.encodeUnknownSync(AssetAccessError);
+const decodeAccessError = Schema.decodeUnknownSync(AssetAccessError);
const uploadInput = {
name: "screenshot.png",
@@ -58,3 +65,31 @@ describe("AttachmentCreateUploadUrlInput", () => {
).toBe(false);
});
});
+
+describe("AssetWorkspaceAssetNotFoundError", () => {
+ const resource = {
+ _tag: "media-file" as const,
+ threadId: ThreadId.make("thread-1"),
+ path: "~/Downloads/clip.mp4",
+ };
+
+ it("carries the checked path across the wire", () => {
+ const encoded = encodeAccessError(
+ new AssetWorkspaceAssetNotFoundError({
+ resource,
+ checkedPath: "/Users/graham/Downloads/clip.mp4",
+ }),
+ );
+ const error = decodeAccessError(JSON.parse(JSON.stringify(encoded)));
+
+ expect(error).toBeInstanceOf(AssetWorkspaceAssetNotFoundError);
+ expect(error).toMatchObject({ checkedPath: "/Users/graham/Downloads/clip.mp4" });
+ });
+
+ it("decodes an error from a server that sends no checked path", () => {
+ const error = decodeAccessError({ _tag: "AssetWorkspaceAssetNotFoundError", resource });
+
+ expect(error).toBeInstanceOf(AssetWorkspaceAssetNotFoundError);
+ expect(error).not.toHaveProperty("checkedPath");
+ });
+});
diff --git a/packages/contracts/src/assets.ts b/packages/contracts/src/assets.ts
index 6737e01d47b..e21a71dd7dd 100644
--- a/packages/contracts/src/assets.ts
+++ b/packages/contracts/src/assets.ts
@@ -207,6 +207,8 @@ export class AssetWorkspaceAssetNotFoundError extends Schema.TaggedError<AssetWo
"AssetWorkspaceAssetNotFoundError",
{
resource: AssetResource,
+ // Absolute path after home/workspace resolution; absent on older servers.
+ checkedPath: Schema.optionalKey(Schema.String),
},
) {
override get message(): string {