feat(auth): separate filesystem read and write permissions (#9788)

Co-authored-by: Claude Fable 5 <[email protected]>
This commit is contained in:
Julius MarmingeandClaude Fable 5 authored and GitHub committed 2026-10-06 20:30:11 -07:00
1 parent 2eda8ac6a3
commit 321c6f9d26
62 files changed
+2988 -267

No files matched your search

@@ -14,7 +14,7 @@ import {
} from "../lib/composerImages";
import { resolveOwnedComposerAttachmentFileUri } from "../lib/composerAttachmentFiles";
import { VideoAttachmentTile } from "./VideoAttachmentTile";
import { type MediaActionsSource } from "../lib/mediaActions";
import { type MediaActionsSource } from "../lib/mediaActionsSource";
import { PresentationSource } from "./NativePresentation";
import type { FilePreviewSource } from "./FilePreviewModal";
import { isPdfFile } from "../lib/filePreview";
@@ -1,7 +1,7 @@
import type { AssetResource, EnvironmentId } from "@t3tools/contracts";
import type { FileBackedComposerAttachment } from "../lib/composerImages";
import type { MediaActionsSource } from "../lib/mediaActions";
import type { MediaActionsSource } from "../lib/mediaActionsSource";
export interface ResolvedFilePreviewSource {
readonly kind: "image" | "pdf" | "document";
@@ -2,7 +2,7 @@ import { MenuView } from "@react-native-menu/menu";
import type { ReactElement } from "react";
import { Platform, View, type PressableProps, type StyleProp, type ViewStyle } from "react-native";
import type { useMediaActions } from "../lib/mediaActions";
import type { useMediaActions } from "../state/mediaActions";
import { SymbolView } from "./AppSymbol";
import { ControlPillMenu } from "./ControlPill";
@@ -3,7 +3,7 @@ import { Pressable, View } from "react-native";
import ImageViewing from "react-native-image-viewing";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useMediaActions } from "../lib/mediaActions";
import { useMediaActions } from "../state/mediaActions";
import { AppText } from "./AppText";
import { SymbolView } from "./AppSymbol";
import type { ResolvedFilePreviewSource } from "./FilePreviewModal.types";
@@ -7,7 +7,8 @@ import { ActivityIndicator, AppState, Pressable, View } from "react-native";
import { AppText } from "./AppText";
import { SymbolView } from "./AppSymbol";
import { VideoThumbnailImage } from "./VideoThumbnailImage";
import { useMediaActions, type MediaActionsSource } from "../lib/mediaActions";
import { useMediaActions } from "../state/mediaActions";
import { type MediaActionsSource } from "../lib/mediaActionsSource";
import { MediaActionsMenu } from "./MediaActionsMenu";
/** Loads only after Play or opening the viewer. Source replacement never starts playback itself. */
@@ -2,7 +2,8 @@ import { Platform, Pressable, View, type StyleProp, type ViewStyle } from "react
import { cn } from "../lib/cn";
import type { DraftComposerFileAttachment } from "../lib/composerImages";
import { useMediaActions, type MediaActionsSource } from "../lib/mediaActions";
import { useMediaActions } from "../state/mediaActions";
import { type MediaActionsSource } from "../lib/mediaActionsSource";
import { SymbolView } from "./AppSymbol";
import { AppText } from "./AppText";
import { MediaActionsMenu } from "./MediaActionsMenu";
@@ -5,7 +5,8 @@ import { ActivityIndicator, Keyboard, Modal, Pressable, View } from "react-nativ
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { loadLocalAttachmentPreview } from "../lib/localAttachmentPreview";
import { useMediaActions, type MediaActionsSource } from "../lib/mediaActions";
import { useMediaActions } from "../state/mediaActions";
import { type MediaActionsSource } from "../lib/mediaActionsSource";
import {
mediaVideoPreviewUri,
mediaVideoThumbnailKey,
+1 -1
View File
@@ -274,7 +274,7 @@ describe("mobile dependency graph", () => {
["native", "features", 8, "native must not add imports from features"],
// lib -> state: attachment/session plumbing that predates the cycle
// cleanup; each remaining edge needs a real owner-side seam.
["lib", "state", 11, "lib must not add imports from state"],
["lib", "state", 10, "lib must not add imports from state"],
];
for (const [from, to, ceiling, message] of ceilings) {
@@ -1,3 +1,5 @@
import { resolveFilesystemReadAccess } from "@t3tools/client-runtime/state/filesystem";
import { environmentSession } from "../../state/session";
import { NativeStackScreenOptions } from "../../native/StackHeader";
import { StackActions, useNavigation, type StaticScreenProps } from "@react-navigation/native";
import { useCallback, useEffect, useId, useMemo, useRef, useState } from "react";
@@ -24,10 +26,12 @@ import { isPdfFile } from "../../lib/filePreview";
import { tryOpenExternalUrl } from "../../lib/openExternalUrl";
import { useUniwindTheme } from "../../lib/useUniwindTheme";
import type { MediaVideoPreviewSource } from "../../lib/videoPreviewSource";
import { useMediaActions, type MediaActionsSource } from "../../lib/mediaActions";
import { useMediaActions } from "../../state/mediaActions";
import { type MediaActionsSource } from "../../lib/mediaActionsSource";
import { useThreadSelection } from "../../state/use-thread-selection";
import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktree";
import { useEnvironmentQuery } from "../../state/query";
import { useEnvironmentPresentation } from "../../state/presentation";
import { projectEnvironment } from "../../state/projects";
import type { AssetUrlFailureReason } from "../../state/asset-url-state";
import {
@@ -370,14 +374,15 @@ function useThreadFilesWorkspace(params: {
};
}
function FilesUnavailable() {
function FilesUnavailable({
detail = "This thread does not have an active workspace path.",
}: {
detail?: string;
}) {
return (
<View className="flex-1 items-center justify-center bg-sheet px-6">
<NativeStackScreenOptions options={{ title: "Files" }} />
<EmptyState
title="Files unavailable"
detail="This thread does not have an active workspace path."
/>
<EmptyState title="Files unavailable" detail={detail} />
</View>
);
}
@@ -420,9 +425,20 @@ export function ThreadFilesTreeScreen(props: ThreadFilesRouteScreenProps) {
props.route.params,
);
const revealedInspectorRef = useRef(false);
const fileAccessSession = useEnvironmentQuery(
environmentId !== null ? environmentSession.sessionStateAtom(environmentId) : null,
);
const fileEnvironment = useEnvironmentPresentation(environmentId);
const fileAccess = resolveFilesystemReadAccess({
isCatalogReady: fileEnvironment.isReady,
connection: fileEnvironment.presentation?.connection ?? null,
session: fileAccessSession.data,
sessionError: fileAccessSession.error,
});
const { canReadFiles } = fileAccess;
const entriesQuery = useFileTreeEntries({
environmentId,
cwd: fileInspector.supported ? null : cwd,
cwd: !canReadFiles || fileInspector.supported ? null : cwd,
searchQuery,
});
const handleReturnToThread = useCallback(() => {
@@ -509,6 +525,14 @@ export function ThreadFilesTreeScreen(props: ThreadFilesRouteScreenProps) {
return <LoadingScreen message="Opening files..." messagePlacement="above-spinner" />;
}
if (!canReadFiles) {
if (fileAccess.isPending) {
return <LoadingScreen message="Checking file access..." messagePlacement="above-spinner" />;
}
return (
<FilesUnavailable detail={fileAccess.error ?? "This connection cannot read host files."} />
);
}
if (cwd === null) {
return <FilesUnavailable />;
}
@@ -656,8 +680,23 @@ export function ThreadFileScreen(props: ThreadFileRouteScreenProps) {
!isVideoFile &&
!isAudioFile &&
(resolvedActiveMode === "source" || isMarkdownPreviewFile(relativePath));
const fileAccessSession = useEnvironmentQuery(
environmentId !== null ? environmentSession.sessionStateAtom(environmentId) : null,
);
const fileEnvironment = useEnvironmentPresentation(environmentId);
const fileAccess = resolveFilesystemReadAccess({
isCatalogReady: fileEnvironment.isReady,
connection: fileEnvironment.presentation?.connection ?? null,
session: fileAccessSession.data,
sessionError: fileAccessSession.error,
});
const { canReadFiles } = fileAccess;
const fileQuery = useEnvironmentQuery(
environmentId !== null && cwd !== null && relativePath !== null && needsFileContents
canReadFiles &&
environmentId !== null &&
cwd !== null &&
relativePath !== null &&
needsFileContents
? projectEnvironment.readFile({
environmentId,
input: { cwd, relativePath },
@@ -861,6 +900,14 @@ export function ThreadFileScreen(props: ThreadFileRouteScreenProps) {
return <LoadingScreen message="Opening file..." messagePlacement="above-spinner" />;
}
if (!canReadFiles) {
if (fileAccess.isPending) {
return <LoadingScreen message="Checking file access..." messagePlacement="above-spinner" />;
}
return (
<FilesUnavailable detail={fileAccess.error ?? "This connection cannot read host files."} />
);
}
if (cwd === null) {
return <FilesUnavailable />;
}
@@ -5,7 +5,8 @@ import { FilePreviewLoading } from "./FilePreviewFeedback";
import { EmptyState } from "../../components/EmptyState";
import { FilePreviewModal, type FilePreviewSource } from "../../components/FilePreviewModal";
import { PresentationSource } from "../../components/NativePresentation";
import { useMediaActions, type MediaActionsSource } from "../../lib/mediaActions";
import { useMediaActions } from "../../state/mediaActions";
import { type MediaActionsSource } from "../../lib/mediaActionsSource";
import { MediaActionsMenu } from "../../components/MediaActionsMenu";
function ResolvedWorkspaceFileImagePreview(props: {
@@ -1,3 +1,5 @@
import { AuthFilesystemReadScope } from "@t3tools/contracts";
import { readEnvironmentScope } from "../../state/session";
import { executeAtomQuery } from "@t3tools/client-runtime/state/runtime";
import type { EnvironmentId } from "@t3tools/contracts";
import {
@@ -30,6 +32,7 @@ export function preloadWorkspaceFileContents(input: {
readonly theme: ReviewDiffTheme;
}): void {
if (
!readEnvironmentScope(input.environmentId, AuthFilesystemReadScope) ||
isWorkspaceBrowserPreviewPath(input.relativePath) ||
isWorkspaceImagePreviewPath(input.relativePath) ||
isVideoPreviewFile(input.relativePath)
@@ -1,3 +1,5 @@
import { resolveFilesystemReadAccess } from "@t3tools/client-runtime/state/filesystem";
import { environmentSession } from "../../state/session";
import type { EnvironmentId } from "@t3tools/contracts";
import { SymbolView } from "../../components/AppSymbol";
import { MaterialScreenContent } from "../../components/MaterialScreenContent";
@@ -15,6 +17,8 @@ import { AppText as Text, AppTextInput as TextInput } from "../../components/App
import { MaterialFilesHeader } from "./MaterialFilesHeader";
import { nativeHeaderScrollEdgeEffects } from "../../native/StackHeader";
import { useUniwindTheme } from "../../lib/useUniwindTheme";
import { useEnvironmentQuery } from "../../state/query";
import { useEnvironmentPresentation } from "../../state/presentation";
import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
import { FileTreeBrowser } from "./FileTreeBrowser";
import { useFileTreeEntries } from "./useFileTreeEntries";
@@ -36,9 +40,20 @@ export function ThreadFileNavigatorPane(props: {
const foregroundColor = theme["--color-foreground"];
const sheetColor = theme["--color-sheet"];
const headerScrollEdgeEffects = nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version);
const fileAccessSession = useEnvironmentQuery(
environmentSession.sessionStateAtom(props.environmentId),
);
const fileEnvironment = useEnvironmentPresentation(props.environmentId);
const fileAccess = resolveFilesystemReadAccess({
isCatalogReady: fileEnvironment.isReady,
connection: fileEnvironment.presentation?.connection ?? null,
session: fileAccessSession.data,
sessionError: fileAccessSession.error,
});
const { canReadFiles } = fileAccess;
const entriesQuery = useFileTreeEntries({
environmentId: props.environmentId,
cwd: props.cwd,
cwd: canReadFiles ? props.cwd : null,
searchQuery,
});
const handlePreviewFile = useCallback(
@@ -75,8 +90,14 @@ export function ThreadFileNavigatorPane(props: {
entries={entriesQuery.entries}
loadedDirectories={entriesQuery.loadedDirectories}
onLoadDirectory={entriesQuery.loadDirectory}
error={entriesQuery.error}
isPending={entriesQuery.isPending}
error={
canReadFiles
? entriesQuery.error
: fileAccess.isPending
? null
: (fileAccess.error ?? "This connection cannot read host files.")
}
isPending={fileAccess.isPending || entriesQuery.isPending}
searchQuery={searchQuery}
searchTruncated={entriesQuery.searchTruncated}
selectedPath={props.selectedPath}
@@ -32,6 +32,7 @@ import {
createBrowseNavigationCoordinator,
filterFilesystemBrowseEntries,
getFilesystemBrowsePath,
resolveFilesystemReadAccess,
} from "@t3tools/client-runtime/state/filesystem";
import {
appendBrowsePathSegment,
@@ -41,6 +42,7 @@ import {
import {
AuthOrchestrationOperateScope,
AuthSourceControlWriteScope,
AuthFilesystemReadScope,
CommandId,
type EnvironmentId,
type EnvironmentMachineKind,
@@ -61,7 +63,8 @@ import { useProjects, useServerConfigs, waitForProject } from "../../state/entit
import { filesystemEnvironment } from "../../state/filesystem";
import { projectEnvironment } from "../../state/projects";
import { useEnvironmentQuery } from "../../state/query";
import { readEnvironmentScope, useEnvironmentScope } from "../../state/session";
import { environmentSession, useEnvironmentScope, readEnvironmentScope } from "../../state/session";
import { useEnvironmentPresentation } from "../../state/presentation";
import { sourceControlEnvironment } from "../../state/sourceControl";
import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText";
import { EnvironmentMachineSymbol } from "../../components/EnvironmentMachineSymbol";
@@ -345,7 +348,11 @@ function useBrowsePathInput(environment: EnvironmentOption | null, pinnedDirecto
setIsBrowseNavigating(true);
const committed = await browseNavigation.run(
async () => {
if (environment && canPreloadBrowsePath(environmentRuntime?.connectionState)) {
if (
environment &&
readEnvironmentScope(environment.environmentId, AuthFilesystemReadScope) &&
canPreloadBrowsePath(environmentRuntime?.connectionState)
) {
await loadBrowsePath({
environmentId: environment.environmentId,
input: { partialPath: selectedDirectoryPath },
@@ -877,8 +884,19 @@ function FolderBrowser(props: {
() => (browsePath.directoryPath.length > 0 ? { partialPath: browsePath.directoryPath } : null),
[browsePath.directoryPath],
);
const fileAccessSession = useEnvironmentQuery(
environmentSession.sessionStateAtom(props.environment.environmentId),
);
const fileEnvironment = useEnvironmentPresentation(props.environment.environmentId);
const fileAccess = resolveFilesystemReadAccess({
isCatalogReady: fileEnvironment.isReady,
connection: fileEnvironment.presentation?.connection ?? null,
session: fileAccessSession.data,
sessionError: fileAccessSession.error,
});
const { canReadFiles } = fileAccess;
const browseState = useEnvironmentQuery(
browseInput === null
!canReadFiles || browseInput === null
? null
: filesystemEnvironment.browse({
environmentId: props.environment.environmentId,
@@ -900,9 +918,12 @@ function FolderBrowser(props: {
return (
<>
<SectionTitle>Browse folders</SectionTitle>
{!canReadFiles && !fileAccess.isPending ? (
<ErrorBanner message={fileAccess.error ?? "This connection cannot browse host folders."} />
) : null}
{browseState.error ? <ErrorBanner message={browseState.error} /> : null}
<ListSection>
{browseState.isPending && browseState.data === null ? (
{fileAccess.isPending || (browseState.isPending && browseState.data === null) ? (
<View className="items-center py-5">
<ActivityIndicator colorClassName="accent-icon-muted" />
</View>
+18 -16
View File
@@ -825,23 +825,25 @@ export function ReviewSheet(props: ReviewSheetProps) {
>
{listHeader}
{!selectedSection ? (
<View
className={
Platform.OS === "android"
? "items-center px-6 py-5"
: "border-b border-border bg-card px-4 py-5"
}
>
<Text className="text-sm font-t3-bold text-foreground">No review diffs</Text>
<Text
className={cn(
"text-xs leading-normal text-foreground-muted",
Platform.OS === "android" && "mt-2 text-center",
)}
error ? null : (
<View
className={
Platform.OS === "android"
? "items-center px-6 py-5"
: "border-b border-border bg-card px-4 py-5"
}
>
This thread has no ready turn diffs and the worktree diff is empty.
</Text>
</View>
<Text className="text-sm font-t3-bold text-foreground">No review diffs</Text>
<Text
className={cn(
"text-xs leading-normal text-foreground-muted",
Platform.OS === "android" && "mt-2 text-center",
)}
>
This thread has no ready turn diffs and the worktree diff is empty.
</Text>
</View>
)
) : selectedSection.isLoading && selectedSection.diff === null ? (
<View
className={cn(
@@ -0,0 +1,210 @@
import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints";
import {
AuthFilesystemReadScope,
CheckpointRef,
EnvironmentId,
MessageId,
ThreadId,
RunId,
type AuthSessionState,
} from "@t3tools/contracts";
import { beforeEach, expect, it, vi } from "vite-plus/test";
const state = vi.hoisted(() => ({
session: null as Pick<AuthSessionState, "authenticated" | "scopes"> | null,
sessionError: null as string | null,
sessionAtom: {},
effects: [] as Array<() => void>,
checkpoints: [] as ReadonlyArray<ThreadCheckpointSummary>,
}));
vi.mock("@t3tools/client-runtime/state/thread-checkpoints", () => ({
deriveThreadCheckpointSummaries: () => state.checkpoints,
}));
vi.mock("react", () => ({
useCallback: <A>(callback: A) => callback,
useEffect: (effect: () => void) => state.effects.push(effect),
useMemo: <A>(factory: () => A) => factory(),
}));
vi.mock("../../state/session", () => ({
environmentSession: { sessionStateAtom: () => state.sessionAtom },
}));
vi.mock("../../state/presentation", () => ({
useEnvironmentPresentation: () => ({
isReady: true,
presentation: { connection: { phase: "connected", error: null } },
}),
}));
vi.mock("../../state/use-thread-detail", () => ({
useSelectedThreadProjection: () => ({ projection: {} }),
}));
vi.mock("../../state/use-selected-thread-worktree", () => ({
useSelectedThreadWorktree: () => ({ selectedThreadCwd: "/repo" }),
}));
vi.mock("../../state/query", () => ({
useEnvironmentQuery: (atom: unknown) => ({
data: atom === state.sessionAtom ? state.session : null,
error: atom === state.sessionAtom ? state.sessionError : null,
isPending: atom === state.sessionAtom && state.session === null,
refresh: vi.fn(),
}),
}));
vi.mock("../../state/queries", () => ({
useCheckpointDiff: () => ({ data: null, error: null, isPending: false, refresh: vi.fn() }),
}));
vi.mock("../../state/review", () => ({
reviewEnvironment: { diffPreview: vi.fn() },
}));
vi.mock("./reviewState", () => ({
setReviewAsyncError: vi.fn(),
setReviewGitSections: vi.fn(),
setReviewSelectedSectionId: vi.fn(),
setReviewTurnDiff: vi.fn(),
setReviewTurnDiffLoading: vi.fn(),
}));
import { setReviewSelectedSectionId, type ReviewCacheForThread } from "./reviewState";
import { useReviewSections } from "./useReviewSections";
beforeEach(() => {
vi.clearAllMocks();
state.effects = [];
state.session = { authenticated: true, scopes: [AuthFilesystemReadScope] };
state.sessionError = null;
state.checkpoints = [
{
runId: RunId.make("turn-1"),
checkpointTurnCount: 1,
checkpointRef: CheckpointRef.make("refs/t3/checkpoints/thread/1"),
status: "ready",
files: [],
assistantMessageId: MessageId.make("message-1"),
completedAt: "2026-04-01T00:00:00.000Z",
},
];
});
const checkpointDiff = "diff --git a/checkpoint.ts b/checkpoint.ts";
const localDiff = "diff --git a/local.ts b/local.ts";
function makeReviewCache(
kind: "working-tree" | "branch-range" = "working-tree",
): ReviewCacheForThread {
return {
threadKey: "environment:thread",
gitSections: [
{
id: kind,
kind,
title: "Dirty worktree",
baseRef: "HEAD",
headRef: null,
diff: localDiff,
diffHash: "cached-local",
truncated: false,
},
],
turnDiffById: { "turn:1": checkpointDiff },
selectedSectionId: `git:${kind}`,
asyncState: { loadingTurnIds: {}, error: null },
expandedFileIdsBySection: {},
revealedLargeFileIdsBySection: {},
viewedFileIdsBySection: {},
};
}
function makeInput(reviewCache = makeReviewCache()) {
return {
environmentId: EnvironmentId.make("environment"),
threadId: ThreadId.make("thread"),
reviewCache,
};
}
function renderSections(input: ReturnType<typeof makeInput>) {
const result = useReviewSections(input);
const effects = state.effects.splice(0);
effects.forEach((effect) => effect());
return result;
}
it("hides cached local diffs after file access is lost while retaining checkpoint diffs", () => {
const input = makeInput();
expect(renderSections(input).selectedSection?.diff).toBe(localDiff);
state.session = { authenticated: true, scopes: [] };
const denied = renderSections(input);
expect(denied.reviewSections.map((section) => section.id)).toEqual(["turn:1"]);
expect(denied.selectedSection?.diff).toBe(checkpointDiff);
expect(setReviewSelectedSectionId).toHaveBeenCalledWith("environment:thread", "turn:1");
});
it.each(["working-tree", "branch-range"] as const)(
"preserves a cached %s selection while an expired grant reloads",
(kind) => {
const input = makeInput(makeReviewCache(kind));
expect(renderSections(input).selectedSection?.diff).toBe(localDiff);
state.session = null;
const pending = renderSections(input);
expect(pending.selectedSection).toEqual(
expect.objectContaining({ id: `git:${kind}`, diff: null, isLoading: true }),
);
expect(pending.loadingGitDiffs).toBe(true);
expect(pending.reviewSections.find((section) => section.id === "turn:1")?.diff).toBe(
checkpointDiff,
);
expect(setReviewSelectedSectionId).not.toHaveBeenCalled();
state.session = { authenticated: true, scopes: [AuthFilesystemReadScope] };
expect(renderSections(input).selectedSection).toEqual(
expect.objectContaining({ id: `git:${kind}`, diff: localDiff, isLoading: false }),
);
expect(setReviewSelectedSectionId).not.toHaveBeenCalled();
},
);
it("falls back to a checkpoint when a pending grant resolves without file access", () => {
const input = makeInput();
state.session = null;
renderSections(input);
expect(setReviewSelectedSectionId).not.toHaveBeenCalled();
state.session = { authenticated: true, scopes: [] };
const denied = renderSections(input);
expect(denied.reviewSections.map((section) => section.id)).toEqual(["turn:1"]);
expect(denied.selectedSection?.diff).toBe(checkpointDiff);
expect(setReviewSelectedSectionId).toHaveBeenCalledWith("environment:thread", "turn:1");
});
it("reports a failed access check when no checkpoint can replace the local review", () => {
state.checkpoints = [];
const input = makeInput();
expect(renderSections(input).selectedSection?.diff).toBe(localDiff);
state.sessionError = "The session request timed out.";
const unavailable = renderSections(input);
expect(unavailable.selectedSection).toBeNull();
expect(unavailable.reviewSections).toEqual([]);
expect(unavailable.error).toBe(state.sessionError);
});
it("reports denied file access when no checkpoint can replace the local review", () => {
state.checkpoints = [];
const input = makeInput();
expect(renderSections(input).selectedSection?.diff).toBe(localDiff);
state.session = { authenticated: true, scopes: [] };
const denied = renderSections(input);
expect(denied.selectedSection).toBeNull();
expect(denied.reviewSections).toEqual([]);
expect(denied.loadingGitDiffs).toBe(false);
expect(denied.error).toBe("This connection cannot read local diffs.");
});
it("keeps a cached checkpoint available when the filesystem access check fails", () => {
state.sessionError = "The session request timed out.";
const checkpoint = renderSections(makeInput());
expect(checkpoint.selectedSection?.diff).toBe(checkpointDiff);
expect(checkpoint.error).toBeNull();
});
@@ -1,3 +1,5 @@
import { resolveFilesystemReadAccess } from "@t3tools/client-runtime/state/filesystem";
import { environmentSession } from "../../state/session";
import { useCallback, useEffect, useMemo } from "react";
import * as DateTime from "effect/DateTime";
@@ -9,6 +11,7 @@ import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
import { useCheckpointDiff } from "../../state/queries";
import { useEnvironmentQuery } from "../../state/query";
import { useEnvironmentPresentation } from "../../state/presentation";
import { reviewEnvironment } from "../../state/review";
import { useSelectedThreadProjection } from "../../state/use-thread-detail";
import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktree";
@@ -35,10 +38,21 @@ export function useReviewSections(input: {
}) {
const { environmentId, reviewCache, threadId } = input;
const enabled = input.enabled ?? true;
const fileAccessSession = useEnvironmentQuery(
environmentId === undefined ? null : environmentSession.sessionStateAtom(environmentId),
);
const fileEnvironment = useEnvironmentPresentation(environmentId ?? null);
const fileAccess = resolveFilesystemReadAccess({
isCatalogReady: fileEnvironment.isReady,
connection: fileEnvironment.presentation?.connection ?? null,
session: fileAccessSession.data,
sessionError: fileAccessSession.error,
});
const { canReadFiles } = fileAccess;
const selectedThread = useSelectedThreadProjection();
const { selectedThreadCwd } = useSelectedThreadWorktree();
const diffPreview = useEnvironmentQuery(
enabled && environmentId !== undefined && selectedThreadCwd !== null
canReadFiles && enabled && environmentId !== undefined && selectedThreadCwd !== null
? reviewEnvironment.diffPreview({
environmentId,
input: { cwd: selectedThreadCwd },
@@ -70,24 +84,33 @@ export function useReviewSections(input: {
) as Record<string, ThreadCheckpointSummary>,
[readyCheckpoints],
);
const reviewSections = useMemo(
() =>
buildReviewSectionItems({
checkpoints: readyCheckpoints,
gitSections: diffPreview.data?.sources ?? reviewCache.gitSections,
turnDiffById: reviewCache.turnDiffById,
loadingTurnIds,
loadingGitSections: diffPreview.isPending,
}),
[
diffPreview.isPending,
diffPreview.data?.sources,
const reviewSections = useMemo(() => {
const sections = buildReviewSectionItems({
checkpoints: readyCheckpoints,
gitSections:
canReadFiles || fileAccess.isPending
? (diffPreview.data?.sources ?? reviewCache.gitSections)
: [],
turnDiffById: reviewCache.turnDiffById,
loadingTurnIds,
readyCheckpoints,
reviewCache.gitSections,
reviewCache.turnDiffById,
],
);
loadingGitSections: fileAccess.isPending || diffPreview.isPending,
});
// Keep the selected section while its grant loads, without displaying cached host files.
return fileAccess.isPending
? sections.map((section) =>
section.kind === "turn" ? section : { ...section, diff: null, isLoading: true },
)
: sections;
}, [
canReadFiles,
diffPreview.data?.sources,
diffPreview.isPending,
fileAccess.isPending,
loadingTurnIds,
readyCheckpoints,
reviewCache.gitSections,
reviewCache.turnDiffById,
]);
const selectedSection = useMemo(
() =>
reviewSections.find((section) => section.id === reviewCache.selectedSectionId) ??
@@ -181,10 +204,16 @@ export function useReviewSections(input: {
);
return {
error: diffPreview.error ?? activeTurnDiff.error ?? reviewCache.asyncState.error,
error:
diffPreview.error ??
activeTurnDiff.error ??
reviewCache.asyncState.error ??
(selectedSection === null && !fileAccess.isPending && !canReadFiles
? (fileAccess.error ?? "This connection cannot read local diffs.")
: null),
isSelectedSectionPending:
selectedSection?.kind === "turn" ? activeTurnDiff.isPending : diffPreview.isPending,
loadingGitDiffs: diffPreview.isPending,
loadingGitDiffs: fileAccess.isPending || diffPreview.isPending,
diffPreviewRevision: diffPreview.data
? DateTime.formatIso(diffPreview.data.generatedAt)
: undefined,
@@ -13,7 +13,8 @@ import { AppText as Text } from "../../components/AppText";
import type { FilePreviewSource } from "../../components/FilePreviewModal";
import { MediaActionsMenu } from "../../components/MediaActionsMenu";
import { PresentationSource } from "../../components/NativePresentation";
import { useMediaActions, type MediaActionsSource } from "../../lib/mediaActions";
import { useMediaActions } from "../../state/mediaActions";
import { type MediaActionsSource } from "../../lib/mediaActionsSource";
import { useAssetUrlState } from "../../state/assets";
import {
MARKDOWN_IMAGE_MAX_WIDTH,
@@ -1,3 +1,6 @@
import { resolveFilesystemReadAccess } from "@t3tools/client-runtime/state/filesystem";
import { useEnvironmentPresentation } from "../../state/presentation";
import { environmentSession } from "../../state/session";
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Alert } from "react-native";
@@ -485,8 +488,23 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
// Default mode until the user picks one explicitly — same resolution web
// uses for new draft threads: per-project setting, then the repo's
// checked-in t3.json, then the server's configured default.
const t3ProjectFileQuery = useEnvironmentQuery(
const fileAccessSession = useEnvironmentQuery(
selectedProject !== null && selectedProject.workspaceRoot !== ""
? environmentSession.sessionStateAtom(selectedProject.environmentId)
: null,
);
const fileEnvironment = useEnvironmentPresentation(selectedProject?.environmentId ?? null);
const fileAccess = resolveFilesystemReadAccess({
isCatalogReady: fileEnvironment.isReady,
connection: fileEnvironment.presentation?.connection ?? null,
session: fileAccessSession.data,
sessionError: fileAccessSession.error,
});
const { canReadFiles } = fileAccess;
const fileAccessPending =
selectedProject !== null && selectedProject.workspaceRoot !== "" && fileAccess.isPending;
const t3ProjectFileQuery = useEnvironmentQuery(
canReadFiles && selectedProject !== null && selectedProject.workspaceRoot !== ""
? projectEnvironment.readFile({
environmentId: selectedProject.environmentId,
input: { cwd: selectedProject.workspaceRoot, relativePath: T3_PROJECT_FILE_NAME },
@@ -527,7 +545,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
const defaultWorkspaceModeSettled =
selectedProjectDraft.workspaceSelection?.mode !== undefined ||
projectSettings.sources.defaultThreadEnvMode !== "environment" ||
!t3ProjectFileQuery.isPending;
(!t3ProjectFileQuery.isPending && !fileAccessPending);
const workspaceMode = canChooseWorkspace
? (selectedProjectDraft.workspaceSelection?.mode ?? defaultWorkspaceMode)
: "local";
+1 -1
View File
@@ -4,7 +4,7 @@ import { normalizeNativeMarkdownUrl } from "@t3tools/mobile-markdown-text/links"
import type { FilePreviewSource } from "../components/FilePreviewModal";
import type { MediaVideoPreviewSource } from "./videoPreviewSource";
import type { MediaActionsSource } from "./mediaActions";
import type { MediaActionsSource } from "./mediaActionsSource";
/** Resolves only explicit media references. Ordinary links keep their existing navigation. */
export function resolveMarkdownMediaPreview(
+266
View File
@@ -0,0 +1,266 @@
import {
AuthFilesystemReadScope,
EnvironmentId,
ThreadId,
type AuthSessionState,
} from "@t3tools/contracts";
import { AsyncResult } from "effect/reactivity";
import { beforeEach, expect, it, vi } from "vite-plus/test";
const state = vi.hoisted(() => ({
sessions: new Map<string, Pick<AuthSessionState, "authenticated" | "scopes">>(),
refresh: vi.fn(),
download: vi.fn(),
shareLocal: vi.fn(),
shareDraft: vi.fn(),
navigate: vi.fn(),
copy: vi.fn(),
}));
vi.mock("react", () => ({
useEffect: () => {},
useRef: <A>(current: A) => ({ current }),
useState: <A>(initial: A) => [initial, () => {}],
}));
vi.mock("react-native", () => ({ Alert: { alert: vi.fn() } }));
vi.mock("@react-navigation/native", () => ({
useNavigation: () => ({ navigate: state.navigate }),
}));
vi.mock("@t3tools/mobile-markdown-text/links", () => ({
normalizeNativeMarkdownUrl: (uri: string) => uri,
}));
vi.mock("../state/assets", () => ({
useRefreshAssetUrl: (environmentId: string, resource: unknown) => () =>
state.refresh(environmentId, resource),
}));
vi.mock("../state/session", () => ({
environmentSession: { sessionStateAtom: (environmentId: string) => environmentId },
}));
vi.mock("../state/query", () => ({
useEnvironmentQuery: (environmentId: string) => ({
data: state.sessions.get(environmentId) ?? null,
error: null,
}),
}));
vi.mock("../state/atom-registry", () => ({
appAtomRegistry: {
get: (environmentId: string) => {
const session = state.sessions.get(environmentId);
return session === undefined ? AsyncResult.initial() : AsyncResult.success(session);
},
},
}));
vi.mock("./attachmentDownload", () => ({
downloadAndShareAttachment: state.download,
shareLocalAttachment: state.shareLocal,
}));
vi.mock("./copyTextWithHaptic", () => ({ copyTextWithHaptic: state.copy }));
vi.mock("./localAttachmentPreview", () => ({
loadLocalAttachmentPreview: async () => ({ share: state.shareDraft, dispose: vi.fn() }),
}));
import { useMediaActions } from "../state/mediaActions";
import type { MediaActionsSource } from "./mediaActionsSource";
const environmentId = EnvironmentId.make("media-environment");
const otherEnvironmentId = EnvironmentId.make("other-environment");
const threadId = ThreadId.make("media-thread");
const granted: Pick<AuthSessionState, "authenticated" | "scopes"> = {
authenticated: true,
scopes: [AuthFilesystemReadScope],
};
const denied: Pick<AuthSessionState, "authenticated" | "scopes"> = {
authenticated: true,
scopes: [],
};
function hostSource(_tag: "workspace-file" | "media-file" = "media-file"): MediaActionsSource {
return {
environmentId,
threadId,
resource: { _tag, threadId, path: "/repo/image.png" },
reference: { kind: "file", path: "/repo/image.png", relativePath: "image.png" },
name: "image.png",
mimeType: "image/png",
};
}
beforeEach(() => {
state.sessions.clear();
state.sessions.set(environmentId, denied);
state.refresh.mockReset().mockResolvedValue("https://host.test/image.png");
state.download.mockReset().mockResolvedValue(undefined);
state.shareLocal.mockReset().mockResolvedValue(undefined);
state.shareDraft.mockReset().mockResolvedValue(undefined);
state.navigate.mockReset();
state.copy.mockReset();
});
it.each(["workspace-file", "media-file"] as const)(
"waits for the %s grant before enabling host menu actions",
(_tag) => {
for (const [session, disabled] of [
[null, true],
[granted, false],
[denied, true],
] as const) {
if (session === null) state.sessions.delete(environmentId);
else state.sessions.set(environmentId, session);
const media = useMediaActions(hostSource(_tag));
expect(media.actions.find(({ id }) => id === "save")?.disabled).toBe(disabled);
expect(media.actions.find(({ id }) => id === "open-file")?.disabled).toBe(disabled);
const copyPath = media.actions.find(({ id }) => id === "copy-full-path")!;
expect(copyPath.disabled).not.toBe(true);
copyPath.run();
}
expect(state.copy).toHaveBeenCalledTimes(3);
expect(state.refresh).not.toHaveBeenCalled();
expect(state.download).not.toHaveBeenCalled();
},
);
it("keeps nonhost menu actions available with pending or denied host grants", () => {
const sources: MediaActionsSource[] = [
{ uri: "https://cdn.test/image.png", name: "image.png", mimeType: "image/png" },
{ uri: "file:///device/image.png", name: "image.png", mimeType: "image/png" },
{
environmentId,
resource: { _tag: "attachment", attachmentId: "upload" },
name: "image.png",
mimeType: "image/png",
},
{
attachment: {
id: "draft",
type: "file",
fileUri: "file:///device/image.png",
name: "image.png",
mimeType: "image/png",
sizeBytes: 1,
},
name: "image.png",
mimeType: "image/png",
},
];
for (const session of [null, denied]) {
if (session === null) state.sessions.delete(environmentId);
else state.sessions.set(environmentId, session);
for (const source of sources) {
expect(useMediaActions(source).actions.find(({ id }) => id === "save")?.disabled).toBe(false);
}
}
});
it.each(["workspace-file", "media-file"] as const)(
"blocks denied %s sharing and file opening while preserving path copying",
async (_tag) => {
const media = useMediaActions(hostSource(_tag));
await media.share();
media.actions.find(({ id }) => id === "open-file")!.run();
media.actions.find(({ id }) => id === "copy-full-path")!.run();
expect(state.refresh).not.toHaveBeenCalled();
expect(state.download).not.toHaveBeenCalled();
expect(state.navigate).not.toHaveBeenCalled();
expect(state.copy).toHaveBeenCalledWith("/repo/image.png");
expect(media.actions.find(({ id }) => id === "save")?.disabled).toBe(true);
expect(media.actions.find(({ id }) => id === "open-file")?.disabled).toBe(true);
},
);
it("rechecks a retained menu action after revocation", async () => {
state.sessions.set(environmentId, granted);
const media = useMediaActions(hostSource());
state.sessions.set(environmentId, denied);
await media.share();
media.actions.find(({ id }) => id === "open-file")!.run();
expect(state.refresh).not.toHaveBeenCalled();
expect(state.navigate).not.toHaveBeenCalled();
});
it("reenables sharing after gaining access while preserving a retained callback", async () => {
const media = useMediaActions(hostSource());
state.sessions.set(environmentId, granted);
await media.share();
expect(state.download).toHaveBeenCalledOnce();
expect(useMediaActions(hostSource()).actions.find(({ id }) => id === "save")?.disabled).toBe(
false,
);
});
it.each([false, true])("uses the media environment's grant (allowed: %s)", async (allowed) => {
state.sessions.set(environmentId, allowed ? granted : denied);
state.sessions.set(otherEnvironmentId, allowed ? denied : granted);
await useMediaActions(hostSource()).share();
expect(state.refresh).toHaveBeenCalledTimes(allowed ? 1 : 0);
expect(state.download).toHaveBeenCalledTimes(allowed ? 1 : 0);
});
it("stops before downloading if access is revoked while the URL is refreshed", async () => {
state.sessions.set(environmentId, granted);
state.refresh.mockImplementation(async () => {
state.sessions.set(environmentId, denied);
return "https://host.test/image.png";
});
await useMediaActions(hostSource()).share();
expect(state.refresh).toHaveBeenCalledOnce();
expect(state.download).not.toHaveBeenCalled();
});
it("lets an unresolved grant be authorized by an explicit server request", async () => {
state.sessions.delete(environmentId);
await useMediaActions(hostSource()).share();
expect(state.refresh).toHaveBeenCalledOnce();
expect(state.download).toHaveBeenCalledOnce();
});
it("shares uploaded attachments without host filesystem access", async () => {
await useMediaActions({
environmentId,
resource: { _tag: "attachment", attachmentId: "upload" },
name: "image.png",
mimeType: "image/png",
}).share();
expect(state.refresh).toHaveBeenCalledOnce();
expect(state.download).toHaveBeenCalledOnce();
});
it.each(["https://cdn.test/image.png", "file:///device/image.png"])(
"shares direct media without a host grant: %s",
async (uri) => {
await useMediaActions({ uri, name: "image.png", mimeType: "image/png" }).share();
expect(state.refresh).not.toHaveBeenCalled();
expect(uri.startsWith("file:") ? state.shareLocal : state.download).toHaveBeenCalledOnce();
},
);
it("shares device draft attachments without a host grant", async () => {
await useMediaActions({
attachment: {
id: "draft",
type: "file",
fileUri: "file:///device/image.png",
name: "image.png",
mimeType: "image/png",
sizeBytes: 1,
},
name: "image.png",
mimeType: "image/png",
}).share();
expect(state.refresh).not.toHaveBeenCalled();
expect(state.shareDraft).toHaveBeenCalledOnce();
});
+20
View File
@@ -0,0 +1,20 @@
import type { MediaReference } from "@t3tools/client-runtime/media-reference";
import type { AssetResource, EnvironmentId, ThreadId } from "@t3tools/contracts";
import type { FileBackedComposerAttachment } from "./composerImages";
/** Authored source metadata is kept separate from temporary preview/download URLs. */
export type MediaActionsSource = {
readonly reference?: MediaReference;
readonly name: string;
readonly mimeType: string;
/** Anchors the iOS share sheet to the view that opened the menu. */
readonly sourceIdentifier?: string;
} & (
| { readonly uri: string }
| { readonly attachment: FileBackedComposerAttachment }
| {
readonly environmentId: EnvironmentId;
readonly threadId?: ThreadId;
readonly resource: AssetResource;
}
);
+1 -1
View File
@@ -2,7 +2,7 @@ import type { AssetResource, ChatFileAttachment, EnvironmentId } from "@t3tools/
import { videoMimeType } from "@t3tools/shared/video";
import type { DraftComposerFileAttachment } from "./composerImages";
import type { MediaActionsSource } from "./mediaActions";
import type { MediaActionsSource } from "./mediaActionsSource";
export type MediaVideoPreviewSource = {
readonly type: "media";
+110
View File
@@ -0,0 +1,110 @@
import {
AuthFilesystemReadScope,
EnvironmentAuthorizationError,
EnvironmentId,
ThreadId,
type AuthSessionState,
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import { AsyncResult } from "effect/reactivity";
import { beforeEach, expect, it, vi } from "vite-plus/test";
const state = vi.hoisted(() => ({
session: null as Pick<AuthSessionState, "authenticated" | "scopes"> | null,
phase: "connected" as "connected" | "offline",
assetAtom: {},
mint: vi.fn(),
assetQuery: vi.fn(),
}));
vi.mock("react", () => ({ useCallback: <A>(callback: A) => callback }));
vi.mock("@effect/atom-react", () => ({
useAtomValue: (atom: unknown) =>
atom === state.assetAtom
? AsyncResult.success({ relativeUrl: "/api/assets/image.png", expiresAt: 1 })
: AsyncResult.initial(false),
}));
vi.mock("./session", () => ({
environmentSession: { sessionStateAtom: () => ({}) },
usePreparedConnection: () => ({ _tag: "Some", value: { httpBaseUrl: "https://host.test" } }),
}));
vi.mock("./presentation", () => ({
useEnvironmentPresentation: () => ({
isReady: true,
presentation: { connection: { phase: state.phase, error: null } },
}),
}));
vi.mock("./query", () => ({
useEnvironmentQuery: () => ({ data: state.session, error: null }),
}));
vi.mock("./projectClones", () => ({ environmentProjectCloneListAtom: () => null }));
vi.mock("../connection/runtime", () => ({ connectionAtomRuntime: {} }));
vi.mock("@t3tools/client-runtime/state/assets", async (importOriginal) => ({
...(await importOriginal<typeof import("@t3tools/client-runtime/state/assets")>()),
createAssetEnvironmentAtoms: () => ({ createUrl: state.assetQuery }),
}));
vi.mock("./use-atom-query-runner", () => ({ useAtomQueryRunner: () => state.mint }));
import { useRefreshAssetUrl, useAssetUrlState } from "./assets";
const environmentId = EnvironmentId.make("asset-environment");
const threadId = ThreadId.make("asset-thread");
const resource = { _tag: "media-file", threadId, path: "/repo/image.png" } as const;
beforeEach(() => {
state.session = null;
state.phase = "connected";
state.assetQuery.mockReset().mockReturnValue(state.assetAtom);
state.mint
.mockReset()
.mockResolvedValue(AsyncResult.success({ relativeUrl: "/api/assets/image.png", expiresAt: 1 }));
});
it.each(["workspace-file", "media-file"] as const)(
"keeps %s loading until its file grant resolves",
(_tag) => {
expect(useAssetUrlState(environmentId, { ...resource, _tag })).toEqual({ _tag: "Loading" });
expect(state.assetQuery).not.toHaveBeenCalled();
state.session = { authenticated: true, scopes: [AuthFilesystemReadScope] };
expect(useAssetUrlState(environmentId, { ...resource, _tag })).toEqual({
_tag: "Success",
expiresAt: 1,
url: "https://host.test/api/assets/image.png",
});
},
);
it("hides host assets with a denied grant while preserving attachments", () => {
state.session = { authenticated: true, scopes: [] };
expect(useAssetUrlState(environmentId, resource)).toEqual({ _tag: "Failure", reason: "failed" });
expect(state.assetQuery).not.toHaveBeenCalled();
expect(useAssetUrlState(environmentId, { _tag: "attachment", attachmentId: "upload" })).toEqual({
_tag: "Success",
expiresAt: 1,
url: "https://host.test/api/assets/image.png",
});
});
it("stops waiting for an unresolved grant when the connection is offline", () => {
state.phase = "offline";
expect(useAssetUrlState(environmentId, resource)).toEqual({
_tag: "Failure",
reason: "disconnected",
});
expect(state.assetQuery).not.toHaveBeenCalled();
});
it("lets the server authorize an explicit refresh before the client grant loads", async () => {
await expect(useRefreshAssetUrl(environmentId, resource)()).resolves.toBe(
"https://host.test/api/assets/image.png",
);
expect(state.mint).toHaveBeenCalledWith({ environmentId, input: { resource } });
const denied = new EnvironmentAuthorizationError({
message: "This connection cannot read host files.",
requiredScope: AuthFilesystemReadScope,
});
state.mint.mockResolvedValue(AsyncResult.failure(Cause.fail(denied)));
await expect(useRefreshAssetUrl(environmentId, resource)()).resolves.toBeNull();
});
+28 -27
View File
@@ -1,8 +1,5 @@
import { useAtomValue } from "@effect/atom-react";
import {
type EnvironmentConnectionPhase,
presentConnectionState,
} from "@t3tools/client-runtime/connection";
import { resolveFilesystemReadAccess } from "@t3tools/client-runtime/state/filesystem";
import {
assetUrlStateFromResult,
createAssetEnvironmentAtoms,
@@ -10,16 +7,15 @@ import {
EMPTY_ASSET_URL_ATOM,
} from "@t3tools/client-runtime/state/assets";
import type { AssetResource, EnvironmentId } from "@t3tools/contracts";
import * as Option from "effect/Option";
import { AsyncResult, Atom } from "effect/reactivity";
import { useCallback } from "react";
import { environmentCatalog } from "../connection/catalog";
import { connectionAtomRuntime } from "../connection/runtime";
import { projectFaviconDatabaseCache } from "../lib/projectFaviconDatabaseCache";
import { type AssetUrlState, deriveAssetUrlState } from "./asset-url-state";
import { environmentProjectCloneListAtom } from "./projectClones";
import { environmentSession, usePreparedConnection } from "./session";
import { useEnvironmentPresentation } from "./presentation";
import { useEnvironmentQuery } from "./query";
import { useAtomQueryRunner } from "./use-atom-query-runner";
export type { AssetUrlFailureReason, AssetUrlState } from "./asset-url-state";
@@ -33,35 +29,40 @@ export const projectFaviconUrlAtom = createProjectFaviconUrlAtomFamily({
projectClones: environmentProjectCloneListAtom,
});
const EMPTY_CONNECTION_STATE_ATOM = Atom.make(AsyncResult.initial<never, never>(false)).pipe(
Atom.withLabel("mobile-asset-connection-state:empty"),
);
function useConnectionPhase(environmentId: EnvironmentId | null): EnvironmentConnectionPhase {
const state = useAtomValue(
environmentId === null
? EMPTY_CONNECTION_STATE_ATOM
: environmentCatalog.stateAtom(environmentId),
);
const value = Option.getOrNull(AsyncResult.value(state));
return value === null ? "available" : presentConnectionState(value).phase;
}
export function useAssetUrlState(
environmentId: EnvironmentId | null,
resource: AssetResource | null,
): AssetUrlState {
const fileAccessSession = useEnvironmentQuery(
environmentId === null ? null : environmentSession.sessionStateAtom(environmentId),
);
const fileEnvironment = useEnvironmentPresentation(environmentId);
const fileAccess = resolveFilesystemReadAccess({
isCatalogReady: fileEnvironment.isReady,
connection: fileEnvironment.presentation?.connection ?? null,
session: fileAccessSession.data,
sessionError: fileAccessSession.error,
});
const canReadResource =
fileAccess.canReadFiles ||
(resource?._tag !== "workspace-file" &&
resource?._tag !== "media-file" &&
resource?._tag !== "draft-workspace-file");
const preparedConnection = usePreparedConnection(environmentId);
const connectionPhase = useConnectionPhase(environmentId);
const connectionPhase = fileEnvironment.presentation?.connection.phase ?? "available";
const result = useAtomValue(
environmentId === null || resource === null
!canReadResource || environmentId === null || resource === null
? EMPTY_ASSET_URL_ATOM
: assetEnvironment.createUrl({ environmentId, input: { resource } }),
);
const shared = assetUrlStateFromResult(
result,
preparedConnection._tag === "Some" ? preparedConnection.value.httpBaseUrl : null,
);
const shared = !canReadResource
? fileAccess.isPending
? { _tag: "Loading" as const }
: { _tag: "Failure" as const }
: assetUrlStateFromResult(
result,
preparedConnection._tag === "Some" ? preparedConnection.value.httpBaseUrl : null,
);
return deriveAssetUrlState({
connectionPhase,
// A failure left over from an outage is re-queried as soon as the
@@ -1,36 +1,53 @@
import type { MediaActionsSource } from "../lib/mediaActionsSource";
import { useNavigation } from "@react-navigation/native";
import type { MediaActionId } from "@t3tools/client-runtime/media-actions";
import type { MediaReference } from "@t3tools/client-runtime/media-reference";
import type { AssetResource, EnvironmentId, ThreadId } from "@t3tools/contracts";
import {
AuthFilesystemReadScope,
type AuthSessionState,
type EnvironmentId,
} from "@t3tools/contracts";
import { normalizeNativeMarkdownUrl } from "@t3tools/mobile-markdown-text/links";
import * as Option from "effect/Option";
import { AsyncResult } from "effect/reactivity";
import { useEffect, useRef, useState } from "react";
import { Alert } from "react-native";
import { useRefreshAssetUrl } from "../state/assets";
import { downloadAndShareAttachment, shareLocalAttachment } from "./attachmentDownload";
import type { FileBackedComposerAttachment } from "./composerImages";
import { copyTextWithHaptic } from "./copyTextWithHaptic";
import { loadLocalAttachmentPreview } from "./localAttachmentPreview";
import { useRefreshAssetUrl } from "./assets";
import { appAtomRegistry } from "./atom-registry";
import { useEnvironmentQuery } from "./query";
import { environmentSession } from "./session";
import { downloadAndShareAttachment, shareLocalAttachment } from "../lib/attachmentDownload";
import { copyTextWithHaptic } from "../lib/copyTextWithHaptic";
import { loadLocalAttachmentPreview } from "../lib/localAttachmentPreview";
/** Authored source metadata is kept separate from temporary preview/download URLs. */
export type MediaActionsSource = {
readonly reference?: MediaReference;
readonly name: string;
readonly mimeType: string;
/** Anchors the iOS share sheet to the view that opened the menu. */
readonly sourceIdentifier?: string;
} & (
| { readonly uri: string }
| { readonly attachment: FileBackedComposerAttachment }
| {
readonly environmentId: EnvironmentId;
readonly threadId?: ThreadId;
readonly resource: AssetResource;
}
);
/** An explicit action may ask the server while its grant is still unresolved. */
function allowsHostMedia(session: Pick<AuthSessionState, "authenticated" | "scopes"> | null) {
return (
session === null ||
(session.authenticated && session.scopes?.includes(AuthFilesystemReadScope) === true)
);
}
function canReadHostMedia(environmentId: EnvironmentId | null): boolean {
if (environmentId === null) return true;
const result = appAtomRegistry.get(environmentSession.sessionStateAtom(environmentId));
return result._tag !== "Failure" && allowsHostMedia(Option.getOrNull(AsyncResult.value(result)));
}
export function useMediaActions(source: MediaActionsSource | undefined, onOpenFile?: () => void) {
const navigation = useNavigation();
const hostEnvironmentId =
source &&
"resource" in source &&
(source.resource._tag === "workspace-file" || source.resource._tag === "media-file")
? source.environmentId
: null;
const fileSession = useEnvironmentQuery(
hostEnvironmentId === null ? null : environmentSession.sessionStateAtom(hostEnvironmentId),
);
const canReadMedia =
hostEnvironmentId === null ||
(fileSession.error === null && fileSession.data !== null && allowsHostMedia(fileSession.data));
const refresh = useRefreshAssetUrl(
source && "environmentId" in source ? source.environmentId : null,
source && "resource" in source ? source.resource : null,
@@ -40,11 +57,11 @@ export function useMediaActions(source: MediaActionsSource | undefined, onOpenFi
useEffect(() => () => controller.current?.abort(), []);
const share = () => {
if (!source || controller.current) return;
if (!source || controller.current || !canReadHostMedia(hostEnvironmentId)) return;
const request = new AbortController();
controller.current = request;
setSharing(true);
void (async () => {
return (async () => {
if ("attachment" in source) {
const preview = await loadLocalAttachmentPreview(source.attachment, request.signal);
if (!preview) return;
@@ -56,7 +73,7 @@ export function useMediaActions(source: MediaActionsSource | undefined, onOpenFi
return;
}
const uri = "uri" in source ? normalizeNativeMarkdownUrl(source.uri) : await refresh();
if (request.signal.aborted) return;
if (request.signal.aborted || !canReadHostMedia(hostEnvironmentId)) return;
if (uri === null) throw new Error("The file could not be loaded. Reconnect and try again.");
const input = {
attachment: { name: source.name, mimeType: source.mimeType },
@@ -120,7 +137,9 @@ export function useMediaActions(source: MediaActionsSource | undefined, onOpenFi
{
id: "open-file" as const,
title: "Open in file viewer",
disabled: !canReadMedia,
run: () => {
if (!canReadHostMedia(hostEnvironmentId)) return;
onOpenFile?.();
navigation.navigate("ThreadFile", {
environmentId: String(source.environmentId),
@@ -135,7 +154,7 @@ export function useMediaActions(source: MediaActionsSource | undefined, onOpenFi
id: "save" as const,
title: sharing ? "Opening share sheet…" : "Save or share",
run: share,
disabled: sharing,
disabled: sharing || !canReadMedia,
},
]
: [];
@@ -0,0 +1,100 @@
import { AuthFilesystemReadScope, EnvironmentId, type AuthSessionState } from "@t3tools/contracts";
import { beforeEach, expect, it, vi } from "vite-plus/test";
const state = vi.hoisted(() => ({
session: null as Pick<AuthSessionState, "authenticated" | "scopes"> | null,
sessionError: null as string | null,
phase: "connected" as "connected" | "offline",
sessionAtom: {},
searchAtom: {},
}));
vi.mock("react", async (importOriginal) => ({
...(await importOriginal<typeof import("react")>()),
useCallback: <A>(callback: A) => callback,
useEffect: () => {},
useMemo: <A>(factory: () => A) => factory(),
useState: <A>(value: A) => [value, vi.fn()],
}));
vi.mock("./session", () => ({
environmentSession: { sessionStateAtom: () => state.sessionAtom },
}));
vi.mock("./presentation", () => ({
useEnvironmentPresentation: () => ({
isReady: true,
presentation: { connection: { phase: state.phase, error: null } },
}),
}));
vi.mock("./pull-requests", () => ({ composerPullRequests: {} }));
vi.mock("./projects", () => ({
projectEnvironment: { searchEntries: () => state.searchAtom },
}));
vi.mock("./atom-registry", () => ({ appAtomRegistry: {} }));
vi.mock("./orchestration", () => ({ orchestrationEnvironment: {} }));
vi.mock("./threads", () => ({ useEnvironmentThread: vi.fn() }));
vi.mock("./vcs", () => ({ vcsEnvironment: {} }));
vi.mock("./query", () => ({
useEnvironmentQuery: (atom: unknown) => ({
data:
atom === state.sessionAtom
? state.session
: atom === state.searchAtom
? { entries: [{ path: "src/index.ts", kind: "file" }] }
: null,
error: atom === state.sessionAtom ? state.sessionError : null,
isPending: atom === state.sessionAtom && state.session === null && state.sessionError === null,
refresh: vi.fn(),
}),
}));
import { useComposerPathSearch } from "./queries";
const target = {
environmentId: EnvironmentId.make("test-environment"),
cwd: "/repo",
query: "src",
};
beforeEach(() => {
state.session = null;
state.sessionError = null;
state.phase = "connected";
});
it("keeps a file search pending until its grant loads, then shows matches", () => {
expect(useComposerPathSearch(target)).toMatchObject({
entries: [],
error: null,
isPending: true,
});
state.session = { authenticated: true, scopes: [AuthFilesystemReadScope] };
expect(useComposerPathSearch(target)).toMatchObject({
entries: [{ path: "src/index.ts", kind: "file" }],
error: null,
isPending: false,
});
});
it("shows a confirmed denial and a connection failure separately", () => {
state.session = { authenticated: true, scopes: [] };
expect(useComposerPathSearch(target)).toMatchObject({
entries: [],
error: "This connection cannot search host files.",
isPending: false,
});
state.session = null;
state.phase = "offline";
expect(useComposerPathSearch(target)).toMatchObject({
entries: [],
error: "This environment is not connected.",
isPending: false,
});
});
it("leaves an inactive search idle while its grant loads", () => {
expect(useComposerPathSearch({ ...target, cwd: null, query: null })).toMatchObject({
entries: [],
error: null,
isPending: false,
});
});
+34 -8
View File
@@ -1,4 +1,7 @@
import { filterComposerPullRequestMatches } from "@t3tools/shared/composerPullRequestMatches";
import { resolveFilesystemReadAccess } from "@t3tools/client-runtime/state/filesystem";
import { environmentSession } from "./session";
import { useEnvironmentPresentation } from "./presentation";
import type { VcsRefTarget } from "@t3tools/client-runtime/state/vcs";
import type {
EnvironmentId,
@@ -309,25 +312,48 @@ export function useComposerPathSearch(target: ComposerPathSearchTarget) {
[target.cwd, target.environmentId, target.query],
);
const debouncedTarget = useDebouncedValue(normalizedTarget, COMPOSER_PATH_SEARCH_DEBOUNCE_MS);
const result = useEnvironmentQuery(
const fileAccessSession = useEnvironmentQuery(
debouncedTarget.environmentId === null
? null
: environmentSession.sessionStateAtom(debouncedTarget.environmentId),
);
const fileEnvironment = useEnvironmentPresentation(debouncedTarget.environmentId);
const fileAccess = resolveFilesystemReadAccess({
isCatalogReady: fileEnvironment.isReady,
connection: fileEnvironment.presentation?.connection ?? null,
session: fileAccessSession.data,
sessionError: fileAccessSession.error,
});
const { canReadFiles } = fileAccess;
const searchTarget =
debouncedTarget.environmentId !== null &&
debouncedTarget.cwd !== null &&
debouncedTarget.query.length > 0
? projectEnvironment.searchEntries({
debouncedTarget.cwd !== null &&
debouncedTarget.query.length > 0
? {
environmentId: debouncedTarget.environmentId,
input: {
cwd: debouncedTarget.cwd,
query: debouncedTarget.query,
limit: COMPOSER_PATH_SEARCH_LIMIT,
},
})
: null,
}
: null;
const result = useEnvironmentQuery(
canReadFiles && searchTarget !== null ? projectEnvironment.searchEntries(searchTarget) : null,
);
const hasTarget = searchTarget !== null;
return {
entries: result.data?.entries ?? [],
error: result.error,
isPending: normalizedTarget.query !== debouncedTarget.query || result.isPending,
error:
!hasTarget || fileAccess.isPending
? null
: canReadFiles
? result.error
: (fileAccess.error ?? "This connection cannot search host files."),
isPending:
normalizedTarget.query !== debouncedTarget.query ||
(hasTarget && (fileAccess.isPending || result.isPending)),
refresh: result.refresh,
};
}
@@ -1,5 +1,6 @@
import {
AuthEnvironmentMaintainScope,
AuthFilesystemReadScope,
AuthProvidersManageScope,
AuthSettingsWriteScope,
DEFAULT_SERVER_SETTINGS,
@@ -301,3 +302,43 @@ it.effect("requires task permission before attaching a prepared worktree to a th
expect(handled).toBe(false);
}).pipe(Effect.scoped),
);
it.effect("separates host file URLs from readable attachment URLs", () =>
Effect.gen(function* () {
const group = WsRpcGroup.omit(
...[...WsRpcGroup.requests.keys()].filter(
(
tag,
): tag is Exclude<keyof typeof RPC_REQUIRED_SCOPES, typeof WS_METHODS.assetsCreateUrl> =>
tag !== WS_METHODS.assetsCreateUrl,
),
);
let handled = 0;
const client = yield* RpcTest.makeClient(group).pipe(
Effect.provide(
Layer.mergeAll(
group.toLayerHandler(WS_METHODS.assetsCreateUrl, () =>
Effect.sync(() => {
handled++;
return { relativeUrl: "/api/assets/file", expiresAt: 1 };
}),
),
RpcAuthorization.layer([AuthOrchestrationReadScope]),
),
),
);
yield* client[WS_METHODS.assetsCreateUrl]({
resource: { _tag: "attachment", attachmentId: "image" },
});
for (const resource of [
{ _tag: "workspace-file", threadId: ThreadId.make("thread"), path: "file.txt" },
{ _tag: "media-file", threadId: ThreadId.make("thread"), path: "/repo/image.png" },
{ _tag: "draft-workspace-file", cwd: "/repo", path: "file.txt" },
] as const) {
expect(
yield* client[WS_METHODS.assetsCreateUrl]({ resource }).pipe(Effect.flip),
).toMatchObject({ requiredScope: AuthFilesystemReadScope });
}
expect(handled).toBe(1);
}).pipe(Effect.scoped),
);
+21 -9
View File
@@ -2,6 +2,7 @@ import {
CLIENT_GUARDED_RPC_SCOPES,
type DeviceListInput,
clientRpcRequiredScopes,
AssetCreateUrlInput,
AuthAccessReadScope,
ServerSettingsPatch,
ProviderInstanceMutation,
@@ -9,11 +10,12 @@ import {
AuthSettingsWriteScope,
AuthProvidersManageScope,
AuthEnvironmentMaintainScope,
AuthFilesystemReadScope,
AuthFilesystemWriteScope,
AuthOrchestrationOperateScope,
AuthOrchestrationReadScope,
AuthRelayReadScope,
AuthRelayWriteScope,
AuthReviewWriteScope,
AuthTerminalOperateScope,
ORCHESTRATION_V2_WS_METHODS,
type AuthEnvironmentScope,
@@ -131,15 +133,15 @@ export const RPC_REQUIRED_SCOPES = {
[WS_METHODS.pullRequestsLabelCandidates]: AuthOrchestrationReadScope,
[WS_METHODS.sourceControlLookupRepository]: AuthOrchestrationReadScope,
[WS_METHODS.subscribeProjectClones]: AuthOrchestrationReadScope,
[WS_METHODS.projectsListEntries]: AuthOrchestrationReadScope,
[WS_METHODS.projectsReadFile]: AuthOrchestrationReadScope,
[WS_METHODS.projectsSearchContents]: AuthOrchestrationReadScope,
[WS_METHODS.projectsSearchEntries]: AuthOrchestrationReadScope,
[WS_METHODS.projectsWriteFile]: AuthOrchestrationOperateScope,
[WS_METHODS.projectsListEntries]: AuthFilesystemReadScope,
[WS_METHODS.projectsReadFile]: AuthFilesystemReadScope,
[WS_METHODS.projectsSearchContents]: AuthFilesystemReadScope,
[WS_METHODS.projectsSearchEntries]: AuthFilesystemReadScope,
[WS_METHODS.projectsWriteFile]: AuthFilesystemWriteScope,
[WS_METHODS.projectsEnsureScratch]: AuthOrchestrationOperateScope,
[WS_METHODS.projectsCreateNew]: AuthOrchestrationOperateScope,
[WS_METHODS.shellOpenInEditor]: AuthOrchestrationOperateScope,
[WS_METHODS.filesystemBrowse]: AuthOrchestrationReadScope,
[WS_METHODS.filesystemBrowse]: AuthFilesystemReadScope,
[WS_METHODS.agentSessionsScan]: AuthOrchestrationReadScope,
[WS_METHODS.agentSessionsImport]: AuthOrchestrationOperateScope,
[WS_METHODS.assetsCreateUrl]: AuthOrchestrationReadScope,
@@ -154,8 +156,8 @@ export const RPC_REQUIRED_SCOPES = {
[WS_METHODS.vcsRefreshStatus]: AuthOrchestrationReadScope,
[WS_METHODS.gitResolvePullRequest]: AuthOrchestrationReadScope,
[WS_METHODS.vcsListRefs]: AuthOrchestrationReadScope,
[WS_METHODS.reviewGetDiffPreview]: AuthReviewWriteScope,
[WS_METHODS.reviewGetDiffFileContents]: AuthReviewWriteScope,
[WS_METHODS.reviewGetDiffPreview]: AuthFilesystemReadScope,
[WS_METHODS.reviewGetDiffFileContents]: AuthFilesystemReadScope,
[WS_METHODS.terminalOpen]: AuthTerminalOperateScope,
[WS_METHODS.terminalAttach]: AuthTerminalOperateScope,
[WS_METHODS.terminalWrite]: AuthTerminalOperateScope,
@@ -227,6 +229,16 @@ const requiredScopesForRpcCall = (
method: string,
payload: unknown,
): ReadonlyArray<AuthEnvironmentScope> => {
if (method === WS_METHODS.assetsCreateUrl) {
const { resource } = Schema.decodeUnknownSync(AssetCreateUrlInput)(payload);
return [
resource._tag === "workspace-file" ||
resource._tag === "media-file" ||
resource._tag === "draft-workspace-file"
? AuthFilesystemReadScope
: AuthOrchestrationReadScope,
];
}
if (method === WS_METHODS.serverUpdateSettings) return requiredScopesForSettingsUpdate(payload);
const guarded = clientRpcRequiredScopes(method, payload);
if (guarded.length > 0) return guarded;
+2 -24
View File
@@ -2,16 +2,7 @@ import {
AuthAccessReadScope,
AuthAccessWriteScope,
AuthStandardClientScopes,
AuthSettingsWriteScope,
AuthProvidersManageScope,
AuthEnvironmentMaintainScope,
AuthOrchestrationOperateScope,
AuthOrchestrationReadScope,
AuthRelayReadScope,
AuthRelayWriteScope,
AuthReviewWriteScope,
AuthSourceControlWriteScope,
AuthTerminalOperateScope,
AuthGrantScope,
EnvironmentAuthInvalidError,
type EnvironmentAuthInvalidReason,
EnvironmentHttpApi,
@@ -367,20 +358,7 @@ export const layer = HttpApiBuilder.group(
? undefined
: parseAllowedOAuthScope({
value: args.payload.scope,
allowedScopes: new Set<AuthEnvironmentScope>([
AuthOrchestrationReadScope,
AuthOrchestrationOperateScope,
AuthSettingsWriteScope,
AuthProvidersManageScope,
AuthEnvironmentMaintainScope,
AuthTerminalOperateScope,
AuthReviewWriteScope,
AuthSourceControlWriteScope,
AuthAccessReadScope,
AuthAccessWriteScope,
AuthRelayReadScope,
AuthRelayWriteScope,
]),
allowedScopes: new Set(AuthGrantScope.literals),
});
if (requestedScopes === null) {
return yield* failEnvironmentInvalidRequest("invalid_scope");
+3 -3
View File
@@ -1,8 +1,8 @@
import { AuthEnvironmentScope } from "@t3tools/contracts";
import { AuthGrantScope } from "@t3tools/contracts";
import { Flag } from "effect/cli";
export const authScopesFlag = (defaults: ReadonlyArray<AuthEnvironmentScope>) =>
Flag.Literals("scope", AuthEnvironmentScope.literals).pipe(
export const authScopesFlag = (defaults: ReadonlyArray<AuthGrantScope>) =>
Flag.Literals("scope", AuthGrantScope.literals).pipe(
Flag.withDescription(
`Authorization scope to grant. Repeat for multiple scopes; replaces the default set: ${defaults.join(", ")}.`,
),
+106
View File
@@ -0,0 +1,106 @@
import {
AuthFilesystemReadScope,
EnvironmentAuthorizationError,
EnvironmentId,
ThreadId,
type AuthSessionState,
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import { AsyncResult } from "effect/reactivity";
import { beforeEach, expect, it, vi } from "vite-plus/test";
const state = vi.hoisted(() => ({
session: null as Pick<AuthSessionState, "authenticated" | "scopes"> | null,
phase: "connected" as "connected" | "offline",
assetAtom: {},
mint: vi.fn(),
assetQuery: vi.fn(),
}));
vi.mock("react", () => ({ useCallback: <A>(callback: A) => callback }));
vi.mock("@effect/atom-react", () => ({
useAtomValue: (atom: unknown) =>
atom === state.assetAtom
? AsyncResult.success({ relativeUrl: "/api/assets/image.png", expiresAt: 1 })
: AsyncResult.initial(false),
}));
vi.mock("~/state/session", () => ({
usePreparedConnection: () => ({ _tag: "Some", value: { httpBaseUrl: "https://host.test" } }),
}));
vi.mock("~/state/filesystem", async () => {
const { resolveFilesystemReadAccess } = await import("@t3tools/client-runtime/state/filesystem");
return {
useFilesystemReadAccess: () =>
resolveFilesystemReadAccess({
isCatalogReady: true,
connection: { phase: state.phase, error: null },
session: state.session,
sessionError: null,
}),
};
});
vi.mock("~/state/assets", () => ({
assetEnvironment: { createUrl: state.assetQuery },
}));
vi.mock("~/state/use-atom-query-runner", () => ({ useAtomQueryRunner: () => state.mint }));
import { useAssetUrlRefresh, useAssetUrlState } from "./assetUrls";
const environmentId = EnvironmentId.make("asset-environment");
const threadId = ThreadId.make("asset-thread");
const resource = { _tag: "media-file", threadId, path: "/repo/image.png" } as const;
beforeEach(() => {
state.session = null;
state.phase = "connected";
state.assetQuery.mockReset().mockReturnValue(state.assetAtom);
state.mint
.mockReset()
.mockResolvedValue(AsyncResult.success({ relativeUrl: "/api/assets/image.png", expiresAt: 1 }));
});
it.each(["workspace-file", "media-file"] as const)(
"keeps %s loading until its file grant resolves",
(_tag) => {
expect(useAssetUrlState(environmentId, { ...resource, _tag })).toEqual({ _tag: "Loading" });
expect(state.assetQuery).not.toHaveBeenCalled();
state.session = { authenticated: true, scopes: [AuthFilesystemReadScope] };
expect(useAssetUrlState(environmentId, { ...resource, _tag })).toEqual({
_tag: "Success",
expiresAt: 1,
url: "https://host.test/api/assets/image.png",
});
},
);
it("hides host assets with a denied grant while preserving attachments", () => {
state.session = { authenticated: true, scopes: [] };
expect(useAssetUrlState(environmentId, resource)).toEqual({ _tag: "Failure" });
expect(state.assetQuery).not.toHaveBeenCalled();
expect(useAssetUrlState(environmentId, { _tag: "attachment", attachmentId: "upload" })).toEqual({
_tag: "Success",
expiresAt: 1,
url: "https://host.test/api/assets/image.png",
});
});
it("stops waiting for an unresolved grant when the connection is offline", () => {
state.phase = "offline";
expect(useAssetUrlState(environmentId, resource)).toEqual({ _tag: "Failure" });
expect(state.assetQuery).not.toHaveBeenCalled();
});
it("lets the server authorize an explicit refresh before the client grant loads", async () => {
await expect(useAssetUrlRefresh(environmentId, resource)()).resolves.toBe(
"https://host.test/api/assets/image.png",
);
expect(state.mint).toHaveBeenCalledWith({ environmentId, input: { resource } });
const denied = new EnvironmentAuthorizationError({
message: "This connection cannot read host files.",
requiredScope: AuthFilesystemReadScope,
});
state.mint.mockResolvedValue(AsyncResult.failure(Cause.fail(denied)));
await expect(useAssetUrlRefresh(environmentId, resource)()).rejects.toBe(denied);
});
+40 -13
View File
@@ -11,6 +11,7 @@ import { AsyncResult } from "effect/reactivity";
import { useCallback, useMemo } from "react";
import { assetEnvironment } from "~/state/assets";
import { useFilesystemReadAccess } from "~/state/filesystem";
import { usePreparedConnection } from "~/state/session";
import { useAtomQueryRunner } from "~/state/use-atom-query-runner";
@@ -20,12 +21,19 @@ export function useAssetUrlState(
environmentId: EnvironmentId | null,
resource: AssetResource | null,
): AssetUrlState {
const fileAccess = useFilesystemReadAccess(environmentId);
const canReadResource =
fileAccess.canReadFiles ||
(resource?._tag !== "workspace-file" &&
resource?._tag !== "media-file" &&
resource?._tag !== "draft-workspace-file");
const preparedConnection = usePreparedConnection(environmentId);
const result = useAtomValue(
environmentId === null || resource === null
!canReadResource || environmentId === null || resource === null
? EMPTY_ASSET_URL_ATOM
: assetEnvironment.createUrl({ environmentId, input: { resource } }),
);
if (!canReadResource) return { _tag: fileAccess.isPending ? "Loading" : "Failure" };
return assetUrlStateFromResult(
result,
preparedConnection._tag === "Some" ? preparedConnection.value.httpBaseUrl : null,
@@ -55,21 +63,40 @@ export function useAssetUrls(
resources: ReadonlyArray<AssetResource>,
): ReadonlyArray<string | null> {
const preparedConnection = usePreparedConnection(environmentId);
const { canReadFiles } = useFilesystemReadAccess(environmentId);
const allowedResources = useMemo(
() =>
canReadFiles
? resources
: resources.filter(
(resource) =>
resource._tag !== "workspace-file" &&
resource._tag !== "media-file" &&
resource._tag !== "draft-workspace-file",
),
[canReadFiles, resources],
);
const results = useAtomValue(
assetEnvironment.createUrls({
environmentId,
resources,
resources: allowedResources,
}),
);
return useMemo(
() =>
preparedConnection._tag === "None"
? resources.map(() => null)
: results.map((result) =>
AsyncResult.isSuccess(result)
? resolveAssetUrl(preparedConnection.value.httpBaseUrl, result.value.relativeUrl)
: null,
),
[preparedConnection, resources, results],
);
return useMemo(() => {
if (preparedConnection._tag === "None") return resources.map(() => null);
let resultIndex = 0;
return resources.map((resource) => {
if (
!canReadFiles &&
(resource._tag === "workspace-file" ||
resource._tag === "media-file" ||
resource._tag === "draft-workspace-file")
)
return null;
const result = results[resultIndex++];
return result && AsyncResult.isSuccess(result)
? resolveAssetUrl(preparedConnection.value.httpBaseUrl, result.value.relativeUrl)
: null;
});
}, [canReadFiles, preparedConnection, resources, results]);
}
@@ -0,0 +1,100 @@
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
import { AsyncResult } from "effect/reactivity";
import { act, type ComponentProps, type ReactNode } from "react";
import { create, type ReactTestRenderer } from "react-test-renderer";
import { expect, it, vi } from "vite-plus/test";
const mint = vi.hoisted(() => vi.fn());
vi.mock("@effect/atom-react", () => ({ useAtomValue: () => null }));
vi.mock("../hooks/useTheme", () => ({ useTheme: () => ({ resolvedTheme: "dark" }) }));
vi.mock("../hooks/useSettings", async (importOriginal) => {
const actual = await importOriginal<typeof import("../hooks/useSettings")>();
const settings = actual.getClientSettings();
return {
...actual,
useClientSettings: (select: (value: typeof settings) => unknown) => select(settings),
};
});
vi.mock("./ui/tooltip", async () => {
const { cloneElement, isValidElement } = await import("react");
return {
Tooltip: ({ children }: { children: ReactNode }) => <>{children}</>,
TooltipTrigger({
render,
children,
}: ComponentProps<typeof import("./ui/tooltip").TooltipTrigger>) {
if (!isValidElement(render)) return <>{children}</>;
return children === undefined ? render : cloneElement(render, undefined, children);
},
TooltipPopup: () => null,
};
});
vi.mock("../state/use-atom-query-runner", () => ({ useAtomQueryRunner: () => mint }));
vi.mock("../state/use-atom-command", () => ({ useAtomCommand: () => vi.fn() }));
vi.mock("../state/session", async (importOriginal) => ({
...(await importOriginal<typeof import("../state/session")>()),
readEnvironmentScope: () => false,
useEnvironmentScope: () => false,
usePreparedConnection: () => ({ _tag: "Some", value: { httpBaseUrl: "https://host.test" } }),
}));
vi.mock("../state/entities", () => ({
readEnvironmentSupportsServerBrowser: () => false,
readThreadShell: () => null,
useProjects: () => [],
useServerConfigs: () => new Map(),
}));
vi.mock("../remoteOpen", () => ({
useRemoteOpenResolution: () => ({ state: { mode: "local-exec" }, isResolved: true }),
}));
vi.mock("../editorPreferences", () => ({
useOpenInPreferredEditor: () => vi.fn(),
usePreferredEditor: () => [null, vi.fn()],
}));
vi.mock("~/lib/openPullRequestLink", () => ({
findProjectForChangeRequest: () => undefined,
matchesLinkedPullRequestUrl: () => false,
parseChangeRequestUrl: () => null,
useOpenChangeRequestLink: () => vi.fn(),
}));
import ChatMarkdown from "./ChatMarkdown";
it("opens host media through server authorization before the client grant loads", async () => {
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
mint.mockResolvedValue(
AsyncResult.success({ relativeUrl: "/api/assets/image.png", expiresAt: 1 }),
);
const onImageExpand = vi.fn();
const threadRef = {
environmentId: EnvironmentId.make("media-environment"),
threadId: ThreadId.make("media-thread"),
};
let renderer: ReactTestRenderer | undefined;
try {
await act(async () => {
renderer = create(
<ChatMarkdown
cwd="/repo"
threadRef={threadRef}
text="[Open image](/tmp/image.png)"
onImageExpand={onImageExpand}
/>,
);
});
await act(async () => {
const link = renderer!.root
.findAllByType("a")
.find((node) => node.props.href === "/tmp/image.png");
expect(link).toBeDefined();
link!.props.onClick({ preventDefault: vi.fn(), stopPropagation: vi.fn() });
});
expect(onImageExpand).toHaveBeenCalledWith(
expect.objectContaining({
images: [expect.objectContaining({ src: "https://host.test/api/assets/image.png" })],
}),
);
} finally {
await act(async () => renderer?.unmount());
vi.unstubAllGlobals();
}
});
+7 -2
View File
@@ -1,5 +1,5 @@
import { usePullRequestLinking } from "~/hooks/usePullRequestLinking";
import { AuthOrchestrationOperateScope } from "@t3tools/contracts";
import { AuthFilesystemReadScope, AuthOrchestrationOperateScope } from "@t3tools/contracts";
import { useAtomValue } from "@effect/atom-react";
import {
COMPOSER_CONTEXT_CLIPBOARD_MIME,
@@ -2757,7 +2757,12 @@ function useChatMarkdownState({
);
const findWorkspaceBasenameMatch = useCallback(
async (workspaceRelativePath: string) => {
if (!cwd || environmentId === null || !needsWorkspaceBasenameLookup(workspaceRelativePath)) {
if (
!cwd ||
environmentId === null ||
!readEnvironmentScope(environmentId, AuthFilesystemReadScope) ||
!needsWorkspaceBasenameLookup(workspaceRelativePath)
) {
return null;
}
const result = await searchProjectEntries({
+28 -7
View File
@@ -32,6 +32,7 @@ import {
import {
AuthOrchestrationOperateScope,
AuthSourceControlWriteScope,
AuthFilesystemReadScope,
type DesktopWslState,
type EnvironmentId,
type EnvironmentMachineKind,
@@ -100,7 +101,7 @@ import {
} from "./settings/ThemePreviewCircles";
import { readLocalApi } from "../localApi";
import { desktopLocalBackendId } from "../connection/desktopLocal";
import { filesystemEnvironment } from "../state/filesystem";
import { filesystemEnvironment, useFilesystemReadAccess } from "../state/filesystem";
import { projectEnvironment } from "../state/projects";
import { useEnvironmentQuery } from "../state/query";
import { serverEnvironment } from "../state/server";
@@ -1160,11 +1161,14 @@ function OpenCommandPaletteDialog(props: {
);
const relativePathNeedsActiveProject =
isExplicitRelativeProjectPath(query.trim()) && currentProjectCwdForBrowse === null;
const browseQuery = useEnvironmentQuery(
const browseAccess = useFilesystemReadAccess(browseEnvironmentId);
const hasBrowseTarget =
isBrowsing &&
browsePath.directoryPath.length > 0 &&
browseEnvironmentId !== null &&
!relativePathNeedsActiveProject
browsePath.directoryPath.length > 0 &&
browseEnvironmentId !== null &&
!relativePathNeedsActiveProject;
const browseQuery = useEnvironmentQuery(
browseAccess.canReadFiles && hasBrowseTarget
? filesystemEnvironment.browse({
environmentId: browseEnvironmentId,
input: {
@@ -1175,7 +1179,11 @@ function OpenCommandPaletteDialog(props: {
: null,
);
const browseResult = browseQuery.data;
const isBrowsePending = browseQuery.isPending;
const isBrowsePending = hasBrowseTarget && (browseAccess.isPending || browseQuery.isPending);
const browseAccessError =
hasBrowseTarget && !browseAccess.isPending && !browseAccess.canReadFiles
? (browseAccess.error ?? "This connection cannot browse host folders.")
: null;
const browseEntries = browseResult?.entries ?? EMPTY_BROWSE_ENTRIES;
const { visibleEntries: visibleBrowseEntries, exactEntry: exactBrowseEntry } = useMemo(
() =>
@@ -1202,7 +1210,10 @@ function OpenCommandPaletteDialog(props: {
const environment = environments.find(
(candidate) => candidate.environmentId === environmentId,
);
if (!canPreloadBrowsePath(environment?.connection.phase)) {
if (
!readEnvironmentScope(environmentId, AuthFilesystemReadScope) ||
!canPreloadBrowsePath(environment?.connection.phase)
) {
return;
}
@@ -2992,6 +3003,7 @@ function OpenCommandPaletteDialog(props: {
const willCreateProjectPath =
canSubmitBrowsePath &&
!isBrowsePending &&
browseAccessError === null &&
query.trim().length > 0 &&
!hasHighlightedBrowseItem &&
(hasTrailingPathSeparator(query) ? !browseResult : exactBrowseEntry === null);
@@ -3512,6 +3524,15 @@ function OpenCommandPaletteDialog(props: {
</div>
</div>
) : null}
{browseAccessError ? (
<div role="alert" className="px-4 py-3 text-sm text-muted-foreground">
{browseAccessError}
</div>
) : isBrowsePending && browseResult === null ? (
<div role="status" className="px-4 py-3 text-sm text-muted-foreground">
Loading folders...
</div>
) : null}
<CommandPaletteVirtualizedResults
rows={resultRows.rows}
listRef={resultListRef}
+22 -3
View File
@@ -23,6 +23,7 @@ import * as Schema from "effect/Schema";
import * as DateTime from "effect/DateTime";
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { useCodeViewFileReveal } from "./diffs/useCodeViewFileReveal";
import { useFilesystemReadAccess } from "~/state/filesystem";
import { useOpenInPreferredEditor } from "../editorPreferences";
import { useFileContextMenuHandler } from "../fileContextMenu";
import { type DraftId } from "../composerDraftStore";
@@ -223,6 +224,8 @@ export default function DiffPanel({
const activeThreadId = routeThreadRef?.threadId ?? null;
const activeThread = useThreadShell(routeThreadRef);
const activeThreadProjection = useThreadProjection(routeThreadRef)?.projection ?? null;
const fileAccess = useFilesystemReadAccess(activeThread?.environmentId ?? null);
const { canReadFiles } = fileAccess;
const activeProjectId = activeThread?.projectId ?? null;
const activeProject = useProject(
activeThread && activeProjectId
@@ -337,7 +340,7 @@ export default function DiffPanel({
{ enabled: isGitRepo && selectedTurn !== undefined },
);
const primaryBranchDiffPreview = useEnvironmentQuery(
selectedRunId === null && activeThread && activeCwd
canReadFiles && selectedRunId === null && activeThread && activeCwd
? reviewEnvironment.diffPreview({
environmentId: activeThread.environmentId,
input: {
@@ -354,7 +357,7 @@ export default function DiffPanel({
serverConfig?.cwd !== undefined &&
serverConfig.cwd !== activeCwd;
const fallbackBranchDiffPreview = useEnvironmentQuery(
shouldRetryBranchDiffAtEnvironmentCwd && activeThread && serverConfig
canReadFiles && shouldRetryBranchDiffAtEnvironmentCwd && activeThread && serverConfig
? reviewEnvironment.diffPreview({
environmentId: activeThread.environmentId,
input: {
@@ -386,6 +389,7 @@ export default function DiffPanel({
return undefined;
}
if (!canReadFiles) return undefined;
return createGitDiffFileContentsLoader(getDiffFileContents, {
environmentId: activeThread.environmentId,
cwd: preview.cwd,
@@ -394,7 +398,14 @@ export default function DiffPanel({
headRef: selectedGitSource.headRef,
cacheKey: selectedGitSource.diffHash,
});
}, [activeThread, branchDiffPreview.data, getDiffFileContents, selectedGitSource, selectedRunId]);
}, [
activeThread,
branchDiffPreview.data,
getDiffFileContents,
canReadFiles,
selectedGitSource,
selectedRunId,
]);
const loadDiffFilesRef = useRef(currentLoadDiffFiles);
loadDiffFilesRef.current = currentLoadDiffFiles;
const loadDiffFiles = useCallback<FileDiffContentsLoader>(async (fileDiff) => {
@@ -1051,6 +1062,14 @@ export default function DiffPanel({
<div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
No completed turns yet.
</div>
) : selectedRunId === null && !canReadFiles ? (
fileAccess.isPending ? (
<DiffPanelLoadingState label="Checking file access..." />
) : (
<div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
{fileAccess.error ?? "This connection cannot read local diffs."}
</div>
)
) : (
<>
<div className="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden bg-background">
@@ -3,7 +3,11 @@ import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import type { EnvironmentId, ScopedThreadRef } from "@t3tools/contracts";
import {
AuthFilesystemWriteScope,
type EnvironmentId,
type ScopedThreadRef,
} from "@t3tools/contracts";
import {
buildCollapsedProposedPlanPreviewMarkdown,
buildProposedPlanMarkdownFilename,
@@ -32,6 +36,7 @@ import { stackedThreadToast, toastManager } from "../ui/toast";
import { projectEnvironment } from "~/state/projects";
import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
import { useAtomCommand } from "~/state/use-atom-command";
import { readEnvironmentScope, useEnvironmentScope } from "~/state/session";
export const ProposedPlanCard = memo(function ProposedPlanCard({
planMarkdown,
@@ -47,6 +52,7 @@ export const ProposedPlanCard = memo(function ProposedPlanCard({
workspaceRoot: string | undefined;
}) {
const [expanded, setExpanded] = useState(false);
const canWriteFiles = useEnvironmentScope(environmentId, AuthFilesystemWriteScope);
const [isSaveDialogOpen, setIsSaveDialogOpen] = useState(false);
const [savePath, setSavePath] = useState("");
const [isSavingToWorkspace, setIsSavingToWorkspace] = useState(false);
@@ -85,6 +91,7 @@ export const ProposedPlanCard = memo(function ProposedPlanCard({
};
const openSaveDialog = () => {
if (!canWriteFiles) return;
if (!workspaceRoot) {
toastManager.add(
stackedThreadToast({
@@ -101,7 +108,7 @@ export const ProposedPlanCard = memo(function ProposedPlanCard({
const handleSaveToWorkspace = () => {
const relativePath = savePath.trim();
if (!workspaceRoot) {
if (!workspaceRoot || !readEnvironmentScope(environmentId, AuthFilesystemWriteScope)) {
return;
}
if (!relativePath) {
@@ -165,7 +172,10 @@ export const ProposedPlanCard = memo(function ProposedPlanCard({
{isCopied ? "Copied!" : "Copy to clipboard"}
</MenuItem>
<MenuItem onClick={handleDownload}>Download as markdown</MenuItem>
<MenuItem onClick={openSaveDialog} disabled={!workspaceRoot || isSavingToWorkspace}>
<MenuItem
onClick={openSaveDialog}
disabled={!canWriteFiles || !workspaceRoot || isSavingToWorkspace}
>
Save to workspace
</MenuItem>
</MenuPopup>
@@ -250,7 +260,7 @@ export const ProposedPlanCard = memo(function ProposedPlanCard({
<Button
size="sm"
onClick={() => void handleSaveToWorkspace()}
disabled={isSavingToWorkspace}
disabled={!canWriteFiles || isSavingToWorkspace}
>
{isSavingToWorkspace ? "Saving..." : "Save"}
</Button>
@@ -6,6 +6,7 @@ import type {
ScopedThreadRef,
} from "@t3tools/contracts";
import { filePreviewDelimiter } from "@t3tools/shared/delimitedPreview";
import { AuthFilesystemWriteScope } from "@t3tools/contracts";
import {
isWorkspaceAudioPreviewPath,
isWorkspaceImagePreviewPath,
@@ -29,6 +30,7 @@ import {
import type { WorkerPoolManager } from "@pierre/diffs/worker";
import { EditProvider, File, Virtualizer, useWorkerPool } from "@pierre/diffs/react";
import { DiffWorkerPoolProvider } from "../DiffWorkerPoolProvider";
import { useFilesystemReadAccess } from "~/state/filesystem";
import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
@@ -63,6 +65,7 @@ import { assetEnvironment } from "~/state/assets";
import { usePreviewAvailable } from "~/browser/previewRuntime";
import { useEnvironmentHttpBaseUrl, usePrimaryEnvironmentId } from "~/state/environments";
import { previewEnvironment } from "~/state/preview";
import { useEnvironmentScope } from "~/state/session";
import { useAtomCommand } from "~/state/use-atom-command";
import { useAtomQueryRunner } from "~/state/use-atom-query-runner";
@@ -1038,6 +1041,9 @@ export default function FilePreviewPanel({
// A file outside the workspace (an absolute path) is shown, never edited.
const isHostFile =
attachment !== undefined || (relativePath !== null && isAbsolutePath(relativePath));
const fileAccess = useFilesystemReadAccess(environmentId);
const { canReadFiles } = fileAccess;
const canWriteFiles = useEnvironmentScope(environmentId, AuthFilesystemWriteScope);
// Media and PDFs render from their absolute path, so their contents are never
// shown. The read still runs: a folder named `assets.png` is only knowable as a
// folder from the read failure, and the server stats before reading, so a folder
@@ -1164,7 +1170,7 @@ export default function FilePreviewPanel({
};
const handleOpenInBrowser = useCallback(() => {
if (!absolutePath || !environmentHttpBaseUrl) return;
if (!canReadFiles || !absolutePath || !environmentHttpBaseUrl) return;
void (async () => {
const result = await openFileInPreview({
threadRef,
@@ -1186,7 +1192,31 @@ export default function FilePreviewPanel({
}),
);
})();
}, [absolutePath, createAssetUrl, cwd, environmentHttpBaseUrl, openPreview, threadRef]);
}, [
absolutePath,
canReadFiles,
createAssetUrl,
cwd,
environmentHttpBaseUrl,
openPreview,
threadRef,
]);
if (attachment === undefined && !canReadFiles) {
if (fileAccess.isPending) {
return (
<div className="flex min-h-0 flex-1 items-center justify-center gap-2 text-sm text-muted-foreground">
<Spinner className="size-4" />
Checking file access...
</div>
);
}
return (
<div className="p-4 text-sm text-muted-foreground">
{fileAccess.error ?? "This connection cannot read host files."}
</div>
);
}
return (
<div className="flex min-h-0 flex-1 flex-col overflow-hidden bg-background">
@@ -1266,6 +1296,11 @@ export default function FilePreviewPanel({
) : null}
</div>
) : null}
{relativePath && !attachment && !isHostFile && !canWriteFiles && !fileAccess.isPending ? (
<div className="shrink-0 border-b px-3 py-1.5 text-2xs text-muted-foreground">
Read-only connection. Unsaved edits are kept until write access returns.
</div>
) : null}
{previewPath &&
attachment === undefined &&
!isMedia &&
@@ -1368,7 +1403,7 @@ export default function FilePreviewPanel({
relativePath={relativePath}
threadRef={threadRef}
contents={file.data.contents}
readOnly={isHostFile}
readOnly={isHostFile || !canWriteFiles}
onPendingChange={onPendingChange}
/>
) : tableDelimiter && renderTable ? (
@@ -1378,7 +1413,7 @@ export default function FilePreviewPanel({
text={file.data.contents}
delimiter={tableDelimiter}
/>
) : file.data.truncated || isHostFile ? (
) : file.data.truncated || isHostFile || !canWriteFiles ? (
<SourceFilePreview
name={relativePath}
text={file.data.contents}
@@ -93,6 +93,31 @@ describe("FileSaveCoordinator", () => {
expect(persist).toHaveBeenCalledWith("unsaved");
});
it.each([false, true])(
"keeps an edit pending after write permission is removed (closing=%s)",
async (closeEditor) => {
vi.useFakeTimers();
let canWrite = true;
const persist = vi.fn().mockResolvedValue(AsyncResult.success(undefined));
const onPendingChange = vi.fn();
const coordinator = new FileSaveCoordinator({
debounceMs: 500,
canPersist: () => canWrite,
persist,
onPendingChange,
onConfirmed: vi.fn(),
});
coordinator.change("unsaved");
canWrite = false;
if (closeEditor) coordinator.dispose();
await vi.runAllTimersAsync();
expect(persist).not.toHaveBeenCalled();
expect(onPendingChange).toHaveBeenLastCalledWith(true);
},
);
it("flushes an edit made while a write was in flight when the editor closes", async () => {
vi.useFakeTimers();
const inFlight = deferred();
@@ -2,9 +2,11 @@ import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime";
export interface FileSaveCoordinatorOptions<A, E> {
readonly debounceMs: number;
readonly canPersist?: () => boolean;
readonly persist: (contents: string) => Promise<AtomCommandResult<A, E>>;
readonly onPendingChange: (pending: boolean) => void;
readonly onConfirmed: (contents: string) => void;
/** Return false when another editor has newer unsaved contents. */
readonly onConfirmed: (contents: string) => boolean | void;
}
export class FileSaveCoordinator<A = unknown, E = unknown> {
@@ -49,20 +51,24 @@ export class FileSaveCoordinator<A = unknown, E = unknown> {
private async persistLatest(): Promise<void> {
if (this.saving || this.latestRevision === this.confirmedRevision) return;
if (this.options.canPersist?.() === false) {
return;
}
this.saving = true;
const contents = this.latestContents;
const revision = this.latestRevision;
const result = await this.options.persist(contents);
const succeeded = result._tag === "Success";
let confirmed = false;
if (succeeded) {
this.confirmedRevision = revision;
this.options.onConfirmed(contents);
confirmed = this.options.onConfirmed(contents) !== false;
}
this.saving = false;
if (revision === this.latestRevision) {
if (succeeded) this.options.onPendingChange(false);
if (confirmed) this.options.onPendingChange(false);
return;
}
@@ -1,23 +1,165 @@
import type { ProjectReadFileResult } from "@t3tools/contracts";
import { EnvironmentId } from "@t3tools/contracts";
import { AsyncResult } from "effect/reactivity";
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
const registryTasks = vi.hoisted(() => new Set<() => void>());
vi.mock("~/rpc/atomRegistry", async () => {
const { AtomRegistry } = await import("effect/reactivity");
return {
appAtomRegistry: AtomRegistry.make({
scheduleTask: (task) => {
registryTasks.add(task);
return () => {
registryTasks.delete(task);
};
},
}),
};
});
import { appAtomRegistry } from "~/rpc/atomRegistry";
import { projectEnvironment } from "~/state/projects";
import { FileSaveCoordinator } from "./fileSaveCoordinator";
import {
clearProjectFileQueryData,
confirmProjectFileQueryData,
getOptimisticProjectFileQueryData,
getUnsavedProjectFileQueryData,
resolveProjectFileQueryData,
setProjectFileQueryData,
} from "./projectFilesQueryState";
const environmentId = EnvironmentId.make("environment-project-files-query-test");
const optimisticFile = projectEnvironment.optimisticFile({
environmentId,
cwd: "/repo",
relativePath: "convex.json",
});
function drainRegistryTasks(): void {
while (registryTasks.size > 0) {
const tasks = [...registryTasks];
registryTasks.clear();
for (const task of tasks) task();
}
}
describe("project files queries", () => {
afterEach(() => {
clearProjectFileQueryData(environmentId, "/repo", "convex.json");
drainRegistryTasks();
vi.useRealTimers();
vi.unstubAllGlobals();
});
it("resumes an unsaved draft after closing the preview and restoring write access", async () => {
vi.stubGlobal("window", {});
vi.useFakeTimers();
const closePreview = appAtomRegistry.mount(optimisticFile);
let canWrite = true;
const persist = vi.fn().mockResolvedValue(AsyncResult.success(undefined));
const onPendingChange = vi.fn();
const makeCoordinator = () =>
new FileSaveCoordinator({
debounceMs: 500,
canPersist: () => canWrite,
persist,
onPendingChange,
onConfirmed: (contents) =>
confirmProjectFileQueryData(environmentId, "/repo", "convex.json", contents),
});
const initial = makeCoordinator();
setProjectFileQueryData(environmentId, "/repo", "convex.json", "unsaved draft");
initial.change("unsaved draft");
canWrite = false;
initial.dispose();
closePreview();
await vi.runAllTimersAsync();
drainRegistryTasks();
expect(persist).not.toHaveBeenCalled();
expect(onPendingChange).toHaveBeenLastCalledWith(true);
const unsaved = getUnsavedProjectFileQueryData(environmentId, "/repo", "convex.json");
expect(unsaved?.contents).toBe("unsaved draft");
canWrite = true;
const reopened = makeCoordinator();
reopened.change(unsaved!.contents);
await vi.advanceTimersByTimeAsync(500);
expect(persist).toHaveBeenCalledOnce();
expect(persist).toHaveBeenCalledWith("unsaved draft");
expect(onPendingChange).toHaveBeenLastCalledWith(false);
expect(getUnsavedProjectFileQueryData(environmentId, "/repo", "convex.json")).toBeNull();
reopened.dispose();
drainRegistryTasks();
expect(appAtomRegistry.getNodes().has(optimisticFile)).toBe(false);
});
it("releases a retained unsaved draft when explicitly cleared", () => {
setProjectFileQueryData(environmentId, "/repo", "convex.json", "first draft");
setProjectFileQueryData(environmentId, "/repo", "convex.json", "latest draft");
drainRegistryTasks();
expect(getUnsavedProjectFileQueryData(environmentId, "/repo", "convex.json")?.contents).toBe(
"latest draft",
);
clearProjectFileQueryData(environmentId, "/repo", "convex.json");
drainRegistryTasks();
expect(appAtomRegistry.getNodes().has(optimisticFile)).toBe(false);
});
it("keeps a reopened editor's newer draft pending when the old editor's write finishes", async () => {
vi.stubGlobal("window", {});
vi.useFakeTimers();
let canWrite = true;
const saved = AsyncResult.success(undefined);
let finishFirstWrite!: (result: typeof saved) => void;
const firstWrite = new Promise<typeof saved>((resolve) => {
finishFirstWrite = resolve;
});
const persist = vi.fn().mockReturnValueOnce(firstWrite).mockResolvedValue(saved);
const onPendingChange = vi.fn();
const makeCoordinator = () =>
new FileSaveCoordinator({
debounceMs: 500,
canPersist: () => canWrite,
persist,
onPendingChange,
onConfirmed: (contents) =>
confirmProjectFileQueryData(environmentId, "/repo", "convex.json", contents),
});
const initial = makeCoordinator();
setProjectFileQueryData(environmentId, "/repo", "convex.json", "first draft");
initial.change("first draft");
await vi.advanceTimersByTimeAsync(500);
initial.dispose();
const reopened = makeCoordinator();
setProjectFileQueryData(environmentId, "/repo", "convex.json", "newer draft");
reopened.change("newer draft");
canWrite = false;
finishFirstWrite(saved);
await vi.runAllTimersAsync();
expect(persist).toHaveBeenCalledOnce();
expect(onPendingChange).toHaveBeenLastCalledWith(true);
expect(getUnsavedProjectFileQueryData(environmentId, "/repo", "convex.json")?.contents).toBe(
"newer draft",
);
canWrite = true;
reopened.change("newer draft");
await vi.advanceTimersByTimeAsync(500);
expect(persist).toHaveBeenLastCalledWith("newer draft");
expect(onPendingChange).toHaveBeenLastCalledWith(false);
expect(getUnsavedProjectFileQueryData(environmentId, "/repo", "convex.json")).toBeNull();
reopened.dispose();
});
it("keeps the latest optimistic draft when an older write finishes", () => {
vi.stubGlobal("window", {});
const initial = {
@@ -1,14 +1,35 @@
import {
AuthFilesystemReadScope,
EnvironmentId,
type AuthSessionState,
type ProjectListEntriesResult,
ProjectReadFileError,
type ProjectReadFileResult,
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import { Atom, AtomRegistry } from "effect/reactivity";
import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
const authorizationMocks = vi.hoisted(() => ({
sessionAtom: null as Atom.Atom<
AsyncResult.AsyncResult<Pick<AuthSessionState, "authenticated" | "scopes">, Error>
> | null,
phase: "connected" as "connected" | "offline",
}));
vi.mock("~/state/session", () => ({
environmentSession: { sessionStateAtom: () => authorizationMocks.sessionAtom },
}));
vi.mock("~/state/presentation", () => ({
useEnvironmentPresentation: () => ({
isReady: true,
presentation: { connection: { phase: authorizationMocks.phase, error: null } },
}),
}));
const projectMocks = vi.hoisted(() => ({
listEntries: vi.fn(),
optimisticFile: vi.fn(),
@@ -64,6 +85,7 @@ vi.mock("react", async (importOriginal) => {
...actual,
useCallback: reactHooks.useCallback,
useEffect: reactHooks.useEffect,
useMemo: <A,>(factory: () => A) => factory(),
useRef: reactHooks.useRef,
};
});
@@ -77,6 +99,7 @@ vi.mock("~/state/queries", () => ({
}));
import { useWorkspaceMutationRefresh } from "~/hooks/useWorkspaceMutationRefresh";
import { useT3ProjectFileState } from "~/hooks/useT3ProjectFileScripts";
import { useProjectEntriesQuery, useProjectFileQuery } from "./projectFilesQueryState";
const environmentId = EnvironmentId.make("environment-1");
@@ -114,12 +137,179 @@ async function flushEffects(): Promise<void> {
describe("project query refresh", () => {
beforeEach(() => {
authorizationMocks.sessionAtom = Atom.make(
AsyncResult.success({ authenticated: true, scopes: [AuthFilesystemReadScope] }),
);
authorizationMocks.phase = "connected";
projectMocks.listEntries.mockReset();
projectMocks.optimisticFile.mockReset();
projectMocks.readFile.mockReset();
reactHooks.reset();
});
it("does not query or expose optimistic file contents without read permission", () => {
authorizationMocks.sessionAtom = Atom.make(
AsyncResult.success({ authenticated: true, scopes: [] }),
);
const registry = AtomRegistry.make();
atomHooks.registry = registry;
projectMocks.optimisticFile.mockReturnValue(Atom.make({ data: file("cached contents") }));
try {
const query = useProjectFileQuery(environmentId, "/repo", "src/preview.ts");
expect(projectMocks.readFile).not.toHaveBeenCalled();
expect(query.data).toBeNull();
expect(query.error).toBe("This connection cannot read host files.");
expect(query.isPending).toBe(false);
const entries = useProjectEntriesQuery(environmentId, "/repo");
expect(projectMocks.listEntries).not.toHaveBeenCalled();
expect(entries.data).toBeNull();
expect(entries.error).toBe("This connection cannot read host files.");
expect(entries.isPending).toBe(false);
} finally {
registry.dispose();
atomHooks.registry = null;
}
});
it("keeps t3.json and the file tree loading until the file grant arrives", () => {
authorizationMocks.sessionAtom = Atom.make(AsyncResult.initial());
const registry = AtomRegistry.make();
atomHooks.registry = registry;
const config = {
defaultThreadEnvMode: "worktree",
scripts: [{ name: "Test", command: "vp test" }],
};
projectMocks.readFile.mockReturnValue(
Atom.make(AsyncResult.success(file(JSON.stringify(config)))),
);
projectMocks.listEntries.mockReturnValue(
Atom.make(AsyncResult.success(projectEntries(["t3.json"]))),
);
projectMocks.optimisticFile.mockReturnValue(Atom.make(null));
try {
expect(useProjectFileQuery(environmentId, "/repo", "t3.json")).toMatchObject({
data: null,
error: null,
isPending: true,
});
expect(useProjectEntriesQuery(environmentId, "/repo")).toMatchObject({
data: null,
error: null,
isPending: true,
});
expect(useT3ProjectFileState(environmentId, "/repo").status).toBe("loading");
expect(projectMocks.readFile).not.toHaveBeenCalled();
expect(projectMocks.listEntries).not.toHaveBeenCalled();
authorizationMocks.sessionAtom = Atom.make(
AsyncResult.success({ authenticated: true, scopes: [AuthFilesystemReadScope] }),
);
expect(useT3ProjectFileState(environmentId, "/repo")).toEqual({
status: "valid",
file: config,
scripts: config.scripts,
});
expect(useProjectEntriesQuery(environmentId, "/repo")).toMatchObject({
data: projectEntries(["t3.json"]),
error: null,
isPending: false,
});
} finally {
registry.dispose();
atomHooks.registry = null;
}
});
it.each(["connected", "offline"] as const)(
"preserves cached t3.json defaults and scripts during a granted refresh while %s",
(phase) => {
authorizationMocks.phase = phase;
authorizationMocks.sessionAtom = Atom.make(
AsyncResult.success(
{ authenticated: true, scopes: [AuthFilesystemReadScope] },
{ waiting: true },
),
);
const registry = AtomRegistry.make();
atomHooks.registry = registry;
const config = {
defaultThreadEnvMode: "worktree",
scripts: [{ name: "Test", command: "vp test" }],
};
projectMocks.readFile.mockReturnValue(
Atom.make(AsyncResult.success(file(JSON.stringify(config)), { waiting: true })),
);
projectMocks.optimisticFile.mockReturnValue(Atom.make(null));
try {
expect(useProjectFileQuery(environmentId, "/repo", "t3.json")).toMatchObject({
error: null,
isPending: true,
});
expect(useT3ProjectFileState(environmentId, "/repo")).toEqual({
status: "valid",
file: config,
scripts: config.scripts,
});
} finally {
registry.dispose();
atomHooks.registry = null;
}
},
);
it.each([
{ phase: "connected", sessionError: "The session request timed out." },
{ phase: "offline", sessionError: null },
] as const)(
"reports unavailable file access for $phase connections",
({ phase, sessionError }) => {
authorizationMocks.phase = phase;
authorizationMocks.sessionAtom = Atom.make(
sessionError === null
? AsyncResult.initial()
: AsyncResult.failure(Cause.fail(new Error(sessionError))),
);
const registry = AtomRegistry.make();
atomHooks.registry = registry;
projectMocks.optimisticFile.mockReturnValue(Atom.make({ data: file("cached contents") }));
try {
const unavailable = {
data: null,
error: sessionError ?? "This environment is not connected.",
isPending: false,
};
expect(useProjectFileQuery(environmentId, "/repo", "src/preview.ts")).toMatchObject(
unavailable,
);
expect(useProjectEntriesQuery(environmentId, "/repo")).toMatchObject(unavailable);
expect(projectMocks.readFile).not.toHaveBeenCalled();
expect(projectMocks.listEntries).not.toHaveBeenCalled();
} finally {
registry.dispose();
atomHooks.registry = null;
}
},
);
it("leaves disabled file queries idle while the file grant loads", () => {
authorizationMocks.sessionAtom = Atom.make(AsyncResult.initial());
const registry = AtomRegistry.make();
atomHooks.registry = registry;
projectMocks.optimisticFile.mockReturnValue(Atom.make(null));
try {
expect(useProjectFileQuery(environmentId, "/repo", "t3.json", false)).toMatchObject({
data: null,
error: null,
isPending: false,
});
expect(useT3ProjectFileState(environmentId, null).status).toBe("missing");
expect(projectMocks.readFile).not.toHaveBeenCalled();
} finally {
registry.dispose();
atomHooks.registry = null;
}
});
it("replaces an in-flight initial read when a workspace mutation arrives", async () => {
const requests: Array<ReturnType<typeof deferred<ProjectReadFileResult>>> = [];
const readAtom = Atom.make(
@@ -12,11 +12,15 @@ import { AsyncResult, Atom } from "effect/reactivity";
import { useCallback } from "react";
import { appAtomRegistry } from "~/rpc/atomRegistry";
import { useFilesystemReadAccess } from "~/state/filesystem";
import { projectEnvironment } from "~/state/projects";
import { useProjectPathSearch } from "~/state/queries";
import { executeAtomQuery } from "@t3tools/client-runtime/state/runtime";
const EMPTY_PROJECT_FILE_PATH = "";
const EMPTY_PROJECT_ENTRIES_QUERY_ATOM = Atom.make(
AsyncResult.initial<ProjectListEntriesResult, never>(false),
);
const EMPTY_PROJECT_FILE_QUERY_ATOM = Atom.make(
AsyncResult.initial<ProjectReadFileResult, never>(false),
).pipe(Atom.withLabel("project-file-query:empty"));
@@ -29,6 +33,15 @@ export function optimisticFileAtom(
return projectEnvironment.optimisticFile({ environmentId, cwd, relativePath });
}
// Dirty contents must survive a closed preview, including failed or unauthorized saves.
const unsavedFileMounts = new Map<ReturnType<typeof optimisticFileAtom>, () => void>();
function releaseUnsavedFile(atom: ReturnType<typeof optimisticFileAtom>): void {
const unmount = unsavedFileMounts.get(atom);
unsavedFileMounts.delete(atom);
unmount?.();
}
interface ProjectQueryState<A> {
readonly data: A | null;
readonly error: string | null;
@@ -70,7 +83,11 @@ export function setProjectFileQueryData(
relativePath: string,
contents: string,
): void {
appAtomRegistry.set(optimisticFileAtom(environmentId, cwd, relativePath), {
const atom = optimisticFileAtom(environmentId, cwd, relativePath);
if (!unsavedFileMounts.has(atom)) {
unsavedFileMounts.set(atom, appAtomRegistry.mount(atom));
}
appAtomRegistry.set(atom, {
confirmedAgainst: undefined,
data: {
relativePath,
@@ -101,6 +118,15 @@ export function getProjectFileContents(
return Option.getOrUndefined(AsyncResult.value(result))?.contents;
}
export function getUnsavedProjectFileQueryData(
environmentId: EnvironmentId,
cwd: string,
relativePath: string,
): ProjectReadFileResult | null {
const optimistic = appAtomRegistry.get(optimisticFileAtom(environmentId, cwd, relativePath));
return optimistic?.confirmedAgainst === undefined ? (optimistic?.data ?? null) : null;
}
export function confirmProjectFileQueryData(
environmentId: EnvironmentId,
cwd: string,
@@ -117,6 +143,7 @@ export function confirmProjectFileQueryData(
confirmedAgainst: appAtomRegistry.get(queryAtom),
};
appAtomRegistry.set(atom, confirmed);
releaseUnsavedFile(atom);
appAtomRegistry.refresh(queryAtom);
void executeAtomQuery(appAtomRegistry, queryAtom, {
reportDefect: false,
@@ -144,7 +171,9 @@ export function clearProjectFileQueryData(
cwd: string,
relativePath: string,
): void {
appAtomRegistry.set(optimisticFileAtom(environmentId, cwd, relativePath), null);
const atom = optimisticFileAtom(environmentId, cwd, relativePath);
appAtomRegistry.set(atom, null);
releaseUnsavedFile(atom);
}
function failureCause<A>(result: AsyncResult.AsyncResult<A, unknown>): unknown {
@@ -163,14 +192,22 @@ export function useProjectEntriesQuery(
cwd: string,
directoryPath?: string,
): ProjectQueryState<ProjectListEntriesResult> {
const atom = getProjectEntriesQueryAtom(environmentId, cwd, directoryPath);
const fileAccess = useFilesystemReadAccess(environmentId);
const { canReadFiles } = fileAccess;
const atom = canReadFiles
? getProjectEntriesQueryAtom(environmentId, cwd, directoryPath)
: EMPTY_PROJECT_ENTRIES_QUERY_ATOM;
const result = useAtomValue(atom);
const refreshAtom = useAtomRefresh(atom);
const refresh = useCallback(() => refreshAtom(), [refreshAtom]);
return {
data: Option.getOrNull(AsyncResult.value(result)),
error: errorMessage(failureCause(result)),
isPending: result.waiting,
error: fileAccess.isPending
? null
: canReadFiles
? errorMessage(failureCause(result))
: (fileAccess.error ?? "This connection cannot read host files."),
isPending: fileAccess.isPending || result.waiting,
refresh,
};
}
@@ -218,9 +255,13 @@ export function useProjectFileQuery(
): ProjectFileQueryState {
// The caller decides what to read. A media path is not skipped here: a folder
// named `assets.png` is only knowable as a folder from the read failure.
const atom = enabled
? getProjectFileQueryAtom(environmentId, cwd, relativePath)
: EMPTY_PROJECT_FILE_QUERY_ATOM;
const fileAccess = useFilesystemReadAccess(environmentId);
const { canReadFiles } = fileAccess;
const isQueryEnabled = enabled;
const atom =
enabled && canReadFiles
? getProjectFileQueryAtom(environmentId, cwd, relativePath)
: EMPTY_PROJECT_FILE_QUERY_ATOM;
const result = useAtomValue(atom);
const refreshAtom = useAtomRefresh(atom);
const refresh = useCallback(() => refreshAtom(), [refreshAtom]);
@@ -233,11 +274,16 @@ export function useProjectFileQuery(
const readError = isProjectReadFileError(cause) ? cause : null;
return {
data: optimisticFile?.data ?? data,
error: errorMessage(cause),
data: canReadFiles ? (optimisticFile?.data ?? data) : null,
error:
!isQueryEnabled || fileAccess.isPending
? null
: canReadFiles
? errorMessage(cause)
: (fileAccess.error ?? "This connection cannot read host files."),
isPending: isQueryEnabled && (fileAccess.isPending || result.waiting),
readError,
isNotFile: readError?.failure === "path_not_file",
isPending: result.waiting,
refresh,
};
}
@@ -4,13 +4,22 @@ import { act, StrictMode } from "react";
import { create, type ReactTestRenderer } from "react-test-renderer";
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
const { writeFile, confirmFile } = vi.hoisted(() => ({
const { writeFile, confirmFile, readScope, getUnsavedFile } = vi.hoisted(() => ({
writeFile: vi.fn(),
confirmFile: vi.fn(),
readScope: vi.fn(),
getUnsavedFile: vi.fn(),
}));
vi.mock("~/state/projects", () => ({ projectEnvironment: { writeFile: {} } }));
vi.mock("~/state/session", () => ({
readEnvironmentScope: readScope,
useEnvironmentScope: readScope,
}));
vi.mock("~/state/use-atom-command", () => ({ useAtomCommand: () => writeFile }));
vi.mock("./projectFilesQueryState", () => ({ confirmProjectFileQueryData: confirmFile }));
vi.mock("./projectFilesQueryState", () => ({
confirmProjectFileQueryData: confirmFile,
getUnsavedProjectFileQueryData: getUnsavedFile,
}));
import { setMarkdownTaskChecked } from "./filePreviewMode";
import { useFileSaveCoordinator } from "./useFileSaveCoordinator";
@@ -54,6 +63,8 @@ beforeEach(() => {
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
writeFile.mockReset().mockResolvedValue(AsyncResult.success(undefined));
confirmFile.mockReset();
readScope.mockReset().mockReturnValue(true);
getUnsavedFile.mockReset().mockReturnValue(null);
onPendingChange.mockReset();
});
@@ -124,6 +135,57 @@ describe("file-save React lifecycle", () => {
expect(writeFile.mock.calls[0]![0].input.contents).toBe("pending edit");
});
it.each([false, true])(
"keeps edits pending after permission is revoked before a React update (unmount: %s)",
async (unmount) => {
mount();
changeHandler()("pending edit");
readScope.mockReturnValue(false);
if (unmount) {
await act(async () => renderer!.unmount());
renderer = null;
}
await vi.runAllTimersAsync();
expect(writeFile).not.toHaveBeenCalled();
expect(confirmFile).not.toHaveBeenCalled();
expect(onPendingChange).toHaveBeenLastCalledWith("file.txt", true);
},
);
it("resumes an unsaved draft when write permission returns after effect replay", async () => {
readScope.mockReturnValue(false);
getUnsavedFile.mockReturnValue({ contents: "pending draft" });
mount();
await vi.runAllTimersAsync();
expect(writeFile).not.toHaveBeenCalled();
readScope.mockReturnValue(true);
act(() =>
renderer!.update(
<StrictMode>
<FileSurface {...defaultProps} />
</StrictMode>,
),
);
await vi.advanceTimersByTimeAsync(500);
expect(writeFile).toHaveBeenCalledExactlyOnceWith({
environmentId,
input: { cwd: "/workspace", relativePath: "file.txt", contents: "pending draft" },
});
expect(onPendingChange).toHaveBeenLastCalledWith("file.txt", false);
});
it("recovers an existing draft once after StrictMode setup replay", async () => {
getUnsavedFile.mockReturnValue({ contents: "reopened draft" });
mount();
await vi.runAllTimersAsync();
expect(writeFile).toHaveBeenCalledExactlyOnceWith({
environmentId,
input: { cwd: "/workspace", relativePath: "file.txt", contents: "reopened draft" },
});
expect(onPendingChange).toHaveBeenLastCalledWith("file.txt", false);
});
it.each([
{ relativePath: "other.txt" },
{ cwd: "/other-workspace" },
@@ -1,11 +1,15 @@
import type { EnvironmentId } from "@t3tools/contracts";
import { AuthFilesystemWriteScope, type EnvironmentId } from "@t3tools/contracts";
import { createRef, useEffect, useMemo } from "react";
import { projectEnvironment } from "~/state/projects";
import { readEnvironmentScope, useEnvironmentScope } from "~/state/session";
import { useAtomCommand } from "~/state/use-atom-command";
import { FileSaveCoordinator } from "./fileSaveCoordinator";
import { confirmProjectFileQueryData } from "./projectFilesQueryState";
import {
confirmProjectFileQueryData,
getUnsavedProjectFileQueryData,
} from "./projectFilesQueryState";
const FILE_SAVE_DEBOUNCE_MS = 500;
@@ -22,6 +26,7 @@ export function useFileSaveCoordinator({
relativePath,
onPendingChange,
}: FileSaveOptions): Pick<FileSaveCoordinator, "change"> {
const canWriteFiles = useEnvironmentScope(environmentId, AuthFilesystemWriteScope);
const writeFile = useAtomCommand(projectEnvironment.writeFile);
const session = useMemo(() => {
const coordinatorRef = createRef<FileSaveCoordinator>();
@@ -30,15 +35,15 @@ export function useFileSaveCoordinator({
setup: () => {
const coordinator = new FileSaveCoordinator({
debounceMs: FILE_SAVE_DEBOUNCE_MS,
canPersist: () => readEnvironmentScope(environmentId, AuthFilesystemWriteScope),
onPendingChange: (pending) => onPendingChange(relativePath, pending),
persist: (nextContents) =>
writeFile({
environmentId,
input: { cwd, relativePath, contents: nextContents },
}),
onConfirmed: (confirmedContents) => {
confirmProjectFileQueryData(environmentId, cwd, relativePath, confirmedContents);
},
onConfirmed: (confirmedContents) =>
confirmProjectFileQueryData(environmentId, cwd, relativePath, confirmedContents),
});
coordinatorRef.current = coordinator;
return () => {
@@ -52,5 +57,18 @@ export function useFileSaveCoordinator({
// StrictMode replays effect setup. Retired file sessions stay inert, while the
// replay gets a fresh coordinator instead of reusing a disposed one.
useEffect(session.setup, [session]);
useEffect(() => {
if (!canWriteFiles) return;
let cancelled = false;
// Replay must retire the first session before recovery queues a draft to flush.
queueMicrotask(() => {
if (cancelled) return;
const unsaved = getUnsavedProjectFileQueryData(environmentId, cwd, relativePath);
if (unsaved) session.change(unsaved.contents);
});
return () => {
cancelled = true;
};
}, [canWriteFiles, cwd, environmentId, relativePath, session]);
return session;
}
@@ -0,0 +1,307 @@
import {
AuthFilesystemReadScope,
EnvironmentId,
ThreadId,
type AuthSessionState,
} from "@t3tools/contracts";
import { AsyncResult } from "effect/reactivity";
import { createElement, isValidElement, type ReactNode } from "react";
import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
function deferred<T>() {
let resolve!: (value: T | PromiseLike<T>) => void;
const promise = new Promise<T>((resolvePromise) => {
resolve = resolvePromise;
});
return { promise, resolve };
}
const state = vi.hoisted(() => ({
sessions: new Map<string, Pick<AuthSessionState, "authenticated" | "scopes">>(),
mint: vi.fn(),
download: vi.fn(),
png: vi.fn(),
showMenu: vi.fn(),
openFile: vi.fn(),
clipboard: vi.fn(),
menuFinished: null as (() => void) | null,
}));
vi.mock("react", async (importOriginal) => ({
...(await importOriginal<typeof import("react")>()),
useCallback: <A,>(callback: A) => callback,
useRef: <A,>(current: A) => ({ current }),
useState: <A,>(initial: A) => [initial, () => {}],
}));
vi.mock("../../hooks/useCopyToClipboard", () => ({ writeTextToClipboard: vi.fn() }));
vi.mock("../../localApi", () => ({
readLocalApi: () => ({ contextMenu: { show: state.showMenu } }),
}));
vi.mock("../../state/assets", () => ({ assetEnvironment: { createUrl: {} } }));
vi.mock("../../state/use-atom-query-runner", () => ({ useAtomQueryRunner: () => state.mint }));
vi.mock("../../state/session", () => ({
environmentSession: { sessionStateAtom: (environmentId: string) => environmentId },
readPreparedConnection: () => ({ httpBaseUrl: "https://host.test" }),
}));
vi.mock("../../state/query", () => ({
useEnvironmentQuery: (environmentId: string) => ({
data: state.sessions.get(environmentId) ?? null,
error: null,
}),
}));
vi.mock("../../rpc/atomRegistry", () => ({
appAtomRegistry: {
get: (environmentId: string) => {
const session = state.sessions.get(environmentId);
return session === undefined ? AsyncResult.initial() : AsyncResult.success(session);
},
},
}));
vi.mock("./mediaContent", () => ({ downloadMedia: state.download, readMediaPng: state.png }));
vi.mock("../ui/tooltip", () => ({
Tooltip: "Tooltip",
TooltipTrigger: "TooltipTrigger",
TooltipPopup: "TooltipPopup",
}));
vi.mock("../ui/toast", () => ({
stackedThreadToast: <A,>(toast: A) => toast,
toastManager: {
add: (toast: { type: string }) => {
if (toast.type !== "loading") state.menuFinished?.();
return "toast";
},
update: () => state.menuFinished?.(),
},
}));
import { MediaActions, useMediaActions, type MediaActionSource } from "./MediaActions";
const environmentId = EnvironmentId.make("media-environment");
const otherEnvironmentId = EnvironmentId.make("other-environment");
const threadId = ThreadId.make("media-thread");
const granted: Pick<AuthSessionState, "authenticated" | "scopes"> = {
authenticated: true,
scopes: [AuthFilesystemReadScope],
};
const denied: Pick<AuthSessionState, "authenticated" | "scopes"> = {
authenticated: true,
scopes: [],
};
function hostSource(_tag: "workspace-file" | "media-file" = "media-file"): MediaActionSource {
return {
kind: "image",
name: "image.png",
src: null,
asset: { environmentId, resource: { _tag, threadId, path: "/repo/image.png" } },
reference: { kind: "file", path: "/repo/image.png", relativePath: "image.png" },
onOpenFile: state.openFile,
};
}
function openMenu(source: MediaActionSource) {
const find = (node: ReactNode): ((event: unknown) => void) | undefined => {
if (Array.isArray(node)) return node.map(find).find((handler) => handler !== undefined);
if (!isValidElement<{ children?: ReactNode; onContextMenu?: (event: unknown) => void }>(node))
return undefined;
return node.props.onContextMenu ?? find(node.props.children);
};
const handler = find(MediaActions({ source, children: createElement("img") }));
if (!handler) throw new Error("Media menu handler missing");
handler({
defaultPrevented: false,
preventDefault() {},
stopPropagation() {},
currentTarget: { getBoundingClientRect: () => ({ left: 0, bottom: 0 }) },
clientX: 1,
clientY: 1,
});
}
beforeEach(() => {
state.sessions.clear();
state.sessions.set(environmentId, denied);
state.mint
.mockReset()
.mockResolvedValue(AsyncResult.success({ relativeUrl: "/api/assets/image.png", expiresAt: 1 }));
state.download.mockReset().mockResolvedValue(undefined);
state.png.mockReset().mockResolvedValue(new Blob(["png"], { type: "image/png" }));
state.showMenu.mockReset().mockResolvedValue(null);
state.openFile.mockReset();
state.menuFinished = null;
class TestClipboardItem {
constructor(readonly items: Record<string, Promise<Blob>>) {}
}
state.clipboard.mockReset().mockImplementation(async (items: TestClipboardItem[]) => {
await Promise.all(items.flatMap((item) => Object.values(item.items)));
});
vi.stubGlobal("ClipboardItem", TestClipboardItem);
vi.stubGlobal("navigator", { clipboard: { write: state.clipboard } });
});
afterEach(() => vi.unstubAllGlobals());
it.each(["workspace-file", "media-file"] as const)(
"waits for the %s grant before enabling host menu actions",
(_tag) => {
for (const [session, disabled] of [
[null, true],
[granted, false],
[denied, true],
] as const) {
if (session === null) state.sessions.delete(environmentId);
else state.sessions.set(environmentId, session);
openMenu(hostSource(_tag));
const items = state.showMenu.mock.lastCall![0];
expect(items).toEqual(
expect.arrayContaining([
expect.objectContaining({ id: "save", disabled }),
expect.objectContaining({ id: "copy-image", disabled }),
expect.objectContaining({ id: "open-file", disabled }),
]),
);
expect(items).toContainEqual({ id: "copy-full-path", label: "Copy full path" });
}
expect(state.mint).not.toHaveBeenCalled();
expect(state.download).not.toHaveBeenCalled();
},
);
it("keeps nonhost menu actions available with pending or denied host grants", () => {
const sources: MediaActionSource[] = [
{ kind: "image", name: "image.png", src: "https://cdn.test/image.png" },
{ kind: "image", name: "image.png", src: "blob:local-image" },
{
kind: "image",
name: "image.png",
src: null,
asset: { environmentId, resource: { _tag: "attachment", attachmentId: "upload" } },
},
];
for (const session of [null, denied]) {
if (session === null) state.sessions.delete(environmentId);
else state.sessions.set(environmentId, session);
for (const source of sources) {
openMenu(source);
expect(state.showMenu.mock.lastCall![0]).toEqual(
expect.arrayContaining([
expect.objectContaining({ id: "save", disabled: false }),
expect.objectContaining({ id: "copy-image", disabled: false }),
]),
);
}
}
});
it.each(["workspace-file", "media-file"] as const)(
"disables denied %s byte actions and prevents imperative requests",
async (_tag) => {
const source = hostSource(_tag);
openMenu(source);
expect(state.showMenu).toHaveBeenCalledWith(
expect.arrayContaining([
expect.objectContaining({ id: "save", disabled: true }),
expect.objectContaining({ id: "copy-image", disabled: true }),
expect.objectContaining({ id: "open-file", disabled: true }),
]),
{ x: 1, y: 1 },
);
await expect(useMediaActions(source).save()).rejects.toThrow("cannot read host files");
await expect(useMediaActions(source).copyImage()).rejects.toThrow("cannot read host files");
expect(state.mint).not.toHaveBeenCalled();
expect(state.download).not.toHaveBeenCalled();
expect(state.clipboard).not.toHaveBeenCalled();
},
);
it.each(["save", "copy-image", "open-file"])(
"rechecks access when %s is selected from an already open native menu",
async (action) => {
state.sessions.set(environmentId, granted);
const choice = deferred<string>();
const completed = deferred<void>();
state.showMenu.mockReturnValue(choice.promise);
state.menuFinished = () => completed.resolve();
state.openFile.mockImplementation(() => completed.resolve());
openMenu(hostSource());
state.sessions.set(environmentId, denied);
choice.resolve(action);
await completed.promise;
expect(state.mint).not.toHaveBeenCalled();
expect(state.download).not.toHaveBeenCalled();
expect(state.clipboard).not.toHaveBeenCalled();
expect(state.openFile).not.toHaveBeenCalled();
},
);
it("reenables the menu and a retained action when file access is gained", async () => {
const actions = useMediaActions(hostSource());
state.sessions.set(environmentId, granted);
openMenu(hostSource());
await actions.save();
expect(state.download).toHaveBeenCalledOnce();
expect(state.showMenu).toHaveBeenCalledWith(
expect.arrayContaining([expect.objectContaining({ id: "save", disabled: false })]),
expect.anything(),
);
});
it.each([false, true])("uses the media environment's grant (allowed: %s)", async (allowed) => {
state.sessions.set(environmentId, allowed ? granted : denied);
state.sessions.set(otherEnvironmentId, allowed ? denied : granted);
await useMediaActions(hostSource())
.save()
.catch(() => {});
expect(state.mint).toHaveBeenCalledTimes(allowed ? 1 : 0);
expect(state.download).toHaveBeenCalledTimes(allowed ? 1 : 0);
});
it("stops before downloading if access is revoked while minting the URL", async () => {
state.sessions.set(environmentId, granted);
state.mint.mockImplementation(async () => {
state.sessions.set(environmentId, denied);
return AsyncResult.success({ relativeUrl: "/api/assets/image.png", expiresAt: 1 });
});
await expect(useMediaActions(hostSource()).save()).rejects.toThrow("cannot read host files");
expect(state.download).not.toHaveBeenCalled();
});
it("lets the server authorize an explicit action before the grant resolves", async () => {
state.sessions.delete(environmentId);
await useMediaActions(hostSource()).save();
expect(state.mint).toHaveBeenCalledOnce();
expect(state.download).toHaveBeenCalledOnce();
});
it("saves uploaded attachments without filesystem access", async () => {
await useMediaActions({
kind: "image",
name: "image.png",
src: null,
asset: { environmentId, resource: { _tag: "attachment", attachmentId: "upload" } },
}).save();
expect(state.mint).toHaveBeenCalledOnce();
expect(state.download).toHaveBeenCalledOnce();
});
it.each(["https://cdn.test/image.png", "blob:local-image"])(
"saves direct media without a host grant: %s",
async (src) => {
await useMediaActions({ kind: "image", name: "image.png", src }).save();
expect(state.mint).not.toHaveBeenCalled();
expect(state.download).toHaveBeenCalledWith(src, "image.png");
},
);
+55 -9
View File
@@ -5,13 +5,23 @@ import {
} from "@t3tools/client-runtime/media-reference";
import { resolveAssetUrl } from "@t3tools/client-runtime/state/assets";
import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
import type { AssetResource, ContextMenuItem, EnvironmentId } from "@t3tools/contracts";
import {
AuthFilesystemReadScope,
type AssetResource,
type AuthSessionState,
type ContextMenuItem,
type EnvironmentId,
} from "@t3tools/contracts";
import * as Option from "effect/Option";
import { AsyncResult } from "effect/reactivity";
import { useCallback, useRef, useState, type ReactElement } from "react";
import { writeTextToClipboard } from "../../hooks/useCopyToClipboard";
import { readLocalApi } from "../../localApi";
import { appAtomRegistry } from "../../rpc/atomRegistry";
import { assetEnvironment } from "../../state/assets";
import { readPreparedConnection } from "../../state/session";
import { useEnvironmentQuery } from "../../state/query";
import { environmentSession, readPreparedConnection } from "../../state/session";
import { useAtomQueryRunner } from "../../state/use-atom-query-runner";
import { stackedThreadToast, toastManager } from "../ui/toast";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
@@ -32,13 +42,45 @@ function mediaFileName(source: MediaActionSource): string {
);
}
/** An explicit action may ask the server while its grant is still unresolved. */
function allowsHostMedia(session: Pick<AuthSessionState, "authenticated" | "scopes"> | null) {
return (
session === null ||
(session.authenticated && session.scopes?.includes(AuthFilesystemReadScope) === true)
);
}
function canReadHostMedia(environmentId: EnvironmentId | null): boolean {
if (environmentId === null) return true;
const result = appAtomRegistry.get(environmentSession.sessionStateAtom(environmentId));
return result._tag !== "Failure" && allowsHostMedia(Option.getOrNull(AsyncResult.value(result)));
}
/** Explicit byte operations get fresh capabilities without replacing a player's active source. */
function useMediaActions(source: MediaActionSource) {
/** Exported for tests that drive the byte operations without the menu. */
export function useMediaActions(source: MediaActionSource) {
const hostEnvironmentId =
source.asset &&
(source.asset.resource._tag === "workspace-file" || source.asset.resource._tag === "media-file")
? source.asset.environmentId
: null;
const fileSession = useEnvironmentQuery(
hostEnvironmentId === null ? null : environmentSession.sessionStateAtom(hostEnvironmentId),
);
const canReadMedia =
hostEnvironmentId === null ||
(fileSession.error === null && fileSession.data !== null && allowsHostMedia(fileSession.data));
const assertCanReadMedia = useCallback(() => {
if (!canReadHostMedia(hostEnvironmentId)) {
throw new Error("This connection cannot read host files.");
}
}, [hostEnvironmentId]);
const createAssetUrl = useAtomQueryRunner(assetEnvironment.createUrl, {
reportFailure: false,
refresh: true,
});
const actionUrl = useCallback(async () => {
assertCanReadMedia();
if (!source.asset) {
if (!source.src) throw new Error("This media is unavailable. Try reopening the preview.");
return source.src;
@@ -48,14 +90,16 @@ function useMediaActions(source: MediaActionSource) {
if (!connection) throw new Error("Reconnect to this environment and try again.");
const result = await createAssetUrl({ environmentId, input: { resource } });
if (result._tag === "Failure") throw squashAtomCommandFailure(result);
assertCanReadMedia();
const url = resolveAssetUrl(connection.httpBaseUrl, result.value.relativeUrl);
if (!url) throw new Error("The environment returned an invalid media URL.");
return url;
}, [source, createAssetUrl]);
}, [source, createAssetUrl, assertCanReadMedia]);
const save = useCallback(async () => {
await downloadMedia(await actionUrl(), mediaFileName(source));
}, [actionUrl, source]);
const copyImage = useCallback(async () => {
assertCanReadMedia();
if (!navigator.clipboard?.write || typeof ClipboardItem === "undefined") {
throw new Error(
"Image copying is unavailable. Use a secure browser connection or save the image.",
@@ -65,8 +109,8 @@ function useMediaActions(source: MediaActionSource) {
await navigator.clipboard.write([
new ClipboardItem({ "image/png": actionUrl().then(readMediaPng) }),
]);
}, [actionUrl]);
return { save, copyImage };
}, [actionUrl, assertCanReadMedia]);
return { save, copyImage, canReadMedia, assertCanReadMedia };
}
/** Adds source-aware actions and a tooltip to the existing media element without a layout wrapper. */
@@ -77,7 +121,7 @@ export function MediaActions({
source: MediaActionSource;
children: ReactElement;
}) {
const { save, copyImage } = useMediaActions(source);
const { save, copyImage, canReadMedia, assertCanReadMedia } = useMediaActions(source);
const [tooltipOpen, setTooltipOpen] = useState(false);
const menuOpen = useRef(false);
const reference = source.reference;
@@ -92,7 +136,7 @@ export function MediaActions({
let progressToast: ReturnType<typeof toastManager.add> | undefined;
try {
const noun = source.kind === "image" ? "image" : "video";
const unavailable = source.src === null && source.asset === undefined;
const unavailable = !canReadMedia || (source.src === null && source.asset === undefined);
const canCopyImage =
typeof navigator !== "undefined" &&
Boolean(navigator.clipboard?.write) &&
@@ -105,7 +149,8 @@ export function MediaActions({
} else if (reference?.kind === "url") {
items.push({ id: "copy-url", label: "Copy URL" });
}
if (source.onOpenFile) items.push({ id: "open-file", label: "Open in file viewer" });
if (source.onOpenFile)
items.push({ id: "open-file", label: "Open in file viewer", disabled: !canReadMedia });
items.push({ id: "save", label: `Save ${noun}`, disabled: unavailable });
if (source.kind === "image") {
items.push({
@@ -133,6 +178,7 @@ export function MediaActions({
title: action === "copy-url" ? "URL copied" : "Path copied",
});
} else if (action === "open-file") {
assertCanReadMedia();
source.onOpenFile?.();
} else if (action === "save" || action === "copy-image") {
progressToast = toastManager.add({
@@ -63,6 +63,13 @@ vi.mock("~/state/session", async (importOriginal) => ({
readPreparedConnection: mocks.readPreparedConnection,
}));
// File-preview errors share a module with asset hooks. Keep the pure URL resolver
// without importing those hooks and their environment runtime into chrome tests.
vi.mock("~/assets/assetUrls", async () => {
const { resolveAssetUrl } = await import("@t3tools/client-runtime/state/assets");
return { resolveAssetUrl };
});
// Stubbed at the direct dependency rather than letting the real module pull in
// `useSettings` -> `state/server`, which would drag the whole settings and
// connection graph into a test that only cares about the browser chrome.
@@ -0,0 +1,131 @@
import { scopeThreadRef } from "@t3tools/client-runtime/environment";
import { AuthFilesystemReadScope, EnvironmentId, ThreadId } from "@t3tools/contracts";
import type { ReactNode } from "react";
import { act, create, type ReactTestRenderer } from "react-test-renderer";
import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
const state = vi.hoisted(() => ({
canReadFiles: true,
isCheckingAccess: false,
error: null as string | null,
readScope: vi.fn(),
openFile: vi.fn(),
}));
const target = {
environmentId: EnvironmentId.make("content-search-secondary"),
cwd: "/project",
projectName: "Project",
threadRef: scopeThreadRef(
EnvironmentId.make("content-search-secondary"),
ThreadId.make("content-search-thread"),
),
};
vi.mock("~/hooks/useActiveProjectTarget", () => ({ useActiveProjectTarget: () => target }));
vi.mock("~/hooks/useTheme", () => ({ useTheme: () => ({ resolvedTheme: "light" }) }));
vi.mock("~/rightPanelStore", () => ({
useRightPanelStore: { getState: () => ({ openFile: state.openFile }) },
}));
vi.mock("~/state/session", () => ({ readEnvironmentScope: state.readScope }));
vi.mock("~/state/queries", () => ({
useProjectContentSearch: ({ query }: { query: string }) => ({
canReadFiles: state.canReadFiles,
isCheckingAccess: state.isCheckingAccess,
error: state.error,
isPending: state.isCheckingAccess,
hasQuery: query.length > 0,
truncated: false,
invalidRegex: false,
matches:
state.canReadFiles && query.length > 0
? [
{
resultIndex: 0,
path: "src/index.ts",
lineNumber: 3,
lineContent: "match",
matchRanges: [],
},
]
: [],
}),
}));
vi.mock("../CommandPaletteContent", () => ({ CommandPaletteContent: "section" }));
vi.mock("../chat/PierreEntryIcon", () => ({ PierreEntryIcon: () => null }));
vi.mock("./HighlightedSearchLine", () => ({ HighlightedSearchLine: () => null }));
vi.mock("../ui/scroll-area", () => ({ ScrollArea: "div" }));
vi.mock("../ui/toggle", () => ({ Toggle: "button" }));
vi.mock("../ui/tooltip", () => ({
Tooltip: "div",
TooltipPopup: "span",
TooltipTrigger: ({ render }: { render: ReactNode }) => render,
}));
import { ProjectContentSearchDialog } from "./ProjectContentSearchDialog";
let renderer: ReactTestRenderer | undefined;
const onOpenChange = vi.fn();
beforeEach(() => {
state.canReadFiles = true;
state.isCheckingAccess = false;
state.error = null;
state.readScope.mockReset().mockReturnValue(true);
state.openFile.mockClear();
onOpenChange.mockClear();
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
vi.stubGlobal("document", { querySelector: () => null });
});
afterEach(async () => {
await act(() => renderer?.unmount());
vi.unstubAllGlobals();
});
async function openSearch() {
await act(() => {
renderer = create(<ProjectContentSearchDialog onOpenChange={onOpenChange} />);
});
return renderer!.root;
}
it("enables search after access resolves and opens a result in its own environment", async () => {
state.canReadFiles = false;
state.isCheckingAccess = true;
const root = await openSearch();
expect(root.findByType("section").props.inputProps.disabled).toBe(true);
expect(
root.findAllByType("div").some((node) => node.children.includes("Checking file access…")),
).toBe(true);
state.canReadFiles = true;
state.isCheckingAccess = false;
await act(() => renderer!.update(<ProjectContentSearchDialog onOpenChange={onOpenChange} />));
expect(root.findByType("section").props.inputProps.disabled).toBe(false);
await act(() => root.findByType("section").props.onValueChange("match"));
await act(() => root.findByProps({ "data-content-search-result": 0 }).props.onClick());
expect(state.readScope).toHaveBeenCalledWith(target.environmentId, AuthFilesystemReadScope);
expect(state.openFile).toHaveBeenCalledWith(target.threadRef, "src/index.ts", 3);
expect(onOpenChange).toHaveBeenCalledWith(false);
});
it.each(["pointer", "keyboard"])(
"rechecks access before a retained %s action opens a result",
async (action) => {
const root = await openSearch();
await act(() => root.findByType("section").props.onValueChange("match"));
const openResult = root.findByProps({ "data-content-search-result": 0 }).props.onClick;
const onKeyDown = root.findByType("section").props.inputProps.onKeyDown;
state.readScope.mockReturnValue(false);
await act(() => {
if (action === "pointer") openResult();
else onKeyDown({ key: "Enter", preventDefault() {} });
});
expect(state.openFile).not.toHaveBeenCalled();
expect(onOpenChange).not.toHaveBeenCalled();
},
);
@@ -1,5 +1,5 @@
import { Spinner } from "~/components/ui/spinner";
import type { ProjectContentMatch } from "@t3tools/contracts";
import { AuthFilesystemReadScope, type ProjectContentMatch } from "@t3tools/contracts";
import { useCallback, useEffect, useMemo, useState, type ReactNode } from "react";
@@ -8,6 +8,7 @@ import { useTheme } from "~/hooks/useTheme";
import { cn } from "~/lib/utils";
import { useRightPanelStore } from "~/rightPanelStore";
import { useProjectContentSearch } from "~/state/queries";
import { readEnvironmentScope } from "~/state/session";
import { PierreEntryIcon } from "../chat/PierreEntryIcon";
import { CommandPaletteContent } from "../CommandPaletteContent";
@@ -56,6 +57,7 @@ function groupMatches(matches: ReadonlyArray<ProjectContentMatch>): MatchGroup[]
function SearchOptionButton(props: {
readonly active: boolean;
readonly disabled: boolean;
readonly label: string;
readonly onClick: () => void;
readonly children: ReactNode;
@@ -66,6 +68,7 @@ function SearchOptionButton(props: {
render={
<Toggle
aria-label={props.label}
disabled={props.disabled}
pressed={props.active}
size="segmented"
variant="segmented"
@@ -121,7 +124,7 @@ function OpenContentSearchDialog(props: {
wholeWord,
useRegex,
});
const canOpenMatches = !search.isPending;
const canOpenMatches = search.canReadFiles && !search.isPending && search.error === null;
const matches = search.matches;
const visibleMatches = useMemo(() => matches.slice(0, visibleCount), [matches, visibleCount]);
const groups = useMemo(() => groupMatches(visibleMatches), [visibleMatches]);
@@ -153,13 +156,16 @@ function OpenContentSearchDialog(props: {
}, []);
const openMatch = (match: ProjectContentMatch) => {
if (!canOpenMatches) return;
if (!canOpenMatches || !readEnvironmentScope(target.environmentId, AuthFilesystemReadScope)) {
return;
}
props.onOpenChange(false);
useRightPanelStore.getState().openFile(target.threadRef, match.path, match.lineNumber);
};
const fileCount = useMemo(() => new Set(matches.map((match) => match.path)).size, [matches]);
const showSearchStatus =
search.hasQuery || search.isPending || search.error !== null || search.invalidRegex;
search.canReadFiles &&
(search.hasQuery || search.isPending || search.error !== null || search.invalidRegex);
return (
<CommandPaletteContent
@@ -170,6 +176,7 @@ function OpenContentSearchDialog(props: {
<div className="absolute inset-e-2.5 top-1/2 flex shrink-0 -translate-y-1/2 items-center gap-0.5 rounded-md border bg-muted/30 p-0.5">
<SearchOptionButton
active={caseSensitive}
disabled={!search.canReadFiles}
label="Match case"
onClick={() => setCaseSensitive((current) => !current)}
>
@@ -177,6 +184,7 @@ function OpenContentSearchDialog(props: {
</SearchOptionButton>
<SearchOptionButton
active={wholeWord}
disabled={!search.canReadFiles}
label="Match whole word"
onClick={() => setWholeWord((current) => !current)}
>
@@ -184,6 +192,7 @@ function OpenContentSearchDialog(props: {
</SearchOptionButton>
<SearchOptionButton
active={useRegex}
disabled={!search.canReadFiles}
label="Use regular expression"
onClick={() => setUseRegex((current) => !current)}
>
@@ -193,6 +202,7 @@ function OpenContentSearchDialog(props: {
}
inputProps={{
className: "pe-30",
disabled: !search.canReadFiles,
placeholder: `Search in ${target.projectName}`,
onKeyDown: (event) => {
if (event.key === "ArrowDown" && matches.length > 0) {
@@ -241,9 +251,13 @@ function OpenContentSearchDialog(props: {
{matches.length === 0 ? (
<div className="flex flex-1 items-center justify-center px-6 text-center text-sm text-muted-foreground">
{search.hasQuery && !search.isPending && !search.error
? "No results found."
: "Type to search across your project."}
{search.isCheckingAccess
? "Checking file access…"
: !search.canReadFiles
? search.error
: search.hasQuery && !search.isPending && !search.error
? "No results found."
: "Type to search across your project."}
</div>
) : (
<ScrollArea className="min-h-0 flex-1" scrollFade>
@@ -30,12 +30,14 @@ import {
AuthOrchestrationReadScope,
AuthRelayReadScope,
AuthRelayWriteScope,
AuthReviewWriteScope,
AuthSourceControlWriteScope,
AuthFilesystemReadScope,
AuthFilesystemWriteScope,
AuthStandardClientScopes,
AuthTerminalOperateScope,
type AuthClientSession,
type AuthEnvironmentScope,
type AuthGrantScope,
type AuthPairingLink,
type AuthPairingCredentialResult,
type AdvertisedEndpoint,
@@ -226,19 +228,19 @@ function formatAccessTimestamp(value: string): string {
}
const PAIRING_SCOPE_OPTIONS: ReadonlyArray<{
readonly scope: AuthEnvironmentScope;
readonly scope: AuthGrantScope;
readonly title: string;
readonly description: string;
}> = [
{
scope: AuthOrchestrationReadScope,
title: "View environment",
description: "Read threads, status, diffs, and configuration.",
description: "Read threads, status, checkpoints, and configuration.",
},
{
scope: AuthOrchestrationOperateScope,
title: "Operate tasks",
description: "Start tasks and perform changes in the environment.",
description: "Start, update, and stop tasks.",
},
{
scope: AuthSettingsWriteScope,
@@ -266,9 +268,14 @@ const PAIRING_SCOPE_OPTIONS: ReadonlyArray<{
description: "Commit, push, manage branches and repositories, and change pull requests.",
},
{
scope: AuthReviewWriteScope,
title: "Write reviews",
description: "Create comments while reviewing changes.",
scope: AuthFilesystemReadScope,
title: "Read files",
description: "Browse host files, search workspaces, and inspect local changes.",
},
{
scope: AuthFilesystemWriteScope,
title: "Write files",
description: "Edit workspace files and save plans to disk.",
},
{
scope: AuthAccessReadScope,
@@ -1105,7 +1112,7 @@ const AuthorizedClientsHeaderAction = memo(function AuthorizedClientsHeaderActio
const primaryEnvironmentId = usePrimaryEnvironmentId();
const [dialogOpen, setDialogOpen] = useState(false);
const [pairingLabel, setPairingLabel] = useState("");
const [pairingScopes, setPairingScopes] = useState<ReadonlyArray<AuthEnvironmentScope>>([
const [pairingScopes, setPairingScopes] = useState<ReadonlyArray<AuthGrantScope>>([
...AuthStandardClientScopes,
]);
const selectedScopes = pairingScopes.filter((scope) => delegatableScopes.includes(scope));
@@ -1145,7 +1152,7 @@ const AuthorizedClientsHeaderAction = memo(function AuthorizedClientsHeaderActio
}
}, [delegatableScopes, onPairingLinkCreated, pairingLabel, primaryEnvironmentId, selectedScopes]);
const togglePairingScope = useCallback((scope: AuthEnvironmentScope, checked: boolean) => {
const togglePairingScope = useCallback((scope: AuthGrantScope, checked: boolean) => {
setPairingScopes((current) =>
checked ? [...current, scope] : current.filter((currentScope) => currentScope !== scope),
);
@@ -1217,9 +1224,9 @@ const AuthorizedClientsHeaderAction = memo(function AuthorizedClientsHeaderActio
disabled={isCreatingPairingLink}
onClick={() =>
setPairingScopes(
delegatableScopes.includes(AuthOrchestrationReadScope)
? [AuthOrchestrationReadScope]
: [],
[AuthOrchestrationReadScope, AuthFilesystemReadScope].filter((scope) =>
delegatableScopes.includes(scope),
),
)
}
>
+2 -1
View File
@@ -2,6 +2,7 @@ import type {
AuthBrowserSessionResult,
AuthClientMetadata,
AuthEnvironmentScope,
AuthGrantScope,
AuthPairingCredentialResult,
ServerAuthSessionMethod,
AuthSessionId,
@@ -354,7 +355,7 @@ export async function submitServerAuthCredential(credential: string): Promise<vo
export async function createServerPairingCredential(input?: {
readonly label?: string;
readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
readonly scopes?: ReadonlyArray<AuthGrantScope>;
}): Promise<AuthPairingCredentialResult> {
const trimmedLabel = input?.label?.trim();
try {
+21 -1
View File
@@ -1,5 +1,25 @@
import { createFilesystemEnvironmentAtoms } from "@t3tools/client-runtime/state/filesystem";
import {
createFilesystemEnvironmentAtoms,
resolveFilesystemReadAccess,
} from "@t3tools/client-runtime/state/filesystem";
import type { EnvironmentId } from "@t3tools/contracts";
import { connectionAtomRuntime } from "../connection/runtime";
import { useEnvironmentPresentation } from "./presentation";
import { useEnvironmentQuery } from "./query";
import { environmentSession } from "./session";
export const filesystemEnvironment = createFilesystemEnvironmentAtoms(connectionAtomRuntime);
export function useFilesystemReadAccess(environmentId: EnvironmentId | null) {
const session = useEnvironmentQuery(
environmentId === null ? null : environmentSession.sessionStateAtom(environmentId),
);
const environment = useEnvironmentPresentation(environmentId);
return resolveFilesystemReadAccess({
isCatalogReady: environment.isReady,
connection: environment.presentation?.connection ?? null,
session: session.data,
sessionError: session.error,
});
}
@@ -0,0 +1,241 @@
import { AuthFilesystemReadScope, EnvironmentId, type AuthSessionState } from "@t3tools/contracts";
import { beforeEach, expect, it, vi } from "vite-plus/test";
const state = vi.hoisted(() => ({
session: null as Pick<AuthSessionState, "authenticated" | "scopes"> | null,
sessionError: null as string | null,
sessionWaiting: false,
phase: "connected" as "connected" | "offline",
sessionAtom: {},
searchAtom: {},
contentAtom: {},
contentRequests: vi.fn(),
contentError: null as string | null,
contentData: {
matches: [{ path: "src/index.ts", lineNumber: 3, lineContent: "a match", matchRanges: [] }],
truncated: false,
},
}));
vi.mock("react", async (importOriginal) => ({
...(await importOriginal<typeof import("react")>()),
useCallback: <A>(callback: A) => callback,
useEffect: () => {},
useMemo: <A>(factory: () => A) => factory(),
useState: <A>(value: A) => [value, vi.fn()],
}));
vi.mock("./session", () => ({
environmentSession: { sessionStateAtom: () => state.sessionAtom },
}));
vi.mock("./presentation", () => ({
useEnvironmentPresentation: () => ({
isReady: true,
presentation: { connection: { phase: state.phase, error: null } },
}),
}));
vi.mock("./projects", () => ({
projectEnvironment: { searchEntries: () => state.searchAtom },
projectContentSearch: (target: unknown) => {
state.contentRequests(target);
return state.contentAtom;
},
}));
vi.mock("../rpc/atomRegistry", () => ({ appAtomRegistry: {} }));
vi.mock("./orchestration", () => ({ orchestrationEnvironment: {} }));
vi.mock("./threads", () => ({ useEnvironmentThread: vi.fn() }));
vi.mock("./vcs", () => ({ vcsEnvironment: {} }));
vi.mock("./query", () => ({
useEnvironmentQuery: (atom: unknown) => ({
data:
atom === state.sessionAtom
? state.session
: atom === state.searchAtom
? { entries: [{ path: "src/index.ts", kind: "file" }] }
: atom === state.contentAtom
? state.contentData
: null,
error:
atom === state.sessionAtom
? state.sessionError
: atom === state.contentAtom
? state.contentError
: null,
isPending:
atom === state.sessionAtom &&
(state.sessionWaiting || (state.session === null && state.sessionError === null)),
refresh: vi.fn(),
}),
}));
import { useProjectContentSearch, useProjectPathSearch } from "./queries";
const useComposerPathSearch = (input: Parameters<typeof useProjectPathSearch>[0]) =>
useProjectPathSearch(input, 20);
const target = {
environmentId: EnvironmentId.make("test-environment"),
cwd: "/repo",
query: "src",
};
beforeEach(() => {
state.session = null;
state.sessionError = null;
state.sessionWaiting = false;
state.phase = "connected";
state.contentRequests.mockClear();
state.contentError = null;
});
it("keeps a file search pending until its grant loads, then shows matches", () => {
expect(useComposerPathSearch(target)).toMatchObject({
entries: [],
error: null,
isPending: true,
});
state.session = { authenticated: true, scopes: [AuthFilesystemReadScope] };
expect(useComposerPathSearch(target)).toMatchObject({
entries: [{ path: "src/index.ts", kind: "file" }],
error: null,
isPending: false,
});
});
it("shows a confirmed denial and a connection failure separately", () => {
state.session = { authenticated: true, scopes: [] };
expect(useComposerPathSearch(target)).toMatchObject({
entries: [],
error: "This connection cannot search host files.",
isPending: false,
});
state.session = null;
state.phase = "offline";
expect(useComposerPathSearch(target)).toMatchObject({
entries: [],
error: "This environment is not connected.",
isPending: false,
});
});
it("leaves an inactive search idle while its grant loads", () => {
expect(useComposerPathSearch({ ...target, cwd: null, query: null })).toMatchObject({
entries: [],
error: null,
isPending: false,
});
});
const contentTarget = {
...target,
query: " a match ",
caseSensitive: true,
wholeWord: true,
useRegex: false,
};
it("waits for content-search access before issuing a request, including an empty search", () => {
for (const query of ["", contentTarget.query]) {
const result = useProjectContentSearch({ ...contentTarget, query });
expect(state.contentRequests).not.toHaveBeenCalled();
expect(result).toMatchObject({
canReadFiles: false,
isCheckingAccess: true,
matches: [],
error: null,
isPending: true,
});
}
expect(state.contentRequests).not.toHaveBeenCalled();
});
it("shows content-search denial before typing and never issues an unauthorized request", () => {
state.session = { authenticated: true, scopes: [] };
for (const query of ["", contentTarget.query]) {
const result = useProjectContentSearch({ ...contentTarget, query });
expect(state.contentRequests).not.toHaveBeenCalled();
expect(result).toMatchObject({
canReadFiles: false,
isCheckingAccess: false,
matches: [],
error: "This connection cannot search host files.",
isPending: false,
});
}
expect(state.contentRequests).not.toHaveBeenCalled();
});
it("preserves content query whitespace and options when access is granted", () => {
state.session = { authenticated: true, scopes: [AuthFilesystemReadScope] };
expect(useProjectContentSearch(contentTarget)).toMatchObject({
matches: state.contentData.matches,
error: null,
isPending: false,
});
expect(state.contentRequests).toHaveBeenCalledWith({
environmentId: contentTarget.environmentId,
input: {
cwd: contentTarget.cwd,
query: contentTarget.query,
limit: 500,
caseSensitive: true,
wholeWord: true,
useRegex: false,
},
});
});
it("keeps confirmed content access during revalidation and drops results when it is revoked", () => {
state.session = { authenticated: true, scopes: [AuthFilesystemReadScope] };
state.sessionWaiting = true;
expect(useProjectContentSearch(contentTarget)).toMatchObject({
matches: state.contentData.matches,
isPending: false,
});
state.contentRequests.mockClear();
state.sessionWaiting = false;
state.session = { authenticated: true, scopes: [] };
const result = useProjectContentSearch(contentTarget);
expect(state.contentRequests).not.toHaveBeenCalled();
expect(result).toMatchObject({
canReadFiles: false,
matches: [],
error: "This connection cannot search host files.",
isPending: false,
});
expect(state.contentRequests).not.toHaveBeenCalled();
});
it("fails closed after a session check fails, even with a cached grant and matches", () => {
state.session = { authenticated: true, scopes: [AuthFilesystemReadScope] };
state.sessionError = "The session has expired.";
const result = useProjectContentSearch(contentTarget);
expect(state.contentRequests).not.toHaveBeenCalled();
expect(result).toMatchObject({
canReadFiles: false,
matches: [],
error: state.sessionError,
isPending: false,
});
expect(state.contentRequests).not.toHaveBeenCalled();
});
it("keeps inactive content search idle and reports a disconnected target without querying", () => {
expect(
useProjectContentSearch({ ...contentTarget, environmentId: null, cwd: null }),
).toMatchObject({
matches: [],
error: null,
isPending: false,
});
state.phase = "offline";
const result = useProjectContentSearch(contentTarget);
expect(state.contentRequests).not.toHaveBeenCalled();
expect(result).toMatchObject({
canReadFiles: false,
matches: [],
error: "This environment is not connected.",
isPending: false,
});
expect(state.contentRequests).not.toHaveBeenCalled();
});
+38 -12
View File
@@ -25,6 +25,7 @@ import { AsyncResult, Atom } from "effect/reactivity";
import { useCallback, useEffect, useMemo, useState } from "react";
import { appAtomRegistry } from "../rpc/atomRegistry";
import { useFilesystemReadAccess } from "./filesystem";
import { orchestrationEnvironment } from "./orchestration";
import { isPaginatedBranchesNextPagePending } from "./paginatedBranches";
import { projectContentSearch, projectEnvironment } from "./projects";
@@ -237,12 +238,14 @@ export function useProjectPathSearch(
[target.cwd, target.environmentId, target.imageOnly, target.kind, target.query],
);
const debouncedTarget = useDebouncedValue(normalizedTarget, PROJECT_PATH_SEARCH_DEBOUNCE_MS);
const result = useEnvironmentQuery(
const fileAccess = useFilesystemReadAccess(debouncedTarget.environmentId);
const { canReadFiles } = fileAccess;
const searchTarget =
debouncedTarget.environmentId !== null &&
debouncedTarget.cwd !== null &&
debouncedTarget.query !== null &&
(allowEmptyQuery || debouncedTarget.query.length > 0)
? projectEnvironment.searchEntries({
debouncedTarget.cwd !== null &&
debouncedTarget.query !== null &&
(allowEmptyQuery || debouncedTarget.query.length > 0)
? {
environmentId: debouncedTarget.environmentId,
input: {
cwd: debouncedTarget.cwd,
@@ -251,15 +254,24 @@ export function useProjectPathSearch(
...(debouncedTarget.kind ? { kind: debouncedTarget.kind } : {}),
...(debouncedTarget.imageOnly ? { imageOnly: true } : {}),
},
})
: null,
}
: null;
const result = useEnvironmentQuery(
canReadFiles && searchTarget !== null ? projectEnvironment.searchEntries(searchTarget) : null,
);
const hasTarget = searchTarget !== null;
return {
entries: result.data?.entries ?? EMPTY_PROJECT_ENTRIES,
error: result.error,
error:
!hasTarget || fileAccess.isPending
? null
: canReadFiles
? result.error
: (fileAccess.error ?? "This connection cannot search host files."),
isPending:
!areProjectPathSearchTargetsEqual(normalizedTarget, debouncedTarget) || result.isPending,
!areProjectPathSearchTargetsEqual(normalizedTarget, debouncedTarget) ||
(hasTarget && (fileAccess.isPending || result.isPending)),
searchedQuery: debouncedTarget.query ?? "",
truncated: result.data?.truncated ?? false,
refresh: result.refresh,
@@ -280,13 +292,18 @@ interface ProjectContentSearchTarget {
}
export function useProjectContentSearch(target: ProjectContentSearchTarget) {
const hasTarget = target.environmentId !== null && target.cwd !== null;
const fileAccess = useFilesystemReadAccess(target.environmentId);
const canReadFiles = hasTarget && fileAccess.canReadFiles;
const isCheckingAccess = hasTarget && fileAccess.isPending;
// Whitespace is significant in content queries; trimming is only used to
// decide whether the input is blank.
const query = target.query;
const hasQuery = query.trim().length > 0;
const debouncedQuery = useDebouncedValue(query, PROJECT_CONTENT_SEARCH_DEBOUNCE_MS);
const result = useEnvironmentQuery(
target.environmentId !== null &&
canReadFiles &&
target.environmentId !== null &&
target.cwd !== null &&
hasQuery &&
debouncedQuery.trim().length > 0
@@ -305,9 +322,18 @@ export function useProjectContentSearch(target: ProjectContentSearchTarget) {
);
return {
canReadFiles,
isCheckingAccess,
matches: result.data?.matches ?? EMPTY_CONTENT_MATCHES,
error: result.error,
isPending: hasQuery && (query !== debouncedQuery || result.isPending),
error:
!hasTarget || isCheckingAccess
? null
: canReadFiles
? result.error
: (fileAccess.error ?? "This connection cannot search host files."),
isPending:
isCheckingAccess ||
(canReadFiles && hasQuery && (query !== debouncedQuery || result.isPending)),
hasQuery,
truncated: result.data?.truncated ?? false,
invalidRegex: target.useRegex && result.data?.regexFallbackError !== undefined,
+4 -2
View File
@@ -92,7 +92,7 @@ after 30 days.
## The environment is the filesystem boundary
Projects are organizational boundaries, not filesystem sandboxes.
`orchestration:read` permits reading files the server account can read, including
`filesystem:read` permits reading files the server account can read, including
absolute paths outside a project. This lets clients display artifacts that an
agent writes in a temporary directory. Relative paths and writes still follow
the [workspace path rules](../../apps/server/src/workspace/WorkspaceFileSystem.ts).
@@ -104,7 +104,9 @@ file's identity when serving it, so atomic replacement requires a new URL while
editing the same file in place does not. An HTML file authorized this way cannot
load sibling assets; directory-scoped workspace previews are a separate grant.
Clients should share the authored file reference so they do not disclose the
temporary URL's credential.
temporary URL's credential. `filesystem:read` is checked when the URL is minted,
not when it is served: a URL issued before the grant was revoked keeps working
until it expires, and it is not bound to the session that minted it.
Host videos can change in place. Their [HTTP
responses](../../apps/server/src/http.ts) omit cache validators because file
+4
View File
@@ -293,6 +293,10 @@ permissions. Existing clients keep their original grants after an update; to
receive newly separated permissions, pair the client again with the scopes it
needs. Reconnecting or refreshing a session does not expand its grant.
`filesystem:read` allows browsing host files, opening workspace files, and viewing
local changes. Add `filesystem:write` to allow editing files or saving plans to
the workspace. These scopes control direct file access from the client.
To remove an environment from T3 Connect, open your account menu's **T3 Connect**
page, or **Settings → T3 Connect** on mobile, and choose **Deregister**. This
revokes its cloud access and frees its host space even when the environment is
@@ -1,12 +1,119 @@
import { describe, expect, it } from "vite-plus/test";
import { AuthFilesystemReadScope, AuthOrchestrationReadScope } from "@t3tools/contracts";
import {
canPreloadBrowsePath,
createBrowseNavigationCoordinator,
filterFilesystemBrowseEntries,
getFilesystemBrowsePath,
resolveFilesystemReadAccess,
} from "./filesystem.ts";
describe("filesystem read access", () => {
it("waits for the initial catalog before declaring a missing environment disconnected", () => {
expect(
resolveFilesystemReadAccess({
isCatalogReady: false,
connection: null,
session: null,
sessionError: null,
}),
).toEqual({ canReadFiles: false, isPending: true, error: null });
});
it("stops waiting when the loaded catalog has no matching environment", () => {
expect(
resolveFilesystemReadAccess({
isCatalogReady: true,
connection: null,
session: null,
sessionError: null,
}),
).toEqual({
canReadFiles: false,
isPending: false,
error: "This environment is not connected.",
});
});
it.each(["available", "offline", "error"] as const)(
"stops waiting for an unresolved session when the connection is %s",
(phase) => {
expect(
resolveFilesystemReadAccess({
isCatalogReady: true,
connection: { phase, error: null },
session: null,
sessionError: null,
}),
).toEqual({
canReadFiles: false,
isPending: false,
error: "This environment is not connected.",
});
},
);
it.each(["connected", "connecting", "reconnecting"] as const)(
"waits for the session check while %s",
(phase) => {
expect(
resolveFilesystemReadAccess({
isCatalogReady: true,
connection: { phase, error: null },
session: null,
sessionError: null,
}),
).toEqual({ canReadFiles: false, isPending: true, error: null });
},
);
it("reports the transport failure when the session cannot be checked", () => {
expect(
resolveFilesystemReadAccess({
isCatalogReady: true,
connection: { phase: "error", error: "The relay is unavailable." },
session: null,
sessionError: null,
}),
).toEqual({ canReadFiles: false, isPending: false, error: "The relay is unavailable." });
});
it.each([false, true])(
"preserves a cached file grant offline with catalog ready=%s",
(isCatalogReady) => {
const input = {
isCatalogReady,
connection: { phase: "offline", error: null },
session: { authenticated: true, scopes: [AuthFilesystemReadScope] },
sessionError: null,
} as const;
expect(resolveFilesystemReadAccess(input)).toEqual({
canReadFiles: true,
isPending: false,
error: null,
});
expect(
resolveFilesystemReadAccess({ ...input, sessionError: "The session has expired." }),
).toEqual({ canReadFiles: false, isPending: false, error: "The session has expired." });
},
);
it.each([
{ authenticated: true, scopes: [AuthOrchestrationReadScope] },
{ authenticated: false, scopes: [AuthFilesystemReadScope] },
] as const)("does not infer file access from an ungranted session", (session) => {
expect(
resolveFilesystemReadAccess({
isCatalogReady: true,
connection: { phase: "connected", error: null },
session,
sessionError: null,
}),
).toEqual({ canReadFiles: false, isPending: false, error: null });
});
});
describe("filesystem browse model", () => {
it("derives the browse target and navigation state", () => {
expect(getFilesystemBrowsePath("~/projects/t3")).toEqual({
@@ -1,7 +1,15 @@
import { type FilesystemBrowseEntry, WS_METHODS } from "@t3tools/contracts";
import {
AuthFilesystemReadScope,
type AuthSessionState,
type FilesystemBrowseEntry,
WS_METHODS,
} from "@t3tools/contracts";
import { Atom } from "effect/reactivity";
import type { EnvironmentConnectionPhase } from "../connection/presentation.ts";
import type {
EnvironmentConnectionPhase,
EnvironmentConnectionPresentation,
} from "../connection/presentation.ts";
import type { EnvironmentRegistry } from "../connection/registry.ts";
import {
canNavigateUp,
@@ -13,6 +21,38 @@ import {
} from "./projects.ts";
import { createEnvironmentRpcQueryAtomFamily } from "./runtime.ts";
export function resolveFilesystemReadAccess(input: {
readonly isCatalogReady: boolean;
readonly connection: Pick<EnvironmentConnectionPresentation, "phase" | "error"> | null;
readonly session: Pick<AuthSessionState, "authenticated" | "scopes"> | null;
readonly sessionError: string | null;
}) {
if (input.sessionError !== null) {
return { canReadFiles: false, isPending: false, error: input.sessionError };
}
if (input.session === null) {
// Wait for the catalog before interpreting a missing presentation as offline.
// Once ready, an offline environment cannot finish its session check.
const isPending =
!input.isCatalogReady ||
input.connection?.phase === "connected" ||
input.connection?.phase === "connecting" ||
input.connection?.phase === "reconnecting";
return {
canReadFiles: false,
isPending,
error: isPending ? null : (input.connection?.error ?? "This environment is not connected."),
};
}
return {
canReadFiles:
input.session.authenticated &&
input.session.scopes?.includes(AuthFilesystemReadScope) === true,
isPending: false,
error: null,
};
}
export function getFilesystemBrowsePath(query: string, platform = "", enabled = true) {
const isBrowsing = enabled && isFilesystemBrowseQuery(query, platform);
const directoryPath = isBrowsing ? getBrowseDirectoryPath(query) : "";
+14
View File
@@ -0,0 +1,14 @@
import { describe, expect, it } from "vite-plus/test";
import * as Schema from "effect/Schema";
import { AuthEnvironmentScopes, AuthGrantScopes, AuthStandardClientScopes } from "./auth.ts";
describe("authorization grants", () => {
it("decodes legacy review credentials without offering them in new grants", () => {
expect(Schema.decodeUnknownSync(AuthEnvironmentScopes)(["review:write"])).toEqual([
"review:write",
]);
expect(() => Schema.decodeUnknownSync(AuthGrantScopes)(["review:write"])).toThrow();
expect(AuthStandardClientScopes).not.toContain("review:write");
});
});
+16 -3
View File
@@ -85,7 +85,10 @@ export const AuthProvidersManageScope = "providers:manage" as const;
export const AuthEnvironmentMaintainScope = "environment:maintain" as const;
export const AuthTerminalOperateScope = "terminal:operate" as const;
export const AuthSourceControlWriteScope = "source-control:write" as const;
export const AuthReviewWriteScope = "review:write" as const;
export const AuthFilesystemReadScope = "filesystem:read" as const;
export const AuthFilesystemWriteScope = "filesystem:write" as const;
/** Retained for decoding existing credentials; grants no current RPC access. */
const AuthReviewWriteScope = "review:write" as const;
export const AuthAccessReadScope = "access:read" as const;
export const AuthAccessWriteScope = "access:write" as const;
export const AuthRelayReadScope = "relay:read" as const;
@@ -97,6 +100,8 @@ export const AuthEnvironmentScope = Schema.Literals([
AuthProvidersManageScope,
AuthEnvironmentMaintainScope,
AuthTerminalOperateScope,
AuthFilesystemReadScope,
AuthFilesystemWriteScope,
AuthReviewWriteScope,
AuthSourceControlWriteScope,
AuthAccessReadScope,
@@ -108,6 +113,13 @@ export type AuthEnvironmentScope = typeof AuthEnvironmentScope.Type;
export const AuthEnvironmentScopes = Schema.Array(AuthEnvironmentScope);
export type AuthEnvironmentScopes = typeof AuthEnvironmentScopes.Type;
export const AuthGrantScope = Schema.Literals(
AuthEnvironmentScope.literals.filter((scope) => scope !== AuthReviewWriteScope),
);
export type AuthGrantScope = typeof AuthGrantScope.Type;
export const AuthGrantScopes = Schema.Array(AuthGrantScope);
export type AuthGrantScopes = typeof AuthGrantScopes.Type;
export const AuthStandardClientScopes = [
AuthOrchestrationReadScope,
AuthOrchestrationOperateScope,
@@ -115,8 +127,9 @@ export const AuthStandardClientScopes = [
AuthProvidersManageScope,
AuthEnvironmentMaintainScope,
AuthTerminalOperateScope,
AuthReviewWriteScope,
AuthSourceControlWriteScope,
AuthFilesystemReadScope,
AuthFilesystemWriteScope,
AuthRelayReadScope,
] as const;
export const AuthAdministrativeScopes = [
@@ -355,7 +368,7 @@ export type AuthRevokeClientSessionInput = typeof AuthRevokeClientSessionInput.T
export const AuthCreatePairingCredentialInput = Schema.Struct({
label: Schema.optionalKey(TrimmedNonEmptyString),
scopes: Schema.optionalKey(AuthEnvironmentScopes),
scopes: Schema.optionalKey(AuthGrantScopes),
});
export type AuthCreatePairingCredentialInput = typeof AuthCreatePairingCredentialInput.Type;