Compare commits

...
Author SHA1 Message Date
Julius Marmingeandcodex 48e11f6ba2 fix(web): structure preview asset URL failures
Co-authored-by: codex <[email protected]>
2026-06-20 19:01:24 -07:00
Julius Marmingeandcodex 352cca0906 Share preview request ordering across surfaces
Co-authored-by: codex <[email protected]>
2026-06-20 19:01:23 -07:00
Julius Marmingeandcodex a6f1072834 Ignore superseded image preview requests
Co-authored-by: codex <[email protected]>
2026-06-20 19:01:23 -07:00
Julius Marmingeandcodex 948bf61626 Retrigger service conventions check
Co-authored-by: codex <[email protected]>
2026-06-20 19:01:23 -07:00
0075ca2bb2 Clarify markdown preview fallback toast
Co-authored-by: Codex <[email protected]>
Co-authored-by: codex <[email protected]>
2026-06-20 19:01:23 -07:00
360747433f Add markdown preview failure fallback
Co-authored-by: Codex <[email protected]>
Co-authored-by: codex <[email protected]>
2026-06-20 19:01:23 -07:00
3be757f51a Preview workspace image files
Co-authored-by: Codex <[email protected]>
Co-authored-by: codex <[email protected]>
2026-06-20 19:01:23 -07:00
6 changed files with 495 additions and 99 deletions

No files matched your search

@@ -0,0 +1,117 @@
import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime";
import type { PreviewSessionSnapshot, ScopedThreadRef } from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import { AsyncResult } from "effect/unstable/reactivity";
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
import { readThreadPreviewState, resetPreviewStateForTests } from "~/previewStateStore";
import { selectThreadRightPanelState, useRightPanelStore } from "~/rightPanelStore";
import {
BrowserPreviewUnavailableError,
isBrowserPreviewAssetUrlInvalidError,
type OpenPreviewMutation,
openFileInPreview,
openUrlInPreview,
} from "./openFileInPreview";
const threadRef = {
environmentId: "environment-1" as ScopedThreadRef["environmentId"],
threadId: "thread-1" as ScopedThreadRef["threadId"],
};
const snapshot = (tabId: string, url: string): PreviewSessionSnapshot => ({
threadId: threadRef.threadId,
tabId,
navStatus: { _tag: "Success", url, title: "" },
canGoBack: false,
canGoForward: false,
updatedAt: "2026-06-21T00:00:00.000Z",
});
beforeEach(() => {
resetPreviewStateForTests();
useRightPanelStore.setState({ byThreadKey: {} });
});
afterEach(() => vi.unstubAllGlobals());
describe("openFileInPreview", () => {
it("uses the fixed unavailable-runtime message", () => {
expect(new BrowserPreviewUnavailableError().message).toBe(
"The integrated browser is unavailable in this runtime.",
);
});
it("reports invalid asset URLs with safe context and the exact parser cause", async () => {
vi.stubGlobal("window", { desktopBridge: { preview: {} } });
const parserCause = new TypeError("invalid URL");
const InvalidUrl = vi.fn(function InvalidUrl() {
throw parserCause;
});
vi.stubGlobal("URL", InvalidUrl);
const openPreview = vi.fn();
const httpBaseUrl = "not a URL";
const relativeUrl = "/api/assets/signed-secret-token/docs/report.pdf";
const expiresAt = Date.now();
const result = await openFileInPreview({
threadRef,
filePath: "docs/report.pdf",
httpBaseUrl,
createAssetUrl: async () => AsyncResult.success({ relativeUrl, expiresAt }),
openPreview,
});
const error = result._tag === "Failure" ? Cause.squash(result.cause) : undefined;
expect(isBrowserPreviewAssetUrlInvalidError(error)).toBe(true);
if (!isBrowserPreviewAssetUrlInvalidError(error)) {
throw new Error("Expected BrowserPreviewAssetUrlInvalidError");
}
expect(error).toMatchObject({
environmentId: "environment-1",
threadId: "thread-1",
filePath: "docs/report.pdf",
httpBaseUrlLength: httpBaseUrl.length,
relativeUrlLength: relativeUrl.length,
expiresAt,
});
expect(error.cause).toBe(parserCause);
expect(error.message).toBe("The environment returned an invalid asset URL.");
expect(error).not.toHaveProperty("httpBaseUrl");
expect(error).not.toHaveProperty("relativeUrl");
expect(JSON.stringify(error)).not.toContain("signed-secret-token");
expect(openPreview).not.toHaveBeenCalled();
});
});
it("does not apply an older preview response after another caller starts a newer request", async () => {
const firstSnapshot = snapshot("tab-1", "https://assets.test/first.png");
const secondSnapshot = snapshot("tab-2", "https://assets.test/second.png");
let resolveFirst!: (result: AtomCommandResult<PreviewSessionSnapshot, never>) => void;
const openPreview: OpenPreviewMutation<never> = ({ input }) =>
input.url === "https://assets.test/first.png"
? new Promise<AtomCommandResult<PreviewSessionSnapshot, never>>((resolve) => {
resolveFirst = resolve;
})
: Promise.resolve(AsyncResult.success(secondSnapshot));
const firstRequest = openUrlInPreview({
threadRef,
url: "https://assets.test/first.png",
openPreview,
});
await openUrlInPreview({
threadRef,
url: "https://assets.test/second.png",
openPreview,
});
resolveFirst(AsyncResult.success(firstSnapshot));
await firstRequest;
expect(readThreadPreviewState(threadRef).snapshot).toEqual(secondSnapshot);
expect(
selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, threadRef).surfaces,
).toEqual([{ id: "browser:tab-2", kind: "preview", resourceId: "tab-2" }]);
});
+161 -44
View File
@@ -6,15 +6,20 @@ import type {
PreviewSessionSnapshot,
ScopedThreadRef,
} from "@t3tools/contracts";
import { scopedThreadKey } from "@t3tools/client-runtime/environment";
import {
type AtomCommandResult,
mapAtomCommandResult,
} from "@t3tools/client-runtime/state/runtime";
import {
isWorkspaceBrowserPreviewPath,
isWorkspaceImagePreviewPath,
isWorkspacePreviewEntryPath,
} from "@t3tools/shared/filePreview";
import * as Cause from "effect/Cause";
import * as Data from "effect/Data";
import * as Schema from "effect/Schema";
import { AsyncResult } from "effect/unstable/reactivity";
import { resolveAssetUrl } from "~/assets/assetUrls";
import {
applyPreviewServerSnapshot,
isPreviewSupportedInRuntime,
@@ -22,34 +27,123 @@ import {
} from "~/previewStateStore";
import { useRightPanelStore } from "~/rightPanelStore";
export const isBrowserPreviewFile = (path: string): boolean =>
/\.(?:html?|pdf)$/i.test(path.split(/[?#]/, 1)[0] ?? "");
export const isBrowserPreviewFile = isWorkspaceBrowserPreviewPath;
export const isImagePreviewFile = isWorkspaceImagePreviewPath;
export const isWorkspacePreviewFile = isWorkspacePreviewEntryPath;
export class BrowserPreviewUnavailableError extends Data.TaggedError(
export class BrowserPreviewUnavailableError extends Schema.TaggedErrorClass<BrowserPreviewUnavailableError>()(
"BrowserPreviewUnavailableError",
)<{
readonly message: string;
}> {}
{},
) {
override get message(): string {
return "The integrated browser is unavailable in this runtime.";
}
}
export class BrowserPreviewThreadContextUnavailableError extends Schema.TaggedErrorClass<BrowserPreviewThreadContextUnavailableError>()(
"BrowserPreviewThreadContextUnavailableError",
{},
) {
override get message(): string {
return "Thread context is unavailable.";
}
}
export class BrowserPreviewEnvironmentDisconnectedError extends Schema.TaggedErrorClass<BrowserPreviewEnvironmentDisconnectedError>()(
"BrowserPreviewEnvironmentDisconnectedError",
{
environmentId: Schema.String,
threadId: Schema.String,
},
) {
override get message(): string {
return "Environment is not connected.";
}
}
export class BrowserPreviewAssetUrlInvalidError extends Schema.TaggedErrorClass<BrowserPreviewAssetUrlInvalidError>()(
"BrowserPreviewAssetUrlInvalidError",
{
environmentId: Schema.String,
threadId: Schema.String,
filePath: Schema.String,
httpBaseUrlLength: Schema.Int,
relativeUrlLength: Schema.Int,
expiresAt: Schema.Int,
cause: Schema.Defect(),
},
) {
override get message(): string {
return "The environment returned an invalid asset URL.";
}
}
export const isBrowserPreviewAssetUrlInvalidError = Schema.is(BrowserPreviewAssetUrlInvalidError);
export type OpenPreviewMutation<E = unknown> = (input: {
readonly environmentId: EnvironmentId;
readonly input: PreviewOpenInput;
}) => Promise<AtomCommandResult<PreviewSessionSnapshot, E>>;
export async function openUrlInPreview<E>(input: {
readonly threadRef: ScopedThreadRef;
readonly url: string;
readonly openPreview: OpenPreviewMutation<E>;
}): Promise<AtomCommandResult<void, E>> {
interface PreviewRequest {
readonly isCurrent: () => boolean;
readonly complete: () => void;
}
const activePreviewRequestByThread = new Map<string, symbol>();
const beginPreviewRequest = (
threadRef: ScopedThreadRef,
signal: AbortSignal | undefined,
): PreviewRequest => {
const threadKey = scopedThreadKey(threadRef);
const requestId = Symbol();
activePreviewRequestByThread.set(threadKey, requestId);
return {
isCurrent: () =>
activePreviewRequestByThread.get(threadKey) === requestId && signal?.aborted !== true,
complete: () => {
if (activePreviewRequestByThread.get(threadKey) === requestId) {
activePreviewRequestByThread.delete(threadKey);
}
},
};
};
const openUrlForPreviewRequest = async <E>(
input: {
readonly threadRef: ScopedThreadRef;
readonly url: string;
readonly openPreview: OpenPreviewMutation<E>;
},
request: PreviewRequest,
): Promise<AtomCommandResult<void, E>> => {
const result = await input.openPreview({
environmentId: input.threadRef.environmentId,
input: { threadId: input.threadRef.threadId, url: input.url },
});
if (!request.isCurrent()) {
return AsyncResult.success(undefined);
}
return mapAtomCommandResult(result, (snapshot) => {
applyPreviewServerSnapshot(input.threadRef, snapshot);
rememberPreviewUrl(input.threadRef, input.url);
useRightPanelStore.getState().openBrowser(input.threadRef, snapshot.tabId);
});
};
export async function openUrlInPreview<E>(input: {
readonly threadRef: ScopedThreadRef;
readonly url: string;
readonly openPreview: OpenPreviewMutation<E>;
readonly signal?: AbortSignal;
}): Promise<AtomCommandResult<void, E>> {
const request = beginPreviewRequest(input.threadRef, input.signal);
try {
return await openUrlForPreviewRequest(input, request);
} finally {
request.complete();
}
}
export async function openFileInPreview<AssetError, PreviewError>(input: {
@@ -61,38 +155,61 @@ export async function openFileInPreview<AssetError, PreviewError>(input: {
readonly input: { readonly resource: AssetResource };
}) => Promise<AtomCommandResult<AssetCreateUrlResult, AssetError>>;
readonly openPreview: OpenPreviewMutation<PreviewError>;
}): Promise<AtomCommandResult<void, AssetError | PreviewError | BrowserPreviewUnavailableError>> {
if (!isPreviewSupportedInRuntime()) {
return AsyncResult.failure(
Cause.fail(
new BrowserPreviewUnavailableError({
message: "The integrated browser is unavailable in this runtime.",
}),
),
);
}
const assetResult = await input.createAssetUrl({
environmentId: input.threadRef.environmentId,
input: {
resource: {
_tag: "workspace-file",
threadId: input.threadRef.threadId,
path: input.filePath,
readonly signal?: AbortSignal;
}): Promise<
AtomCommandResult<
void,
AssetError | PreviewError | BrowserPreviewUnavailableError | BrowserPreviewAssetUrlInvalidError
>
> {
const request = beginPreviewRequest(input.threadRef, input.signal);
try {
if (!isPreviewSupportedInRuntime()) {
return AsyncResult.failure(Cause.fail(new BrowserPreviewUnavailableError()));
}
const assetResult = await input.createAssetUrl({
environmentId: input.threadRef.environmentId,
input: {
resource: {
_tag: "workspace-file",
threadId: input.threadRef.threadId,
path: input.filePath,
},
},
},
});
if (assetResult._tag === "Failure") {
return AsyncResult.failure(assetResult.cause);
}
const assetUrl = resolveAssetUrl(input.httpBaseUrl, assetResult.value.relativeUrl);
if (assetUrl === null) {
return AsyncResult.failure(
Cause.die(new Error("The environment returned an invalid asset URL.")),
});
if (!request.isCurrent()) {
return AsyncResult.success(undefined);
}
if (assetResult._tag === "Failure") {
return AsyncResult.failure(assetResult.cause);
}
let assetUrl: string;
try {
assetUrl = new URL(assetResult.value.relativeUrl, input.httpBaseUrl).toString();
} catch (cause) {
return AsyncResult.failure(
Cause.fail(
new BrowserPreviewAssetUrlInvalidError({
environmentId: input.threadRef.environmentId,
threadId: input.threadRef.threadId,
filePath: input.filePath,
httpBaseUrlLength: input.httpBaseUrl.length,
relativeUrlLength: assetResult.value.relativeUrl.length,
expiresAt: assetResult.value.expiresAt,
cause,
}),
),
);
}
return await openUrlForPreviewRequest(
{
threadRef: input.threadRef,
url: assetUrl,
openPreview: input.openPreview,
},
request,
);
} finally {
request.complete();
}
return openUrlInPreview({
threadRef: input.threadRef,
url: assetUrl,
openPreview: input.openPreview,
});
}
+34 -20
View File
@@ -76,10 +76,11 @@ import { useAtomCommand } from "../state/use-atom-command";
import { useAtomQueryRunner } from "../state/use-atom-query-runner";
import { isPreviewSupportedInRuntime } from "../previewStateStore";
import {
isBrowserPreviewFile,
isWorkspacePreviewFile,
openFileInPreview,
openUrlInPreview,
BrowserPreviewUnavailableError,
BrowserPreviewEnvironmentDisconnectedError,
BrowserPreviewThreadContextUnavailableError,
} from "../browser/openFileInPreview";
class CodeHighlightErrorBoundary extends React.Component<
@@ -1060,11 +1061,15 @@ const MarkdownFileLink = memo(function MarkdownFileLink({
const error = squashAtomCommandFailure(result);
toastManager.add(
stackedThreadToast({
type: "error",
title: "Unable to open file in browser",
description: error instanceof Error ? error.message : "An error occurred.",
type: "warning",
title: "Unable to open file preview",
description:
error instanceof Error
? `${error.message} Opening the file instead.`
: "Opening the file instead.",
}),
);
handleOpenInFilePreview();
} catch (cause) {
reportMarkdownActionFailure(
{ operation: "open-file-in-browser", target: targetPath },
@@ -1072,14 +1077,18 @@ const MarkdownFileLink = memo(function MarkdownFileLink({
);
toastManager.add(
stackedThreadToast({
type: "error",
title: "Unable to open file in browser",
description: cause instanceof Error ? cause.message : "An error occurred.",
type: "warning",
title: "Unable to open file preview",
description:
cause instanceof Error
? `${cause.message} Opening the file instead.`
: "Opening the file instead.",
}),
);
handleOpenInFilePreview();
}
})();
}, [onOpenInBrowser, targetPath]);
}, [handleOpenInFilePreview, onOpenInBrowser, targetPath]);
const handleCopy = useCallback(
(value: string, title: string) => {
@@ -1284,12 +1293,8 @@ function ChatMarkdown({
(url: string) => {
if (!threadRef) {
return Promise.resolve(
AsyncResult.failure<void, BrowserPreviewUnavailableError>(
Cause.fail(
new BrowserPreviewUnavailableError({
message: "Thread context is unavailable.",
}),
),
AsyncResult.failure<void, BrowserPreviewThreadContextUnavailableError>(
Cause.fail(new BrowserPreviewThreadContextUnavailableError()),
),
);
}
@@ -1299,12 +1304,20 @@ function ChatMarkdown({
);
const openMarkdownFileInPreview = useCallback(
(path: string) => {
if (!threadRef || preparedConnection._tag === "None") {
if (!threadRef) {
return Promise.resolve(
AsyncResult.failure<void, BrowserPreviewUnavailableError>(
AsyncResult.failure<void, BrowserPreviewThreadContextUnavailableError>(
Cause.fail(new BrowserPreviewThreadContextUnavailableError()),
),
);
}
if (preparedConnection._tag === "None") {
return Promise.resolve(
AsyncResult.failure<void, BrowserPreviewEnvironmentDisconnectedError>(
Cause.fail(
new BrowserPreviewUnavailableError({
message: "Environment is not connected.",
new BrowserPreviewEnvironmentDisconnectedError({
environmentId: threadRef.environmentId,
threadId: threadRef.threadId,
}),
),
),
@@ -1468,9 +1481,10 @@ function ChatMarkdown({
threadRef={threadRef}
onOpen={openInPreferredEditor}
onOpenInBrowser={
fileLinkMeta.workspaceRelativePath !== null &&
threadRef &&
isPreviewSupportedInRuntime() &&
isBrowserPreviewFile(fileLinkMeta.filePath)
isWorkspacePreviewFile(fileLinkMeta.filePath)
? () => openMarkdownFileInPreview(fileLinkMeta.filePath)
: undefined
}
+76 -3
View File
@@ -110,6 +110,8 @@ import {
type RightPanelSurface,
useRightPanelStore,
} from "../rightPanelStore";
import { isImagePreviewFile, openFileInPreview } from "../browser/openFileInPreview";
import { resolvePathLinkTarget } from "../terminal-links";
import {
isPreviewSupportedInRuntime,
setActivePreviewTab,
@@ -179,7 +181,12 @@ import {
import { terminalEnvironment } from "../state/terminal";
import { threadEnvironment } from "../state/threads";
import { vcsEnvironment } from "../state/vcs";
import { useEnvironments, usePrimaryEnvironment } from "../state/environments";
import {
useEnvironmentHttpBaseUrl,
useEnvironments,
usePrimaryEnvironment,
} from "../state/environments";
import { assetEnvironment } from "../state/assets";
import {
useProject,
useProjects,
@@ -228,6 +235,7 @@ import { sanitizeThreadErrorMessage } from "~/rpc/transportError";
import { RightPanelSheet } from "./RightPanelSheet";
import { previewEnvironment } from "../state/preview";
import { useAtomCommand } from "../state/use-atom-command";
import { useAtomQueryRunner } from "../state/use-atom-query-runner";
import { Button } from "./ui/button";
import {
buildVersionMismatchDismissalKey,
@@ -1012,6 +1020,10 @@ function ChatViewContent(props: ChatViewProps) {
reportFailure: false,
});
const openPreview = useAtomCommand(previewEnvironment.open, { reportFailure: false });
const createAssetUrl = useAtomQueryRunner(assetEnvironment.createUrl, {
reportFailure: false,
});
const filePreviewAbortControllerRef = useRef<AbortController | null>(null);
const closePreview = useAtomCommand(previewEnvironment.close, "preview close");
const { environments } = useEnvironments();
const primaryEnvironment = usePrimaryEnvironment();
@@ -1339,6 +1351,9 @@ function ChatViewContent(props: ChatViewProps) {
? scopeProjectRef(activeThread.environmentId, activeThread.projectId)
: null;
const activeProject = useProject(activeProjectRef);
const activeEnvironmentHttpBaseUrl = useEnvironmentHttpBaseUrl(
activeProject?.environmentId ?? null,
);
const activeEnvironmentShell = useEnvironmentQuery(
activeThread ? environmentShell.stateAtom(activeThread.environmentId) : null,
);
@@ -2737,12 +2752,70 @@ function ChatViewContent(props: ChatViewProps) {
if (!activeThreadRef || !activeProject) return;
useRightPanelStore.getState().open(activeThreadRef, "files");
}, [activeProject, activeThreadRef]);
useEffect(
() => () => {
filePreviewAbortControllerRef.current?.abort();
},
[activeThreadKey],
);
const openFileSurface = useCallback(
(relativePath: string) => {
if (!activeThreadRef || !activeProject) return;
useRightPanelStore.getState().openFile(activeThreadRef, relativePath);
filePreviewAbortControllerRef.current?.abort();
const openFallback = () => {
useRightPanelStore.getState().openFile(activeThreadRef, relativePath);
};
if (
!isImagePreviewFile(relativePath) ||
!isPreviewSupportedInRuntime() ||
!activeWorkspaceRoot ||
!activeEnvironmentHttpBaseUrl
) {
openFallback();
return;
}
const abortController = new AbortController();
filePreviewAbortControllerRef.current = abortController;
const absolutePath = resolvePathLinkTarget(relativePath, activeWorkspaceRoot);
void (async () => {
const result = await openFileInPreview({
threadRef: activeThreadRef,
filePath: absolutePath,
httpBaseUrl: activeEnvironmentHttpBaseUrl,
createAssetUrl,
openPreview,
signal: abortController.signal,
});
if (abortController.signal.aborted) {
return;
}
if (result._tag === "Success") {
return;
}
if (isAtomCommandInterrupted(result)) {
openFallback();
return;
}
const error = squashAtomCommandFailure(result);
toastManager.add(
stackedThreadToast({
type: "warning",
title: "Unable to open image preview",
description: error instanceof Error ? error.message : "Opening the file instead.",
}),
);
openFallback();
})();
},
[activeProject, activeThreadRef],
[
activeEnvironmentHttpBaseUrl,
activeProject,
activeThreadRef,
activeWorkspaceRoot,
createAssetUrl,
openPreview,
],
);
const togglePreviewPanel = useCallback(() => {
if (!activeThreadRef || !isPreviewSupportedInRuntime()) return;
+98 -23
View File
@@ -21,6 +21,9 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useOpenInPreferredEditor } from "../editorPreferences";
import { type DraftId } from "../composerDraftStore";
import { openDiffFilePrimaryAction } from "../diffFileActions";
import { isImagePreviewFile, openFileInPreview } from "../browser/openFileInPreview";
import { resolvePathLinkTarget } from "../terminal-links";
import { isPreviewSupportedInRuntime } from "../previewStateStore";
import { useCheckpointDiff } from "~/lib/checkpointDiffState";
import { cn } from "~/lib/utils";
import { selectThreadDiffPanelSelection, useDiffPanelStore } from "../diffPanelStore";
@@ -61,10 +64,16 @@ import {
} from "./ui/menu";
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
import { useEnvironmentQuery } from "../state/query";
import { assetEnvironment } from "../state/assets";
import { previewEnvironment } from "../state/preview";
import { serverEnvironment } from "../state/server";
import { reviewEnvironment } from "../state/review";
import { vcsEnvironment } from "../state/vcs";
import { useEnvironmentHttpBaseUrl } from "../state/environments";
import { useAtomCommand } from "../state/use-atom-command";
import { useAtomQueryRunner } from "../state/use-atom-query-runner";
import { buildBaseRefChoices, filterBaseRefChoices } from "../lib/baseRefChoices";
import { stackedThreadToast, toastManager } from "./ui/toast";
type DiffRenderMode = "stacked" | "split";
type DiffThemeType = "light" | "dark";
@@ -213,6 +222,12 @@ export default function DiffPanel({ mode = "inline", composerDraftTarget }: Diff
: null,
);
const activeCwd = activeThread?.worktreePath ?? activeProject?.workspaceRoot;
const environmentHttpBaseUrl = useEnvironmentHttpBaseUrl(activeThread?.environmentId ?? null);
const createAssetUrl = useAtomQueryRunner(assetEnvironment.createUrl, {
reportFailure: false,
});
const openPreview = useAtomCommand(previewEnvironment.open, { reportFailure: false });
const filePreviewAbortControllerRef = useRef<AbortController | null>(null);
const serverConfig = useAtomValue(
serverEnvironment.configValueAtom(activeThread?.environmentId ?? null),
);
@@ -443,32 +458,92 @@ export default function DiffPanel({ mode = "inline", composerDraftTarget }: Diff
codeViewRef.current?.scrollTo({ type: "item", id: file.fileKey, align: "start" });
}, [codeViewFiles, selectedFilePath, selectedFileRevealRequestId]);
useEffect(
() => () => {
filePreviewAbortControllerRef.current?.abort();
},
[routeThreadRef?.environmentId, routeThreadRef?.threadId],
);
const openDiffFile = useCallback(
(filePath: string) => {
openDiffFilePrimaryAction({
threadRef: routeThreadRef,
filePath,
activeCwd,
openInEditor: (targetPath) => {
void (async () => {
const result = await openInPreferredEditor(targetPath);
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
console.warn("Failed to open diff file in editor.", {
operation: "open-diff-file",
...(routeThreadRef
? {
environmentId: routeThreadRef.environmentId,
threadId: routeThreadRef.threadId,
}
: {}),
...safeErrorLogAttributes(squashAtomCommandFailure(result)),
});
}
})();
},
});
filePreviewAbortControllerRef.current?.abort();
const openFallback = () => {
openDiffFilePrimaryAction({
threadRef: routeThreadRef,
filePath,
activeCwd,
openInEditor: (targetPath) => {
void (async () => {
const result = await openInPreferredEditor(targetPath);
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
console.warn("Failed to open diff file in editor.", {
operation: "open-diff-file",
...(routeThreadRef
? {
environmentId: routeThreadRef.environmentId,
threadId: routeThreadRef.threadId,
}
: {}),
...safeErrorLogAttributes(squashAtomCommandFailure(result)),
});
}
})();
},
});
};
if (
!routeThreadRef ||
!activeCwd ||
!environmentHttpBaseUrl ||
!isPreviewSupportedInRuntime() ||
!isImagePreviewFile(filePath)
) {
openFallback();
return;
}
const abortController = new AbortController();
filePreviewAbortControllerRef.current = abortController;
void (async () => {
const result = await openFileInPreview({
threadRef: routeThreadRef,
filePath: resolvePathLinkTarget(filePath, activeCwd),
httpBaseUrl: environmentHttpBaseUrl,
createAssetUrl,
openPreview,
signal: abortController.signal,
});
if (abortController.signal.aborted) {
return;
}
if (result._tag === "Success") {
return;
}
if (isAtomCommandInterrupted(result)) {
openFallback();
return;
}
const error = squashAtomCommandFailure(result);
toastManager.add(
stackedThreadToast({
type: "warning",
title: "Unable to open image preview",
description: error instanceof Error ? error.message : "Opening the file instead.",
}),
);
openFallback();
})();
},
[activeCwd, openInPreferredEditor, routeThreadRef],
[
activeCwd,
createAssetUrl,
environmentHttpBaseUrl,
openInPreferredEditor,
openPreview,
routeThreadRef,
],
);
const toggleDiffFileCollapsed = useCallback(
(fileKey: string) => {
@@ -15,7 +15,7 @@ import { ChevronRight, Code2, Eye, FolderTree, Globe2, LoaderCircle } from "luci
import * as Schema from "effect/Schema";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { isBrowserPreviewFile, openFileInPreview } from "~/browser/openFileInPreview";
import { isWorkspacePreviewFile, openFileInPreview } from "~/browser/openFileInPreview";
import ChatMarkdown from "~/components/ChatMarkdown";
import { OpenInPicker } from "~/components/chat/OpenInPicker";
import { useTheme } from "~/hooks/useTheme";
@@ -633,8 +633,8 @@ export default function FilePreviewPanel({
isMarkdown &&
markdownView.path === relativePath &&
(revealLine === null || markdownView.revealRequestId === revealRequestId);
const canOpenInBrowser =
relativePath !== null && isPreviewSupportedInRuntime() && isBrowserPreviewFile(relativePath);
const canOpenInPreview =
relativePath !== null && isPreviewSupportedInRuntime() && isWorkspacePreviewFile(relativePath);
const absolutePath = relativePath ? resolvePathLinkTarget(relativePath, cwd) : null;
const breadcrumbs = useMemo(
() => (relativePath ? fileBreadcrumbs(projectName, relativePath) : []),
@@ -661,7 +661,7 @@ export default function FilePreviewPanel({
});
};
const handleOpenInBrowser = useCallback(() => {
const handleOpenInPreview = useCallback(() => {
if (!absolutePath || !environmentHttpBaseUrl) return;
void (async () => {
const result = await openFileInPreview({
@@ -678,7 +678,7 @@ export default function FilePreviewPanel({
toastManager.add(
stackedThreadToast({
type: "error",
title: "Unable to open file in browser",
title: "Unable to open file in preview",
description: error instanceof Error ? error.message : "An error occurred.",
}),
);
@@ -757,15 +757,15 @@ export default function FilePreviewPanel({
</TooltipPopup>
</Tooltip>
) : null}
{canOpenInBrowser ? (
{canOpenInPreview ? (
<Tooltip>
<TooltipTrigger
render={
<Toggle
className="shrink-0"
pressed={false}
onPressedChange={handleOpenInBrowser}
aria-label="Open file in preview browser"
onPressedChange={handleOpenInPreview}
aria-label="Open file in preview"
variant="ghost"
size="sm"
>
@@ -773,7 +773,7 @@ export default function FilePreviewPanel({
</Toggle>
}
/>
<TooltipPopup>Open file in preview browser</TooltipPopup>
<TooltipPopup>Open file in preview</TooltipPopup>
</Tooltip>
) : null}
<Tooltip>