@devries-cameron20 / t3code Mirror · read-only / commits / 826ef55b74
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 23:15 UTC

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

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Julius Marminge <julius0216@outlook.com>

Scott Norteman committed Oct 20, 2026 at 00:48 UTC 826ef55b749bf2f331d163056ae5301985fa134b
8 files changed +277 -25
apps/server/src/assets/AssetAccess.test.ts
+35
@@ -387,6 +387,41 @@ describe("AssetAccess", () => {
387 }).pipe(Effect.provide(layerTest)),
388 );
389
390 + it.effect.each([
391 + { form: "absolute", requestedPath: undefined, checked: ["absolute.mp4"] },
392 + {
393 + form: "workspace-relative",
394 + requestedPath: "clips/relative.mp4",
395 + checked: ["workspace", "clips", "relative.mp4"],
396 + },
397 + {
398 + form: "home-relative",
399 + requestedPath: "~/Downloads/home.mp4",
400 + checked: ["home", "Downloads", "home.mp4"],
401 + },
402 + ])("reports the absolute path it checked for a missing $form media path", (scenario) =>
403 + Effect.gen(function* () {
404 + const fs = yield* FileSystem.FileSystem;
405 + const path = yield* Path.Path;
406 + const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-missing-" });
407 + const root = path.join(directory, "workspace");
408 + yield* fs.makeDirectory(root);
409 + const checkedPath = path.join(directory, ...scenario.checked);
410 + const error = yield* issueAssetUrl({
411 + resource: {
412 + _tag: "media-file",
413 + threadId: ThreadId.make("thread-1"),
414 + path: scenario.requestedPath ?? checkedPath,
415 + },
416 + workspaceRoot: root,
417 + }).pipe(
418 + Effect.flip,
419 + Effect.provideService(HostProcess.HomeDirectory, path.join(directory, "home")),
420 + );
421 + expect(error).toMatchObject({ _tag: "AssetWorkspaceAssetNotFoundError", checkedPath });
422 + }).pipe(Effect.provide(layerTest)),
423 + );
424 +
425 it.effect.skipIf(!symlinksSupported)(
426 "rejects non-previewable files, disguised targets, and directories",
427 () =>
apps/server/src/assets/AssetAccess.ts
+8 -2
@@ -359,7 +359,10 @@ const finalizeAbsoluteMediaFileAsset = Effect.fn("AssetAccess.finalizeAbsoluteMe
359 ),
360 );
361 if (!canonicalFile) {
362 - return yield* new AssetWorkspaceAssetNotFoundError({ resource: input.resource });
362 + return yield* new AssetWorkspaceAssetNotFoundError({
363 + resource: input.resource,
364 + checkedPath: input.requestedPath,
365 + });
366 }
367 if (hostPreviewMimeTypeFromExtension(path.extname(canonicalFile)) === null) {
368 return yield* new AssetPreviewTypeValidationError({ resource: input.resource });
@@ -385,7 +388,10 @@ const finalizeAbsoluteMediaFileAsset = Effect.fn("AssetAccess.finalizeAbsoluteMe
388 ),
389 );
390 if (!opened) {
388 - return yield* new AssetWorkspaceAssetNotFoundError({ resource: input.resource });
391 + return yield* new AssetWorkspaceAssetNotFoundError({
392 + resource: input.resource,
393 + checkedPath: input.requestedPath,
394 + });
395 }
396 return {
397 claims: {
apps/web/src/components/ChatMarkdown.assets.browser.test.tsx
+134 -11
@@ -1,12 +1,28 @@
1 +import { PrimaryConnectionTarget } from "@t3tools/client-runtime/connection";
2 import { RegistryContext } from "@effect/atom-react";
2 -import { type AssetCreateUrlResult, EnvironmentId, ThreadId } from "@t3tools/contracts";
3 +import {
4 + AssetAccessError,
5 + AssetWorkspaceAssetNotFoundError,
6 + AssetPreviewTypeValidationError,
7 + type AssetCreateUrlResult,
8 + EnvironmentId,
9 + ThreadId,
10 +} from "@t3tools/contracts";
11 import * as Effect from "effect/Effect";
12 +import * as Cause from "effect/Cause";
13 +import * as Schema from "effect/Schema";
14 import { AtomRegistry } from "effect/reactivity";
15 import { act, type ReactNode } from "react";
16 import { createRoot, type Root } from "react-dom/client";
17 import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
18
19 const mint = vi.hoisted(() => vi.fn<() => Promise<AssetCreateUrlResult>>());
20 +const remoteOpen = vi.hoisted(() => ({
21 + state: { mode: "local-exec" as "local-exec" | "remote-unavailable" },
22 + isResolved: true,
23 + label: "media-host",
24 + httpBaseUrl: "https://host.test",
25 +}));
26 // Atoms derived from the server config run in the real registry over a missing config.
27 vi.mock(import("../state/server"), async (original) => {
28 const actual = await original();
@@ -21,8 +37,14 @@ vi.mock(import("../state/server"), async (original) => {
37 vi.mock(import("../state/assets"), async (original) => {
38 const actual = await original();
39 const { Atom } = await import("effect/reactivity");
40 + const isAssetError = Schema.is(AssetAccessError);
41 const family = Atom.family((_key: string) =>
25 - Atom.make(Effect.tryPromise(() => mint())).pipe(Atom.keepAlive),
42 + Atom.make(
43 + Effect.tryPromise({
44 + try: () => mint(),
45 + catch: (error) => (isAssetError(error) ? error : new Cause.UnknownError(error)),
46 + }),
47 + ).pipe(Atom.keepAlive),
48 );
49 return {
50 ...actual,
@@ -40,14 +62,30 @@ vi.mock(import("../state/session"), async (original) => ({
62 ...(await original()),
63 readEnvironmentScope: () => false,
64 useEnvironmentScope: () => false,
43 - readPreparedConnection: (() => ({ httpBaseUrl: "https://host.test" })) as never,
65 + readPreparedConnection: (() => ({
66 + httpBaseUrl: "https://host.test",
67 + target: remoteOpen.isResolved
68 + ? new PrimaryConnectionTarget({
69 + environmentId: EnvironmentId.make("media-environment"),
70 + label: remoteOpen.label,
71 + httpBaseUrl: remoteOpen.httpBaseUrl,
72 + wsBaseUrl: "wss://host.test",
73 + })
74 + : undefined,
75 + })) as never,
76 usePreparedConnection: (() => ({
77 _tag: "Some",
78 value: { httpBaseUrl: "https://host.test" },
79 })) as never,
80 }));
81
82 +vi.mock(import("../remoteOpen"), async (original) => ({
83 + ...(await original()),
84 + useRemoteOpenResolution: () => remoteOpen,
85 +}));
86 +
87 import ChatMarkdown from "./ChatMarkdown";
88 +import { toastManager } from "./ui/toast";
89
90 const roots: Root[] = [];
91 let registry: AtomRegistry.AtomRegistry;
@@ -68,9 +106,24 @@ afterEach(async () => {
106 for (const root of roots.splice(0)) await act(async () => root.unmount());
107 registry.dispose();
108 document.body.replaceChildren();
109 + remoteOpen.isResolved = true;
110 + remoteOpen.state.mode = "local-exec";
111 + remoteOpen.label = "media-host";
112 + remoteOpen.httpBaseUrl = "https://host.test";
113 + vi.restoreAllMocks();
114 vi.unstubAllGlobals();
115 });
116
117 +function deferred<T>() {
118 + let resolve!: (value: T) => void;
119 + let reject!: (error: unknown) => void;
120 + const promise = new Promise<T>((resolvePromise, rejectPromise) => {
121 + resolve = resolvePromise;
122 + reject = rejectPromise;
123 + });
124 + return { promise, resolve, reject };
125 +}
126 +
127 function createTestRoot() {
128 const container = document.body.appendChild(document.createElement("div"));
129 const root = createRoot(container);
@@ -88,7 +141,8 @@ function createTestRoot() {
141
142 it("opens host media through server authorization before the client grant loads", async () => {
143 mint.mockResolvedValue({ relativeUrl: "/api/assets/image.png", expiresAt: 1 });
91 - const onImageExpand = vi.fn();
144 + const expanded = deferred<unknown>();
145 + const onImageExpand = vi.fn(expanded.resolve);
146 const { container, render } = createTestRoot();
147 await render(
148 <ChatMarkdown
@@ -104,13 +158,9 @@ it("opens host media through server authorization before the client grant loads"
158 const link = container.querySelector<HTMLAnchorElement>('a[href="/tmp/image.png"]');
159 expect(link).not.toBeNull();
160 await act(async () => link!.click());
107 - await vi.waitFor(() =>
108 - expect(onImageExpand).toHaveBeenCalledWith(
109 - expect.objectContaining({
110 - images: [expect.objectContaining({ src: "https://host.test/api/assets/image.png" })],
111 - }),
112 - ),
113 - );
161 + expect(await expanded.promise).toMatchObject({
162 + images: [expect.objectContaining({ src: "https://host.test/api/assets/image.png" })],
163 + });
164 });
165
166 const threadRef = {
@@ -118,6 +168,79 @@ const threadRef = {
168 threadId: ThreadId.make("media-thread"),
169 };
170
171 +it.each([
172 + {
173 + name: "a remote lookup whose host resolves while it is pending",
174 + checkedPath: "/home/remote/Downloads/image.png",
175 + description: "The file was not found on settled-host at /home/remote/Downloads/image.png.",
176 + },
177 + {
178 + name: "an older remote server without a checked path",
179 + description: "The file was not found on settled-host at ~/Downloads/image.png.",
180 + },
181 + {
182 + name: "a missing file on this device",
183 + local: true,
184 + checkedPath: "/home/local/Downloads/image.png",
185 + description: "Media file was not found.",
186 + },
187 + {
188 + name: "a different remote failure",
189 + unsupported: true,
190 + description: "Only images, videos, audio, HTML, and PDF files can be previewed.",
191 + },
192 +])("reports the media failure for $name", async (scenario) => {
193 + const lookup = deferred<AssetCreateUrlResult>();
194 + const started = deferred<void>();
195 + const reported = deferred<Parameters<typeof toastManager.add>[0]>();
196 + mint.mockImplementation(() => {
197 + started.resolve();
198 + return lookup.promise;
199 + });
200 + vi.spyOn(toastManager, "add").mockImplementation((toast) => {
201 + reported.resolve(toast);
202 + return "media-toast";
203 + });
204 + remoteOpen.isResolved = false;
205 + const { container, render } = createTestRoot();
206 + const content = (
207 + <ChatMarkdown cwd="/repo" threadRef={threadRef} text="[Open image](~/Downloads/image.png)" />
208 + );
209 + await render(content);
210 + const link = container.querySelector<HTMLAnchorElement>('a[href="~/Downloads/image.png"]');
211 + expect(link).not.toBeNull();
212 + await act(async () => {
213 + link!.click();
214 + await started.promise;
215 + });
216 +
217 + remoteOpen.isResolved = true;
218 + remoteOpen.state.mode = scenario.local ? "local-exec" : "remote-unavailable";
219 + remoteOpen.httpBaseUrl = scenario.local ? "http://localhost:3773" : "https://host.test";
220 + remoteOpen.label = "settled-host";
221 + await render(content);
222 + const resource = {
223 + _tag: "media-file" as const,
224 + path: "~/Downloads/image.png",
225 + threadId: threadRef.threadId,
226 + };
227 + await act(async () => {
228 + lookup.reject(
229 + scenario.unsupported
230 + ? new AssetPreviewTypeValidationError({ resource })
231 + : new AssetWorkspaceAssetNotFoundError({
232 + resource,
233 + ...(scenario.checkedPath ? { checkedPath: scenario.checkedPath } : {}),
234 + }),
235 + );
236 + await reported.promise;
237 + });
238 + expect(await reported.promise).toMatchObject({
239 + title: "Media unavailable",
240 + description: scenario.description,
241 + });
242 +});
243 +
244 function markdown(workspaceMutationId?: string | null) {
245 return (
246 <ChatMarkdown
apps/web/src/components/ChatMarkdown.tsx
+33 -5
@@ -48,6 +48,7 @@ import {
48 } from "lucide-react";
49 import { Check, Copy, Maximize2, Minimize2 } from "lucide";
50 import {
51 + AssetWorkspaceAssetNotFoundError,
52 AuthPreviewOperateScope,
53 type AssetResource,
54 type EditorId,
@@ -78,6 +79,7 @@ import { MISSING_FILE_ACCESS_MESSAGE } from "@t3tools/client-runtime/state/asset
79 import { mediaKindFromPath, mediaMimeTypeFromExtension } from "@t3tools/shared/filePreview";
80 import * as Cause from "effect/Cause";
81 import * as Option from "effect/Option";
82 +import * as Schema from "effect/Schema";
83 import { AsyncResult, Atom } from "effect/reactivity";
84 import React, {
85 Children,
@@ -183,7 +185,11 @@ import { isElectron } from "../env";
185 import { readLocalApi } from "../localApi";
186 import { useAssetUrlRefresh, useAssetUrlState } from "../assets/assetUrls";
187 import { cn } from "../lib/utils";
186 -import { useRemoteOpenResolution, type RemoteOpenMode } from "../remoteOpen";
188 +import {
189 + resolveRemoteOpenState,
190 + useRemoteOpenResolution,
191 + type RemoteOpenMode,
192 +} from "../remoteOpen";
193 import { useRightPanelStore } from "../rightPanelStore";
194 import { readThreadShell, useProjects } from "../state/entities";
195 import { serverEnvironment } from "../state/server";
@@ -228,6 +234,8 @@ import {
234 import { resolveLinkTarget } from "../browser/browserLinkTarget";
235 import { PullRequestLinkPreview } from "./pullRequest/PullRequestLinkPreview";
236
237 +const isAssetNotFoundError = Schema.is(AssetWorkspaceAssetNotFoundError);
238 +
239 interface ChatMarkdownProps {
240 /** Compact markdown transforms remove blocks before rendering inside a label. */
241 inline?: boolean;
@@ -2466,14 +2474,34 @@ function useChatMarkdownState({
2474 },
2475 (error: unknown) => {
2476 if (mediaRequestId.current !== requestId) return;
2477 + let description =
2478 + error instanceof Error
2479 + ? error.message
2480 + : "The file could not be loaded. It may have been moved or deleted.";
2481 + if (
2482 + isAssetNotFoundError(error) &&
2483 + error.resource._tag === "media-file" &&
2484 + environmentId !== null
2485 + ) {
2486 + // The connection may resolve while the media lookup is pending.
2487 + const target = readPreparedConnection(environmentId)?.target ?? null;
2488 + if (
2489 + target !== null &&
2490 + resolveRemoteOpenState({
2491 + target,
2492 + sshAlias: null,
2493 + remoteOpenTargets: undefined,
2494 + isDesktopRenderer: window.desktopBridge !== undefined,
2495 + }).mode !== "local-exec"
2496 + ) {
2497 + description = `The file was not found on ${target.label} at ${error.checkedPath ?? error.resource.path}.`;
2498 + }
2499 + }
2500 toastManager.add(
2501 stackedThreadToast({
2502 type: "error",
2503 title: "Media unavailable",
2473 - description:
2474 - error instanceof Error
2475 - ? error.message
2476 - : "The file could not be loaded. It may have been moved or deleted.",
2504 + description,
2505 }),
2506 );
2507 },
packages/client-runtime/src/state/assets.test.ts
+24 -2
@@ -12,6 +12,7 @@ import {
12 WS_METHODS,
13 } from "@t3tools/contracts";
14 import * as Cause from "effect/Cause";
15 +import * as Result from "effect/Result";
16 import * as Effect from "effect/Effect";
17 import * as Stream from "effect/Stream";
18 import * as SubscriptionRef from "effect/SubscriptionRef";
@@ -66,6 +67,13 @@ describe("createAssetEnvironmentAtoms", () => {
67 { name: "windows path", path: "C:\\Users\\demo\\clip.mp4", fallback: true },
68 { name: "inspection failure", path: "/tmp/clip.mp4", error: "inspection", fallback: true },
69 { name: "foreign thread", path: "/tmp/clip.mp4", error: "context", fallback: true },
70 + { name: "missing on both hosts", path: "/tmp/clip.mp4", localFails: true },
71 + {
72 + name: "a defect in the local retry",
73 + path: "/tmp/clip.mp4",
74 + localFails: true,
75 + localDefect: true,
76 + },
77 { name: "remote success", path: "/tmp/clip.mp4", success: true },
78 { name: "relative path", path: "clip.mp4" },
79 { name: "no primary", path: "/tmp/clip.mp4", primary: "none" },
@@ -92,7 +100,7 @@ describe("createAssetEnvironmentAtoms", () => {
100 ? new AssetWorkspaceAssetInspectionError({ resource, cause: new Error("unreadable") })
101 : scenario.error === "context"
102 ? new AssetWorkspaceContextNotFoundError({ resource })
95 - : new AssetWorkspaceAssetNotFoundError({ resource });
103 + : new AssetWorkspaceAssetNotFoundError({ resource, checkedPath: "/tmp/clip.mp4" });
104 const calls: EnvironmentId[] = [];
105 const supervisors = new Map<
106 EnvironmentId,
@@ -102,6 +110,14 @@ describe("createAssetEnvironmentAtoms", () => {
110 const client = {
111 [WS_METHODS.assetsCreateUrl]: () => {
112 calls.push(environmentId);
113 + if (environmentId === localId && scenario.localFails) {
114 + const localError = Effect.fail(
115 + new AssetWorkspaceAssetNotFoundError({ resource, checkedPath: "/local/clip.mp4" }),
116 + );
117 + return scenario.localDefect
118 + ? localError.pipe(Effect.ensuring(Effect.die("cleanup failed")))
119 + : localError;
120 + }
121 return environmentId === remoteId && !scenario.success
122 ? Effect.fail(error)
123 : Effect.succeed({
@@ -167,10 +183,16 @@ describe("createAssetEnvironmentAtoms", () => {
183 ? "https://local.test/api/assets/local/media"
184 : "/api/assets/remote/media",
185 );
186 + } else if (scenario.localDefect) {
187 + const cause = yield* Effect.sandbox(result).pipe(Effect.flip);
188 + expect(Cause.findErrorOption(cause)).toEqual(Option.some(error));
189 + expect(Cause.findDefect(cause)).toEqual(Result.succeed("cleanup failed"));
190 } else {
191 expect(yield* Effect.flip(result)).toEqual(error);
192 }
173 - expect(calls).toEqual(scenario.fallback ? [remoteId, localId] : [remoteId]);
193 + expect(calls).toEqual(
194 + scenario.fallback || scenario.localFails ? [remoteId, localId] : [remoteId],
195 + );
196 if (scenario.primary === "reconnecting") {
197 registry.set(localEnvironment, localTarget);
198 expect((yield* result).relativeUrl).toBe("https://local.test/api/assets/local/media");
packages/client-runtime/src/state/assets.ts
+5 -4
@@ -13,6 +13,7 @@ import {
13 getProjectFaviconResourceKey,
14 isProjectFaviconFallbackUrl,
15 } from "@t3tools/shared/projectFavicon";
16 +import * as Cause from "effect/Cause";
17 import * as Effect from "effect/Effect";
18 import * as Option from "effect/Option";
19 import * as Result from "effect/Result";
@@ -156,10 +157,10 @@ export function createAssetEnvironmentAtoms<R, E>(
157 )
158 return yield* error;
159 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
159 - const asset = yield* registry.run(
160 - local.environmentId,
161 - request(WS_METHODS.assetsCreateUrl, input),
162 - );
160 + // Map the full cause so retry defects and interruption survive.
161 + const asset = yield* registry
162 + .run(local.environmentId, request(WS_METHODS.assetsCreateUrl, input))
163 + .pipe(Effect.catchCause((cause) => Effect.failCause(Cause.map(cause, () => error))));
164 return { ...asset, relativeUrl: new URL(asset.relativeUrl, local.httpBaseUrl).href };
165 });
166 const createUrl = createEnvironmentQueryAtomFamily(runtime, {
packages/contracts/src/assets.test.ts
+36 -1
@@ -1,13 +1,20 @@
1 import * as Schema from "effect/Schema";
2 import { describe, expect, it } from "vite-plus/test";
3
4 -import { AttachmentCreateUploadUrlInput } from "./assets.ts";
4 +import {
5 + AssetAccessError,
6 + AssetWorkspaceAssetNotFoundError,
7 + AttachmentCreateUploadUrlInput,
8 +} from "./assets.ts";
9 +import { ThreadId } from "./baseSchemas.ts";
10 import {
11 PROVIDER_SEND_TURN_MAX_FILE_BYTES,
12 PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
13 } from "./chatAttachment.ts";
14
15 const isUploadInput = Schema.is(AttachmentCreateUploadUrlInput);
16 +const encodeAccessError = Schema.encodeUnknownSync(AssetAccessError);
17 +const decodeAccessError = Schema.decodeUnknownSync(AssetAccessError);
18
19 const uploadInput = {
20 name: "screenshot.png",
@@ -58,3 +65,31 @@ describe("AttachmentCreateUploadUrlInput", () => {
65 ).toBe(false);
66 });
67 });
68 +
69 +describe("AssetWorkspaceAssetNotFoundError", () => {
70 + const resource = {
71 + _tag: "media-file" as const,
72 + threadId: ThreadId.make("thread-1"),
73 + path: "~/Downloads/clip.mp4",
74 + };
75 +
76 + it("carries the checked path across the wire", () => {
77 + const encoded = encodeAccessError(
78 + new AssetWorkspaceAssetNotFoundError({
79 + resource,
80 + checkedPath: "/Users/graham/Downloads/clip.mp4",
81 + }),
82 + );
83 + const error = decodeAccessError(JSON.parse(JSON.stringify(encoded)));
84 +
85 + expect(error).toBeInstanceOf(AssetWorkspaceAssetNotFoundError);
86 + expect(error).toMatchObject({ checkedPath: "/Users/graham/Downloads/clip.mp4" });
87 + });
88 +
89 + it("decodes an error from a server that sends no checked path", () => {
90 + const error = decodeAccessError({ _tag: "AssetWorkspaceAssetNotFoundError", resource });
91 +
92 + expect(error).toBeInstanceOf(AssetWorkspaceAssetNotFoundError);
93 + expect(error).not.toHaveProperty("checkedPath");
94 + });
95 +});
packages/contracts/src/assets.ts
+2
@@ -207,6 +207,8 @@ export class AssetWorkspaceAssetNotFoundError extends Schema.TaggedError<AssetWo
207 "AssetWorkspaceAssetNotFoundError",
208 {
209 resource: AssetResource,
210 + // Absolute path after home/workspace resolution; absent on older servers.
211 + checkedPath: Schema.optionalKey(Schema.String),
212 },
213 ) {
214 override get message(): string {