fix: refresh sidebar file and image previews
This commit is contained in:
1 parent
4ba4871af7
commit
321775b2e0
19 files changed
+532
-26
No files matched your search
@@ -0,0 +1,25 @@
|
||||
## What Changed
|
||||
|
||||
- subscribe mounted workspace file previews to debounced filesystem change events from the connected T3 server
|
||||
- re-read text previews when files change and perform a fresh read after remounting
|
||||
- refresh open image previews with revisioned URLs and require revalidation for mutable workspace assets
|
||||
- keep immutable attachment caching unchanged
|
||||
|
||||
This supersedes #4379, preserves Alex's original commits, rebases them onto current `main`, and adds the missing image-preview behavior.
|
||||
|
||||
## Why
|
||||
|
||||
Agent edits happen directly on disk, bypassing the file-write RPC that could invalidate client state. Text previews therefore kept cached query data, while image previews reused a mutable signed URL served with a one-hour cache lifetime. Watching the file on the connected server fixes both local and T3 connection flows without polling.
|
||||
|
||||
## Testing
|
||||
|
||||
- `vp test run apps/server/src/workspace/WorkspaceFileSystem.test.ts apps/server/src/assets/AssetAccess.test.ts apps/server/src/auth/RpcAuthorization.test.ts packages/client-runtime/src/state/runtime.test.ts apps/web/src/components/files/projectFilesQueryState.test.ts apps/web/src/components/files/workspaceImagePreview.test.ts`
|
||||
- contracts, client-runtime, server, web, and mobile typechecks
|
||||
- targeted lint and formatting checks
|
||||
|
||||
## Checklist
|
||||
|
||||
- [x] This PR is small and focused
|
||||
- [x] I explained what changed and why
|
||||
- [x] Screenshots are not applicable because this fixes stale data without changing the UI
|
||||
- [x] Video is not applicable because no animation or interaction design changed
|
||||
@@ -1,5 +1,6 @@
|
||||
import { executeAtomQuery } from "@t3tools/client-runtime/state/runtime";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
|
||||
import { appAtomRegistry } from "../../state/atom-registry";
|
||||
import { projectEnvironment } from "../../state/projects";
|
||||
@@ -10,6 +11,7 @@ import type { ReviewDiffTheme } from "../review/shikiReviewHighlighter";
|
||||
|
||||
const inFlightPreloads = new Map<string, Promise<void>>();
|
||||
const MAX_HIGHLIGHT_PRELOAD_CHARACTERS = 256 * 1024;
|
||||
const WORKSPACE_FILE_PRELOAD_RETAIN_MS = 1_000;
|
||||
|
||||
function preloadKey(input: {
|
||||
readonly cwd: string;
|
||||
@@ -36,10 +38,12 @@ export function preloadWorkspaceFileContents(input: {
|
||||
|
||||
const preload = executeAtomQuery(
|
||||
appAtomRegistry,
|
||||
projectEnvironment.readFile({
|
||||
environmentId: input.environmentId,
|
||||
input: { cwd: input.cwd, relativePath: input.relativePath },
|
||||
}),
|
||||
projectEnvironment
|
||||
.readFile({
|
||||
environmentId: input.environmentId,
|
||||
input: { cwd: input.cwd, relativePath: input.relativePath },
|
||||
})
|
||||
.pipe(Atom.setIdleTTL(WORKSPACE_FILE_PRELOAD_RETAIN_MS)),
|
||||
{
|
||||
label: "workspace file preload",
|
||||
reportDefect: false,
|
||||
|
||||
@@ -59,10 +59,12 @@ describe("AssetAccess", () => {
|
||||
expect(yield* resolveAsset(token, "report.html")).toEqual({
|
||||
kind: "file",
|
||||
path: canonicalHtmlPath,
|
||||
cacheControl: "private, no-cache",
|
||||
});
|
||||
expect(yield* resolveAsset(token, "report.css")).toEqual({
|
||||
kind: "file",
|
||||
path: canonicalCssPath,
|
||||
cacheControl: "private, no-cache",
|
||||
});
|
||||
expect(yield* resolveAsset(token, "../secret.txt")).toBeNull();
|
||||
expect(yield* resolveAsset(token, ".env")).toBeNull();
|
||||
@@ -176,6 +178,7 @@ describe("AssetAccess", () => {
|
||||
expect(yield* resolveAsset(token, "icon.png")).toEqual({
|
||||
kind: "file",
|
||||
path: canonicalImagePath,
|
||||
cacheControl: "private, no-cache",
|
||||
});
|
||||
expect(yield* resolveAsset(token, "other.png")).toBeNull();
|
||||
expect(yield* resolveAsset(token, "../icon.png")).toBeNull();
|
||||
@@ -202,6 +205,7 @@ describe("AssetAccess", () => {
|
||||
expect(yield* resolveAsset(token, "ignored.png")).toEqual({
|
||||
kind: "file",
|
||||
path: attachmentPath,
|
||||
cacheControl: "private, max-age=3600",
|
||||
});
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
@@ -227,7 +231,11 @@ describe("AssetAccess", () => {
|
||||
faviconSuffix.slice(0, faviconSeparatorIndex),
|
||||
faviconSuffix.slice(faviconSeparatorIndex + 1),
|
||||
),
|
||||
).toEqual({ kind: "file", path: canonicalFaviconPath });
|
||||
).toEqual({
|
||||
kind: "file",
|
||||
path: canonicalFaviconPath,
|
||||
cacheControl: "private, no-cache",
|
||||
});
|
||||
|
||||
yield* fileSystem.remove(faviconPath);
|
||||
const fallbackResult = yield* issueAssetUrl({
|
||||
|
||||
@@ -91,7 +91,11 @@ const AssetClaimsJson = Schema.fromJsonString(AssetClaimsSchema);
|
||||
const decodeAssetClaims = Schema.decodeUnknownOption(AssetClaimsJson);
|
||||
const encodeAssetClaims = Schema.encodeSync(AssetClaimsJson);
|
||||
|
||||
export type ResolvedAsset = { readonly kind: "file"; readonly path: string };
|
||||
export type ResolvedAsset = {
|
||||
readonly kind: "file";
|
||||
readonly path: string;
|
||||
readonly cacheControl: "private, max-age=3600" | "private, no-cache";
|
||||
};
|
||||
|
||||
function decodeClaims(encodedPayload: string): AssetClaims | null {
|
||||
try {
|
||||
@@ -384,7 +388,11 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
|
||||
Effect.orElseSucceed(() => Option.none()),
|
||||
);
|
||||
return Option.isSome(info) && info.value.type === "File"
|
||||
? ({ kind: "file", path: attachmentPath } satisfies ResolvedAsset)
|
||||
? ({
|
||||
kind: "file",
|
||||
path: attachmentPath,
|
||||
cacheControl: "private, max-age=3600",
|
||||
} satisfies ResolvedAsset)
|
||||
: null;
|
||||
}
|
||||
|
||||
@@ -394,7 +402,13 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
|
||||
workspaceRoot: claims.workspaceRoot,
|
||||
relativePath: claims.relativePath,
|
||||
});
|
||||
return faviconPath ? ({ kind: "file", path: faviconPath } satisfies ResolvedAsset) : null;
|
||||
return faviconPath
|
||||
? ({
|
||||
kind: "file",
|
||||
path: faviconPath,
|
||||
cacheControl: "private, no-cache",
|
||||
} satisfies ResolvedAsset)
|
||||
: null;
|
||||
}
|
||||
|
||||
const decodedPath = decodeRelativePath(relativePath);
|
||||
@@ -407,7 +421,11 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
|
||||
relativePath: claims.relativePath,
|
||||
});
|
||||
return exactWorkspaceFile
|
||||
? ({ kind: "file", path: exactWorkspaceFile } satisfies ResolvedAsset)
|
||||
? ({
|
||||
kind: "file",
|
||||
path: exactWorkspaceFile,
|
||||
cacheControl: "private, no-cache",
|
||||
} satisfies ResolvedAsset)
|
||||
: null;
|
||||
}
|
||||
const segments = decodedPath.split(/[\\/]/);
|
||||
@@ -425,5 +443,11 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
|
||||
workspaceRoot: claims.workspaceRoot,
|
||||
relativePath: joinedRelativePath,
|
||||
});
|
||||
return workspaceFile ? ({ kind: "file", path: workspaceFile } satisfies ResolvedAsset) : null;
|
||||
return workspaceFile
|
||||
? ({
|
||||
kind: "file",
|
||||
path: workspaceFile,
|
||||
cacheControl: "private, no-cache",
|
||||
} satisfies ResolvedAsset)
|
||||
: null;
|
||||
});
|
||||
@@ -55,6 +55,7 @@ export const RPC_REQUIRED_SCOPES = {
|
||||
[WS_METHODS.sourceControlPublishRepository]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.projectsListEntries]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.projectsReadFile]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.projectsWatchFile]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.projectsSearchContents]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.projectsSearchEntries]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.projectsWriteFile]: AuthOrchestrationOperateScope,
|
||||
|
||||
@@ -273,7 +273,7 @@ export const assetRouteLayer = HttpRouter.add(
|
||||
return yield* HttpServerResponse.file(asset.path, {
|
||||
status: 200,
|
||||
headers: {
|
||||
"Cache-Control": "private, max-age=3600",
|
||||
"Cache-Control": asset.cacheControl,
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
},
|
||||
}).pipe(
|
||||
|
||||
@@ -2,8 +2,11 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it, describe, expect } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
|
||||
@@ -265,4 +268,42 @@ it.layer(TestLayer, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
describe("watchFile", () => {
|
||||
it.effect("emits when a missing workspace file is created", () =>
|
||||
Effect.gen(function* () {
|
||||
const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
|
||||
const cwd = yield* makeTempDir;
|
||||
const eventFiber = yield* workspaceFileSystem
|
||||
.watchFile({ cwd, relativePath: "t3.json" })
|
||||
.pipe(Stream.runHead, Effect.timeout("5 seconds"), Effect.forkChild);
|
||||
|
||||
yield* Effect.sleep("100 millis");
|
||||
yield* writeTextFile(cwd, "t3.json", '{"scripts":[]}');
|
||||
|
||||
const event = yield* Fiber.join(eventFiber);
|
||||
expect(Option.getOrUndefined(event)).toEqual({ relativePath: "t3.json" });
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("emits when an in-workspace symlink target changes", () =>
|
||||
Effect.gen(function* () {
|
||||
const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const cwd = yield* makeTempDir;
|
||||
yield* writeTextFile(cwd, "src/target.txt", "initial");
|
||||
yield* fileSystem.symlink(path.join(cwd, "src/target.txt"), path.join(cwd, "linked.txt"));
|
||||
const eventFiber = yield* workspaceFileSystem
|
||||
.watchFile({ cwd, relativePath: "linked.txt" })
|
||||
.pipe(Stream.runHead, Effect.timeout("5 seconds"), Effect.forkChild);
|
||||
|
||||
yield* Effect.sleep("100 millis");
|
||||
yield* writeTextFile(cwd, "src/target.txt", "updated");
|
||||
|
||||
const event = yield* Fiber.join(eventFiber);
|
||||
expect(Option.getOrUndefined(event)).toEqual({ relativePath: "linked.txt" });
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -10,17 +10,20 @@
|
||||
import * as NodeFSP from "node:fs/promises";
|
||||
|
||||
import type {
|
||||
ProjectFileChangeEvent,
|
||||
ProjectReadFileInput,
|
||||
ProjectReadFileResult,
|
||||
ProjectWriteFileInput,
|
||||
ProjectWriteFileResult,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import * as WorkspaceEntries from "./WorkspaceEntries.ts";
|
||||
import * as WorkspacePaths from "./WorkspacePaths.ts";
|
||||
@@ -37,10 +40,12 @@ export class WorkspaceFileSystemOperationError extends Schema.TaggedErrorClass<W
|
||||
operation: Schema.Literals([
|
||||
"realpath-workspace-root",
|
||||
"realpath-target",
|
||||
"realpath-watch-directory",
|
||||
"open",
|
||||
"stat",
|
||||
"read",
|
||||
"close",
|
||||
"watch",
|
||||
"make-directory",
|
||||
"write-file",
|
||||
]),
|
||||
@@ -111,6 +116,13 @@ export class WorkspaceFileSystem extends Context.Service<
|
||||
ProjectReadFileResult,
|
||||
WorkspaceFileSystemError | WorkspacePaths.WorkspacePathOutsideRootError
|
||||
>;
|
||||
/** Watch a workspace-relative file and emit after its directory entry changes. */
|
||||
readonly watchFile: (
|
||||
input: ProjectReadFileInput,
|
||||
) => Stream.Stream<
|
||||
ProjectFileChangeEvent,
|
||||
WorkspaceFileSystemError | WorkspacePaths.WorkspacePathOutsideRootError
|
||||
>;
|
||||
/**
|
||||
* Write a file relative to the workspace root.
|
||||
*
|
||||
@@ -259,6 +271,126 @@ export const make = Effect.gen(function* () {
|
||||
);
|
||||
});
|
||||
|
||||
const watchFile: WorkspaceFileSystem["Service"]["watchFile"] = (input) =>
|
||||
Stream.unwrap(
|
||||
Effect.gen(function* () {
|
||||
const target = yield* workspacePaths.resolveRelativePathWithinRoot({
|
||||
workspaceRoot: input.cwd,
|
||||
relativePath: input.relativePath,
|
||||
});
|
||||
const watchDirectory = path.dirname(target.absolutePath);
|
||||
const realWorkspaceRoot = yield* Effect.tryPromise({
|
||||
try: () => NodeFSP.realpath(input.cwd),
|
||||
catch: (cause) =>
|
||||
new WorkspaceFileSystemOperationError({
|
||||
workspaceRoot: input.cwd,
|
||||
relativePath: input.relativePath,
|
||||
resolvedPath: target.absolutePath,
|
||||
operationPath: input.cwd,
|
||||
operation: "realpath-workspace-root",
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
const realWatchDirectory = yield* Effect.tryPromise({
|
||||
try: () => NodeFSP.realpath(watchDirectory),
|
||||
catch: (cause) =>
|
||||
new WorkspaceFileSystemOperationError({
|
||||
workspaceRoot: input.cwd,
|
||||
relativePath: input.relativePath,
|
||||
resolvedPath: target.absolutePath,
|
||||
operationPath: watchDirectory,
|
||||
operation: "realpath-watch-directory",
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
const relativeRealDirectory = path.relative(realWorkspaceRoot, realWatchDirectory);
|
||||
if (
|
||||
relativeRealDirectory.startsWith(`..${path.sep}`) ||
|
||||
relativeRealDirectory === ".." ||
|
||||
path.isAbsolute(relativeRealDirectory)
|
||||
) {
|
||||
return yield* new WorkspaceFilePathEscapeError({
|
||||
workspaceRoot: input.cwd,
|
||||
relativePath: input.relativePath,
|
||||
resolvedWorkspaceRoot: realWorkspaceRoot,
|
||||
resolvedPath: realWatchDirectory,
|
||||
});
|
||||
}
|
||||
|
||||
const realTargetPath = yield* Effect.tryPromise({
|
||||
try: async () => {
|
||||
try {
|
||||
return await NodeFSP.realpath(target.absolutePath);
|
||||
} catch (cause) {
|
||||
if ((cause as NodeJS.ErrnoException).code === "ENOENT") {
|
||||
return null;
|
||||
}
|
||||
throw cause;
|
||||
}
|
||||
},
|
||||
catch: (cause) =>
|
||||
new WorkspaceFileSystemOperationError({
|
||||
workspaceRoot: input.cwd,
|
||||
relativePath: input.relativePath,
|
||||
resolvedPath: target.absolutePath,
|
||||
operationPath: target.absolutePath,
|
||||
operation: "realpath-target",
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
if (realTargetPath !== null) {
|
||||
const relativeRealTarget = path.relative(realWorkspaceRoot, realTargetPath);
|
||||
if (
|
||||
relativeRealTarget.startsWith(`..${path.sep}`) ||
|
||||
relativeRealTarget === ".." ||
|
||||
path.isAbsolute(relativeRealTarget)
|
||||
) {
|
||||
return yield* new WorkspaceFilePathEscapeError({
|
||||
workspaceRoot: input.cwd,
|
||||
relativePath: input.relativePath,
|
||||
resolvedWorkspaceRoot: realWorkspaceRoot,
|
||||
resolvedPath: realTargetPath,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const watchEntry = (watchPath: string, fileName: string) => {
|
||||
const watchedAbsolutePath = path.join(watchPath, fileName);
|
||||
return fileSystem.watch(watchPath).pipe(
|
||||
Stream.filter((event) => {
|
||||
return (
|
||||
event.path === fileName ||
|
||||
event.path === watchedAbsolutePath ||
|
||||
path.resolve(watchPath, event.path) === watchedAbsolutePath
|
||||
);
|
||||
}),
|
||||
Stream.mapError(
|
||||
(cause) =>
|
||||
new WorkspaceFileSystemOperationError({
|
||||
workspaceRoot: input.cwd,
|
||||
relativePath: input.relativePath,
|
||||
resolvedPath: target.absolutePath,
|
||||
operationPath: watchPath,
|
||||
operation: "watch",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
const lexicalTargetPath = path.join(realWatchDirectory, path.basename(target.absolutePath));
|
||||
const lexicalEvents = watchEntry(realWatchDirectory, path.basename(target.absolutePath));
|
||||
const resolvedTargetEvents =
|
||||
realTargetPath !== null && realTargetPath !== lexicalTargetPath
|
||||
? watchEntry(path.dirname(realTargetPath), path.basename(realTargetPath))
|
||||
: Stream.empty;
|
||||
return Stream.merge(lexicalEvents, resolvedTargetEvents).pipe(
|
||||
Stream.debounce(Duration.millis(100)),
|
||||
Stream.map(() => ({ relativePath: target.relativePath })),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
const writeFile: WorkspaceFileSystem["Service"]["writeFile"] = Effect.fn(
|
||||
"WorkspaceFileSystem.writeFile",
|
||||
)(function* (input) {
|
||||
@@ -297,7 +429,7 @@ export const make = Effect.gen(function* () {
|
||||
return { relativePath: target.relativePath };
|
||||
});
|
||||
|
||||
return WorkspaceFileSystem.of({ readFile, writeFile });
|
||||
return WorkspaceFileSystem.of({ readFile, watchFile, writeFile });
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(WorkspaceFileSystem, make);
|
||||
@@ -1645,6 +1645,21 @@ const makeWsRpcLayer = (
|
||||
),
|
||||
{ "rpc.aggregate": "workspace" },
|
||||
),
|
||||
[WS_METHODS.projectsWatchFile]: (input) =>
|
||||
observeRpcStream(
|
||||
WS_METHODS.projectsWatchFile,
|
||||
workspaceFileSystem.watchFile(input).pipe(
|
||||
Stream.mapError(
|
||||
(cause) =>
|
||||
new ProjectReadFileError({
|
||||
...input,
|
||||
...projectFileFailureContext(cause),
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
{ "rpc.aggregate": "workspace" },
|
||||
),
|
||||
[WS_METHODS.projectsWriteFile]: (input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.projectsWriteFile,
|
||||
|
||||
@@ -41,6 +41,7 @@ import { useAtomCommand } from "~/state/use-atom-command";
|
||||
import { useAtomQueryRunner } from "~/state/use-atom-query-runner";
|
||||
|
||||
import FileBrowserPanel from "./FileBrowserPanel";
|
||||
import { workspaceImagePreviewUrl } from "./workspaceImagePreview";
|
||||
import {
|
||||
type FileCommentAnnotationEntry,
|
||||
type FileCommentAnnotationGroup,
|
||||
@@ -61,6 +62,7 @@ import {
|
||||
confirmProjectFileQueryData,
|
||||
getOptimisticProjectFileQueryData,
|
||||
setProjectFileQueryData,
|
||||
useProjectFileChangeRevision,
|
||||
useProjectFileQuery,
|
||||
} from "./projectFilesQueryState";
|
||||
|
||||
@@ -120,6 +122,8 @@ type FilePostRender = NonNullable<FileOptions<unknown>["onPostRender"]>;
|
||||
function WorkspaceImagePreview(props: {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly threadRef: ScopedThreadRef;
|
||||
readonly cwd: string;
|
||||
readonly relativePath: string;
|
||||
readonly absolutePath: string;
|
||||
readonly alt: string;
|
||||
}) {
|
||||
@@ -128,9 +132,12 @@ function WorkspaceImagePreview(props: {
|
||||
threadId: props.threadRef.threadId,
|
||||
path: props.absolutePath,
|
||||
});
|
||||
const revision = useProjectFileChangeRevision(props.environmentId, props.cwd, props.relativePath);
|
||||
const resolvedUrl =
|
||||
assetUrl._tag === "Success" ? workspaceImagePreviewUrl(assetUrl.url, revision) : null;
|
||||
const [failedUrl, setFailedUrl] = useState<string | null>(null);
|
||||
|
||||
if (assetUrl._tag === "Failure" || (assetUrl._tag === "Success" && failedUrl === assetUrl.url)) {
|
||||
if (assetUrl._tag === "Failure" || (resolvedUrl !== null && failedUrl === resolvedUrl)) {
|
||||
return (
|
||||
<div className="flex min-h-0 flex-1 items-center justify-center px-6 text-center text-xs leading-relaxed text-destructive">
|
||||
Unable to load workspace image.
|
||||
@@ -142,9 +149,9 @@ function WorkspaceImagePreview(props: {
|
||||
<div className="flex min-h-0 flex-1 items-center justify-center overflow-auto p-4">
|
||||
<img
|
||||
className="max-h-full max-w-full object-contain"
|
||||
src={assetUrl.url}
|
||||
src={resolvedUrl ?? undefined}
|
||||
alt={props.alt}
|
||||
onError={() => setFailedUrl(assetUrl.url)}
|
||||
onError={() => setFailedUrl(resolvedUrl)}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
@@ -975,6 +982,8 @@ export default function FilePreviewPanel({
|
||||
key={absolutePath}
|
||||
environmentId={environmentId}
|
||||
threadRef={threadRef}
|
||||
cwd={cwd}
|
||||
relativePath={relativePath}
|
||||
absolutePath={absolutePath}
|
||||
alt={relativePath}
|
||||
/>
|
||||
|
||||
@@ -1,23 +1,27 @@
|
||||
import { useAtomRefresh, useAtomValue } from "@effect/atom-react";
|
||||
import type {
|
||||
EnvironmentId,
|
||||
ProjectFileChangeEvent,
|
||||
ProjectListEntriesResult,
|
||||
ProjectReadFileResult,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Option from "effect/Option";
|
||||
import { AsyncResult, Atom } from "effect/unstable/reactivity";
|
||||
import { useCallback } from "react";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
|
||||
import { appAtomRegistry } from "~/rpc/atomRegistry";
|
||||
import { projectEnvironment } from "~/state/projects";
|
||||
import { useProjectPathSearch } from "~/state/queries";
|
||||
import { executeAtomQuery } from "@t3tools/client-runtime/state/runtime";
|
||||
import { useProjectPathSearch } from "~/state/queries";
|
||||
|
||||
const EMPTY_PROJECT_FILE_PATH = "";
|
||||
const EMPTY_PROJECT_FILE_QUERY_ATOM = Atom.make(
|
||||
AsyncResult.initial<ProjectReadFileResult, never>(false),
|
||||
).pipe(Atom.withLabel("project-file-query:empty"));
|
||||
const EMPTY_PROJECT_FILE_CHANGE_ATOM = Atom.make(
|
||||
AsyncResult.initial<ProjectFileChangeEvent, never>(false),
|
||||
).pipe(Atom.withLabel("project-file-change:empty"));
|
||||
function optimisticFileAtom(environmentId: EnvironmentId, cwd: string, relativePath: string) {
|
||||
return projectEnvironment.optimisticFile({ environmentId, cwd, relativePath });
|
||||
}
|
||||
@@ -163,15 +167,39 @@ export function useProjectFilePickerQuery(
|
||||
};
|
||||
}
|
||||
|
||||
export function useProjectFileChangeRevision(
|
||||
environmentId: EnvironmentId,
|
||||
cwd: string,
|
||||
relativePath: string | null,
|
||||
): number {
|
||||
const atom = relativePath
|
||||
? projectEnvironment.watchFile({ environmentId, input: { cwd, relativePath } })
|
||||
: EMPTY_PROJECT_FILE_CHANGE_ATOM;
|
||||
const result = useAtomValue(atom);
|
||||
const previousResultRef = useRef(result);
|
||||
const [revision, setRevision] = useState(0);
|
||||
|
||||
useEffect(() => {
|
||||
if (previousResultRef.current === result) return;
|
||||
previousResultRef.current = result;
|
||||
if (AsyncResult.isSuccess(result)) {
|
||||
setRevision((current) => current + 1);
|
||||
}
|
||||
}, [result]);
|
||||
|
||||
return revision;
|
||||
}
|
||||
|
||||
export function useProjectFileQuery(
|
||||
environmentId: EnvironmentId,
|
||||
cwd: string,
|
||||
relativePath: string | null,
|
||||
enabled = true,
|
||||
): ProjectQueryState<ProjectReadFileResult> {
|
||||
const atom = enabled
|
||||
? getProjectFileQueryAtom(environmentId, cwd, relativePath)
|
||||
: EMPTY_PROJECT_FILE_QUERY_ATOM;
|
||||
const atom =
|
||||
enabled && relativePath !== null
|
||||
? getProjectFileQueryAtom(environmentId, cwd, relativePath)
|
||||
: EMPTY_PROJECT_FILE_QUERY_ATOM;
|
||||
const result = useAtomValue(atom);
|
||||
const refreshAtom = useAtomRefresh(atom);
|
||||
const refresh = useCallback(() => refreshAtom(), [refreshAtom]);
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { workspaceImagePreviewUrl } from "./workspaceImagePreview";
|
||||
|
||||
describe("workspaceImagePreviewUrl", () => {
|
||||
it("changes the image URL for every filesystem revision", () => {
|
||||
expect(workspaceImagePreviewUrl("https://example.test/image.png", 0)).toBe(
|
||||
"https://example.test/image.png?t3-file-revision=0",
|
||||
);
|
||||
expect(workspaceImagePreviewUrl("https://example.test/image.png", 2)).toBe(
|
||||
"https://example.test/image.png?t3-file-revision=2",
|
||||
);
|
||||
});
|
||||
|
||||
it("preserves existing query parameters", () => {
|
||||
expect(workspaceImagePreviewUrl("https://example.test/image.png?token=abc", 1)).toBe(
|
||||
"https://example.test/image.png?token=abc&t3-file-revision=1",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,4 @@
|
||||
export function workspaceImagePreviewUrl(assetUrl: string, revision: number): string {
|
||||
const separator = assetUrl.includes("?") ? "&" : "?";
|
||||
return `${assetUrl}${separator}t3-file-revision=${revision}`;
|
||||
}
|
||||
@@ -49,6 +49,7 @@ export type EnvironmentSubscriptionRpcTag =
|
||||
| typeof WS_METHODS.subscribeTerminalMetadata
|
||||
| typeof WS_METHODS.subscribePreviewEvents
|
||||
| typeof WS_METHODS.subscribeDiscoveredLocalServers
|
||||
| typeof WS_METHODS.projectsWatchFile
|
||||
| typeof WS_METHODS.subscribeResourceTelemetry
|
||||
| typeof WS_METHODS.previewAutomationConnect
|
||||
| typeof WS_METHODS.subscribeVcsStatus
|
||||
|
||||
@@ -7,6 +7,8 @@ import {
|
||||
createEnvironmentCommand,
|
||||
createEnvironmentRpcCommand,
|
||||
createEnvironmentRpcQueryAtomFamily,
|
||||
createEnvironmentRpcSubscriptionAtomFamily,
|
||||
refreshQueryOnSuccess,
|
||||
} from "./runtime.ts";
|
||||
import {
|
||||
type CreateProjectInput,
|
||||
@@ -54,6 +56,32 @@ export function createProjectEnvironmentAtoms<R, E>(
|
||||
key: ({ environmentId, input }: { environmentId: string; input: { projectId: string } }) =>
|
||||
JSON.stringify([environmentId, input.projectId]),
|
||||
};
|
||||
const readFileQuery = createEnvironmentRpcQueryAtomFamily(runtime, {
|
||||
label: "environment-data:projects:read-file-query",
|
||||
tag: WS_METHODS.projectsReadFile,
|
||||
// Workspace files can change outside T3 Code, so always revalidate cached reads on mount.
|
||||
staleTimeMs: 0,
|
||||
idleTtlMs: 0,
|
||||
});
|
||||
const fileChanges = createEnvironmentRpcSubscriptionAtomFamily(runtime, {
|
||||
label: "environment-data:projects:file-changes",
|
||||
tag: WS_METHODS.projectsWatchFile,
|
||||
idleTtlMs: 0,
|
||||
});
|
||||
type ReadFileAtom = ReturnType<typeof readFileQuery>;
|
||||
const liveReadFileAtoms = new WeakMap<ReadFileAtom, ReadFileAtom>();
|
||||
const readFile = (target: Parameters<typeof readFileQuery>[0]): ReadFileAtom => {
|
||||
const queryAtom = readFileQuery(target);
|
||||
const cached = liveReadFileAtoms.get(queryAtom);
|
||||
if (cached) return cached;
|
||||
|
||||
const changesAtom = fileChanges(target);
|
||||
const liveAtom = refreshQueryOnSuccess(queryAtom, changesAtom).pipe(
|
||||
Atom.withLabel(`environment-data:projects:read-file:${target.input.relativePath}`),
|
||||
);
|
||||
liveReadFileAtoms.set(queryAtom, liveAtom);
|
||||
return liveAtom;
|
||||
};
|
||||
return {
|
||||
searchEntries: createEnvironmentRpcQueryAtomFamily(runtime, {
|
||||
label: "environment-data:projects:search-entries",
|
||||
@@ -66,12 +94,8 @@ export function createProjectEnvironmentAtoms<R, E>(
|
||||
staleTimeMs: 30_000,
|
||||
idleTtlMs: 5 * 60_000,
|
||||
}),
|
||||
readFile: createEnvironmentRpcQueryAtomFamily(runtime, {
|
||||
label: "environment-data:projects:read-file",
|
||||
tag: WS_METHODS.projectsReadFile,
|
||||
staleTimeMs: 30_000,
|
||||
idleTtlMs: 5 * 60_000,
|
||||
}),
|
||||
readFile,
|
||||
watchFile: fileChanges,
|
||||
optimisticFile: (target: OptimisticProjectFileTarget) =>
|
||||
optimisticFileFamily(optimisticProjectFileKey(target)),
|
||||
create: createEnvironmentCommand(runtime, {
|
||||
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
executeAtomQuery,
|
||||
isAtomCommandInterrupted,
|
||||
mapAtomCommandResult,
|
||||
refreshQueryOnSuccess,
|
||||
runAtomCommand,
|
||||
settleAsyncResult,
|
||||
settlePromise,
|
||||
@@ -62,6 +63,135 @@ describe("settleAsyncResult", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("refreshQueryOnSuccess", () => {
|
||||
it.effect("refreshes the query for new success signals without replaying a cached signal", () =>
|
||||
Effect.gen(function* () {
|
||||
let reads = 0;
|
||||
const query = Atom.make(
|
||||
Effect.sync(() => {
|
||||
reads += 1;
|
||||
return reads;
|
||||
}),
|
||||
);
|
||||
const signal = Atom.make<AsyncResult.AsyncResult<string, never>>(
|
||||
AsyncResult.initial<string, never>(false),
|
||||
);
|
||||
const liveQuery = refreshQueryOnSuccess(query, signal);
|
||||
const registry = AtomRegistry.make();
|
||||
const unmount = registry.mount(liveQuery);
|
||||
|
||||
expect(
|
||||
yield* AtomRegistry.getResult(registry, liveQuery, {
|
||||
suspendOnWaiting: true,
|
||||
}),
|
||||
).toBe(1);
|
||||
expect(reads).toBe(1);
|
||||
|
||||
registry.set(signal, AsyncResult.success("changed"));
|
||||
expect(
|
||||
yield* AtomRegistry.getResult(registry, liveQuery, {
|
||||
suspendOnWaiting: true,
|
||||
}),
|
||||
).toBe(2);
|
||||
|
||||
unmount();
|
||||
registry.dispose();
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps a preloaded zero-TTL query warm through the consumer handoff", () =>
|
||||
Effect.gen(function* () {
|
||||
let reads = 0;
|
||||
const query = Atom.make(
|
||||
Effect.sync(() => {
|
||||
reads += 1;
|
||||
return reads;
|
||||
}),
|
||||
).pipe(Atom.setIdleTTL(0));
|
||||
const signal = Atom.make<AsyncResult.AsyncResult<string, never>>(
|
||||
AsyncResult.initial<string, never>(false),
|
||||
).pipe(Atom.setIdleTTL(0));
|
||||
const liveQuery = refreshQueryOnSuccess(query, signal);
|
||||
const preloadedQuery = liveQuery.pipe(Atom.setIdleTTL(1_000));
|
||||
const registry = AtomRegistry.make();
|
||||
|
||||
const preload = yield* Effect.promise(() =>
|
||||
executeAtomQuery(registry, preloadedQuery, {
|
||||
label: "preload",
|
||||
}),
|
||||
);
|
||||
expect(AsyncResult.isSuccess(preload)).toBe(true);
|
||||
expect(reads).toBe(1);
|
||||
|
||||
const unmountConsumer = registry.mount(liveQuery);
|
||||
expect(
|
||||
yield* AtomRegistry.getResult(registry, liveQuery, {
|
||||
suspendOnWaiting: true,
|
||||
}),
|
||||
).toBe(1);
|
||||
expect(reads).toBe(1);
|
||||
|
||||
unmountConsumer();
|
||||
registry.dispose();
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("revalidates a stale cached query after the live query remounts", () =>
|
||||
Effect.gen(function* () {
|
||||
let contents = "initial";
|
||||
let reads = 0;
|
||||
const query = Atom.make(
|
||||
Effect.sync(() => {
|
||||
reads += 1;
|
||||
return contents;
|
||||
}),
|
||||
).pipe(Atom.swr({ staleTime: 0, revalidateOnMount: true }), Atom.setIdleTTL(0));
|
||||
const signal = Atom.make<AsyncResult.AsyncResult<string, never>>(
|
||||
AsyncResult.initial<string, never>(false),
|
||||
);
|
||||
const liveQuery = refreshQueryOnSuccess(query, signal);
|
||||
const scheduledTasks: Array<() => void> = [];
|
||||
const registry = AtomRegistry.make({
|
||||
defaultIdleTTL: 5 * 60_000,
|
||||
scheduleTask: (task) => {
|
||||
let active = true;
|
||||
scheduledTasks.push(() => {
|
||||
if (active) task();
|
||||
});
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
},
|
||||
});
|
||||
const unmountInitial = registry.mount(liveQuery);
|
||||
|
||||
expect(
|
||||
yield* AtomRegistry.getResult(registry, liveQuery, {
|
||||
suspendOnWaiting: true,
|
||||
}),
|
||||
).toBe("initial");
|
||||
const readsAfterInitialMount = reads;
|
||||
|
||||
unmountInitial();
|
||||
contents = "updated";
|
||||
while (scheduledTasks.length > 0) {
|
||||
scheduledTasks.shift()?.();
|
||||
}
|
||||
|
||||
const unmountUpdated = registry.mount(liveQuery);
|
||||
expect(
|
||||
yield* AtomRegistry.getResult(registry, liveQuery, {
|
||||
suspendOnWaiting: true,
|
||||
}),
|
||||
).toBe("updated");
|
||||
expect(reads).toBe(readsAfterInitialMount + 1);
|
||||
|
||||
unmountUpdated();
|
||||
registry.dispose();
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
describe("atom command result helpers", () => {
|
||||
it("maps successful command values", () => {
|
||||
const result = mapAtomCommandResult(AsyncResult.success(2), (value) => value * 3);
|
||||
|
||||
@@ -79,6 +79,29 @@ export interface AtomCommandReporter {
|
||||
readonly error: (message: string, cause: Cause.Cause<unknown>) => void;
|
||||
}
|
||||
|
||||
export function refreshQueryOnSuccess<A, E, B, E2>(
|
||||
queryAtom: Atom.Atom<AsyncResult.AsyncResult<A, E>>,
|
||||
signalAtom: Atom.Atom<AsyncResult.AsyncResult<B, E2>>,
|
||||
): Atom.Atom<AsyncResult.AsyncResult<A, E>> {
|
||||
return Atom.transform(
|
||||
queryAtom,
|
||||
(get) => {
|
||||
const current = get.once(queryAtom);
|
||||
get.once(signalAtom);
|
||||
get.subscribe(queryAtom, (result) => {
|
||||
get.setSelf(result);
|
||||
});
|
||||
get.subscribe(signalAtom, (result) => {
|
||||
if (AsyncResult.isSuccess(result)) {
|
||||
get.refresh(queryAtom);
|
||||
}
|
||||
});
|
||||
return current;
|
||||
},
|
||||
{ initialValueTarget: queryAtom },
|
||||
).pipe(Atom.setIdleTTL(0));
|
||||
}
|
||||
|
||||
export interface AtomCommand<W, A, E> {
|
||||
readonly label: string;
|
||||
readonly run: (registry: AtomRegistry.AtomRegistry, input: W) => Promise<AtomCommandResult<A, E>>;
|
||||
|
||||
@@ -204,6 +204,11 @@ export const ProjectReadFileResult = Schema.Struct({
|
||||
});
|
||||
export type ProjectReadFileResult = typeof ProjectReadFileResult.Type;
|
||||
|
||||
export const ProjectFileChangeEvent = Schema.Struct({
|
||||
relativePath: TrimmedNonEmptyString,
|
||||
});
|
||||
export type ProjectFileChangeEvent = typeof ProjectFileChangeEvent.Type;
|
||||
|
||||
export const ProjectFileFailure = Schema.Literals([
|
||||
"workspace_path_outside_root",
|
||||
"resolved_path_outside_root",
|
||||
@@ -216,10 +221,12 @@ export type ProjectFileFailure = typeof ProjectFileFailure.Type;
|
||||
export const ProjectFileOperation = Schema.Literals([
|
||||
"realpath-workspace-root",
|
||||
"realpath-target",
|
||||
"realpath-watch-directory",
|
||||
"open",
|
||||
"stat",
|
||||
"read",
|
||||
"close",
|
||||
"watch",
|
||||
"make-directory",
|
||||
"write-file",
|
||||
]);
|
||||
|
||||
@@ -73,6 +73,7 @@ import {
|
||||
ProjectListEntriesError,
|
||||
ProjectListEntriesInput,
|
||||
ProjectListEntriesResult,
|
||||
ProjectFileChangeEvent,
|
||||
ProjectReadFileError,
|
||||
ProjectReadFileInput,
|
||||
ProjectReadFileResult,
|
||||
@@ -170,6 +171,7 @@ export const WS_METHODS = {
|
||||
projectsListEntries: "projects.listEntries",
|
||||
projectsReadFile: "projects.readFile",
|
||||
projectsSearchContents: "projects.searchContents",
|
||||
projectsWatchFile: "projects.watchFile",
|
||||
projectsSearchEntries: "projects.searchEntries",
|
||||
projectsWriteFile: "projects.writeFile",
|
||||
|
||||
@@ -460,6 +462,13 @@ export const WsProjectsReadFileRpc = Rpc.make(WS_METHODS.projectsReadFile, {
|
||||
error: Schema.Union([ProjectReadFileError, EnvironmentAuthorizationError]),
|
||||
});
|
||||
|
||||
export const WsProjectsWatchFileRpc = Rpc.make(WS_METHODS.projectsWatchFile, {
|
||||
payload: ProjectReadFileInput,
|
||||
success: ProjectFileChangeEvent,
|
||||
error: Schema.Union([ProjectReadFileError, EnvironmentAuthorizationError]),
|
||||
stream: true,
|
||||
});
|
||||
|
||||
export const WsProjectsWriteFileRpc = Rpc.make(WS_METHODS.projectsWriteFile, {
|
||||
payload: ProjectWriteFileInput,
|
||||
success: ProjectWriteFileResult,
|
||||
@@ -812,6 +821,7 @@ export const WsRpcGroup = RpcGroup.make(
|
||||
WsProjectsListEntriesRpc,
|
||||
WsProjectsReadFileRpc,
|
||||
WsProjectsSearchContentsRpc,
|
||||
WsProjectsWatchFileRpc,
|
||||
WsProjectsSearchEntriesRpc,
|
||||
WsProjectsWriteFileRpc,
|
||||
WsShellOpenInEditorRpc,
|
||||
|
||||
Reference in new issue
Block a user