feat(auth): separate environment administration permissions (#9786)

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 e9c3d950f0
commit 28ce9d1c17
162 files changed
+8378 -1114

No files matched your search

+1
View File
@@ -150,6 +150,7 @@ Architecture and its constraints: `docs/internals/overview.md`. Glossary: `docs/
## Taste
- Complexity belongs at the adapter boundary. Orchestration stays pure, UI stays dumb.
- Client mutations use `createEnvironmentRpcCommand`. Add protected methods to `CLIENT_GUARDED_RPC_SCOPES` in contracts and use the command's `permissionAtom` for UI availability. Grants are checked at execution against the destination environment; the server remains authoritative. Keep raw RPC clients inside `rpc/`, and extend the permission behavior tests when adding a protected method.
- Server features are services; transports stay thin. A `ws.ts` RPC handler, HTTP route, or MCP tool decodes input, calls one service method, and maps errors. See [Effect services](docs/internals/effect-services.md).
- `apps/web/src/components/ui` exports own their look. Pick a `variant` or `size`; do not restyle one with `className`. If none fits and the look is a generic concept, add a variant to the component; a look that belongs to one feature stays in that feature's own component, not in `components/ui`. Layout classes (width, flex, margin, position) belong on the parent. `shadcn/no-restyle` fails lint on violations. See [Web UI](docs/internals/web-ui.md).
- Inferred types over annotations. `any` is the enemy.
@@ -25,7 +25,14 @@ vi.mock("react-native", () => ({
Platform: { OS: "ios" },
}));
vi.mock("../cloud/linkEnvironment", () => ({
vi.mock("expo-constants", () => ({
default: { expoConfig: {} },
}));
vi.mock("expo-device", () => ({}));
vi.mock("../cloud/linkEnvironment", async (importOriginal) => ({
...(await importOriginal<typeof import("../cloud/linkEnvironment")>()),
linkEnvironmentToCloudWithPreference: vi.fn(() => Effect.void),
}));
@@ -78,6 +85,7 @@ describe("liveActivityPreferences", () => {
previousEnabled: true,
clerkToken: "clerk-token",
connections: [connection],
canConfigureEnvironment: () => true,
});
expect(updateAgentAwarenessRegistrationPreferences).toHaveBeenCalledWith({
@@ -98,6 +106,7 @@ describe("liveActivityPreferences", () => {
previousEnabled: false,
clerkToken: "clerk-token",
connections: [connection],
canConfigureEnvironment: () => true,
});
expect(updateAgentAwarenessRegistrationPreferences).toHaveBeenCalledWith({
@@ -118,6 +127,7 @@ describe("liveActivityPreferences", () => {
previousEnabled: true,
clerkToken: null,
connections: [connection],
canConfigureEnvironment: () => true,
});
expect(updateAgentAwarenessRegistrationPreferences).toHaveBeenCalledWith({
@@ -139,6 +149,7 @@ describe("liveActivityPreferences", () => {
previousEnabled: false,
clerkToken: "clerk-token",
connections: [connection, managedConnection],
canConfigureEnvironment: () => true,
});
expect(linkEnvironmentToCloudWithPreference).toHaveBeenCalledTimes(1);
@@ -162,6 +173,7 @@ describe("liveActivityPreferences", () => {
previousEnabled: true,
clerkToken: "clerk-token",
connections: [connection],
canConfigureEnvironment: () => true,
}),
);
@@ -184,4 +196,105 @@ describe("liveActivityPreferences", () => {
});
}).pipe(Effect.provide(layerTest));
});
it.effect("only re-links environments with relay access when enabling updates", () => {
const readOnlyConnection: SavedRemoteConnection = {
...connection,
environmentId: "read-only" as EnvironmentId,
};
return Effect.gen(function* () {
yield* setLiveActivityUpdatesEnabled({
enabled: true,
previousEnabled: false,
clerkToken: "clerk-token",
connections: [readOnlyConnection, connection],
canConfigureEnvironment: (environmentId) => environmentId === connection.environmentId,
});
expect(updateAgentAwarenessRegistrationPreferences).toHaveBeenCalledWith({
liveActivitiesEnabled: true,
});
expect(linkEnvironmentToCloudWithPreference).toHaveBeenCalledExactlyOnceWith({
clerkToken: "clerk-token",
connection,
liveActivitiesEnabled: true,
});
}).pipe(Effect.provide(layerTest));
});
it.effect("keeps device updates independently switchable without relay access", () =>
Effect.gen(function* () {
for (const enabled of [false, true]) {
yield* setLiveActivityUpdatesEnabled({
enabled,
previousEnabled: !enabled,
clerkToken: "clerk-token",
connections: [connection],
canConfigureEnvironment: () => false,
});
}
expect(updateAgentAwarenessRegistrationPreferences).toHaveBeenNthCalledWith(1, {
liveActivitiesEnabled: false,
});
expect(updateAgentAwarenessRegistrationPreferences).toHaveBeenNthCalledWith(2, {
liveActivitiesEnabled: true,
});
expect(linkEnvironmentToCloudWithPreference).not.toHaveBeenCalled();
}).pipe(Effect.provide(layerTest)),
);
it.effect("checks current relay access after updating the device registration", () => {
let canConfigureEnvironment = true;
vi.mocked(updateAgentAwarenessRegistrationPreferences).mockImplementationOnce(() =>
Effect.sync(() => {
canConfigureEnvironment = false;
}),
);
return Effect.gen(function* () {
yield* setLiveActivityUpdatesEnabled({
enabled: false,
previousEnabled: true,
clerkToken: "clerk-token",
connections: [connection],
canConfigureEnvironment: () => canConfigureEnvironment,
});
expect(linkEnvironmentToCloudWithPreference).not.toHaveBeenCalled();
expect(updateAgentAwarenessRegistrationPreferences).toHaveBeenCalledTimes(1);
}).pipe(Effect.provide(layerTest));
});
it.effect("does not retry environment changes after relay access is revoked", () => {
let canConfigureEnvironment = true;
vi.mocked(linkEnvironmentToCloudWithPreference).mockImplementationOnce(() =>
Effect.sync(() => {
canConfigureEnvironment = false;
}).pipe(
Effect.andThen(
Effect.fail(new CloudEnvironmentLinkError({ message: "relay access revoked" })),
),
),
);
return Effect.gen(function* () {
const exit = yield* Effect.exit(
setLiveActivityUpdatesEnabled({
enabled: false,
previousEnabled: true,
clerkToken: "clerk-token",
connections: [connection],
canConfigureEnvironment: () => canConfigureEnvironment,
}),
);
expect(exit._tag).toBe("Failure");
expect(linkEnvironmentToCloudWithPreference).toHaveBeenCalledTimes(1);
expect(updateAgentAwarenessRegistrationPreferences).toHaveBeenNthCalledWith(2, {
liveActivitiesEnabled: true,
});
}).pipe(Effect.provide(layerTest));
});
});
@@ -1,4 +1,5 @@
import * as Effect from "effect/Effect";
import type { EnvironmentId } from "@t3tools/contracts";
import type { SavedRemoteConnection } from "../../lib/connection";
import { linkEnvironmentToCloudWithPreference } from "../cloud/linkEnvironment";
@@ -10,11 +11,26 @@ export const setLiveActivityUpdatesEnabled = Effect.fn("setLiveActivityUpdatesEn
readonly previousEnabled: boolean;
readonly clerkToken: string | null;
readonly connections: ReadonlyArray<SavedRemoteConnection>;
readonly canConfigureEnvironment: (environmentId: EnvironmentId) => boolean;
}) {
const linkedConnections = input.connections.filter(
(connection) => connection.bearerToken !== null,
);
const updateEnvironmentPreference = Effect.fn("updateEnvironmentPreference")(function* (
connection: SavedRemoteConnection,
enabled: boolean,
clerkToken: string,
) {
if (!input.canConfigureEnvironment(connection.environmentId)) return;
yield* linkEnvironmentToCloudWithPreference({
clerkToken,
connection,
liveActivitiesEnabled: enabled,
});
});
const updateRelayPreference = Effect.fn("updateRelayPreference")(function* (enabled: boolean) {
yield* updateAgentAwarenessRegistrationPreferences({
liveActivitiesEnabled: enabled,
@@ -25,12 +41,7 @@ export const setLiveActivityUpdatesEnabled = Effect.fn("setLiveActivityUpdatesEn
yield* Effect.forEach(
linkedConnections,
(connection) =>
linkEnvironmentToCloudWithPreference({
clerkToken,
connection,
liveActivitiesEnabled: enabled,
}),
(connection) => updateEnvironmentPreference(connection, enabled, clerkToken),
{ concurrency: "unbounded" },
);
});
@@ -50,11 +61,7 @@ export const setLiveActivityUpdatesEnabled = Effect.fn("setLiveActivityUpdatesEn
yield* Effect.forEach(
linkedConnections,
(connection) =>
linkEnvironmentToCloudWithPreference({
clerkToken,
connection,
liveActivitiesEnabled: input.previousEnabled,
}).pipe(
updateEnvironmentPreference(connection, input.previousEnabled, clerkToken).pipe(
Effect.catchCause((cause) =>
Effect.logWarning(
`Could not restore Live Activity preference for environment ${connection.environmentId}.`,
@@ -4,6 +4,7 @@ import type {
} from "@t3tools/client-runtime/state/shell";
import { LegendList } from "@legendapp/list/react-native";
import {
AuthOrchestrationOperateScope,
type EnvironmentId,
type EnvironmentMachineKind,
resolveEnvironmentMachineKind,
@@ -30,6 +31,7 @@ import { ProjectFavicon } from "../../components/ProjectFavicon";
import { relativeTime } from "../../lib/time";
import { useUniwindTheme } from "../../lib/useUniwindTheme";
import { useServerConfigs } from "../../state/entities";
import { useEnvironmentScope } from "../../state/session";
import { ThreadSwipeable } from "../home/thread-swipe-actions";
import type { ArchivedThreadGroup, ArchivedThreadSortOrder } from "./archivedThreadList";
import { SettingsScreenContent } from "../settings/components/SettingsScreen";
@@ -191,24 +193,74 @@ function ArchivedThreadRow(props: {
}) {
const { width: windowWidth } = useWindowDimensions();
const cardColor = useUniwindTheme()["--color-grouped-card"];
const canOperateThread = useEnvironmentScope(
props.thread.environmentId,
AuthOrchestrationOperateScope,
);
const timestamp = relativeTime(props.thread.archivedAt ?? props.thread.updatedAt);
const subtitle = [props.environmentLabel, props.thread.branch].filter((part): part is string =>
Boolean(part),
);
const rowContent = (
<View
className={`flex-row items-center gap-3 bg-grouped-card px-4 py-3 ${props.isLast ? "" : "border-b border-separator"}`}
>
<View className="h-[34px] w-[34px] items-center justify-center rounded-[11px] bg-subtle">
<SymbolView
name="archivebox.fill"
size={15}
tintColorClassName="accent-icon-subtle"
type="monochrome"
/>
</View>
<View className="min-w-0 flex-1 gap-1">
<View className="flex-row items-center gap-2">
<Text
className="min-w-0 flex-1 text-base font-t3-bold leading-snug text-foreground"
numberOfLines={1}
>
{props.thread.title}
</Text>
<Text className="min-w-[30px] text-right text-xs tabular-nums text-foreground-tertiary">
{timestamp}
</Text>
</View>
{subtitle.length > 0 ? (
<View className="flex-row items-center gap-1.5">
<SymbolView
name="arrow.triangle.branch"
size={10}
tintColorClassName="accent-icon-subtle"
type="monochrome"
/>
<Text
className="min-w-0 flex-1 font-mono text-2xs text-foreground-tertiary"
numberOfLines={1}
>
{subtitle.join(" · ")}
</Text>
</View>
) : null}
</View>
</View>
);
// Keep the group's rounded corners on both interactive and read-only rows.
const containerStyle = {
borderTopLeftRadius: props.isFirst ? 20 : 0,
borderTopRightRadius: props.isFirst ? 20 : 0,
borderBottomLeftRadius: props.isLast ? 20 : 0,
borderBottomRightRadius: props.isLast ? 20 : 0,
overflow: "hidden" as const,
};
if (!canOperateThread) return <View style={containerStyle}>{rowContent}</View>;
return (
<ThreadSwipeable
resetKey={`${props.thread.environmentId}:${props.thread.id}`}
threadKey={`${props.thread.environmentId}:${props.thread.id}`}
backgroundColor={cardColor}
// Round + clip the swipeable container so the group's corners stay
// rounded while rows swipe; the row itself stays square inside.
containerStyle={{
borderTopLeftRadius: props.isFirst ? 20 : 0,
borderTopRightRadius: props.isFirst ? 20 : 0,
borderBottomLeftRadius: props.isLast ? 20 : 0,
borderBottomRightRadius: props.isLast ? 20 : 0,
overflow: "hidden",
}}
containerStyle={containerStyle}
fullSwipeWidth={windowWidth - 32}
onDelete={props.onDelete}
onSwipeableClose={props.onSwipeableClose}
@@ -222,50 +274,7 @@ function ArchivedThreadRow(props: {
simultaneousWith={props.simultaneousSwipeGesture}
threadTitle={props.thread.title}
>
{() => (
<View
className={`flex-row items-center gap-3 bg-grouped-card px-4 py-3 ${props.isLast ? "" : "border-b border-separator"}`}
>
<View className="h-[34px] w-[34px] items-center justify-center rounded-[11px] bg-subtle">
<SymbolView
name="archivebox.fill"
size={15}
tintColorClassName="accent-icon-subtle"
type="monochrome"
/>
</View>
<View className="min-w-0 flex-1 gap-1">
<View className="flex-row items-center gap-2">
<Text
className="min-w-0 flex-1 text-base font-t3-bold leading-snug text-foreground"
numberOfLines={1}
>
{props.thread.title}
</Text>
<Text className="min-w-[30px] text-right text-xs tabular-nums text-foreground-tertiary">
{timestamp}
</Text>
</View>
{subtitle.length > 0 ? (
<View className="flex-row items-center gap-1.5">
<SymbolView
name="arrow.triangle.branch"
size={10}
tintColorClassName="accent-icon-subtle"
type="monochrome"
/>
<Text
className="min-w-0 flex-1 font-mono text-2xs text-foreground-tertiary"
numberOfLines={1}
>
{subtitle.join(" · ")}
</Text>
</View>
) : null}
</View>
</View>
)}
{() => rowContent}
</ThreadSwipeable>
);
}
@@ -0,0 +1,326 @@
import { makeThreadShellFixture } from "../../test-fixtures";
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
import {
AuthOrchestrationOperateScope,
EnvironmentId,
ProjectId,
ProviderInstanceId,
ThreadId,
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import { AsyncResult } from "effect/reactivity";
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
const state = vi.hoisted(() => ({
pendingOrder: null as object | null,
dropBusy: false,
scopes: new Map<string, Set<string>>(),
shells: [] as EnvironmentThreadShell[],
requests: [] as {
action: string;
environmentId: string;
input: { threadId: string; orderKey?: string };
}[],
dialogs: [] as { onConfirm: () => void }[],
alerts: [] as {
title: string;
buttons?: { text: string; onPress?: () => void }[];
}[],
afterRequest: undefined as (() => void) | undefined,
}));
vi.mock("react", () => ({
useCallback: (callback: unknown) => callback,
useRef: (current: unknown) => ({ current }),
}));
vi.mock("react-native", () => ({
Alert: {
alert: (title: string, _message: string, buttons?: { text: string; onPress?: () => void }[]) =>
state.alerts.push({ title, buttons }),
},
}));
vi.mock("expo-haptics", () => ({
impactAsync: async () => {},
ImpactFeedbackStyle: { Light: "light" },
}));
vi.mock("../../components/ConfirmDialogHost", () => ({
showConfirmDialog: (dialog: { onConfirm: () => void }) => state.dialogs.push(dialog),
}));
vi.mock("../archive/useArchivedThreadSnapshots", () => ({
refreshArchivedThreadsForEnvironment: () => {},
}));
vi.mock("../../state/session", () => ({
readEnvironmentScope: (environmentId: string, scope: string) =>
state.scopes.get(environmentId)?.has(scope) === true,
}));
vi.mock("../../state/server", () => ({
environmentServerConfigsAtom: "server-configs",
}));
vi.mock("../../state/atom-registry", () => ({
appAtomRegistry: {
set: (_atom: string, value: boolean) => {
state.dropBusy = value;
},
get: (atom: string) =>
atom === "thread-drop-busy"
? state.dropBusy
: atom === "thread-shells"
? state.shells
: atom === "queued-thread-keys"
? new Set<string>()
: new Map(
[...state.scopes.keys()].map((environmentId) => [
environmentId,
{
environment: {
capabilities: {
threadSettlement: true,
threadSnooze: true,
threadPinning: true,
threadPinReorder: true,
threadTitleRegeneration: true,
},
},
},
]),
),
},
}));
vi.mock("../../state/use-atom-command", () => ({
useAtomCommand: (command: unknown) => command,
}));
// Stubbed at the direct dependency: the real outbox pulls the Expo file-system
// storage into a test that only reads which threads are queued.
vi.mock("../../state/use-thread-outbox", () => ({ queuedThreadKeysAtom: "queued-thread-keys" }));
// The real hold lives in a module-level atom that would leak between cases.
vi.mock("../../state/thread-order", () => ({
threadDropBusyAtom: "thread-drop-busy",
getPendingThreadOrder: () => state.pendingOrder,
beginPendingThreadOrder: () => {
state.pendingOrder = {};
return {
isPending: () => state.pendingOrder !== null,
complete: () => {
state.pendingOrder = null;
},
cancel: () => {
state.pendingOrder = null;
},
};
},
}));
vi.mock("../../state/threads", () => ({
environmentThreadShells: { threadShellsAtom: "thread-shells" },
threadEnvironment: Object.fromEntries(
[
"archive",
"unarchive",
"delete",
"settle",
"unsettle",
"snooze",
"unsnooze",
"pin",
"unpin",
"reorderPin",
"updateMetadata",
].map((action) => [
action,
async (request: {
environmentId: string;
input: { threadId: string; orderKey?: string };
}) => {
state.requests.push({ action, ...request });
if (!state.scopes.get(request.environmentId)?.has(AuthOrchestrationOperateScope)) {
return AsyncResult.failure(Cause.fail(new Error("Thread operation denied")));
}
state.afterRequest?.();
return AsyncResult.success(undefined);
},
]),
),
}));
import { useArchivedThreadListActions, useThreadListActions } from "./useThreadListActions";
const primaryEnvironmentId = EnvironmentId.make("primary");
const otherEnvironmentId = EnvironmentId.make("other");
function makeThread(input: Partial<EnvironmentThreadShell> = {}): EnvironmentThreadShell {
return makeThreadShellFixture({
id: ThreadId.make("thread"),
title: "Thread",
environmentId: primaryEnvironmentId,
projectId: ProjectId.make("project"),
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "model" },
...input,
});
}
const mutationCases = [
["archiveThread", "archive"],
["settleThread", "settle"],
["unsettleThread", "unsettle"],
["snoozeThread", "snooze"],
["unsnoozeThread", "unsnooze"],
["pinThread", "pin"],
["unpinThread", "unpin"],
["regenerateThreadTitle", "updateMetadata"],
] as const;
beforeEach(() => {
state.pendingOrder = null;
state.dropBusy = false;
state.scopes = new Map([
[primaryEnvironmentId, new Set([AuthOrchestrationOperateScope])],
[otherEnvironmentId, new Set<string>()],
]);
state.requests = [];
state.shells = [];
state.dialogs = [];
state.alerts = [];
state.afterRequest = undefined;
});
afterEach(() => vi.unstubAllEnvs());
describe("thread list operation permissions", () => {
it.each(mutationCases)(
"%s rejects a retained callback after its environment loses permission",
async (handler) => {
const actions = useThreadListActions();
state.scopes.get(primaryEnvironmentId)!.clear();
await actions[handler](makeThread(), "2099-01-01T00:00:00.000Z");
expect(state.requests).toEqual([]);
},
);
it.each(mutationCases)("%s requires the target environment's permission", async (handler) => {
await useThreadListActions()[handler](
makeThread({ environmentId: otherEnvironmentId }),
"2099-01-01T00:00:00.000Z",
);
expect(state.requests).toEqual([]);
});
it.each(mutationCases)(
"%s works when the target environment gains only task permission",
async (handler, action) => {
state.scopes.get(primaryEnvironmentId)!.clear();
const actions = useThreadListActions();
state.scopes.get(otherEnvironmentId)!.add(AuthOrchestrationOperateScope);
await actions[handler](
makeThread({ environmentId: otherEnvironmentId }),
"2099-01-01T00:00:00.000Z",
);
expect(state.requests).toEqual([
expect.objectContaining({ action, environmentId: otherEnvironmentId }),
]);
},
);
it.each(["ios", "android"])("does not show a forbidden %s delete confirmation", (os) => {
vi.stubEnv("EXPO_OS", os);
useThreadListActions().confirmDeleteThread(makeThread({ environmentId: otherEnvironmentId }));
expect(state.dialogs).toEqual([]);
expect(state.alerts.some((alert) => alert.title === "Delete thread?")).toBe(false);
expect(state.requests).toEqual([]);
});
it.each(["ios", "android"])(
"rechecks permission after a retained %s delete confirmation",
async (os) => {
vi.stubEnv("EXPO_OS", os);
useThreadListActions().confirmDeleteThread(makeThread());
const confirm =
os === "ios"
? state.alerts[0]?.buttons?.find((button) => button.text === "Delete")?.onPress
: state.dialogs[0]?.onConfirm;
expect(confirm).toBeTypeOf("function");
state.scopes.get(primaryEnvironmentId)!.clear();
await confirm!();
expect(state.requests).toEqual([]);
},
);
it("unarchives with only task permission and blocks a later revoked callback", async () => {
const actions = useArchivedThreadListActions(() => {});
const thread = makeThread({ archivedAt: "2026-09-02T00:00:00.000Z" });
await actions.unarchiveThread(thread);
expect(state.requests).toEqual([expect.objectContaining({ action: "unarchive" })]);
state.requests = [];
state.scopes.get(primaryEnvironmentId)!.clear();
await actions.unarchiveThread(thread);
expect(state.requests).toEqual([]);
});
it("keeps delete independent of terminal and source-control permissions", async () => {
vi.stubEnv("EXPO_OS", "android");
useArchivedThreadListActions(() => {}).confirmDeleteThread(makeThread());
await state.dialogs[0]!.onConfirm();
expect(state.requests).toEqual([expect.objectContaining({ action: "delete" })]);
});
});
describe("pinned thread operation permissions", () => {
it("checks every materialization target before writing any keys", async () => {
const moved = makeThread({ pinnedAt: "2026-09-02T00:00:00.000Z" });
state.shells = [
moved,
makeThread({
id: ThreadId.make("other-thread"),
environmentId: otherEnvironmentId,
pinnedAt: "2026-09-02T00:00:00.000Z",
createdAt: "2026-09-02T00:00:00.000Z",
}),
];
expect(await useThreadListActions().moveThread(moved, "up")).toBe(false);
expect(state.requests).toEqual([]);
});
it("moves a keyed thread past a read-only neighbor without writing that neighbor", async () => {
const moved = makeThread({ pinnedAt: "2026-09-02T00:00:00.000Z", pinOrderKey: "m" });
state.shells = [
moved,
makeThread({
id: ThreadId.make("other-thread"),
environmentId: otherEnvironmentId,
pinnedAt: "2026-09-02T00:00:00.000Z",
pinOrderKey: "g",
}),
];
expect(await useThreadListActions().moveThread(moved, "up")).toBe(true);
expect(state.requests).toEqual([
expect.objectContaining({ action: "reorderPin", environmentId: primaryEnvironmentId }),
]);
});
it("rechecks permission between materialization writes", async () => {
const moved = makeThread({ pinnedAt: "2026-09-02T00:00:00.000Z" });
state.shells = [
moved,
makeThread({
id: ThreadId.make("other-thread"),
pinnedAt: "2026-09-02T00:00:00.000Z",
createdAt: "2026-09-02T00:00:00.000Z",
}),
];
state.afterRequest = () => state.scopes.get(primaryEnvironmentId)!.clear();
expect(await useThreadListActions().moveThread(moved, "up")).toBe(false);
expect(state.requests).toHaveLength(1);
});
});
@@ -1,6 +1,7 @@
import type { ThreadMoveDestination } from "../threads/threadOrder";
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
import { canSnooze, effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled";
import { AuthOrchestrationOperateScope } from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as Haptics from "expo-haptics";
import { useCallback, useRef } from "react";
@@ -13,6 +14,7 @@ import { refreshArchivedThreadsForEnvironment } from "../archive/useArchivedThre
import { pinOrderKeyBetween } from "@t3tools/client-runtime/state/thread-sort";
import { appAtomRegistry } from "../../state/atom-registry";
import { environmentServerConfigsAtom } from "../../state/server";
import { readEnvironmentScope } from "../../state/session";
import { environmentThreadShells, threadEnvironment } from "../../state/threads";
import { queuedThreadKeysAtom } from "../../state/use-thread-outbox";
import { useAtomCommand } from "../../state/use-atom-command";
@@ -108,6 +110,12 @@ function actionFailureTitle(action: ThreadListAction): string {
return "Could not delete thread";
}
function checkThreadOperationPermission(thread: EnvironmentThreadShell, title: string): boolean {
if (readEnvironmentScope(thread.environmentId, AuthOrchestrationOperateScope)) return true;
Alert.alert(title, "This connection cannot change threads.");
return false;
}
/** Resolves to true iff the action was dispatched and succeeded. */
function useThreadActionExecutor(
onCompleted?: (action: ThreadListAction, thread: EnvironmentThreadShell) => void,
@@ -121,6 +129,7 @@ function useThreadActionExecutor(
const executeAction = useCallback(
async (action: ThreadListAction, thread: EnvironmentThreadShell) => {
if (!checkThreadOperationPermission(thread, actionFailureTitle(action))) return false;
const key = scopedThreadKey(thread.environmentId, thread.id);
if (inFlightThreadKeys.current.has(key)) {
return false;
@@ -205,6 +214,7 @@ function useConfirmDeleteThread(
) {
return useCallback(
(thread: EnvironmentThreadShell) => {
if (!checkThreadOperationPermission(thread, actionFailureTitle("delete"))) return;
const title = "Delete thread?";
const message = `“${thread.title}” will be permanently deleted, including its terminal history.`;
if (process.env.EXPO_OS === "ios") {
@@ -281,6 +291,7 @@ export function useThreadListActions(): {
);
const snoozeThread = useCallback(
async (thread: EnvironmentThreadShell, snoozedUntil: string) => {
if (!checkThreadOperationPermission(thread, "Could not snooze thread")) return false;
const key = scopedThreadKey(thread.environmentId, thread.id);
if (snoozeInFlightThreadKeys.current.has(key)) {
return false;
@@ -336,6 +347,7 @@ export function useThreadListActions(): {
);
const unsnoozeThread = useCallback(
async (thread: EnvironmentThreadShell) => {
if (!checkThreadOperationPermission(thread, "Could not wake thread")) return false;
const key = scopedThreadKey(thread.environmentId, thread.id);
if (snoozeInFlightThreadKeys.current.has(key)) {
return false;
@@ -383,6 +395,7 @@ export function useThreadListActions(): {
);
const pinThread = useCallback(
async (thread: EnvironmentThreadShell) => {
if (!checkThreadOperationPermission(thread, "Could not pin thread")) return false;
if (!environmentSupportsPinning(thread.environmentId)) {
Alert.alert(
"Could not pin thread",
@@ -423,6 +436,7 @@ export function useThreadListActions(): {
);
const unpinThread = useCallback(
async (thread: EnvironmentThreadShell) => {
if (!checkThreadOperationPermission(thread, "Could not unpin thread")) return false;
if (!environmentSupportsPinning(thread.environmentId)) {
Alert.alert(
"Could not unpin thread",
@@ -479,6 +493,7 @@ export function useThreadListActions(): {
);
const regenerateThreadTitle = useCallback(
async (thread: EnvironmentThreadShell) => {
if (!checkThreadOperationPermission(thread, "Could not regenerate title")) return false;
const key = scopedThreadKey(thread.environmentId, thread.id);
if (
thread.titleRegeneration != null ||
@@ -572,6 +587,7 @@ export function useThreadListActions(): {
});
const moveThread = useCallback(
async (thread: EnvironmentThreadShell, direction: ThreadMoveDestination) => {
if (!checkThreadOperationPermission(thread, "Could not move thread")) return false;
if (getPendingThreadOrder() !== null || appAtomRegistry.get(threadDropBusyAtom)) return false;
const shells = appAtomRegistry.get(environmentThreadShells.threadShellsAtom);
const current = shells.find(
@@ -648,6 +664,11 @@ export function useThreadListActions(): {
const shellByKey = new Map(
shells.map((shell) => [scopedThreadKey(shell.environmentId, shell.id), shell]),
);
for (const assignment of assignments) {
const target = shellByKey.get(assignment.id);
if (target && !checkThreadOperationPermission(target, "Could not move thread"))
return false;
}
selectionHaptic();
appAtomRegistry.set(threadDropBusyAtom, true);
const pending = crossSection
@@ -694,6 +715,7 @@ export function useThreadListActions(): {
if (pending !== null && !pending.isPending()) return false;
const target = shellByKey.get(assignment.id);
if (target === undefined) continue;
if (!checkThreadOperationPermission(target, "Could not move thread")) return false;
const result = await reorder({
environmentId: target.environmentId,
input: { threadId: target.id, orderKey: assignment.orderKey },
@@ -1,6 +1,11 @@
import { useAtomValue } from "@effect/atom-react";
import { useNavigation, type StaticScreenProps } from "@react-navigation/native";
import type { EnvironmentId, ServerProvider } from "@t3tools/contracts";
import {
AuthProvidersManageScope,
AuthOrchestrationReadScope,
type EnvironmentId,
type ServerProvider,
} from "@t3tools/contracts";
import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
import { AsyncResult } from "effect/reactivity";
import { useEffect, useRef, useState } from "react";
@@ -10,8 +15,9 @@ import { useSafeAreaInsets } from "react-native-safe-area-context";
import { AppText as Text } from "../../components/AppText";
import { ProviderIcon } from "../../components/ProviderIcon";
import { ScreenScrollView } from "../../components/ScreenScrollView";
import { appAtomRegistry } from "../../state/atom-registry";
import { serverEnvironment } from "../../state/server";
import { environmentSession } from "../../state/session";
import { environmentSession, useEnvironmentScope, readEnvironmentScope } from "../../state/session";
import { useAtomCommand } from "../../state/use-atom-command";
import { useRemoteConnections } from "../../state/use-remote-environment-registry";
import { ConnectionEnvironmentRow } from "../connection/ConnectionEnvironmentRow";
@@ -75,7 +81,10 @@ function EnvironmentDetail({ environmentId }: { readonly environmentId: Environm
(provider) =>
provider.updateState?.status === "running" || provider.updateState?.status === "queued",
) ?? false;
const disabled = !allowed || pending !== null || running || providerBusy;
const canManageProviders = useEnvironmentScope(environmentId, AuthProvidersManageScope);
const canRead = useEnvironmentScope(environmentId, AuthOrchestrationReadScope);
const busy = !connected || pending !== null || running || providerBusy;
const disabled = !allowed || busy;
const version = config?.environment.serverVersion;
const checkedRelease = release?.fromVersion === version ? release : null;
const capabilities = config?.environment.capabilities;
@@ -111,6 +120,16 @@ function EnvironmentDetail({ environmentId }: { readonly environmentId: Environm
text: "Update",
onPress: () =>
void run("server", async () => {
if (
AsyncResult.isFailure(
appAtomRegistry.get(environmentSession.sessionStateAtom(environmentId)),
) ||
!canMaintainEnvironment(
appAtomRegistry.get(environmentSession.sessionStateValueAtom(environmentId)),
connected,
)
)
return;
const result = await updateServer({
environmentId,
input: {
@@ -131,7 +150,12 @@ function EnvironmentDetail({ environmentId }: { readonly environmentId: Environm
}
function requestProviderUpdate(provider: ServerProvider) {
if (disabled || !canUpdateEnvironmentProvider(provider)) return;
if (
busy ||
!readEnvironmentScope(environmentId, AuthProvidersManageScope) ||
!canUpdateEnvironmentProvider(provider)
)
return;
void run(provider.instanceId, async () => {
const result = await updateProvider({
environmentId,
@@ -274,11 +298,13 @@ function EnvironmentDetail({ environmentId }: { readonly environmentId: Environm
<SettingsActionRow
icon="arrow.clockwise"
label="Refresh providers"
disabled={disabled}
disabled={busy || !canRead}
loading={pending === "refresh"}
onPress={() => {
if (disabled) return;
if (busy || !canRead) return;
void run("refresh", async () => {
if (!readEnvironmentScope(environmentId, AuthOrchestrationReadScope))
return;
const result = await refreshProviders({ environmentId, input: {} });
if (AsyncResult.isFailure(result)) throw squashAtomCommandFailure(result);
setNotice("Provider status refreshed.");
@@ -338,7 +364,7 @@ function EnvironmentDetail({ environmentId }: { readonly environmentId: Environm
<SettingsActionRow
icon="arrow.up.circle"
label={`Update ${provider.displayName ?? provider.driver}`}
disabled={disabled}
disabled={busy || !canManageProviders}
loading={pending === provider.instanceId}
onPress={() => requestProviderUpdate(provider)}
/>
@@ -1,3 +1,5 @@
import { AuthRelayWriteScope } from "@t3tools/contracts";
import { readEnvironmentScope } from "../../state/session";
import { ScreenScrollView as ScrollView } from "../../components/ScreenScrollView";
import { useAuth } from "@clerk/expo";
import { useAtomSet, useAtomValue } from "@effect/atom-react";
@@ -271,6 +273,8 @@ function ConfiguredSettingsNotificationsRouteScreen() {
const updateResult = await settleAsyncResult(() =>
runtime.runPromiseExit(
setLiveActivityUpdatesEnabled({
canConfigureEnvironment: (environmentId) =>
readEnvironmentScope(environmentId, AuthRelayWriteScope),
enabled: true,
previousEnabled: liveActivitiesPreferenceEnabled,
clerkToken: tokenResult.value,
@@ -302,7 +306,7 @@ function ConfiguredSettingsNotificationsRouteScreen() {
Alert.alert(
Platform.OS === "android" ? "Ongoing activity enabled" : "Live Activities enabled",
environmentCount > 0
? `${environmentCount} environment${environmentCount === 1 ? "" : "s"} linked for agent activity updates.`
? "Agent activity updates are enabled for environments this connection can configure."
: "Agent activity updates are enabled. Add an environment to start receiving updates.",
);
} else {
@@ -370,6 +374,8 @@ function ConfiguredSettingsNotificationsRouteScreen() {
const updateResult = await settleAsyncResult(() =>
runtime.runPromiseExit(
setLiveActivityUpdatesEnabled({
canConfigureEnvironment: (environmentId) =>
readEnvironmentScope(environmentId, AuthRelayWriteScope),
enabled: false,
previousEnabled: liveActivitiesPreferenceEnabled,
clerkToken: token,
@@ -1,6 +1,65 @@
import { EnvironmentId } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import { resolveAgentAwarenessPlatformPresentation } from "./SettingsRouteScreen.logic";
import {
resolveAgentAwarenessPlatformPresentation,
resolveAutoSettleReferenceEnvironmentId,
} from "./SettingsRouteScreen.logic";
describe("resolveAutoSettleReferenceEnvironmentId", () => {
const firstId = EnvironmentId.make("first");
const secondId = EnvironmentId.make("second");
it("waits for an earlier grant before exposing a later writable reference", () => {
const second = { environmentId: secondId, canWriteSettings: true };
expect(
resolveAutoSettleReferenceEnvironmentId([
{ environmentId: firstId, canWriteSettings: null },
second,
]),
).toBeNull();
expect(
resolveAutoSettleReferenceEnvironmentId([
{ environmentId: firstId, canWriteSettings: false },
second,
]),
).toBe(secondId);
expect(
resolveAutoSettleReferenceEnvironmentId([
{ environmentId: firstId, canWriteSettings: true },
second,
]),
).toBe(firstId);
});
it("does not wait for later grants after finding the first writable reference", () => {
expect(
resolveAutoSettleReferenceEnvironmentId([
{ environmentId: firstId, canWriteSettings: true },
{ environmentId: secondId, canWriteSettings: null },
]),
).toBe(firstId);
});
it("waits before showing a read-only fallback until all grants are resolved", () => {
expect(
resolveAutoSettleReferenceEnvironmentId([
{ environmentId: firstId, canWriteSettings: false },
{ environmentId: secondId, canWriteSettings: null },
]),
).toBeNull();
expect(
resolveAutoSettleReferenceEnvironmentId([
{ environmentId: firstId, canWriteSettings: false },
{ environmentId: secondId, canWriteSettings: false },
]),
).toBe(firstId);
});
it("has no reference when no environment supports synchronization", () => {
expect(resolveAutoSettleReferenceEnvironmentId([])).toBeNull();
});
});
describe("resolveAgentAwarenessPlatformPresentation", () => {
it("supports agent awareness settings on Android", () => {
@@ -1,3 +1,19 @@
import type { EnvironmentId } from "@t3tools/contracts";
/** Wait for earlier grants before choosing the settings that edits and synchronization use. */
export function resolveAutoSettleReferenceEnvironmentId(
environments: ReadonlyArray<{
readonly environmentId: EnvironmentId;
readonly canWriteSettings: boolean | null;
}>,
): EnvironmentId | null {
for (const environment of environments) {
if (environment.canWriteSettings === null) return null;
if (environment.canWriteSettings) return environment.environmentId;
}
return environments[0]?.environmentId ?? null;
}
export function resolveAgentAwarenessPlatformPresentation(platform: string): {
readonly supported: boolean;
readonly subtitle: string | undefined;
@@ -1,3 +1,6 @@
import { useAtomValue } from "@effect/atom-react";
import { AuthOrchestrationOperateScope } from "@t3tools/contracts";
import { readEnvironmentScope } from "../../state/session";
import type {
EnvironmentId,
ProjectId,
@@ -580,6 +583,9 @@ function TaskForm({
const projects = useProjects().filter((project) => project.environmentId === environmentId);
const config = useEnvironmentServerConfig(environmentId);
const modelOptions = useMemo(() => buildModelOptions(config, null), [config]);
const canOperate = useAtomValue(
serverEnvironment.upsertScheduledTask.permissionAtom(environmentId),
);
const upsert = useAtomCommand(serverEnvironment.upsertScheduledTask, {
label: "scheduled task upsert",
reportFailure: false,
@@ -602,6 +608,7 @@ function TaskForm({
const save = async () => {
if (
!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope) ||
submissionPending.current ||
saving ||
dictationPending ||
@@ -937,7 +944,7 @@ function TaskForm({
: draft.task
}
signatureConfigured={draft.schedule.signature !== null}
disabled={saving || environmentUnavailable}
disabled={!canOperate || saving || environmentUnavailable}
/>
<FormField
label="Skip requests older than (minutes)"
@@ -994,7 +1001,9 @@ function TaskForm({
accessibilityState={{
disabled: saving || dictationPending || taskMissing || environmentUnavailable,
}}
disabled={saving || dictationPending || taskMissing || environmentUnavailable}
disabled={
!canOperate || saving || dictationPending || taskMissing || environmentUnavailable
}
onPress={() => void save()}
className="min-h-12 items-center justify-center rounded-[14px] bg-primary px-4 disabled:opacity-50"
>
@@ -1118,6 +1127,9 @@ function EnvironmentTasks({
const visibleTasks = tasks.data?.tasks.filter(
(task) => projectIds === null || projectIds.includes(task.projectId),
);
const canOperate = useAtomValue(
serverEnvironment.upsertScheduledTask.permissionAtom(environmentId),
);
const setEnabled = useAtomCommand(serverEnvironment.setScheduledTaskEnabled, {
label: "scheduled task enabled",
reportFailure: false,
@@ -1137,6 +1149,7 @@ function EnvironmentTasks({
};
const act = async (task: ScheduledTask, action: "run" | "toggle" | "delete") => {
if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) return;
const result =
action === "run"
? await runNow({ environmentId, input: { id: task.id } })
@@ -1205,10 +1218,19 @@ function EnvironmentTasks({
<ControlPillMenu
actions={[
{ id: "edit", title: "Edit" },
{ id: "toggle", title: task.enabled ? "Pause" : "Resume" },
// A webhook task has no request to run without.
...(task.schedule.type === "webhook" ? [] : [{ id: "run", title: "Run now" }]),
{ id: "delete", title: "Delete", attributes: { destructive: true } },
{
id: "toggle",
title: task.enabled ? "Pause" : "Resume",
attributes: { disabled: !canOperate },
},
...(task.schedule.type === "webhook"
? []
: [{ id: "run", title: "Run now", attributes: { disabled: !canOperate } }]),
{
id: "delete",
title: "Delete",
attributes: { destructive: true, disabled: !canOperate },
},
]}
onPressAction={({ nativeEvent }) => {
const action = nativeEvent.event;
@@ -1,5 +1,7 @@
import { useNavigation } from "@react-navigation/native";
import { SettingsRow } from "./components/SettingsRow";
import { AuthSettingsWriteScope } from "@t3tools/contracts";
import { readEnvironmentScope, useEnvironmentsWithScope } from "../../state/session";
import { ScreenScrollView as ScrollView } from "../../components/ScreenScrollView";
import { AppText as Text } from "../../components/AppText";
import {
@@ -141,6 +143,7 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) {
const navigation = useNavigation();
const { selectedTargets, projectGroups, selectedProjectKey } = useSettingsEnvironmentFilter();
const selectedProject = projectGroups.find((group) => group.key === selectedProjectKey);
const writableEnvironments = useEnvironmentsWithScope(selectedTargets, AuthSettingsWriteScope);
const projectSelected = selectedProjectKey !== null;
const targets = resolveMobileSettingsTargets(
selectedTargets,
@@ -151,6 +154,9 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) {
const [pendingTargets, setPendingTargets] = useState<
readonly ScopedMobileSettingsTarget[] | null
>(null);
const canWriteSettings =
targets.length > 0 &&
targets.every((target) => writableEnvironments.has(target.environment.environmentId));
const displayTargets = pendingWrites > 0 && pendingTargets !== null ? pendingTargets : targets;
const hasConnectedSelection = targets.length > 0;
const reference = displayTargets[0] ?? null;
@@ -165,7 +171,14 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) {
reportFailure: true,
});
const write = (patch: ServerSettingsPatch) => {
if (writeInFlight.current || !hasConnectedSelection) return;
if (
writeInFlight.current ||
!hasConnectedSelection ||
!targets.every((target) =>
readEnvironmentScope(target.environment.environmentId, AuthSettingsWriteScope),
)
)
return;
const writes = planMobileScopedSettingsPatch(targets, projectSelected, patch);
if (writes.length === 0) return;
writeInFlight.current = true;
@@ -182,7 +195,13 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) {
});
};
const clearProjectOverrides = () => {
if (writeInFlight.current) return;
if (
writeInFlight.current ||
!targets.every((target) =>
readEnvironmentScope(target.environment.environmentId, AuthSettingsWriteScope),
)
)
return;
const writes = planMobileScopedSettingsClear(targets, PAGE_PROJECT_KEYS[props.page]);
if (writes.length === 0) return;
writeInFlight.current = true;
@@ -203,7 +222,10 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) {
target.environment.serverConfig.environment.capabilities.projectSettingsOverrides === true,
);
const disabled =
pendingWrites > 0 || !hasConnectedSelection || (projectSelected && !supportsProjectOverrides);
!canWriteSettings ||
pendingWrites > 0 ||
!hasConnectedSelection ||
(projectSelected && !supportsProjectOverrides);
const supportsContinuation = targets.every(
(target) =>
target.environment.serverConfig.environment.capabilities.threadRestartContinuation === true,
@@ -245,6 +267,7 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) {
)}
supportsOverrides={supportsProjectOverrides}
pending={pendingWrites > 0}
disabled={!canWriteSettings}
onClear={clearProjectOverrides}
/>
) : null}
@@ -1,3 +1,5 @@
import { AuthSettingsWriteScope } from "@t3tools/contracts";
import { readEnvironmentScope, useEnvironmentsWithScope } from "../../state/session";
import { AutoSettleDaysField } from "./components/AutoSettleDaysField";
import { ScreenScrollView as ScrollView } from "../../components/ScreenScrollView";
import { useAtomSet, useAtomValue } from "@effect/atom-react";
@@ -61,6 +63,7 @@ const AUTO_SETTLE_DEFAULT_DAYS = DEFAULT_SERVER_SETTINGS.sidebarAutoSettleAfterD
function AutoSettleSettingsRows() {
const { selectedTargets, projectGroups, selectedProjectKey } = useSettingsEnvironmentFilter();
const selectedProject = projectGroups.find((group) => group.key === selectedProjectKey);
const writableEnvironments = useEnvironmentsWithScope(selectedTargets, AuthSettingsWriteScope);
const projectSelected = selectedProjectKey !== null;
const [pendingWrites, setPendingWrites] = useState(0);
const writeInFlight = useRef(false);
@@ -77,6 +80,9 @@ function AutoSettleSettingsRows() {
syncEnvironments,
projectSelected ? (selectedProject?.members.map((member) => member.project) ?? []) : null,
);
const canWriteSettings =
syncTargets.length > 0 &&
syncTargets.every((target) => writableEnvironments.has(target.environment.environmentId));
const displayTargets =
pendingWrites > 0 && pendingTargets !== null ? pendingTargets : syncTargets;
const reference = displayTargets[0] ?? null;
@@ -92,7 +98,13 @@ function AutoSettleSettingsRows() {
snoozeLimitedThreads?: boolean;
},
) => {
if (writeInFlight.current) return;
if (
writeInFlight.current ||
!syncTargets.every((target) =>
readEnvironmentScope(target.environment.environmentId, AuthSettingsWriteScope),
)
)
return;
const writes = planMobileScopedSettingsPatch(syncTargets, projectSelected, patch);
if (writes.length === 0) return;
writeInFlight.current = true;
@@ -127,7 +139,8 @@ function AutoSettleSettingsRows() {
(target) =>
target.environment.serverConfig.environment.capabilities.projectSettingsOverrides === true,
);
const disabled = pendingWrites > 0 || (projectSelected && !supportsProjectOverrides);
const disabled =
!canWriteSettings || pendingWrites > 0 || (projectSelected && !supportsProjectOverrides);
const hasProjectOverrides =
projectSelected &&
syncTargets.some(
@@ -136,7 +149,13 @@ function AutoSettleSettingsRows() {
target.sources.sidebarAutoSettleAfterDays === "project",
);
const clearProjectOverrides = () => {
if (writeInFlight.current) return;
if (
writeInFlight.current ||
!syncTargets.every((target) =>
readEnvironmentScope(target.environment.environmentId, AuthSettingsWriteScope),
)
)
return;
const writes = planMobileScopedSettingsClear(syncTargets, [
"sidebarAutoSettleOnMerge",
"sidebarAutoSettleAfterDays",
@@ -166,6 +185,7 @@ function AutoSettleSettingsRows() {
hasOverrides={hasProjectOverrides}
supportsOverrides={supportsProjectOverrides}
pending={pendingWrites > 0}
disabled={!canWriteSettings}
onClear={clearProjectOverrides}
/>
) : null}
@@ -8,6 +8,7 @@ export function SettingsProjectOverridesSection(props: {
readonly hasOverrides: boolean;
readonly supportsOverrides: boolean;
readonly pending: boolean;
readonly disabled?: boolean;
readonly onClear: () => void;
}) {
return (
@@ -20,6 +21,7 @@ export function SettingsProjectOverridesSection(props: {
<Pressable
accessibilityRole="button"
accessibilityLabel="Use environment defaults"
disabled={props.disabled}
onPress={props.onClear}
className="px-2 py-2 active:opacity-70"
>
@@ -53,6 +53,29 @@ describe("environment maintenance access", () => {
expect(canMaintainEnvironment(null, true)).toBe(false);
});
it.each([
{ scopes: ["environment:maintain"], expected: true },
{ scopes: ["orchestration:operate"], expected: false },
{ scopes: ["providers:manage"], expected: false },
] as const)("uses the advertised update permission for $scopes", ({ scopes, expected }) => {
expect(
canMaintainEnvironment(
{
authenticated: true,
auth: {
policy: "remote-reachable",
bootstrapMethods: [],
sessionMethods: [],
sessionCookieName: "session",
serverUpdateScope: "environment:maintain",
},
scopes,
},
true,
),
).toBe(expected);
});
it("requires remote desktop update support for desktop hosts", () => {
expect(supportsEnvironmentUpdate({})).toBe(false);
expect(supportsEnvironmentUpdate({ serverSelfUpdate: "respawn" })).toBe(true);
@@ -16,7 +16,8 @@ export function canMaintainEnvironment(session: AuthSessionState | null, connect
return (
connected &&
session?.authenticated === true &&
session.scopes?.includes(AuthOrchestrationOperateScope) === true
session.scopes?.includes(session.auth.serverUpdateScope ?? AuthOrchestrationOperateScope) ===
true
);
}
@@ -28,6 +28,7 @@ import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useUniwindTheme } from "../../lib/useUniwindTheme";
import { useFontFamily } from "../../lib/useFontFamily";
import {
AuthOrchestrationOperateScope,
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
PROVIDER_SEND_TURN_MAX_INPUT_CHARS,
resolveEnvironmentMachineKind,
@@ -133,6 +134,7 @@ import { selectIncomingShareAttachmentsForServer } from "../sharing/incoming-sha
import { appAtomRegistry } from "../../state/atom-registry";
import { serverEnvironment } from "../../state/server";
import { fileRoutePathSegments } from "../files/filePath";
import { readEnvironmentScope, useEnvironmentScope } from "../../state/session";
function NewTaskWorkspaceIcon(props: {
readonly workspaceMode: "local" | "worktree";
@@ -219,6 +221,12 @@ export function NewTaskDraftScreen(props: {
connectedEnvironments.find(
(environment) => environment.environmentId === selectedProject.environmentId,
)?.connectionState === "connected";
const canOperate = useEnvironmentScope(
selectedProject?.environmentId ?? null,
AuthOrchestrationOperateScope,
);
const taskPermissionReason =
environmentConnected && !canOperate ? "This connection cannot start tasks." : null;
const modelUnavailable = environmentConnected && flow.selectedModelOption?.isUnavailable === true;
// A project added by cloning exists before its files do: the prompt can be
// written meanwhile, but Start waits for the clone.
@@ -1214,6 +1222,12 @@ export function NewTaskDraftScreen(props: {
if (!selectedProject || !draftKey) {
return;
}
if (
environmentConnected &&
!readEnvironmentScope(selectedProject.environmentId, AuthOrchestrationOperateScope)
) {
return;
}
const draft = getComposerDraftSnapshot(draftKey);
if (appAtomRegistry.get(composerContextImportsAtom)[draftKey]) return;
// Read the latest explicit pick. Antigravity selections stay unchanged
@@ -1378,6 +1392,7 @@ export function NewTaskDraftScreen(props: {
const canStart =
!isImportingContext &&
!cloneBlocksStart &&
taskPermissionReason === null &&
attachmentBlockReason === null &&
!modelUnavailable &&
Boolean(flow.selectedProject) &&
@@ -1655,6 +1670,10 @@ export function NewTaskDraftScreen(props: {
) : null}
{flow.canChooseWorkspace ? <View className="pb-1">{workspaceControls}</View> : null}
{taskPermissionReason ? (
<Text className="px-3 py-2 text-xs text-muted-foreground">{taskPermissionReason}</Text>
) : null}
{modelUnavailable ? (
<Pressable
accessibilityRole="button"
@@ -1794,6 +1813,7 @@ export function NewTaskDraftScreen(props: {
{voicePresentation.showsSend ? (
<ComposerActionButton
accessibilityLabel={
taskPermissionReason ??
attachmentBlockReason ??
(cloneBlocksStart
? projectClone === null || projectClone.phase === "running"
@@ -10,6 +10,7 @@ import { AppText as Text } from "../../components/AppText";
import type { PendingApproval } from "../../lib/threadActivity";
export interface PendingApprovalCardProps {
readonly canOperateThread: boolean;
readonly approval: PendingApproval;
readonly respondingApprovalId: RuntimeRequestId | null;
readonly onRespond: (
@@ -66,11 +67,16 @@ export function PendingApprovalCard(props: PendingApprovalCardProps) {
? "danger"
: "secondary"
}
disabled={disabled}
disabled={disabled || !props.canOperateThread}
onPress={() => void props.onRespond(props.approval.requestId, option.decision)}
/>
))}
</View>
{!props.canOperateThread ? (
<Text className="font-sans text-xs text-adaptive-neutral-500-400">
This connection cannot respond to approvals.
</Text>
) : null}
</View>
);
}
@@ -28,6 +28,7 @@ import {
} from "../../lib/threadActivity";
export interface PendingUserInputCardProps {
readonly canOperateThread: boolean;
readonly pendingUserInput: PendingUserInput;
/**
* Constant while a request is pending (it reserves keyboard space), so the
@@ -200,6 +201,7 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {
icon="stop.fill"
variant="danger"
className="h-9 w-9"
disabled={!props.canOperateThread}
onPress={props.onStopThread}
/>
) : null}
@@ -342,7 +344,7 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {
label="Submit answers"
size="large"
tone={props.answers ? "primary" : "secondary"}
disabled={responseDisabled || props.answers === null}
disabled={!props.canOperateThread || responseDisabled || props.answers === null}
onPress={() => void props.onSubmit()}
/>
{props.pendingUserInput.dismissible ? (
@@ -357,6 +359,11 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {
</Text>
</Pressable>
) : null}
{!props.canOperateThread ? (
<Text className="font-sans text-xs text-foreground-tertiary">
This connection cannot submit answers.
</Text>
) : null}
</Animated.View>
) : null;
return (
@@ -140,6 +140,7 @@ export const COMPOSER_COLLAPSED_CHROME = 60;
export const COMPOSER_EXPANDED_CHROME = 156;
export interface ThreadComposerProps {
readonly canOperateThread: boolean;
readonly draftMessage: string;
readonly draftAttachments: ReadonlyArray<DraftComposerAttachment>;
readonly placeholder: string;
@@ -539,6 +540,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
(pendingPastedTextAttachmentCount > 0 ? "Attaching pasted text" : null) ??
attachmentBlockReason;
const canSend =
(props.canOperateThread || props.connectionState !== "connected") &&
hasContent &&
!contextImports[composerDraftKey] &&
!voiceInput.blocksSubmission &&
@@ -1056,6 +1058,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
accessibilityLabel="Stop agent"
icon="stop.fill"
variant="danger"
disabled={!props.canOperateThread}
onPress={props.onStopThread}
/>
) : (
@@ -1150,6 +1153,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
accessibilityLabel="Stop agent"
icon="stop.fill"
variant="danger"
disabled={!props.canOperateThread}
onPress={props.onStopThread}
/>
) : voicePresentation.showsSend ? (
@@ -1165,6 +1169,12 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
</ComposerDictationToolbar>
</Animated.View>
</ComposerSurface>
{props.connectionState === "connected" && !props.canOperateThread ? (
<Text className="pt-2 text-xs text-foreground-muted">
This connection cannot control this task. You can still edit your draft.
</Text>
) : null}
</Animated.View>
<VideoPreviewModal source={previewVideo} onRequestClose={closePreview} />
@@ -148,6 +148,7 @@ import { useGlobalVoiceInput } from "../voice-input/VoiceInputProvider";
export interface ThreadDetailScreenProps {
readonly worktreeSetup?: WorktreeSetupCardProps | null;
readonly setupWorkingStartedAt?: string | null;
readonly canOperateThread: boolean;
readonly selectedThread: EnvironmentThreadShell;
readonly contentPresentation: ThreadContentPresentation;
readonly screenTone: StatusTone;
@@ -1297,6 +1298,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
>
{props.activePendingApproval ? (
<PendingApprovalCard
canOperateThread={props.canOperateThread}
approval={props.activePendingApproval}
respondingApprovalId={props.respondingApprovalId}
onRespond={props.onRespondToApproval}
@@ -1304,6 +1306,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
) : null}
{props.activePendingUserInput ? (
<PendingUserInputCard
canOperateThread={props.canOperateThread}
pendingUserInput={props.activePendingUserInput}
maxHeight={pendingUserInputMaxHeight}
collapsed={userInputCollapsed}
@@ -1371,6 +1374,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
) : (
<>
<ThreadComposer
canOperateThread={props.canOperateThread}
reportedModelSelection={reportedModelSelection}
editorRef={composerEditorRef}
draftMessage={props.draftMessage}
@@ -15,11 +15,13 @@ import {
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import * as Option from "effect/Option";
import {
AuthOrchestrationOperateScope,
DEFAULT_SERVER_SETTINGS,
EnvironmentId,
ThreadId,
type ProjectScript,
} from "@t3tools/contracts";
import { readEnvironmentScope, useEnvironmentScope } from "../../state/session";
import {
projectScriptCwd,
projectScriptRuntimeEnv,
@@ -333,6 +335,10 @@ function ThreadRouteContent(
selectedThreadProject,
selectedEnvironmentConnection,
} = useThreadSelection();
const canOperateThread = useEnvironmentScope(
selectedThread?.environmentId ?? null,
AuthOrchestrationOperateScope,
);
const selectedThreadDetailState = props.selectedThreadDetailState;
const selectedThreadDetail = Option.getOrNull(selectedThreadDetailState.data);
const { selectedThreadCwd } = useSelectedThreadWorktree();
@@ -673,7 +679,11 @@ function ThreadRouteContent(
void navigation.navigate("Connections");
}, [navigation]);
const handleStopThread = useCallback(() => {
if (!selectedThread || composer.interruptibleRunId === null) {
if (
!selectedThread ||
!readEnvironmentScope(selectedThread.environmentId, AuthOrchestrationOperateScope) ||
composer.interruptibleRunId === null
) {
return;
}
return interruptThreadTurn({
@@ -988,6 +998,7 @@ function ThreadRouteContent(
<View className="flex-1 bg-screen android:overflow-hidden android:rounded-t-[28px] android:bg-thread-canvas">
<ThreadDetailScreen
canOperateThread={canOperateThread}
selectedThread={selectedThreadWithDraftSettings ?? selectedThread}
contentPresentation={contentPresentation}
screenTone={connectionTone(routeConnectionState)}
@@ -17,7 +17,7 @@ import type {
EnvironmentThreadShell,
} from "@t3tools/client-runtime/state/shell";
import type { EnvironmentThreadSearchMatch } from "@t3tools/client-runtime/state/thread-search";
import type { EnvironmentMachineKind } from "@t3tools/contracts";
import { AuthOrchestrationOperateScope, type EnvironmentMachineKind } from "@t3tools/contracts";
import { canSnooze, resolveSnoozePresets } from "@t3tools/client-runtime/state/thread-settled";
import type { MenuAction } from "@react-native-menu/menu";
import { memo, useCallback, useEffect, useMemo, useState, type ComponentProps } from "react";
@@ -34,6 +34,7 @@ import { ProviderIcon, ProviderInstanceIcon } from "../../components/ProviderIco
import { cn } from "../../lib/cn";
import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
import { useUniwindTheme } from "../../lib/useUniwindTheme";
import { useEnvironmentScope } from "../../state/session";
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
import { useThreadPr } from "../../state/use-thread-pr";
import { useSwipeRowDormant } from "../home/swipe-row-activation";
@@ -600,6 +601,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
const handleDelete = useCallback(() => onDeleteThread(thread), [onDeleteThread, thread]);
const handleRename = useCallback(() => onRenameThread(thread), [onRenameThread, thread]);
const canOperateThread = useEnvironmentScope(thread.environmentId, AuthOrchestrationOperateScope);
const handleRegenerateTitle = useCallback(
() => onRegenerateThreadTitle(thread),
[onRegenerateThreadTitle, thread],
@@ -917,8 +919,9 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
: null,
[handleMenuAction, snoozePresetActions, swipeActions.secondary, thread.title],
);
const swipeAccessibilityHint =
secondaryAction === null
const swipeAccessibilityHint = !canOperateThread
? "Opens the thread"
: secondaryAction === null
? `Opens the thread. Swipe left to ${primaryAction.label.toLowerCase()}.`
: `Opens the thread. Swipe left for ${primaryAction.label.toLowerCase()} and snooze actions.`;
@@ -1224,6 +1227,8 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
</RowPressable>
);
if (!canOperateThread) return rowContent(() => {});
return (
<View collapsable={false}>
{customSnoozeOpen && (
@@ -9,6 +9,10 @@ const state = vi.hoisted(() => ({
autoRefresh: async () => {},
refreshingRef: { current: false },
}));
vi.mock("../../state/session", () => ({
useEnvironmentScope: () => true,
readEnvironmentScope: () => true,
}));
vi.mock("react", () => ({
useState: (initial: unknown) => {
const index = state.cursor++;
@@ -1,12 +1,13 @@
import { useAtomValue } from "@effect/atom-react";
import type {
EnvironmentId,
ProviderConsumeResetCreditOutcome,
ProviderConsumeResetCreditInput,
ServerProvider,
ServerProviderResetCredits,
ServerProviderUsageWindow,
UsageProviderKind,
import {
AuthProvidersManageScope,
type EnvironmentId,
type ProviderConsumeResetCreditOutcome,
type ProviderConsumeResetCreditInput,
type ServerProvider,
type ServerProviderResetCredits,
type ServerProviderUsageWindow,
type UsageProviderKind,
} from "@t3tools/contracts";
import {
elapsedShare,
@@ -24,6 +25,7 @@ import { AppText as Text } from "../../components/AppText";
import { ProviderIcon } from "../../components/ProviderIcon";
import { environmentPresentations } from "../../state/presentation";
import { serverEnvironment } from "../../state/server";
import { readEnvironmentScope, useEnvironmentScope } from "../../state/session";
import { useAtomCommand } from "../../state/use-atom-command";
import { useProviderColors } from "./usageProviders";
@@ -207,6 +209,7 @@ export function ResetCredits(props: {
readonly dense?: boolean;
}) {
const { environmentId, input, credits, now, dense = false } = props;
const canManageProviders = useEnvironmentScope(environmentId, AuthProvidersManageScope);
const consume = useAtomCommand(serverEnvironment.consumeResetCredit, {
reportFailure: false,
});
@@ -225,6 +228,7 @@ export function ResetCredits(props: {
}`;
const redeem = async () => {
if (!readEnvironmentScope(environmentId, AuthProvidersManageScope)) return;
setBusy(true);
setStatus(null);
const result = await consume({ environmentId, input });
@@ -241,6 +245,7 @@ export function ResetCredits(props: {
};
const confirm = () => {
if (!readEnvironmentScope(environmentId, AuthProvidersManageScope)) return;
Alert.alert(
"Use a reset credit?",
"This redeems one credit on your account and clears the current rate-limit windows. It cannot be undone.",
@@ -257,13 +262,13 @@ export function ResetCredits(props: {
{credits.availableCount > 0 ? (
<Pressable
accessibilityRole="button"
accessibilityState={{ disabled: busy }}
disabled={busy}
accessibilityState={{ disabled: busy || !canManageProviders }}
disabled={busy || !canManageProviders}
onPress={confirm}
className={
dense
? "rounded-full bg-subtle-strong px-2.5 py-1"
: "min-h-[44px] justify-center rounded-full bg-subtle-strong px-3 py-1.5"
? "rounded-full bg-subtle-strong px-2.5 py-1 disabled:opacity-[0.45]"
: "min-h-[44px] justify-center rounded-full bg-subtle-strong px-3 py-1.5 disabled:opacity-[0.45]"
}
>
<Text
@@ -277,6 +282,11 @@ export function ResetCredits(props: {
</Text>
</Pressable>
) : null}
{!canManageProviders ? (
<Text className="text-xs text-foreground-tertiary">
This connection cannot manage provider accounts.
</Text>
) : null}
{status ? <Text className="text-sm text-foreground">{status}</Text> : null}
</View>
);
@@ -3,6 +3,7 @@ import * as Option from "effect/Option";
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
const mocks = vi.hoisted(() => ({
canOperate: true,
documentUri: "file:///documents",
createAssetUrl: vi.fn(),
createUploadUrl: Symbol("create-upload-url"),
@@ -48,6 +49,7 @@ vi.mock("../state/attachments", () => ({
}));
vi.mock("../state/session", () => ({
readEnvironmentScope: () => mocks.canOperate,
environmentSession: {
preparedConnectionValueAtom: () => mocks.preparedConnection,
},
@@ -194,6 +196,7 @@ function removeCallsFor(attachmentId: string): number {
describe("prepareTurnAttachments", () => {
beforeEach(() => {
mocks.canOperate = true;
mocks.documentUri = "file:///documents";
mocks.createAssetUrl.mockReset();
mocks.createAssetUrl.mockImplementation((target: unknown) => target);
@@ -222,6 +225,80 @@ describe("prepareTurnAttachments", () => {
mocks.upload.mockResolvedValue({ status: 204, body: "", headers: {} });
});
it("does not mint or transfer attachments without task operation access", async () => {
mocks.canOperate = false;
await expect(
prepareTurnAttachments({
environmentId,
attachments: [fileBackedImage],
supportsImageUploads: true,
}),
).rejects.toThrow("cannot upload attachments");
expect(mocks.runAtomCommand).not.toHaveBeenCalled();
expect(mocks.upload).not.toHaveBeenCalled();
});
it("rechecks access after a signed URL is minted before sending any bytes", async () => {
mocks.runAtomCommand.mockImplementationOnce(async () => {
mocks.canOperate = false;
return {
_tag: "Success",
value: {
attachmentId: MINTED_ID,
relativeUrl: "/api/attachments/upload/signed",
expiresAt: 1,
},
};
});
const warning = vi.spyOn(console, "warn").mockImplementation(() => {});
try {
await expect(
prepareTurnAttachments({
environmentId,
attachments: [fileBackedImage],
supportsImageUploads: true,
}),
).rejects.toThrow("cannot upload attachments");
expect(mocks.upload).not.toHaveBeenCalled();
expect(mocks.runAtomCommand).toHaveBeenCalledTimes(1);
} finally {
warning.mockRestore();
}
});
it("does not replace an expired upload when access was revoked during verification", async () => {
mocks.executeAtomQuery.mockImplementationOnce(async () => {
mocks.canOperate = false;
return { _tag: "Failure", error: { _tag: "AssetAttachmentNotFoundError" } };
});
await expect(
prepareTurnAttachments({
environmentId,
attachments: [
{
...fileBackedImage,
uploadedAttachmentId: MINTED_ID,
uploadEnvironmentId: environmentId,
},
],
supportsImageUploads: true,
}),
).rejects.toThrow("cannot upload attachments");
expect(mocks.runAtomCommand).not.toHaveBeenCalled();
expect(mocks.upload).not.toHaveBeenCalled();
});
it("rechecks deletion permission before retrying a failed cleanup", async () => {
mocks.runAtomCommand.mockImplementationOnce(async () => {
mocks.canOperate = false;
return { _tag: "Failure", error: new Error("Retry cleanup") };
});
await expect(releasePendingAttachmentUploads(environmentId, [MINTED_ID])).rejects.toThrow(
"cannot delete pending attachments",
);
expect(mocks.runAtomCommand).toHaveBeenCalledTimes(1);
});
it("keeps existing image attachments on the legacy wire path", async () => {
const prepared = await prepareTurnAttachments({ environmentId, attachments: [image] });
+23 -2
View File
@@ -13,13 +13,16 @@ import type {
EnvironmentId,
UploadChatImageAttachment,
} from "@t3tools/contracts";
import { PROVIDER_SEND_TURN_SUPPORTED_IMAGE_MIME_TYPES } from "@t3tools/contracts";
import {
AuthOrchestrationOperateScope,
PROVIDER_SEND_TURN_SUPPORTED_IMAGE_MIME_TYPES,
} from "@t3tools/contracts";
import * as Option from "effect/Option";
import { appAtomRegistry } from "../state/atom-registry";
import { assetEnvironment } from "../state/assets";
import { attachmentEnvironment } from "../state/attachments";
import { environmentSession } from "../state/session";
import { environmentSession, readEnvironmentScope } from "../state/session";
import { resolveOwnedComposerAttachmentFileUri } from "./composerAttachmentFiles";
import { retainComposerAttachmentFileForPreview } from "./composerAttachmentPreviewRetention";
import {
@@ -109,6 +112,9 @@ export async function releasePendingAttachmentUploads(
attachmentIds: ReadonlyArray<string>,
): Promise<void> {
const deleteOnce = async (attachmentId: string): Promise<boolean> => {
if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) {
throw new Error("This connection cannot delete pending attachments.");
}
const result = await runAtomCommand(
appAtomRegistry,
attachmentEnvironment.remove,
@@ -255,6 +261,7 @@ async function composerImageAttachmentDataUrl(
}
async function uploadFileBytes(
environmentId: EnvironmentId,
attachment: DraftComposerAttachment,
url: string,
signal: AbortSignal,
@@ -262,6 +269,9 @@ async function uploadFileBytes(
): Promise<void> {
const { File, Paths, UploadType } = await import("expo-file-system");
if (signal.aborted) throw new Error("Upload cancelled.");
if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) {
throw new Error("This connection cannot upload attachments.");
}
// Legacy image drafts persisted inline bytes and stage them in a temp cache
// file for the native uploader. Everything else uploads its owned copy.
const fileUri = attachment.fileUri;
@@ -349,6 +359,13 @@ export async function prepareTurnAttachments(input: {
}
}
const requireUploadAccess = () => {
if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) {
throw new Error("This connection cannot upload attachments.");
}
};
requireUploadAccess();
const connection = appAtomRegistry.get(
environmentSession.preparedConnectionValueAtom(environmentId),
);
@@ -365,6 +382,7 @@ export async function prepareTurnAttachments(input: {
try {
for (const attachment of input.attachments) {
if (controller.signal.aborted) throw new Error("Upload cancelled.");
requireUploadAccess();
if (attachment.type === "image" && !input.supportsImageUploads) {
uploadedAttachments.push(...(await toUploadChatImageAttachments([attachment])));
continue;
@@ -393,6 +411,7 @@ export async function prepareTurnAttachments(input: {
// "missing": the pending upload expired, upload the bytes again.
}
requireUploadAccess();
const result = await runAttachmentUploadCycle({
registry: appAtomRegistry,
createUploadUrl: attachmentEnvironment.createUploadUrl,
@@ -402,6 +421,7 @@ export async function prepareTurnAttachments(input: {
// Read the connection at transfer time: the environment may have
// reconnected on a new base URL since this cycle started.
resolveUploadUrl: (relativeUrl) => {
requireUploadAccess();
const currentConnection = appAtomRegistry.get(
environmentSession.preparedConnectionValueAtom(environmentId),
);
@@ -411,6 +431,7 @@ export async function prepareTurnAttachments(input: {
},
transport: (url) => ({
done: uploadFileBytes(
environmentId,
attachment,
url,
controller.signal,
+99
View File
@@ -0,0 +1,99 @@
import {
AuthOrchestrationOperateScope,
EnvironmentAuthorizationError,
EnvironmentId,
} from "@t3tools/contracts";
import { runAttachmentUploadCycle } from "@t3tools/client-runtime/state/attachments";
import * as Cause from "effect/Cause";
import { AsyncResult, AtomRegistry } from "effect/reactivity";
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
const state = vi.hoisted(() => ({
grantedEnvironments: new Set<string>(),
create: vi.fn(),
remove: vi.fn(),
}));
vi.mock("../connection/runtime", () => ({ connectionAtomRuntime: {} }));
vi.mock("./session", () => ({
readEnvironmentScope: (environmentId: string, scope: string) =>
scope === AuthOrchestrationOperateScope && state.grantedEnvironments.has(environmentId),
}));
vi.mock("@t3tools/client-runtime/state/attachments", async (importOriginal) => ({
...(await importOriginal<typeof import("@t3tools/client-runtime/state/attachments")>()),
createAttachmentEnvironmentAtoms: () => ({
createUploadUrl: { label: "create", run: state.create },
remove: { label: "remove", run: state.remove },
}),
}));
import { attachmentEnvironment } from "./attachments";
const environmentId = EnvironmentId.make("secondary");
const registry = AtomRegistry.make();
beforeEach(() => {
state.grantedEnvironments = new Set(["primary"]);
state.create.mockReset().mockResolvedValue(
AsyncResult.success({
attachmentId: "pending",
relativeUrl: "/upload",
expiresAt: 1,
}),
);
state.remove.mockReset().mockResolvedValue(AsyncResult.success(undefined));
});
afterEach(() => {
vi.restoreAllMocks();
});
describe("attachment mutation grants", () => {
it("uses the attachment environment for both mint and deletion", async () => {
const mintResult = await attachmentEnvironment.createUploadUrl.run(registry, {
environmentId,
input: { name: "image.png", mimeType: "image/png", sizeBytes: 1 },
});
const removeResult = await attachmentEnvironment.remove.run(registry, {
environmentId,
input: { attachmentId: "pending" },
});
for (const result of [mintResult, removeResult]) {
expect(result._tag).toBe("Failure");
if (result._tag !== "Failure") throw new Error("Expected permission denial");
const error = Cause.squash<unknown>(result.cause);
expect(error).toBeInstanceOf(EnvironmentAuthorizationError);
expect(error).toMatchObject({ requiredScope: AuthOrchestrationOperateScope });
}
expect(state.create).not.toHaveBeenCalled();
expect(state.remove).not.toHaveBeenCalled();
state.grantedEnvironments.add("secondary");
expect(
(
await attachmentEnvironment.remove.run(registry, {
environmentId,
input: { attachmentId: "pending" },
})
)._tag,
).toBe("Success");
expect(state.remove).toHaveBeenCalledOnce();
});
it("blocks the upload cycle's asynchronous cleanup after grant revocation", async () => {
state.grantedEnvironments.add("secondary");
const transport = vi.fn();
const result = await runAttachmentUploadCycle({
registry,
...attachmentEnvironment,
environmentId,
upload: { name: "image.png", mimeType: "image/png", sizeBytes: 1 },
resolveUploadUrl: () => "https://example.test/upload",
transport,
onMinted: () => {
state.grantedEnvironments.delete("secondary");
return "cancel";
},
});
expect(result.status).toBe("cancelled");
expect(state.create).toHaveBeenCalledOnce();
expect(state.remove).not.toHaveBeenCalled();
expect(transport).not.toHaveBeenCalled();
});
});
+35 -1
View File
@@ -1,5 +1,39 @@
import { createAttachmentEnvironmentAtoms } from "@t3tools/client-runtime/state/attachments";
import type { AtomCommand } from "@t3tools/client-runtime/state/runtime";
import {
AuthOrchestrationOperateScope,
EnvironmentAuthorizationError,
type EnvironmentId,
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import { AsyncResult } from "effect/reactivity";
import { connectionAtomRuntime } from "../connection/runtime";
import { readEnvironmentScope } from "./session";
export const attachmentEnvironment = createAttachmentEnvironmentAtoms(connectionAtomRuntime);
function requireAttachmentWriteAccess<W extends { readonly environmentId: EnvironmentId }, A, E>(
command: AtomCommand<W, A, E>,
): AtomCommand<W, A, E | EnvironmentAuthorizationError> {
return {
...command,
run: async (registry, input) => {
if (!readEnvironmentScope(input.environmentId, AuthOrchestrationOperateScope)) {
return AsyncResult.failure(
Cause.fail(
new EnvironmentAuthorizationError({
message: "This connection cannot change attachments.",
requiredScope: AuthOrchestrationOperateScope,
}),
),
);
}
return command.run(registry, input);
},
};
}
const commands = createAttachmentEnvironmentAtoms(connectionAtomRuntime);
export const attachmentEnvironment = {
createUploadUrl: requireAttachmentWriteAccess(commands.createUploadUrl),
remove: requireAttachmentWriteAccess(commands.remove),
};
@@ -1,5 +1,5 @@
import { useAtomValue } from "@effect/atom-react";
import type { EnvironmentId } from "@t3tools/contracts";
import { AuthOrchestrationOperateScope, type EnvironmentId } from "@t3tools/contracts";
import { Atom } from "effect/reactivity";
import { useEffect, useRef } from "react";
@@ -24,6 +24,7 @@ import {
setComposerDraftAttachmentUpload,
} from "./use-composer-drafts";
import { useRemoteConnectionStatus } from "./use-remote-environment-registry";
import { readEnvironmentScope, useEnvironmentsWithScope } from "./session";
export {
composerAttachmentUploadBlockReason,
@@ -48,6 +49,7 @@ export function useComposerAttachmentUploadState(
}
export function retryComposerAttachmentUpload(environmentId: EnvironmentId, attachmentId: string) {
if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) return;
uploadQueue?.retry(environmentId, attachmentId);
}
@@ -57,6 +59,10 @@ export function useComposerAttachmentUploadWorker() {
const queuedMessages = useThreadOutboxMessages();
const serverConfigs = useServerConfigs();
const { connectedEnvironments } = useRemoteConnectionStatus();
const operableEnvironments = useEnvironmentsWithScope(
connectedEnvironments,
AuthOrchestrationOperateScope,
);
const queueRef = useRef<ReturnType<typeof createComposerAttachmentUploadQueue> | null>(null);
useEffect(() => {
@@ -117,7 +123,12 @@ export function useComposerAttachmentUploadWorker() {
);
const requests = Object.entries(drafts).flatMap(([key, draft]) => {
const environmentId = composerDraftEnvironmentId(key, queued, draft);
if (environmentId === null || !connected.has(environmentId)) return [];
if (
environmentId === null ||
!connected.has(environmentId) ||
!operableEnvironments.has(environmentId)
)
return [];
return draft.attachments
.filter((attachment) =>
canUploadComposerAttachment(attachment, serverConfigs.get(environmentId)),
@@ -125,5 +136,5 @@ export function useComposerAttachmentUploadWorker() {
.map((attachment) => ({ environmentId, attachment }));
});
queueRef.current?.sync(requests);
}, [connectedEnvironments, drafts, queuedMessages, serverConfigs]);
}, [connectedEnvironments, drafts, operableEnvironments, queuedMessages, serverConfigs]);
}
+100
View File
@@ -0,0 +1,100 @@
import {
AuthOrchestrationOperateScope,
EnvironmentId,
type AuthSessionState,
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import { AsyncResult, Atom } from "effect/reactivity";
import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
const harness = vi.hoisted(() => ({ lastAtom: null as Atom.Atom<unknown> | null }));
vi.mock("react", () => ({ useMemo: <A>(factory: () => A) => factory() }));
vi.mock("@effect/atom-react", async () => {
const { appAtomRegistry } = await import("./atom-registry");
return {
useAtomValue: <A>(atom: Atom.Atom<A>) => {
harness.lastAtom = atom;
return appAtomRegistry.get(atom);
},
};
});
vi.mock("../connection/runtime", () => ({ connectionAtomRuntime: {} }));
vi.mock("@t3tools/client-runtime/state/session", () => ({
createEnvironmentSessionAtoms: () => ({
sessionStateAtom: Atom.family((_id: EnvironmentId) =>
Atom.make(AsyncResult.initial<AuthSessionState, Error>()).pipe(Atom.keepAlive),
),
}),
}));
import { appAtomRegistry } from "./atom-registry";
import {
environmentSession,
readEnvironmentScope,
useEnvironmentScope,
useEnvironmentsWithScope,
} from "./session";
const primary = EnvironmentId.make("primary");
const secondary = EnvironmentId.make("secondary");
const session = (canOperate: boolean): AuthSessionState => ({
authenticated: true,
scopes: canOperate ? [AuthOrchestrationOperateScope] : [],
auth: {
policy: "remote-reachable",
bootstrapMethods: [],
sessionMethods: [],
sessionCookieName: "session",
},
});
// The production atom is read-only; the fake session source is writable.
const source = (id: EnvironmentId) =>
environmentSession.sessionStateAtom(id) as unknown as Atom.Writable<
AsyncResult.AsyncResult<AuthSessionState, Error>
>;
const releases: Array<() => void> = [];
beforeEach(() => {
harness.lastAtom = null;
appAtomRegistry.set(source(primary), AsyncResult.success(session(true)));
appAtomRegistry.set(source(secondary), AsyncResult.initial());
});
afterEach(() => {
releases.splice(0).forEach((release) => release());
});
it("keeps pending and denied environments out of worker grants while retaining valid cached access", () => {
expect(useEnvironmentScope(secondary, AuthOrchestrationOperateScope)).toBe(false);
expect(readEnvironmentScope(secondary, AuthOrchestrationOperateScope)).toBe(false);
const environments = [{ environmentId: primary }, { environmentId: secondary }];
expect(useEnvironmentsWithScope(environments, AuthOrchestrationOperateScope)).toEqual(
new Set([primary]),
);
appAtomRegistry.set(source(secondary), AsyncResult.waiting(AsyncResult.success(session(true))));
expect(readEnvironmentScope(secondary, AuthOrchestrationOperateScope)).toBe(true);
expect(useEnvironmentsWithScope(environments, AuthOrchestrationOperateScope)).toEqual(
new Set([primary, secondary]),
);
appAtomRegistry.set(source(secondary), AsyncResult.success(session(false)));
expect(useEnvironmentScope(secondary, AuthOrchestrationOperateScope)).toBe(false);
});
it("reacts to grant revocation, failure, and regrant without a connection list change", () => {
const environments = [{ environmentId: primary }, { environmentId: secondary }];
useEnvironmentsWithScope(environments, AuthOrchestrationOperateScope);
const observed = harness.lastAtom;
if (!observed) throw new Error("Missing worker grant atom");
const changes: unknown[] = [];
releases.push(appAtomRegistry.subscribe(observed, (value) => changes.push(value)));
appAtomRegistry.set(source(secondary), AsyncResult.success(session(true)));
expect(appAtomRegistry.get(observed)).toEqual(new Set([primary, secondary]));
appAtomRegistry.set(source(secondary), AsyncResult.success(session(false)));
expect(appAtomRegistry.get(observed)).toEqual(new Set([primary]));
appAtomRegistry.set(
source(primary),
AsyncResult.failure(Cause.fail(new Error("Session lookup failed"))),
);
expect(appAtomRegistry.get(observed)).toEqual(new Set());
appAtomRegistry.set(source(secondary), AsyncResult.success(session(true)));
expect(appAtomRegistry.get(observed)).toEqual(new Set([secondary]));
expect(changes).not.toHaveLength(0);
});
+60 -2
View File
@@ -1,13 +1,71 @@
import { useAtomValue } from "@effect/atom-react";
import { createEnvironmentSessionAtoms } from "@t3tools/client-runtime/state/session";
import type { EnvironmentId } from "@t3tools/contracts";
import type { AuthEnvironmentScope, AuthSessionState, EnvironmentId } from "@t3tools/contracts";
import * as Option from "effect/Option";
import { Atom } from "effect/reactivity";
import { AsyncResult, Atom } from "effect/reactivity";
import { useMemo } from "react";
import { connectionAtomRuntime } from "../connection/runtime";
import { appAtomRegistry } from "./atom-registry";
export const environmentSession = createEnvironmentSessionAtoms(connectionAtomRuntime);
const EMPTY_SESSION_STATE_ATOM = Atom.make(AsyncResult.initial<AuthSessionState>());
function sessionHasScope(
result: AsyncResult.AsyncResult<AuthSessionState, unknown>,
scope: AuthEnvironmentScope,
): boolean {
const session = Option.getOrNull(AsyncResult.value(result));
return (
result._tag !== "Failure" &&
session?.authenticated === true &&
session.scopes?.includes(scope) === true
);
}
/** Uses the selected environment's grant, including cached scopes during a refresh. */
export function useEnvironmentScope(
environmentId: EnvironmentId | null,
scope: AuthEnvironmentScope,
): boolean {
const result = useAtomValue(
environmentId === null
? EMPTY_SESSION_STATE_ATOM
: environmentSession.sessionStateAtom(environmentId),
);
return sessionHasScope(result, scope);
}
/** Keeps background workers subscribed to each target's grant. */
export function useEnvironmentsWithScope(
environments: ReadonlyArray<{ readonly environmentId: EnvironmentId }>,
scope: AuthEnvironmentScope,
): ReadonlySet<EnvironmentId> {
const permittedEnvironments = useMemo(
() =>
Atom.make((get) => {
const permitted = new Set<EnvironmentId>();
for (const { environmentId } of environments) {
if (sessionHasScope(get(environmentSession.sessionStateAtom(environmentId)), scope)) {
permitted.add(environmentId);
}
}
return permitted;
}),
[environments, scope],
);
return useAtomValue(permittedEnvironments);
}
export function readEnvironmentScope(
environmentId: EnvironmentId,
scope: AuthEnvironmentScope,
): boolean {
const result = appAtomRegistry.get(environmentSession.sessionStateAtom(environmentId));
return sessionHasScope(result, scope);
}
const EMPTY_PREPARED_CONNECTION_ATOM = Atom.make(Option.none()).pipe(
Atom.withLabel("mobile-prepared-connection:empty"),
);
@@ -0,0 +1,260 @@
import { AuthOrchestrationOperateScope, RuntimeRequestId } from "@t3tools/contracts";
import type { DraftComposerImageAttachment } from "../lib/composerImages";
import type { PendingThreadRequests } from "@t3tools/client-runtime/state/thread-requests";
import { AsyncResult, type Atom } from "effect/reactivity";
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
const state = vi.hoisted(() => ({
grantedEnvironments: new Set<string>(),
connectionState: "connected",
draft: { text: "Keep my draft", attachments: [] as DraftComposerImageAttachment[] },
pendingRequests: { approvals: [], userInputs: [] } as PendingThreadRequests,
enqueue: vi.fn(async () => undefined),
clearDraft: vi.fn(),
approve: vi.fn(),
answer: vi.fn(),
feedback: vi.fn(),
updateSettings: vi.fn(),
question: {
id: "language",
header: "Language",
question: "Which language?",
options: [{ label: "TypeScript", description: "Use the existing code" }],
multiSelect: false,
},
thread: {
id: "thread",
environmentId: "secondary",
modelSelection: { instanceId: "codex", model: "gpt-5.4" },
runtimeMode: "full-access",
interactionMode: "default",
runtime: null,
latestRun: null,
},
}));
vi.mock("react", () => ({
useCallback: <A>(callback: A) => callback,
useEffect: () => {},
useRef: <A>(current: A) => ({ current }),
useMemo: <A>(factory: () => A) => factory(),
useState: <A>(initial: A | (() => A)) => [
typeof initial === "function" ? (initial as () => A)() : initial,
vi.fn(),
],
}));
vi.mock("expo-crypto", () => ({ randomUUID: () => "uuid" }));
vi.mock("../lib/attachmentUpload", () => ({ prepareTurnAttachments: vi.fn() }));
vi.mock("../lib/uuid", () => ({ uuidv4: () => "uuid" }));
vi.mock("./queued-run-edit", () => ({
useQueuedRunEdit: () => null,
getQueuedRunEdit: () => null,
}));
vi.mock("./preferences", async () => {
const { Atom, AsyncResult } = await import("effect/reactivity");
return { mobilePreferencesAtom: Atom.make(AsyncResult.success({})) };
});
vi.mock("react-native", () => ({ Alert: { alert: vi.fn() } }));
vi.mock("@effect/atom-react", async () => {
const { appAtomRegistry } = await import("./atom-registry");
return { useAtomValue: <A>(atom: Atom.Atom<A>) => appAtomRegistry.get(atom) };
});
vi.mock("./entities", () => ({ useServerConfigs: () => new Map() }));
vi.mock("./session", () => ({
readEnvironmentScope: (environmentId: string, scope: string) =>
scope === AuthOrchestrationOperateScope && state.grantedEnvironments.has(environmentId),
}));
vi.mock("./use-thread-selection", () => ({
useThreadSelection: () => ({
selectedThread: state.thread,
selectedThreadCreation: null,
selectedEnvironmentRuntime: {
connectionState: state.connectionState,
serverConfig: {
providers: [{ instanceId: "codex", driver: "codex" }],
environment: { capabilities: {} },
},
},
}),
}));
vi.mock("./use-thread-detail", () => ({
useSelectedThreadProjection: () => null,
useSelectedThreadVisibleTurnItems: () => [],
useSelectedThreadPendingRequests: () => state.pendingRequests,
}));
vi.mock("./use-atom-command", () => ({ useAtomCommand: <A>(command: A) => command }));
vi.mock("./threads", async () => {
const { Atom } = await import("effect/reactivity");
return {
environmentThreadDetails: { queueWorkflowAtom: () => Atom.make(null) },
threadEnvironment: {
respondToApproval: state.approve,
respondToUserInput: state.answer,
uploadFeedback: state.feedback,
},
};
});
vi.mock("./use-thread-outbox", async () => {
const { Atom } = await import("effect/reactivity");
return { dispatchingQueuedMessageIdAtom: Atom.make(null), useThreadOutboxMessages: () => ({}) };
});
vi.mock("./thread-outbox", () => ({ enqueueThreadOutboxMessage: state.enqueue }));
vi.mock("./composer-attachment-uploads", async () => {
const { Atom } = await import("effect/reactivity");
return {
composerAttachmentUploadsAtom: Atom.make({}),
composerAttachmentUploadBlockReason: () => null,
composerAttachmentsStillUploading: () => false,
};
});
vi.mock("./use-composer-drafts", async () => {
const { Atom } = await import("effect/reactivity");
return {
composerDraftsAtom: Atom.make({}),
composerContextImportsAtom: Atom.make({}),
getComposerDraftSnapshot: () => state.draft,
clearComposerDraftContent: state.clearDraft,
clearComposerDraft: state.clearDraft,
setComposerDraftText: (_key: string, text: string) => {
state.draft.text = text;
},
updateComposerDraftSettings: state.updateSettings,
ensureComposerDraftsLoaded: () => {},
scheduleUnusedComposerAttachmentCleanup: () => {},
appendComposerDraftAttachments: vi.fn(),
appendComposerDraftText: vi.fn(),
mergeComposerDraftContent: vi.fn(),
removeComposerDraftAttachment: vi.fn(),
useComposerDraft: () => state.draft,
};
});
vi.mock("../lib/composerImages", () => ({
convertPastedImagesToAttachments: vi.fn(),
pasteComposerClipboard: vi.fn(),
pickComposerFiles: vi.fn(),
pickComposerMedia: vi.fn(),
}));
vi.mock("../lib/commandMetadata", () => ({
makeQueuedMessageMetadata: () => ({
messageId: "message",
commandId: "command",
createdAt: "2026-09-05T00:00:00.000Z",
}),
}));
vi.mock("../lib/copyTextWithHaptic", () => ({ copyTextWithHaptic: vi.fn() }));
vi.mock("../lib/modelOptions", () => ({ isModelSelectionUnavailable: () => false }));
vi.mock("./use-remote-environment-registry", () => ({ setPendingConnectionError: vi.fn() }));
import { useThreadComposerState } from "./use-thread-composer-state";
import { useSelectedThreadRequests } from "./use-selected-thread-requests";
beforeEach(() => {
state.grantedEnvironments = new Set(["primary"]);
state.connectionState = "connected";
state.draft = { text: "Keep my draft", attachments: [] };
state.pendingRequests = {
approvals: [
{
requestId: RuntimeRequestId.make("approval"),
requestKind: "command",
createdAt: "2026-09-05T00:00:00.000Z",
responseCapability: "live",
},
],
userInputs: [],
};
vi.clearAllMocks();
state.approve.mockResolvedValue(AsyncResult.success(undefined));
state.answer.mockResolvedValue(AsyncResult.success(undefined));
state.feedback.mockResolvedValue(AsyncResult.success({ feedbackId: "feedback" }));
});
describe("mobile task permissions", () => {
it("keeps a connected read-only task's draft instead of queueing it with another environment's grant", async () => {
const composer = useThreadComposerState();
expect(await composer.onSendMessage()).toBeNull();
expect(state.enqueue).not.toHaveBeenCalled();
expect(state.clearDraft).not.toHaveBeenCalled();
composer.onChangeDraftMessage("Edited locally");
composer.onUpdateInteractionMode("plan");
expect(state.draft.text).toBe("Edited locally");
expect(state.updateSettings).toHaveBeenCalledWith("secondary:thread", {
interactionMode: "plan",
});
});
it("rechecks a retained send callback before clearing or queueing the draft", async () => {
state.grantedEnvironments.add("secondary");
const composer = useThreadComposerState();
state.grantedEnvironments.delete("secondary");
expect(await composer.onSendMessage()).toBeNull();
expect(state.clearDraft).not.toHaveBeenCalled();
expect(state.enqueue).not.toHaveBeenCalled();
state.grantedEnvironments.add("secondary");
expect(await composer.onSendMessage()).toBe("message");
expect(state.enqueue).toHaveBeenCalledWith(
expect.objectContaining({
environmentId: "secondary",
threadId: "thread",
text: "Keep my draft",
}),
);
});
it("preserves offline queueing without dispatching feedback through the queue action", async () => {
state.connectionState = "disconnected";
expect(await useThreadComposerState().onSendMessage()).toBe("message");
expect(state.enqueue).toHaveBeenCalledTimes(1);
state.draft.text = "/feedback The agent stopped early.";
expect(await useThreadComposerState().onSendMessage()).toBeNull();
expect(state.feedback).not.toHaveBeenCalled();
expect(state.enqueue).toHaveBeenCalledTimes(1);
expect(state.clearDraft).toHaveBeenCalledTimes(1);
});
it("rechecks the target environment before an approval response", async () => {
state.grantedEnvironments.add("secondary");
const requests = useSelectedThreadRequests();
state.grantedEnvironments.delete("secondary");
await requests.onRespondToApproval(RuntimeRequestId.make("approval"), "accept");
expect(state.approve).not.toHaveBeenCalled();
state.grantedEnvironments.add("secondary");
await requests.onRespondToApproval(RuntimeRequestId.make("approval"), "accept");
expect(state.approve).toHaveBeenCalledWith({
environmentId: "secondary",
input: { threadId: "thread", requestId: "approval", decision: "accept" },
});
});
it("keeps answer drafts editable after revocation while blocking their submission", async () => {
state.pendingRequests = {
approvals: [],
userInputs: [
{
requestId: RuntimeRequestId.make("input"),
createdAt: "2026-09-05T00:00:00.000Z",
responseCapability: "live",
dismissible: false,
questions: [state.question],
},
],
};
const requestId = RuntimeRequestId.make("input");
useSelectedThreadRequests().onSelectUserInputOption(requestId, state.question, "TypeScript");
state.grantedEnvironments.add("secondary");
const requests = useSelectedThreadRequests();
expect(requests.activePendingUserInputAnswers).toEqual({ language: "TypeScript" });
state.grantedEnvironments.delete("secondary");
await requests.onSubmitUserInput();
expect(state.answer).not.toHaveBeenCalled();
expect(useSelectedThreadRequests().activePendingUserInputAnswers).toEqual({
language: "TypeScript",
});
state.grantedEnvironments.add("secondary");
await requests.onSubmitUserInput();
expect(state.answer).toHaveBeenCalledWith({
environmentId: "secondary",
input: { threadId: "thread", requestId: "input", answers: { language: "TypeScript" } },
});
});
});
@@ -47,6 +47,7 @@ vi.mock("./entities", () => ({
],
]),
}));
vi.mock("./session", () => ({ readEnvironmentScope: () => true }));
vi.mock("./threads", () => ({ threadEnvironment: {} }));
vi.mock("./use-atom-command", () => ({ useAtomCommand: () => vi.fn() }));
vi.mock("./use-thread-selection", () => ({
@@ -19,6 +19,7 @@ import {
type PendingThreadRequests,
type ThreadUserInputQuestion,
} from "@t3tools/client-runtime/state/thread-requests";
import { AuthOrchestrationOperateScope } from "@t3tools/contracts";
import { Atom } from "effect/reactivity";
import { threadEnvironment } from "../state/threads";
@@ -33,6 +34,7 @@ import { appAtomRegistry } from "./atom-registry";
import { useSelectedThreadPendingRequests } from "./use-thread-detail";
import { useThreadSelection } from "./use-thread-selection";
import { useAtomCommand } from "./use-atom-command";
import { readEnvironmentScope } from "./session";
const EMPTY_PENDING_REQUESTS: PendingThreadRequests = { approvals: [], userInputs: [] };
@@ -211,7 +213,10 @@ export function useSelectedThreadRequests() {
const onRespondToApproval = useCallback(
async (requestId: RuntimeRequestId, decision: ProviderApprovalDecision) => {
if (!selectedThreadShell) {
if (
!selectedThreadShell ||
!readEnvironmentScope(selectedThreadShell.environmentId, AuthOrchestrationOperateScope)
) {
return;
}
if (
@@ -241,7 +246,8 @@ export function useSelectedThreadRequests() {
!selectedThreadShell ||
!activePendingUserInput ||
activePendingUserInput.responseCapability === "not_resumable" ||
!activePendingUserInputAnswers
!activePendingUserInputAnswers ||
!readEnvironmentScope(selectedThreadShell.environmentId, AuthOrchestrationOperateScope)
) {
return;
}
@@ -318,7 +324,11 @@ export function useSelectedThreadRequests() {
// Closes an async question without messaging the agent.
const onDismissUserInput = useCallback(async () => {
if (!selectedThreadShell || !activePendingUserInput) {
if (
!selectedThreadShell ||
!activePendingUserInput ||
!readEnvironmentScope(selectedThreadShell.environmentId, AuthOrchestrationOperateScope)
) {
return;
}
@@ -1,3 +1,5 @@
import { AuthOrchestrationOperateScope } from "@t3tools/contracts";
import { readEnvironmentScope } from "./session";
import type { ComposerTextPaste } from "../native/T3ComposerEditor.types";
import { useAtomValue } from "@effect/atom-react";
import { threadRuntimeIsActive } from "@t3tools/client-runtime/state/shell";
@@ -548,6 +550,12 @@ export function useThreadComposerState() {
const onSendMessage = useCallback(
async (followUpOverride?: ActiveTurnComposerAction) => {
if (
selectedThreadShell &&
selectedEnvironmentRuntime?.connectionState === "connected" &&
!readEnvironmentScope(selectedThreadShell.environmentId, AuthOrchestrationOperateScope)
)
return null;
if (!selectedThreadShell) {
return null;
}
@@ -624,6 +632,8 @@ export function useThreadComposerState() {
? parseCodexFeedbackCommand(text)
: null;
if (feedbackCommand) {
if (!readEnvironmentScope(selectedThreadShell.environmentId, AuthOrchestrationOperateScope))
return null;
if (thread.activeProviderThreadId === null) {
Alert.alert("Start a Codex thread first", "Send a message before you submit feedback.");
return null;
@@ -0,0 +1,318 @@
import {
AuthOrchestrationOperateScope,
CommandId,
EnvironmentId,
MessageId,
ProjectId,
ProviderInstanceId,
ThreadId,
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import { AsyncResult, type Atom } from "effect/reactivity";
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
import type { QueuedThreadMessage } from "./thread-outbox-model";
const state = vi.hoisted(() => ({
grantedEnvironments: new Set<string>(),
draftText: "Keep this draft separate",
cleanups: [] as Array<() => void>,
start: vi.fn(),
metadata: vi.fn(),
runtime: vi.fn(),
interaction: vi.fn(),
prepare: vi.fn(),
manager: null as unknown as ReturnType<
typeof import("./thread-outbox-manager").createThreadOutboxManager
>,
thread: {
environmentId: "secondary",
id: "thread",
modelSelection: { instanceId: "codex", model: "gpt-5.4" },
runtimeMode: "full-access",
interactionMode: "default",
session: null,
},
config: {
providers: [{ instanceId: "codex", driver: "codex" }],
environment: { capabilities: {} },
},
}));
vi.mock("react", () => ({
useCallback: <A>(callback: A) => callback,
useEffect: (effect: () => void | (() => void)) => {
const cleanup = effect();
if (cleanup) state.cleanups.push(cleanup);
},
useRef: <A>(value: A) => ({ current: value }),
useState: <A>(initial: A) => [initial, vi.fn()],
}));
vi.mock("react-native", () => ({ Alert: { alert: vi.fn() } }));
vi.mock("@effect/atom-react", async () => {
const { appAtomRegistry } = await import("./atom-registry");
return { useAtomValue: <A>(atom: Atom.Atom<A>) => appAtomRegistry.get(atom) };
});
vi.mock("./session", () => ({
readEnvironmentScope: (environmentId: string, scope: string) =>
scope === AuthOrchestrationOperateScope && state.grantedEnvironments.has(environmentId),
useEnvironmentsWithScope: () => state.grantedEnvironments,
}));
vi.mock("./entities", () => ({
useProjects: () => [],
useThreadShells: () => [state.thread],
useServerConfigs: () => new Map([["secondary", state.config]]),
}));
vi.mock("./server", async () => {
const { Atom } = await import("effect/reactivity");
return {
serverEnvironment: { configValueAtom: Atom.family((_id: string) => Atom.make(state.config)) },
};
});
vi.mock("./threads", async () => {
const { Atom } = await import("effect/reactivity");
return {
threadEnvironment: {
startTurn: state.start,
updateMetadata: state.metadata,
setRuntimeMode: state.runtime,
setInteractionMode: state.interaction,
},
environmentThreadShells: { threadShellsAtom: Atom.make([state.thread]) },
};
});
vi.mock("./use-atom-command", () => ({ useAtomCommand: <A>(command: A) => command }));
vi.mock("../lib/modelOptions", () => ({ isModelSelectionUnavailable: () => false }));
vi.mock("../lib/uuid", () => ({ uuidv4: () => "uuid", randomHex: () => "abcd" }));
vi.mock("../lib/attachmentUpload", () => ({ prepareTurnAttachments: state.prepare }));
vi.mock("./use-remote-environment-registry", () => ({
setPendingConnectionError: vi.fn(),
useRemoteConnectionStatus: () => ({
connectedEnvironments: [{ environmentId: "secondary", connectionState: "connected" }],
}),
}));
vi.mock("./thread-outbox", async () => {
const { createThreadOutboxManager } = await import("./thread-outbox-manager");
const { appAtomRegistry } = await import("./atom-registry");
state.manager = createThreadOutboxManager({
registry: appAtomRegistry,
storage: {
load: async () => ({ messages: [], errors: [] }),
write: async () => {},
remove: async () => {},
},
});
return {
threadOutboxManager: state.manager,
threadOutboxRevision: (id: MessageId) => state.manager.revisionOf(id),
confirmThreadOutboxMessageQueued: (message: QueuedThreadMessage) =>
state.manager.confirmQueued(message),
updateThreadOutboxMessage: (message: QueuedThreadMessage, revision?: number) =>
state.manager.update(message, revision),
};
});
vi.mock("./thread-outbox-removal", () => ({
removeThreadOutboxMessage: (message: QueuedThreadMessage, revision?: number) =>
state.manager.remove(message, revision),
}));
vi.mock("./use-thread-outbox", async () => {
const { Atom } = await import("effect/reactivity");
const { appAtomRegistry } = await import("./atom-registry");
await import("./thread-outbox");
return {
editingQueuedMessageIdsAtom: Atom.make({}).pipe(Atom.keepAlive),
dispatchingQueuedMessageIdAtom: Atom.make<MessageId | null>(null).pipe(Atom.keepAlive),
useThreadOutboxMessages: () => appAtomRegistry.get(state.manager.queuedMessagesByThreadKeyAtom),
useThreadOutboxShellStatuses: () => new Map([["secondary", "live"]]),
};
});
vi.mock("./use-composer-drafts", async () => {
const { Atom } = await import("effect/reactivity");
return {
composerDraftsAtom: Atom.make({}),
removeDeliveredCloudQueuedMessage: async () => {},
appendComposerDraftAttachments: vi.fn(),
flushComposerDrafts: vi.fn(),
getComposerDraftSnapshot: vi.fn(() => ({ text: state.draftText, attachments: [] })),
mergeComposerDraftContent: vi.fn(async (_key: string, input: { text: string }) => {
state.draftText += `\n${input.text}`;
}),
replaceComposerDraftAttachments: vi.fn(),
undoComposerDraftMerge: vi.fn(),
updateComposerDraftSettings: vi.fn(),
waitForComposerDraftsLoaded: vi.fn(),
};
});
import { appAtomRegistry } from "./atom-registry";
import { dispatchingQueuedMessageIdAtom } from "./use-thread-outbox";
import { useThreadOutboxDrain } from "./use-thread-outbox-drain";
const message = (overrides: Partial<QueuedThreadMessage> = {}): QueuedThreadMessage => ({
environmentId: EnvironmentId.make("secondary"),
threadId: ThreadId.make("thread"),
commandId: CommandId.make("command"),
messageId: MessageId.make("message"),
text: "Keep this queued",
attachments: [],
createdAt: "2026-09-05T00:00:00.000Z",
...overrides,
});
const remaining = () =>
Object.values(appAtomRegistry.get(state.manager.queuedMessagesByThreadKeyAtom)).flat();
function runDrain() {
const settled = Promise.withResolvers<void>();
const release = appAtomRegistry.subscribe(dispatchingQueuedMessageIdAtom, (id) => {
if (id === null) settled.resolve();
});
useThreadOutboxDrain();
return settled.promise.finally(release);
}
beforeEach(() => {
state.grantedEnvironments = new Set(["primary"]);
state.draftText = "Keep this draft separate";
appAtomRegistry.set(state.manager.queuedMessagesByThreadKeyAtom, {});
appAtomRegistry.set(dispatchingQueuedMessageIdAtom, null);
for (const command of [state.start, state.metadata, state.runtime, state.interaction]) {
command.mockReset().mockResolvedValue(AsyncResult.success(undefined));
}
state.prepare.mockReset().mockImplementation(async ({ attachments }) => ({
status: "ready",
attachments: [],
draftAttachments: attachments,
pendingAttachmentIds: [],
}));
});
afterEach(() => {
state.cleanups.splice(0).forEach((cleanup) => cleanup());
});
describe("queued task operation access", () => {
it("parks a connected read-only target, then delivers its unchanged queue after a grant", async () => {
const queued = message();
await state.manager.enqueue(queued);
useThreadOutboxDrain();
expect(state.start).not.toHaveBeenCalled();
expect(state.prepare).not.toHaveBeenCalled();
expect(remaining()).toEqual([queued]);
state.grantedEnvironments.add("secondary");
await runDrain();
expect(state.start).toHaveBeenCalledOnce();
expect(remaining()).toEqual([]);
});
it("stops the remaining settings and turn commands when an earlier update loses access", async () => {
state.grantedEnvironments.add("secondary");
const queued = message({
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "different-model" },
runtimeMode: "approval-required",
interactionMode: "plan",
});
await state.manager.enqueue(queued);
state.runtime.mockImplementationOnce(async () => {
state.grantedEnvironments.delete("secondary");
return AsyncResult.success(undefined);
});
await runDrain();
expect(state.runtime).toHaveBeenCalledOnce();
expect(state.interaction).not.toHaveBeenCalled();
expect(state.prepare).not.toHaveBeenCalled();
expect(state.start).not.toHaveBeenCalled();
expect(remaining()).toEqual([queued]);
});
it.each([
{ isCreation: false, accepted: false },
{ isCreation: true, accepted: false },
{ isCreation: false, accepted: true },
{ isCreation: true, accepted: true },
])(
"preserves a rejected queue but removes an accepted turn after access loss (new task: $isCreation, accepted: $accepted)",
async ({ isCreation, accepted }) => {
state.grantedEnvironments.add("secondary");
const queued = message(
isCreation
? {
threadId: ThreadId.make("new-thread"),
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
creation: {
projectId: ProjectId.make("project"),
projectCwd: "/repo",
workspaceMode: "local",
branch: null,
worktreePath: null,
},
}
: {},
);
await state.manager.enqueue(queued);
const started = Promise.withResolvers<void>();
const delivery = Promise.withResolvers<AsyncResult.AsyncResult<void, Error>>();
state.start.mockImplementationOnce(() => {
started.resolve();
return delivery.promise;
});
const drained = runDrain();
await started.promise;
state.grantedEnvironments.delete("secondary");
delivery.resolve(
accepted
? AsyncResult.success(undefined)
: AsyncResult.failure(Cause.fail(new Error("This connection cannot control this task."))),
);
await drained;
expect(remaining()).toEqual(accepted ? [] : [queued]);
expect(state.draftText).toBe("Keep this draft separate");
if (!accepted) {
state.grantedEnvironments.add("secondary");
await runDrain();
expect(state.start).toHaveBeenCalledTimes(2);
expect(remaining()).toEqual([]);
expect(state.draftText).toBe("Keep this draft separate");
}
},
);
it.each([
{ isCreation: false, uploadFails: false },
{ isCreation: true, uploadFails: false },
{ isCreation: false, uploadFails: true },
{ isCreation: true, uploadFails: true },
])(
"keeps the message queued after upload revocation (new task: $isCreation, upload fails: $uploadFails)",
async ({ isCreation, uploadFails }) => {
state.grantedEnvironments.add("secondary");
const queued = message(
isCreation
? {
threadId: ThreadId.make("new-thread"),
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
creation: {
projectId: ProjectId.make("project"),
projectCwd: "/repo",
workspaceMode: "local",
branch: null,
worktreePath: null,
},
}
: {},
);
await state.manager.enqueue(queued);
state.prepare.mockImplementationOnce(async ({ attachments }) => {
state.grantedEnvironments.delete("secondary");
if (uploadFails) throw new Error("This connection cannot upload attachments.");
return {
status: "ready",
attachments: [],
draftAttachments: attachments,
pendingAttachmentIds: [],
};
});
await runDrain();
expect(state.prepare).toHaveBeenCalledOnce();
expect(state.start).not.toHaveBeenCalled();
expect(remaining()).toEqual([queued]);
},
);
});
@@ -13,6 +13,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test"
import type { PreparedTurnAttachments } from "../lib/attachmentUpload";
const harness = vi.hoisted(() => ({
canOperate: true,
manager: null as unknown as ReturnType<
typeof import("./thread-outbox-manager").createThreadOutboxManager
>,
@@ -95,6 +96,11 @@ vi.mock("./use-atom-command", () => ({
useAtomCommand: () => async () => undefined,
}));
vi.mock("./session", () => ({
readEnvironmentScope: () => harness.canOperate,
useEnvironmentsWithScope: () => new Set(),
}));
vi.mock("./use-thread-outbox", async () => {
const { Atom } = await import("effect/reactivity");
return {
@@ -203,6 +209,7 @@ function remainingMessages(): ReadonlyArray<QueuedThreadMessage> {
beforeEach(() => {
appAtomRegistry.set(acknowledgedThreadMessagesAtom, []);
harness.canOperate = true;
harness.draftFile.setDocument({ schemaVersion: 1, drafts: {} });
});
@@ -220,6 +227,27 @@ afterEach(() => {
});
describe("thread outbox attachment preparation", () => {
it("keeps a denied message queued without starting its attachment upload", async () => {
const message = queuedMessage({
messageId: "denied-queued-message",
text: "Keep this queued",
fileUri: "file:///documents/keep.pdf",
});
await harness.manager.enqueue(message);
harness.prepareTurnAttachments.mockResolvedValueOnce({
status: "ready",
attachments: [],
draftAttachments: message.attachments,
pendingAttachmentIds: [],
});
harness.canOperate = false;
await expect(prepareQueuedMessageAttachments(message)).resolves.toEqual({
status: "abandoned",
});
expect(harness.prepareTurnAttachments).not.toHaveBeenCalled();
expect(remainingMessages()).toEqual([message]);
});
it("abandons reused uploads when an editor saves changed text during verification", async () => {
const message = withReusedFileUpload(
queuedMessage({
@@ -7,6 +7,7 @@ import {
import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime";
import { deriveThreadTitleSeed } from "@t3tools/client-runtime/operations";
import {
AuthOrchestrationOperateScope,
CommandId,
DEFAULT_PROVIDER_INTERACTION_MODE,
DEFAULT_RUNTIME_MODE,
@@ -39,6 +40,7 @@ import {
recordPendingThreadCreationOutcome,
} from "./pending-thread-creation";
import { serverEnvironment } from "./server";
import { readEnvironmentScope, useEnvironmentsWithScope } from "./session";
import {
confirmThreadOutboxMessageQueued,
threadOutboxManager,
@@ -226,6 +228,9 @@ export async function prepareQueuedMessageAttachments(
if (!(await confirmThreadOutboxMessageQueued(queuedMessage))) {
return { status: "abandoned" };
}
if (!readEnvironmentScope(queuedMessage.environmentId, AuthOrchestrationOperateScope)) {
return { status: "abandoned" };
}
const revision = threadOutboxRevision(queuedMessage.messageId);
if (!isQueuedMessagePayloadCurrent(queuedMessage, revision)) {
return { status: "abandoned" };
@@ -668,6 +673,10 @@ export function useThreadOutboxDrain(): void {
const projects = useProjects();
const serverConfigs = useServerConfigs();
const { connectedEnvironments } = useRemoteConnectionStatus();
const operableEnvironments = useEnvironmentsWithScope(
connectedEnvironments,
AuthOrchestrationOperateScope,
);
const [retryTick, setRetryTick] = useState(0);
const retryAttemptRef = useRef(new Map<MessageId, number>());
const retryNotBeforeRef = useRef(new Map<MessageId, number>());
@@ -794,6 +803,9 @@ export function useThreadOutboxDrain(): void {
const sendQueuedMessage = useCallback(
async (queuedMessage: QueuedThreadMessage, thread: EnvironmentThreadShell) => {
const hasAccess = () =>
readEnvironmentScope(queuedMessage.environmentId, AuthOrchestrationOperateScope);
if (!hasAccess()) return true;
const serverConfig = appAtomRegistry.get(
serverEnvironment.configValueAtom(queuedMessage.environmentId),
);
@@ -808,6 +820,7 @@ export function useThreadOutboxDrain(): void {
const { reportFailure } = makeDeliveryHelpers(queuedMessage);
if (settings.runtimeMode !== thread.runtimeMode) {
if (!hasAccess()) return true;
const runtimeResult = await setThreadRuntimeMode({
environmentId: queuedMessage.environmentId,
input: {
@@ -824,6 +837,7 @@ export function useThreadOutboxDrain(): void {
}
if (settings.interactionMode !== thread.interactionMode) {
if (!hasAccess()) return true;
const interactionResult = await setThreadInteractionMode({
environmentId: queuedMessage.environmentId,
input: {
@@ -842,6 +856,7 @@ export function useThreadOutboxDrain(): void {
let prepared: PreparedTurnAttachments;
let persistedMessage: QueuedThreadMessage;
let deliveryRevision: number;
if (!hasAccess()) return true;
try {
const preparedResult = await prepareQueuedMessageAttachments(
queuedMessage,
@@ -861,6 +876,7 @@ export function useThreadOutboxDrain(): void {
return true;
}
} catch (error) {
if (!hasAccess()) return true;
logThreadOutboxUploadFailure(queuedMessage, error);
if (!shouldRetryThreadOutboxDelivery(error)) {
return restoreQueuedMessage(
@@ -888,6 +904,7 @@ export function useThreadOutboxDrain(): void {
settings,
currentConfig.providers,
);
if (!hasAccess()) return true;
const deliveryResult = await startTurn({
environmentId: queuedMessage.environmentId,
input: {
@@ -922,6 +939,7 @@ export function useThreadOutboxDrain(): void {
dispatchMode: queuedMessage.dispatchMode ?? "start",
},
});
if (AsyncResult.isFailure(deliveryResult) && !hasAccess()) return true;
const failure = reportFailure(deliveryResult, "start-turn");
if (failure?.action === "retry") {
return false;
@@ -952,6 +970,9 @@ export function useThreadOutboxDrain(): void {
creation: QueuedThreadCreation,
projectCwd: string,
) => {
const hasAccess = () =>
readEnvironmentScope(queuedMessage.environmentId, AuthOrchestrationOperateScope);
if (!hasAccess()) return true;
const modelSelection = queuedMessage.modelSelection;
if (modelSelection === undefined) {
return false;
@@ -997,6 +1018,7 @@ export function useThreadOutboxDrain(): void {
return true;
}
} catch (error) {
if (!hasAccess()) return true;
logThreadOutboxUploadFailure(queuedMessage, error);
if (!shouldRetryThreadOutboxDelivery(error)) {
return restoreQueuedMessage(
@@ -1024,6 +1046,7 @@ export function useThreadOutboxDrain(): void {
settings,
currentConfig.providers,
);
if (!hasAccess()) return true;
const deliveryResult = await startTurn({
environmentId: queuedMessage.environmentId,
input: buildProjectThreadStartTurnInput({
@@ -1054,6 +1077,7 @@ export function useThreadOutboxDrain(): void {
}),
});
const { reportFailure } = makeDeliveryHelpers(queuedMessage);
if (AsyncResult.isFailure(deliveryResult) && !hasAccess()) return true;
const failure = reportFailure(deliveryResult, "start-turn");
if (failure?.action === "retry") {
return false;
@@ -1188,6 +1212,9 @@ export function useThreadOutboxDrain(): void {
environmentConnected: environment?.connectionState === "connected",
threadBusy: threadRuntimeIsActive(thread?.runtime),
});
if (deliveryAction === "send" && !operableEnvironments.has(nextQueuedMessage.environmentId)) {
continue;
}
// The delivery action resolves first; capability checks apply only to
// a message that will send. Checking earlier would restore a
// creation whose startTurn already made the thread as a duplicate draft
@@ -1345,6 +1372,7 @@ export function useThreadOutboxDrain(): void {
connectedEnvironments,
dispatchingQueuedMessageId,
editingQueuedMessageIds,
operableEnvironments,
projects,
queuedMessagesByThreadKey,
retryTick,
+3 -18
View File
@@ -1,5 +1,5 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { AuthAdministrativeScopes } from "@t3tools/contracts";
import { AuthAdministrativeScopes, AuthStandardClientScopes } from "@t3tools/contracts";
import { expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -328,13 +328,7 @@ it.layer(NodeServices.layer)("EnvironmentAuth.layer", (it) => {
);
expect(verified.sessionId.length).toBeGreaterThan(0);
expect(verified.scopes).toEqual([
"orchestration:read",
"orchestration:operate",
"terminal:operate",
"review:write",
"relay:read",
]);
expect(verified.scopes).toEqual(AuthStandardClientScopes);
expect(verified.subject).toBe("one-time-token");
}).pipe(Effect.provide(layerEnvironmentAuth())),
);
@@ -535,16 +529,7 @@ it.layer(NodeServices.layer)("EnvironmentAuth.layer", (it) => {
makeCookieRequest(sessions.cookieName, exchanged.sessionToken),
);
expect(verified.scopes).toEqual([
"orchestration:read",
"orchestration:operate",
"terminal:operate",
"review:write",
"relay:read",
"access:read",
"access:write",
"relay:write",
]);
expect(verified.scopes).toEqual(AuthAdministrativeScopes);
expect(verified.subject).toBe("administrative-bootstrap");
}).pipe(Effect.provide(layerEnvironmentAuth())),
);
@@ -1,3 +1,4 @@
import { AuthAdministrativeScopes } from "@t3tools/contracts";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
@@ -79,29 +80,11 @@ it.layer(NodeServices.layer)("EnvironmentAuth administrative operations", (it) =
const listedAfterRevoke = yield* environmentAuth.listSessions();
expect(issued.method).toBe("bearer-access-token");
expect(issued.scopes).toEqual([
"orchestration:read",
"orchestration:operate",
"terminal:operate",
"review:write",
"relay:read",
"access:read",
"access:write",
"relay:write",
]);
expect(issued.scopes).toEqual(AuthAdministrativeScopes);
expect(issued.client.deviceType).toBe("bot");
expect(issued.client.label).toBe("deploy-bot");
expect(verified.sessionId).toBe(issued.sessionId);
expect(verified.scopes).toEqual([
"orchestration:read",
"orchestration:operate",
"terminal:operate",
"review:write",
"relay:read",
"access:read",
"access:write",
"relay:write",
]);
expect(verified.scopes).toEqual(AuthAdministrativeScopes);
expect(verified.method).toBe("bearer-access-token");
expect(listedBeforeRevoke).toHaveLength(1);
expect(listedBeforeRevoke[0]?.sessionId).toBe(issued.sessionId);
@@ -34,6 +34,7 @@ it.layer(NodeServices.layer)("EnvironmentAuthPolicy.layer", (it) => {
expect(descriptor.policy).toBe("desktop-managed-local");
expect(descriptor.bootstrapMethods).toEqual(["desktop-bootstrap"]);
expect(descriptor.serverUpdateScope).toBe("environment:maintain");
// Packaged desktop has no devUrl, but still needs the port scope: it
// scans upward from 3773 for a free port and binds 127.0.0.1, so a second
// instance shares this one's hostname on a different port.
@@ -88,6 +89,7 @@ it.layer(NodeServices.layer)("EnvironmentAuthPolicy.layer", (it) => {
expect(descriptor.policy).toBe("loopback-browser");
expect(descriptor.bootstrapMethods).toEqual(["one-time-token"]);
expect(descriptor.serverUpdateScope).toBe("environment:maintain");
expect(descriptor.sessionCookieName).toMatch(/^t3_session_3773_[a-f0-9]{12}$/);
}).pipe(
Effect.provide(
@@ -1,4 +1,4 @@
import type { ServerAuthDescriptor } from "@t3tools/contracts";
import { AuthEnvironmentMaintainScope, type ServerAuthDescriptor } from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -40,6 +40,7 @@ export const make = Effect.gen(function* () {
policy,
bootstrapMethods,
sessionMethods: ["browser-session-cookie", "bearer-access-token", "dpop-access-token"],
serverUpdateScope: AuthEnvironmentMaintainScope,
sessionCookieName: resolveSessionCookieName({
mode: config.mode,
port: config.port,
+2 -2
View File
@@ -1,7 +1,7 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import {
AuthAdministrativeScopes,
type AuthEnvironmentScope,
type AuthCreatePairingCredentialInput,
EnvironmentHttpApi,
} from "@t3tools/contracts";
import { expect, it } from "@effect/vitest";
@@ -418,7 +418,7 @@ it.live("one-click approves only access the browser session holds the scopes for
const clientId = yield* registeredClientId(handler);
const params = authorizeParams(clientId);
// Signs a browser in through the real route and returns its session cookie.
const browserCookie = (scopes: ReadonlyArray<AuthEnvironmentScope>) =>
const browserCookie = (scopes: NonNullable<AuthCreatePairingCredentialInput["scopes"]>) =>
Effect.gen(function* () {
const pairing = yield* auth.issuePairingCredential({ scopes });
const response = yield* handler(
+3 -17
View File
@@ -1,3 +1,4 @@
import { AuthAdministrativeScopes, AuthStandardClientScopes } from "@t3tools/contracts";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
import * as Duration from "effect/Duration";
@@ -83,13 +84,7 @@ it.layer(NodeServices.layer)("PairingGrantStore.layer", (it) => {
const second = yield* Effect.flip(bootstrapCredentials.consume(issued.credential));
expect(first.method).toBe("one-time-token");
expect(first.scopes).toEqual([
"orchestration:read",
"orchestration:operate",
"terminal:operate",
"review:write",
"relay:read",
]);
expect(first.scopes).toEqual(AuthStandardClientScopes);
expect(first.subject).toBe("one-time-token");
expect(first.label).toBe("Julius iPhone");
expect(issued.label).toBe("Julius iPhone");
@@ -168,16 +163,7 @@ it.layer(NodeServices.layer)("PairingGrantStore.layer", (it) => {
const third = yield* bootstrapCredentials.consume("desktop-bootstrap-token");
expect(first.method).toBe("desktop-bootstrap");
expect(first.scopes).toEqual([
"orchestration:read",
"orchestration:operate",
"terminal:operate",
"review:write",
"relay:read",
"access:read",
"access:write",
"relay:write",
]);
expect(first.scopes).toEqual(AuthAdministrativeScopes);
expect(first.subject).toBe("desktop-bootstrap");
expect(second.method).toBe("desktop-bootstrap");
expect(third.method).toBe("desktop-bootstrap");
+80 -6
View File
@@ -1,4 +1,9 @@
import {
AuthEnvironmentMaintainScope,
AuthProvidersManageScope,
AuthSettingsWriteScope,
DEFAULT_SERVER_SETTINGS,
ProviderInstanceId,
AuthOrchestrationOperateScope,
AuthOrchestrationReadScope,
AuthRelayReadScope,
@@ -28,7 +33,7 @@ describe("RPC authorization scopes", () => {
AuthOrchestrationReadScope,
);
expect(requiredScopeForRpcMethod(WS_METHODS.serverReportHostPowerState)).toBe(
AuthOrchestrationOperateScope,
AuthEnvironmentMaintainScope,
);
expect(requiredScopeForRpcMethod(WS_METHODS.serverGetBackgroundPolicy)).toBe(
AuthOrchestrationReadScope,
@@ -75,13 +80,13 @@ describe("RPC authorization scopes", () => {
AuthOrchestrationReadScope,
);
expect(requiredScopeForRpcMethod(WS_METHODS.serverPrepareAcpRegistryAgent)).toBe(
AuthOrchestrationOperateScope,
AuthProvidersManageScope,
);
expect(requiredScopeForRpcMethod(WS_METHODS.serverUninstallAcpRegistryManagedBinary)).toBe(
AuthOrchestrationOperateScope,
AuthProvidersManageScope,
);
expect(requiredScopeForRpcMethod(WS_METHODS.serverAcceptAcpRegistryUrlAuth)).toBe(
AuthOrchestrationOperateScope,
AuthProvidersManageScope,
);
expect(requiredScopeForRpcMethod(WS_METHODS.serverListAcpRegistrySessions)).toBe(
AuthOrchestrationReadScope,
@@ -90,7 +95,7 @@ describe("RPC authorization scopes", () => {
AuthOrchestrationOperateScope,
);
expect(requiredScopeForRpcMethod(WS_METHODS.serverLogoutAcpRegistry)).toBe(
AuthOrchestrationOperateScope,
AuthProvidersManageScope,
);
});
@@ -160,9 +165,78 @@ describe("RPC scope middleware", () => {
yield* client[WS_METHODS.serverRetryResourceTelemetry]({}).pipe(Effect.flip),
).toMatchObject({
_tag: "EnvironmentAuthorizationError",
requiredScope: AuthOrchestrationOperateScope,
requiredScope: AuthEnvironmentMaintainScope,
});
expect(handled).toEqual([]);
}).pipe(Effect.scoped),
);
});
describe("settings mutation authorization", () => {
const group = WsRpcGroup.omit(
...[...WsRpcGroup.requests.keys()].filter(
(
tag,
): tag is Exclude<keyof typeof RPC_REQUIRED_SCOPES, typeof WS_METHODS.serverUpdateSettings> =>
tag !== WS_METHODS.serverUpdateSettings,
),
);
const providerInstanceMutation = {
operation: "remove" as const,
instanceId: ProviderInstanceId.make("codex_work"),
};
it.effect("allows provider-only mutations while denying mixed settings without their grant", () =>
Effect.gen(function* () {
let handled = 0;
const client = yield* RpcTest.makeClient(group).pipe(
Effect.provide(
Layer.mergeAll(
group.toLayerHandler(WS_METHODS.serverUpdateSettings, () =>
Effect.sync(() => {
handled++;
return DEFAULT_SERVER_SETTINGS;
}),
),
RpcAuthorization.layer([AuthProvidersManageScope]),
),
),
);
yield* client[WS_METHODS.serverUpdateSettings]({ patch: {}, providerInstanceMutation });
expect(handled).toBe(1);
expect(
yield* client[WS_METHODS.serverUpdateSettings]({
patch: { defaultRuntimeMode: "full-access" },
providerInstanceMutation,
}).pipe(Effect.flip),
).toMatchObject({ requiredScope: AuthSettingsWriteScope });
expect(handled).toBe(1);
}).pipe(Effect.scoped),
);
it.effect("does not let a settings grant create or remove providers", () =>
Effect.gen(function* () {
let handled = false;
const client = yield* RpcTest.makeClient(group).pipe(
Effect.provide(
Layer.mergeAll(
group.toLayerHandler(WS_METHODS.serverUpdateSettings, () =>
Effect.sync(() => {
handled = true;
return DEFAULT_SERVER_SETTINGS;
}),
),
RpcAuthorization.layer([AuthSettingsWriteScope]),
),
),
);
expect(
yield* client[WS_METHODS.serverUpdateSettings]({
patch: {},
providerInstanceMutation,
}).pipe(Effect.flip),
).toMatchObject({ requiredScope: AuthProvidersManageScope });
expect(handled).toBe(false);
}).pipe(Effect.scoped),
);
});
+64 -43
View File
@@ -1,6 +1,13 @@
import {
CLIENT_GUARDED_RPC_SCOPES,
type DeviceListInput,
AuthAccessReadScope,
ServerSettingsPatch,
ProviderInstanceMutation,
requiredScopesForServerSettingsPatch,
AuthSettingsWriteScope,
AuthProvidersManageScope,
AuthEnvironmentMaintainScope,
AuthOrchestrationOperateScope,
AuthOrchestrationReadScope,
AuthRelayReadScope,
@@ -15,6 +22,7 @@ import {
WsRpcGroup,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import * as Layer from "effect/Layer";
import type * as RpcGroup from "effect/rpc/RpcGroup";
@@ -26,6 +34,7 @@ type WsRpcMethod = RpcGroup.Rpcs<typeof WsRpcGroup>["_tag"];
* runtime failure.
*/
export const RPC_REQUIRED_SCOPES = {
...CLIENT_GUARDED_RPC_SCOPES,
[ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: AuthOrchestrationOperateScope,
[ORCHESTRATION_V2_WS_METHODS.getWorkflowScript]: AuthOrchestrationReadScope,
[ORCHESTRATION_V2_WS_METHODS.getTurnDiff]: AuthOrchestrationReadScope,
@@ -41,61 +50,56 @@ export const RPC_REQUIRED_SCOPES = {
[WS_METHODS.projectsMutate]: AuthOrchestrationOperateScope,
[WS_METHODS.serverProbe]: AuthOrchestrationReadScope,
[WS_METHODS.serverGetConfig]: AuthOrchestrationReadScope,
[WS_METHODS.serverRefreshProviders]: AuthOrchestrationOperateScope,
[WS_METHODS.serverUpdateProvider]: AuthOrchestrationOperateScope,
[WS_METHODS.providerAuthStart]: AuthOrchestrationOperateScope,
[WS_METHODS.providerConsumeResetCredit]: AuthOrchestrationOperateScope,
[WS_METHODS.providerAuthComplete]: AuthOrchestrationOperateScope,
[WS_METHODS.chatGptReconnectProfile]: AuthOrchestrationOperateScope,
[WS_METHODS.chatGptImportProfile]: AuthOrchestrationOperateScope,
[WS_METHODS.chatGptHandoffSubscribe]: AuthOrchestrationOperateScope,
[WS_METHODS.codexAuthCallbackSubscribe]: AuthOrchestrationOperateScope,
[WS_METHODS.providerAuthRespond]: AuthOrchestrationOperateScope,
[WS_METHODS.providerAuthCancel]: AuthOrchestrationOperateScope,
[WS_METHODS.providerAuthLogout]: AuthOrchestrationOperateScope,
[WS_METHODS.providerAuthSubscribe]: AuthOrchestrationOperateScope,
[WS_METHODS.providerInstallStart]: AuthOrchestrationOperateScope,
[WS_METHODS.providerInstallCancel]: AuthOrchestrationOperateScope,
[WS_METHODS.serverRefreshProviders]: AuthOrchestrationReadScope,
[WS_METHODS.serverUpdateProvider]: AuthProvidersManageScope,
[WS_METHODS.providerAuthStart]: AuthProvidersManageScope,
[WS_METHODS.providerConsumeResetCredit]: AuthProvidersManageScope,
[WS_METHODS.providerAuthComplete]: AuthProvidersManageScope,
[WS_METHODS.chatGptReconnectProfile]: AuthProvidersManageScope,
[WS_METHODS.chatGptImportProfile]: AuthProvidersManageScope,
[WS_METHODS.chatGptHandoffSubscribe]: AuthProvidersManageScope,
[WS_METHODS.codexAuthCallbackSubscribe]: AuthProvidersManageScope,
[WS_METHODS.providerAuthRespond]: AuthProvidersManageScope,
[WS_METHODS.providerAuthCancel]: AuthProvidersManageScope,
[WS_METHODS.providerAuthLogout]: AuthProvidersManageScope,
[WS_METHODS.providerAuthSubscribe]: AuthProvidersManageScope,
[WS_METHODS.providerInstallStart]: AuthProvidersManageScope,
[WS_METHODS.providerInstallCancel]: AuthProvidersManageScope,
[WS_METHODS.providerInstallSubscribe]: AuthOrchestrationReadScope,
[WS_METHODS.providerInstallRemove]: AuthOrchestrationOperateScope,
[WS_METHODS.serverUpdateServer]: AuthOrchestrationOperateScope,
[WS_METHODS.serverUpdateServerWithProgress]: AuthOrchestrationOperateScope,
[WS_METHODS.serverCommitDesktopUpdate]: AuthOrchestrationOperateScope,
[WS_METHODS.serverUpsertKeybinding]: AuthOrchestrationOperateScope,
[WS_METHODS.serverRemoveKeybinding]: AuthOrchestrationOperateScope,
[WS_METHODS.providerInstallRemove]: AuthProvidersManageScope,
[WS_METHODS.serverUpdateServer]: AuthEnvironmentMaintainScope,
[WS_METHODS.serverUpdateServerWithProgress]: AuthEnvironmentMaintainScope,
[WS_METHODS.serverCommitDesktopUpdate]: AuthEnvironmentMaintainScope,
[WS_METHODS.serverUpsertKeybinding]: AuthSettingsWriteScope,
[WS_METHODS.serverRemoveKeybinding]: AuthSettingsWriteScope,
[WS_METHODS.serverGetSettings]: AuthOrchestrationReadScope,
[WS_METHODS.serverUpdateSettings]: AuthOrchestrationOperateScope,
[WS_METHODS.serverUpdateSettings]: AuthSettingsWriteScope,
[WS_METHODS.serverSearchAcpRegistry]: AuthOrchestrationReadScope,
[WS_METHODS.serverPrepareAcpRegistryAgent]: AuthOrchestrationOperateScope,
[WS_METHODS.serverUninstallAcpRegistryManagedBinary]: AuthOrchestrationOperateScope,
[WS_METHODS.serverAcceptAcpRegistryUrlAuth]: AuthOrchestrationOperateScope,
[WS_METHODS.serverPrepareAcpRegistryAgent]: AuthProvidersManageScope,
[WS_METHODS.serverUninstallAcpRegistryManagedBinary]: AuthProvidersManageScope,
[WS_METHODS.serverAcceptAcpRegistryUrlAuth]: AuthProvidersManageScope,
[WS_METHODS.serverListAcpRegistrySessions]: AuthOrchestrationReadScope,
[WS_METHODS.serverImportAcpRegistrySession]: AuthOrchestrationOperateScope,
[WS_METHODS.serverDeleteAcpRegistrySession]: AuthOrchestrationOperateScope,
[WS_METHODS.serverListAcpRegistryProviders]: AuthOrchestrationReadScope,
[WS_METHODS.serverSetAcpRegistryProvider]: AuthOrchestrationOperateScope,
[WS_METHODS.serverDisableAcpRegistryProvider]: AuthOrchestrationOperateScope,
[WS_METHODS.serverLogoutAcpRegistry]: AuthOrchestrationOperateScope,
[WS_METHODS.serverSetAcpRegistryProvider]: AuthProvidersManageScope,
[WS_METHODS.serverDisableAcpRegistryProvider]: AuthProvidersManageScope,
[WS_METHODS.serverLogoutAcpRegistry]: AuthProvidersManageScope,
[WS_METHODS.serverDiscoverSourceControl]: AuthOrchestrationReadScope,
[WS_METHODS.serverGetTraceDiagnostics]: AuthOrchestrationReadScope,
[WS_METHODS.serverGetProcessDiagnostics]: AuthOrchestrationReadScope,
[WS_METHODS.serverGetHostResources]: AuthOrchestrationReadScope,
[WS_METHODS.serverGetProcessResourceHistory]: AuthOrchestrationReadScope,
[WS_METHODS.serverGetResourceTelemetryHistory]: AuthOrchestrationReadScope,
[WS_METHODS.serverRetryResourceTelemetry]: AuthOrchestrationOperateScope,
[WS_METHODS.serverRetryResourceTelemetry]: AuthEnvironmentMaintainScope,
[WS_METHODS.serverGetUsageSummary]: AuthOrchestrationReadScope,
[WS_METHODS.serverRefreshUsageRates]: AuthOrchestrationReadScope,
[WS_METHODS.serverSignalProcess]: AuthOrchestrationOperateScope,
[WS_METHODS.serverSignalProcess]: AuthEnvironmentMaintainScope,
[WS_METHODS.serverReportClientActivity]: AuthOrchestrationReadScope,
[WS_METHODS.serverReportHostPowerState]: AuthOrchestrationOperateScope,
[WS_METHODS.serverReportHostPowerState]: AuthEnvironmentMaintainScope,
[WS_METHODS.serverGetBackgroundPolicy]: AuthOrchestrationReadScope,
[WS_METHODS.scheduledTasksList]: AuthOrchestrationReadScope,
[WS_METHODS.scheduledTasksSubscribe]: AuthOrchestrationReadScope,
[WS_METHODS.scheduledTasksUpsert]: AuthOrchestrationOperateScope,
[WS_METHODS.scheduledTasksSetEnabled]: AuthOrchestrationOperateScope,
[WS_METHODS.scheduledTasksDelete]: AuthOrchestrationOperateScope,
[WS_METHODS.scheduledTasksRunNow]: AuthOrchestrationOperateScope,
[WS_METHODS.scheduledTasksRotateWebhookToken]: AuthOrchestrationOperateScope,
[WS_METHODS.secretsAnswerRequest]: AuthOrchestrationOperateScope,
// Delivery logs hold request bodies, so they need the same scope as the URL.
[WS_METHODS.scheduledTasksListWebhookDeliveries]: AuthOrchestrationOperateScope,
@@ -195,8 +199,8 @@ export const RPC_REQUIRED_SCOPES = {
[WS_METHODS.previewReportStatus]: AuthOrchestrationOperateScope,
[WS_METHODS.subscribePreviewEvents]: AuthOrchestrationReadScope,
[WS_METHODS.subscribeDiscoveredLocalServers]: AuthOrchestrationReadScope,
[WS_METHODS.deviceConfigure]: AuthOrchestrationOperateScope,
[WS_METHODS.deviceTestHost]: AuthOrchestrationOperateScope,
[WS_METHODS.deviceConfigure]: AuthSettingsWriteScope,
[WS_METHODS.deviceTestHost]: AuthSettingsWriteScope,
[WS_METHODS.deviceList]: AuthOrchestrationReadScope,
[WS_METHODS.deviceOpen]: AuthOrchestrationOperateScope,
[WS_METHODS.deviceClose]: AuthOrchestrationOperateScope,
@@ -227,13 +231,30 @@ export const rpcAuthorizationError = (requiredScope: AuthEnvironmentScope) =>
requiredScope,
});
const SettingsUpdate = Schema.Struct({
patch: ServerSettingsPatch,
providerInstanceMutation: Schema.optionalKey(ProviderInstanceMutation),
});
const requiredScopesForSettingsUpdate = (payload: unknown) => {
const input = Schema.decodeUnknownSync(SettingsUpdate)(payload);
const scopes = requiredScopesForServerSettingsPatch(input.patch);
if (input.providerInstanceMutation === undefined) return scopes;
// An atomic provider mutation carries an empty patch unless it also changes settings.
return Object.values(input.patch).every((value) => value === undefined)
? [AuthProvidersManageScope]
: [...new Set([...scopes, AuthProvidersManageScope])];
};
/** Authorizes every RPC on one connection against that connection's session scopes. */
export const layer = (scopes: ReadonlyArray<AuthEnvironmentScope>) =>
Layer.succeed(RpcScopeAuthorization)((effect, { rpc }) => {
const requiredScope = requiredScopeForRpcMethod(rpc._tag);
return scopes.includes(requiredScope)
? effect
: Effect.fail(rpcAuthorizationError(requiredScope));
Layer.succeed(RpcScopeAuthorization)((effect, { rpc, payload }) => {
const requiredScopes =
rpc._tag === WS_METHODS.serverUpdateSettings
? requiredScopesForSettingsUpdate(payload)
: [requiredScopeForRpcMethod(rpc._tag)];
const requiredScope = requiredScopes.find((scope) => !scopes.includes(scope));
return requiredScope === undefined ? effect : Effect.fail(rpcAuthorizationError(requiredScope));
});
/** Retrying can install or restart tools even though ordinary listing is readable. */
+2 -8
View File
@@ -1,5 +1,5 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { EnvironmentId } from "@t3tools/contracts";
import { AuthStandardClientScopes, EnvironmentId } from "@t3tools/contracts";
import { expect, it } from "@effect/vitest";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
@@ -346,13 +346,7 @@ it.layer(NodeServices.layer)("SessionStore.layer", (it) => {
expect(verified.method).toBe("bearer-access-token");
expect(verified.subject).toBe("test-clock");
expect(verified.scopes).toEqual([
"orchestration:read",
"orchestration:operate",
"terminal:operate",
"review:write",
"relay:read",
]);
expect(verified.scopes).toEqual(AuthStandardClientScopes);
}).pipe(Effect.provide(Layer.merge(layerSessionStore(), TestClock.layer()))),
);
+6
View File
@@ -2,6 +2,9 @@ import {
AuthAccessReadScope,
AuthAccessWriteScope,
AuthStandardClientScopes,
AuthSettingsWriteScope,
AuthProvidersManageScope,
AuthEnvironmentMaintainScope,
AuthOrchestrationOperateScope,
AuthOrchestrationReadScope,
AuthRelayReadScope,
@@ -366,6 +369,9 @@ export const layer = HttpApiBuilder.group(
allowedScopes: new Set<AuthEnvironmentScope>([
AuthOrchestrationReadScope,
AuthOrchestrationOperateScope,
AuthSettingsWriteScope,
AuthProvidersManageScope,
AuthEnvironmentMaintainScope,
AuthTerminalOperateScope,
AuthReviewWriteScope,
AuthAccessReadScope,
@@ -1,6 +1,6 @@
import { assert, describe, it } from "@effect/vitest";
import {
AuthOrchestrationOperateScope,
AuthEnvironmentMaintainScope,
AuthOrchestrationReadScope,
type AuthEnvironmentScope,
ScheduledTaskError,
@@ -319,7 +319,7 @@ describe("WS RPC instrumentation middleware", () => {
message: Option.none(),
}).pipe(Effect.withSpan("signalProcess.child")),
),
connectionMiddleware([AuthOrchestrationReadScope, AuthOrchestrationOperateScope]),
connectionMiddleware([AuthOrchestrationReadScope, AuthEnvironmentMaintainScope]),
),
),
);
@@ -2,7 +2,7 @@ import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import * as CodexInstallation from "./CodexInstallation.ts";
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { describe, it, assert } from "@effect/vitest";
import { describe, it, assert, expect } from "@effect/vitest";
import * as DateTime from "effect/DateTime";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
@@ -2077,6 +2077,98 @@ it.layer(
]);
});
it.effect("shares one in-flight pass between concurrent untargeted refreshes", () =>
Effect.gen(function* () {
const driver = ProviderDriverKind.make("codex");
const instanceId = ProviderInstanceId.make("codex");
const provider = {
instanceId,
driver,
status: "ready",
enabled: true,
installed: true,
auth: { status: "authenticated" },
checkedAt: "2026-06-10T00:00:00.000Z",
version: "1.0.0",
models: [],
slashCommands: [],
skills: [],
} as const satisfies ServerProvider;
const refreshCalls = yield* Ref.make(0);
const probeStarted = yield* Deferred.make<void>();
const releaseProbe = yield* Deferred.make<void>();
const instances = [
{
instanceId,
driverKind: driver,
continuationIdentity: { driverKind: driver, continuationKey: "codex:instance:codex" },
displayName: undefined,
enabled: true,
snapshot: {
resolveMaintenance: () =>
Effect.succeed(
makeManualOnlyProviderMaintenanceCapabilities({
provider: driver,
packageName: null,
}),
),
getSnapshot: Effect.succeed(provider),
refresh: Effect.gen(function* () {
yield* Ref.update(refreshCalls, (count) => count + 1);
yield* Deferred.succeed(probeStarted, undefined);
yield* Deferred.await(releaseProbe);
return provider;
}),
streamChanges: Stream.empty,
applyUsageLimits: () => Effect.void,
},
orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"],
textGeneration: {} as ProviderInstance["textGeneration"],
},
] satisfies ReadonlyArray<ProviderInstance>;
const instanceRegistryLayer = Layer.succeed(
ProviderInstanceRegistry.ProviderInstanceRegistry,
{
getInstance: (requestedId) =>
Effect.succeed(instances.find((instance) => instance.instanceId === requestedId)),
listInstances: Effect.succeed(instances),
listUnavailable: Effect.succeed([]),
streamChanges: Stream.empty,
subscribeChanges: Effect.flatMap(PubSub.unbounded<void>(), PubSub.subscribe),
},
);
const scope = yield* Scope.make();
yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
const runtimeServices = yield* Layer.build(
ProviderRegistry.layer.pipe(
Layer.provideMerge(instanceRegistryLayer),
Layer.provideMerge(
ServerConfig.layerTest(process.cwd(), {
prefix: "t3-provider-registry-shared-refresh-",
}),
),
Layer.provideMerge(NodeServices.layer),
),
).pipe(Scope.provide(scope));
yield* Effect.gen(function* () {
const registry = yield* ProviderRegistry.ProviderRegistry;
const first = yield* registry.refresh().pipe(Effect.forkChild);
yield* Deferred.await(probeStarted);
const second = yield* registry.refresh().pipe(Effect.forkChild);
yield* Effect.yieldNow;
assert.strictEqual(yield* Ref.get(refreshCalls), 1);
yield* Deferred.succeed(releaseProbe, undefined);
expect(yield* Fiber.join(first)).toEqual([expect.objectContaining(provider)]);
expect(yield* Fiber.join(second)).toEqual([expect.objectContaining(provider)]);
assert.strictEqual(yield* Ref.get(refreshCalls), 1);
yield* registry.refresh();
assert.strictEqual(yield* Ref.get(refreshCalls), 2);
}).pipe(Effect.provide(runtimeServices));
}),
);
it.effect("persists the merged snapshot when a live update has empty models", () =>
Effect.gen(function* () {
const cursorDriver = ProviderDriverKind.make("cursor");
+45 -5
View File
@@ -36,10 +36,12 @@ import {
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as Context from "effect/Context";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Equal from "effect/Equal";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as PubSub from "effect/PubSub";
import * as Ref from "effect/Ref";
@@ -701,12 +703,50 @@ export const layer = Layer.effect(
);
});
type RefreshAllCompletion = Deferred.Deferred<ReadonlyArray<ServerProvider>>;
const refreshAllInFlightRef = yield* Ref.make<Option.Option<RefreshAllCompletion>>(
Option.none(),
);
// Untargeted refreshes probe every live source, so any read-scoped client
// can request them. Concurrent callers share one in-flight pass instead of
// each starting their own set of provider processes.
const refreshAll = Effect.fn("refreshAll")(function* () {
const sources = yield* getLiveSources;
return yield* Effect.forEach(sources, (source) => refreshOneSource(source), {
concurrency: "unbounded",
discard: true,
}).pipe(Effect.andThen(Ref.get(providersRef)));
const claimed = yield* Ref.modify(
refreshAllInFlightRef,
(
inFlight,
): readonly [
{ readonly owner: boolean; readonly completion: RefreshAllCompletion },
Option.Option<RefreshAllCompletion>,
] => {
if (Option.isSome(inFlight)) {
return [{ owner: false, completion: inFlight.value }, inFlight];
}
const completion = Deferred.makeUnsafe<ReadonlyArray<ServerProvider>>();
return [{ owner: true, completion }, Option.some(completion)];
},
);
if (claimed.owner) {
// Detached so an interrupted first caller cannot cancel the pass that
// other callers are already awaiting.
yield* getLiveSources.pipe(
Effect.flatMap((sources) =>
Effect.forEach(sources, (source) => refreshOneSource(source), {
concurrency: "unbounded",
discard: true,
}),
),
Effect.andThen(Ref.get(providersRef)),
Effect.onExit((exit) =>
Ref.set(refreshAllInFlightRef, Option.none()).pipe(
Effect.andThen(Deferred.done(claimed.completion, exit)),
),
),
Effect.forkDetach,
);
}
return yield* Deferred.await(claimed.completion);
});
const refresh = Effect.fn("refresh")(function* (provider?: ProviderDriverKind) {
+85
View File
@@ -686,6 +686,91 @@ it.layer(NodeServices.layer)("server settings", (it) => {
}).pipe(Effect.provide(layerServerSettings())),
);
// Only driver-keyed instances are fallback candidates; a custom instance id
// is not one, so the selection stays put until the user changes it.
it.effect.each(["codex"])(
"falls back to enabled instance %s after disabling the selection",
(fallbackId) =>
Effect.scoped(
Effect.gen(function* () {
const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
const serverConfig = yield* ServerConfig.ServerConfig;
const fileSystem = yield* FileSystem.FileSystem;
const writerId = ProviderInstanceId.make("writer");
const fallbackInstanceId = ProviderInstanceId.make(fallbackId);
const selection = { instanceId: writerId, model: "claude-sonnet-4-6" };
const providerInstances = {
[fallbackInstanceId]: {
driver: ProviderDriverKind.make("codex"),
enabled: true,
config: {},
},
[writerId]: {
driver: ProviderDriverKind.make("claudeAgent"),
enabled: true,
config: {},
},
};
yield* serverSettings.updateSettings({
providers: Object.fromEntries(
Object.keys(DEFAULT_SERVER_SETTINGS.providers).map(
(provider) => [provider, { enabled: false }] as const,
),
),
providerInstances,
textGenerationModelSelection: selection,
});
const changes = yield* serverSettings.subscribeChanges;
const next = yield* serverSettings.updateSettings({
providerInstances: {
...providerInstances,
[writerId]: { ...providerInstances[writerId]!, enabled: false },
},
});
const fallbackSelection = {
instanceId: fallbackInstanceId,
model: DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.model,
};
assert.deepEqual(next.textGenerationModelSelection, fallbackSelection);
assert.deepEqual(
(yield* serverSettings.getSettings).textGenerationModelSelection,
fallbackSelection,
);
const change = Option.getOrUndefined(yield* Stream.runHead(changes));
assert.deepEqual(change?.textGenerationModelSelection, fallbackSelection);
const persisted = yield* fileSystem
.readFileString(serverConfig.settingsPath)
.pipe(
Effect.flatMap(Schema.decodeUnknownEffect(Schema.fromJsonString(ServerSettings))),
);
assert.deepEqual(persisted.textGenerationModelSelection, selection);
const restored = yield* serverSettings.updateSettings({ providerInstances });
assert.deepEqual(restored.textGenerationModelSelection, selection);
}),
).pipe(Effect.provide(layerServerSettings())),
);
it.effect("skips explicitly disabled instances when choosing a legacy fallback", () =>
Effect.gen(function* () {
const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
const next = yield* serverSettings.updateSettings({
providerInstances: {
[ProviderInstanceId.make("codex")]: {
driver: ProviderDriverKind.make("codex"),
enabled: false,
config: {},
},
},
});
assert.equal(next.textGenerationModelSelection.instanceId, "claudeAgent");
}).pipe(Effect.provide(layerServerSettings())),
);
it.effect("preserves enabled text generation selections for non-built-in drivers", () =>
Effect.gen(function* () {
const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
+20 -4
View File
@@ -1,5 +1,9 @@
import { useAtomValue } from "@effect/atom-react";
import type { EnvironmentCloudLinkStateResult } from "@t3tools/contracts";
import {
AuthRelayReadScope,
EnvironmentId,
type EnvironmentCloudLinkStateResult,
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
@@ -12,6 +16,7 @@ import { useCallback, useMemo } from "react";
import { usePrimaryEnvironment } from "../state/environments";
import { runtime } from "../lib/runtime";
import { appAtomRegistry } from "../rpc/atomRegistry";
import { readEnvironmentScope, useEnvironmentScope } from "../state/session";
import { readPrimaryCloudLinkState, type CloudLinkTarget } from "./linkEnvironment";
import { hasCloudPublicConfig } from "./publicConfig";
@@ -44,13 +49,24 @@ function targetKey(target: CloudLinkTarget): string {
}
function refreshPrimaryCloudLinkState(target: CloudLinkTarget | null): void {
if (target) {
if (
target &&
readEnvironmentScope(EnvironmentId.make(target.environmentId), AuthRelayReadScope)
) {
appAtomRegistry.refresh(primaryCloudLinkStateAtom(targetKey(target)));
}
}
export function readCachedPrimaryCloudLinkState(target: CloudLinkTarget) {
if (!readEnvironmentScope(EnvironmentId.make(target.environmentId), AuthRelayReadScope))
return null;
const result = appAtomRegistry.get(primaryCloudLinkStateAtom(targetKey(target)));
return result._tag === "Success" ? result.value : null;
}
export function usePrimaryCloudLinkState() {
const primary = usePrimaryEnvironment();
const canReadRelay = useEnvironmentScope(primary?.environmentId ?? null, AuthRelayReadScope);
const target = useMemo(
() =>
primary?.entry.target._tag === "PrimaryConnectionTarget"
@@ -65,7 +81,7 @@ export function usePrimaryCloudLinkState() {
);
// Builds without T3 Connect have no link to read; skip the request.
const atom =
target && hasCloudPublicConfig()
target && hasCloudPublicConfig() && canReadRelay
? primaryCloudLinkStateAtom(targetKey(target))
: EMPTY_PRIMARY_CLOUD_LINK_STATE_ATOM;
const result = useAtomValue(atom);
@@ -79,7 +95,7 @@ export function usePrimaryCloudLinkState() {
}
return {
data: Option.getOrNull(AsyncResult.value(result)),
data: result._tag === "Failure" ? null : Option.getOrNull(AsyncResult.value(result)),
error,
isPending: result.waiting,
refresh,
@@ -0,0 +1,230 @@
import {
AuthRelayReadScope,
AuthRelayWriteScope,
EnvironmentId,
type EnvironmentCloudLinkStateResult,
} from "@t3tools/contracts";
import { AsyncResult } from "effect/reactivity";
import { act, useLayoutEffect } from "react";
import { create, type ReactTestRenderer } from "react-test-renderer";
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
const testState = vi.hoisted(() => ({
scopes: new Set<string>(),
snapshot: null as EnvironmentCloudLinkStateResult | null,
renderedSnapshot: null as EnvironmentCloudLinkStateResult | null,
getToken: vi.fn<() => Promise<string | null>>(),
link: vi.fn(),
unlink: vi.fn(),
preferences: vi.fn(),
refreshDiscovery: vi.fn(),
refreshLink: vi.fn(),
toast: vi.fn(),
}));
vi.mock("@clerk/react", () => ({
useAuth: () => ({ getToken: testState.getToken, isSignedIn: true }),
}));
vi.mock("../components/ui/toast", () => ({ toastManager: { add: testState.toast } }));
vi.mock("../state/relay", () => ({
relayEnvironmentDiscovery: { refresh: testState.refreshDiscovery },
}));
vi.mock("../state/session", () => ({
readEnvironmentScope: (_environmentId: string, scope: string) => testState.scopes.has(scope),
}));
vi.mock("../state/use-atom-command", () => ({ useAtomCommand: (command: unknown) => command }));
vi.mock("./linkEnvironmentAtoms", () => ({
linkPrimaryEnvironment: testState.link,
unlinkPrimaryEnvironment: testState.unlink,
updatePrimaryEnvironmentPreferences: testState.preferences,
}));
vi.mock("./primaryCloudLinkState", () => ({
readCachedPrimaryCloudLinkState: () => testState.snapshot,
usePrimaryCloudLinkState: () => ({
target,
data: testState.renderedSnapshot,
error: null,
isPending: false,
refresh: testState.refreshLink,
}),
}));
vi.mock("./publicConfig", () => ({ resolveRelayClerkTokenOptions: () => ({}) }));
import { useCloudLinkController, type CloudLinkDesiredState } from "./useCloudLinkController";
const target = {
environmentId: EnvironmentId.make("primary"),
label: "Primary",
httpBaseUrl: "http://localhost:3773",
wsBaseUrl: "ws://localhost:3773/ws",
};
const linkedState: EnvironmentCloudLinkStateResult = {
linked: true,
cloudUserId: "account-1",
relayUrl: "https://relay.example.com",
relayIssuer: "https://relay.example.com",
managedTunnelActive: true,
publishAgentActivity: false,
};
let renderer: ReactTestRenderer | null = null;
let controller: ReturnType<typeof useCloudLinkController> | null = null;
function ControllerProbe() {
const value = useCloudLinkController();
useLayoutEffect(() => {
controller = value;
});
return null;
}
async function mountController() {
await act(() => {
renderer = create(<ControllerProbe />);
});
}
async function reconcile(desired: CloudLinkDesiredState) {
let succeeded = false;
await act(async () => {
if (controller === null) throw new Error("Controller is not mounted.");
succeeded = await controller.reconcileCloudState(desired);
});
return succeeded;
}
function expectNoMutations() {
expect(testState.link).not.toHaveBeenCalled();
expect(testState.unlink).not.toHaveBeenCalled();
expect(testState.preferences).not.toHaveBeenCalled();
}
beforeEach(() => {
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
vi.spyOn(console, "error").mockImplementation(() => undefined);
testState.scopes = new Set([AuthRelayReadScope, AuthRelayWriteScope]);
testState.snapshot = linkedState;
testState.renderedSnapshot = linkedState;
testState.getToken.mockReset().mockResolvedValue("clerk-token");
for (const command of [
testState.link,
testState.unlink,
testState.preferences,
testState.refreshDiscovery,
]) {
command.mockReset().mockResolvedValue(AsyncResult.success({}));
}
testState.refreshLink.mockReset();
testState.toast.mockReset();
});
afterEach(async () => {
await act(() => renderer?.unmount());
renderer = null;
controller = null;
vi.restoreAllMocks();
vi.unstubAllGlobals();
});
describe("useCloudLinkController", () => {
it.each([AuthRelayReadScope, AuthRelayWriteScope])(
"does not mutate without %s, even with a cached link snapshot",
async (scope) => {
await mountController();
testState.scopes.delete(scope);
expect(await reconcile({ managedTunnel: true, publish: true })).toBe(false);
expect(testState.getToken).not.toHaveBeenCalled();
expectNoMutations();
},
);
it("does not interpret unavailable link state as an unlinked environment", async () => {
testState.snapshot = null;
await mountController();
expect(await reconcile({ managedTunnel: false, publish: true })).toBe(false);
expect(testState.getToken).not.toHaveBeenCalled();
expectNoMutations();
});
it.each([AuthRelayReadScope, AuthRelayWriteScope])(
"rechecks %s after requesting the cloud token",
async (scope) => {
await mountController();
testState.getToken.mockImplementationOnce(async () => {
testState.scopes.delete(scope);
return "clerk-token";
});
expect(await reconcile({ managedTunnel: false, publish: false })).toBe(false);
expectNoMutations();
},
);
it("stops if the link-state read fails while requesting the cloud token", async () => {
await mountController();
testState.getToken.mockImplementationOnce(async () => {
testState.snapshot = null;
return "clerk-token";
});
expect(await reconcile({ managedTunnel: true, publish: true })).toBe(false);
expectNoMutations();
});
it("uses the latest linked mode to change publishing without replacing the tunnel", async () => {
testState.snapshot = { ...linkedState, linked: false, managedTunnelActive: false };
testState.renderedSnapshot = testState.snapshot;
await mountController();
testState.getToken.mockImplementationOnce(async () => {
testState.snapshot = linkedState;
return "clerk-token";
});
expect(await reconcile({ managedTunnel: true, publish: true })).toBe(true);
expect(testState.link).not.toHaveBeenCalled();
expect(testState.unlink).not.toHaveBeenCalled();
expect(testState.preferences).toHaveBeenCalledExactlyOnceWith({
target,
publishAgentActivity: true,
});
});
it("stops the preference write if management permission is lost after linking", async () => {
await mountController();
testState.link.mockImplementationOnce(async () => {
testState.scopes.delete(AuthRelayWriteScope);
return AsyncResult.success({});
});
expect(await reconcile({ managedTunnel: false, publish: true })).toBe(false);
expect(testState.link).toHaveBeenCalledOnce();
expect(testState.preferences).not.toHaveBeenCalled();
expect(testState.refreshLink).toHaveBeenCalledOnce();
});
it("still lets an authorized user unlink when the cloud token is unavailable", async () => {
await mountController();
testState.getToken.mockRejectedValueOnce(new Error("Cloud sign-in unavailable"));
expect(await reconcile({ managedTunnel: false, publish: false })).toBe(true);
expect(testState.unlink).toHaveBeenCalledExactlyOnceWith({ target, clerkToken: null });
expect(testState.link).not.toHaveBeenCalled();
expect(testState.preferences).not.toHaveBeenCalled();
});
it("unlinks if the link-state read fails while requesting the cloud token", async () => {
await mountController();
testState.getToken.mockImplementationOnce(async () => {
testState.snapshot = null;
throw new Error("Cloud sign-in unavailable");
});
expect(await reconcile({ managedTunnel: false, publish: false })).toBe(true);
expect(testState.unlink).toHaveBeenCalledExactlyOnceWith({ target, clerkToken: null });
expect(testState.link).not.toHaveBeenCalled();
expect(testState.preferences).not.toHaveBeenCalled();
expect(testState.refreshLink).toHaveBeenCalledOnce();
});
});
+35 -3
View File
@@ -1,5 +1,6 @@
import { useAuth } from "@clerk/react";
import { findErrorTraceId } from "@t3tools/client-runtime/errors";
import { EnvironmentId, AuthRelayReadScope, AuthRelayWriteScope } from "@t3tools/contracts";
import {
isAtomCommandInterrupted,
settlePromise,
@@ -9,13 +10,14 @@ import { useState } from "react";
import { toastManager } from "../components/ui/toast";
import { relayEnvironmentDiscovery } from "../state/relay";
import { readEnvironmentScope } from "../state/session";
import { useAtomCommand } from "../state/use-atom-command";
import {
linkPrimaryEnvironment as linkPrimaryEnvironmentAtom,
unlinkPrimaryEnvironment as unlinkPrimaryEnvironmentAtom,
updatePrimaryEnvironmentPreferences as updatePrimaryEnvironmentPreferencesAtom,
} from "./linkEnvironmentAtoms";
import { usePrimaryCloudLinkState } from "./primaryCloudLinkState";
import { readCachedPrimaryCloudLinkState, usePrimaryCloudLinkState } from "./primaryCloudLinkState";
import { resolveRelayClerkTokenOptions } from "./publicConfig";
export interface CloudLinkDesiredState {
@@ -87,8 +89,31 @@ export function useCloudLinkController() {
reportUpdateFailure(new Error("Local environment is not ready yet."));
return false;
}
const tokenResult = await settlePromise(() => getToken(resolveRelayClerkTokenOptions()));
const environmentId = EnvironmentId.make(target.environmentId);
const canManageLink = () => {
if (
!readEnvironmentScope(environmentId, AuthRelayReadScope) ||
!readEnvironmentScope(environmentId, AuthRelayWriteScope)
) {
reportUpdateFailure(
new Error("This connection needs permission to view and manage T3 Connect settings."),
);
return false;
}
return true;
};
const readLinkState = () => {
const state = readCachedPrimaryCloudLinkState(target);
if (state === null) {
reportUpdateFailure(new Error("Wait until the current T3 Connect settings can be read."));
}
return state;
};
if (!canManageLink()) return false;
const wantsLink = desired.managedTunnel || desired.publish;
if (wantsLink && readLinkState() === null) return false;
const tokenResult = await settlePromise(() => getToken(resolveRelayClerkTokenOptions()));
if (!canManageLink()) return false;
// A failure after this point may follow a partially applied mutation (e.g.
// the link succeeded but the preference update did not), so every exit —
@@ -109,6 +134,8 @@ export function useCloudLinkController() {
return false;
}
} else {
const currentLinkState = readLinkState();
if (currentLinkState === null) return false;
if (tokenResult._tag === "Failure") {
reportUpdateFailure(squashAtomCommandFailure(tokenResult));
return false;
@@ -118,7 +145,8 @@ export function useCloudLinkController() {
reportUpdateFailure(new Error("Sign in to T3 Connect before enabling this."));
return false;
}
if (!linked || managedTunnelActive !== desired.managedTunnel) {
const currentManagedTunnel = currentLinkState.managedTunnelActive ?? currentLinkState.linked;
if (!currentLinkState.linked || currentManagedTunnel !== desired.managedTunnel) {
const linkResult = await linkPrimaryEnvironment({
target,
clerkToken,
@@ -132,6 +160,10 @@ export function useCloudLinkController() {
return false;
}
}
if (!canManageLink() || readLinkState() === null) {
primaryCloudLinkState.refresh();
return false;
}
const prefResult = await updatePrimaryEnvironmentPreferences({
target,
publishAgentActivity: desired.publish,
@@ -0,0 +1,299 @@
import {
AuthOrchestrationOperateScope,
EnvironmentId,
ProjectId,
ThreadId,
type AuthEnvironmentScope,
type EditorId,
type ThreadLinkedPullRequest,
} from "@t3tools/contracts";
import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings";
import { AsyncResult } from "effect/reactivity";
import { cloneElement, type ReactElement, 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(() => ({
allowed: true,
listeners: new Set<() => void>(),
openEditor: vi.fn(),
updateMetadata: vi.fn(),
search: vi.fn(),
choose: vi.fn(),
openFile: vi.fn(),
openExternal: vi.fn(),
copy: vi.fn(),
toast: vi.fn(),
linkedPullRequest: null as ThreadLinkedPullRequest | null,
}));
vi.mock("@effect/atom-react", () => ({ useAtomValue: () => serverConfig }));
vi.mock("../hooks/useTheme", () => ({ useTheme: () => ({ resolvedTheme: "dark" }) }));
vi.mock("../hooks/useSettings", () => ({
getClientSettings: () => DEFAULT_CLIENT_SETTINGS,
useClientSettings: (select?: (value: typeof DEFAULT_CLIENT_SETTINGS) => unknown) =>
select ? select(DEFAULT_CLIENT_SETTINGS) : DEFAULT_CLIENT_SETTINGS,
}));
vi.mock("./ui/tooltip", () => ({
Tooltip: ({ children }: { children: ReactNode }) => children,
TooltipTrigger: ({ render, children }: { render: ReactElement; children?: ReactNode }) =>
children === undefined ? render : cloneElement(render, undefined, children),
TooltipPopup: () => null,
}));
vi.mock("./chat/PierreEntryIcon", () => ({ PierreEntryIcon: () => null }));
vi.mock("./ui/toast", () => ({
toastManager: { add: state.toast },
stackedThreadToast: (value: unknown) => value,
}));
vi.mock("../state/use-atom-query-runner", () => ({ useAtomQueryRunner: () => state.search }));
vi.mock("../state/use-atom-command", () => ({
useAtomCommand: (command: string) =>
command === "updateMetadata" ? state.updateMetadata : state.openEditor,
}));
vi.mock("../state/session", async () => {
const { useSyncExternalStore } = await import("react");
const readEnvironmentScope = (id: EnvironmentId | null, scope: AuthEnvironmentScope) =>
id !== null &&
(scope !== AuthOrchestrationOperateScope || id !== threadRef.environmentId || state.allowed);
return {
// Asset atoms read these at module scope; the markdown tests only exercise
// the task grant.
environmentSession: {
sessionStateAtom: () => ({}),
preparedConnectionValueAtom: () => ({}),
},
readEnvironmentScope,
useEnvironmentScope: (id: EnvironmentId | null, scope: AuthEnvironmentScope) =>
useSyncExternalStore(
(listener) => {
state.listeners.add(listener);
return () => state.listeners.delete(listener);
},
() => readEnvironmentScope(id, scope),
),
usePreparedConnection: () => ({ _tag: "None" }),
};
});
vi.mock("../state/server", () => ({
serverEnvironment: { configValueAtom: () => "config" },
}));
vi.mock("../state/threads", () => ({
threadEnvironment: { updateMetadata: "updateMetadata" },
}));
vi.mock("../state/entities", () => ({
readEnvironmentSupportsServerBrowser: () => false,
useServerConfigs: () => new Map([[threadRef.environmentId, serverConfig]]),
readThreadShell: () => ({ linkedPullRequest: state.linkedPullRequest }),
useProjects: () => [{ id: linkedPullRequest.projectId, environmentId: threadRef.environmentId }],
}));
vi.mock("../rightPanelStore", () => ({
useRightPanelStore: { getState: () => ({ openFile: state.openFile }) },
}));
vi.mock("../remoteOpen", () => ({
useRemoteOpenResolution: () => ({ state: { mode: "local-exec" }, isResolved: true }),
}));
vi.mock("../hooks/useLocalStorage", () => ({
useLocalStorage: () => ["vscode", vi.fn()],
getLocalStorageItem: () => "vscode",
setLocalStorageItem: vi.fn(),
}));
vi.mock("../hooks/useCopyToClipboard", () => ({
writeTextToClipboard: state.copy,
useCopyToClipboard: () => ({ copyToClipboard: state.copy, isCopied: false }),
}));
vi.mock("../localApi", () => ({
readLocalApi: () => ({
contextMenu: { show: state.choose },
shell: { openExternal: state.openExternal },
}),
}));
vi.mock("~/lib/openPullRequestLink", () => ({
resolvePullRequestPreviewTarget: () => null,
findProjectForChangeRequest: (projects: readonly { id: ProjectId }[]) => projects[0],
matchesLinkedPullRequestUrl: (candidate: ThreadLinkedPullRequest, href: string) =>
candidate.url === href,
parseChangeRequestUrl: (href: string) =>
href === linkedPullRequest.url
? {
host: "github.com",
repository: linkedPullRequest.repository,
number: linkedPullRequest.number,
}
: null,
useOpenChangeRequestLink: () => vi.fn(),
}));
import ChatMarkdown from "./ChatMarkdown";
const threadRef = {
environmentId: EnvironmentId.make("selected"),
threadId: ThreadId.make("thread"),
};
const linkedPullRequest: ThreadLinkedPullRequest = {
projectId: ProjectId.make("project"),
repository: "example/repo",
number: 42,
url: "https://github.com/example/repo/pull/42",
};
const serverConfig = {
availableEditors: ["vscode", "file-manager"] as readonly EditorId[],
shellRevealInFileManager: true,
shellRevealInFileManagerKind: "xdg-open",
environment: { platform: { os: "linux" }, capabilities: { threadPullRequestLinking: true } },
};
let renderer: ReactTestRenderer | undefined;
beforeEach(() => {
state.allowed = true;
state.listeners.clear();
state.linkedPullRequest = null;
state.openEditor.mockReset().mockResolvedValue(AsyncResult.success(undefined));
state.updateMetadata.mockReset().mockResolvedValue(AsyncResult.success(undefined));
state.search.mockReset().mockResolvedValue(AsyncResult.success({ entries: [] }));
state.choose.mockReset().mockResolvedValue(null);
state.openFile.mockReset();
state.openExternal.mockReset().mockResolvedValue(undefined);
state.copy.mockReset().mockResolvedValue(undefined);
state.toast.mockReset();
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
vi.stubGlobal("window", {});
vi.stubGlobal("navigator", { clipboard: { writeText: state.copy } });
});
afterEach(async () => {
await act(async () => renderer?.unmount());
renderer = undefined;
vi.unstubAllGlobals();
});
async function renderMarkdown(text: string) {
await act(async () => {
renderer = create(<ChatMarkdown cwd="/work" threadRef={threadRef} text={text} />);
});
}
function menuEvent() {
return { preventDefault: vi.fn(), stopPropagation: vi.fn(), clientX: 10, clientY: 10 };
}
function anchor() {
return renderer!.root.findByType("a");
}
async function openContextMenu() {
await act(async () => anchor().props.onContextMenu(menuEvent()));
}
function offeredActions() {
return state.choose.mock.lastCall![0].map((item: { id: string }) => item.id);
}
it("removes host actions after revocation while keeping file preview and copying", async () => {
await renderMarkdown("[Readme](docs/readme.md)");
await openContextMenu();
expect(offeredActions()).toEqual(["open", "reveal", "copy-relative", "copy-full"]);
await act(async () => {
state.allowed = false;
for (const listener of state.listeners) listener();
});
state.choose.mockResolvedValue("copy-full");
await openContextMenu();
expect(offeredActions()).toEqual(["copy-relative", "copy-full"]);
expect(state.copy).toHaveBeenCalledWith("/work/docs/readme.md");
await act(async () => anchor().props.onClick(menuEvent()));
expect(state.openFile).toHaveBeenCalledWith(threadRef, "docs/readme.md", undefined);
expect(state.openEditor).not.toHaveBeenCalled();
});
it("does not launch an editor after revocation during a native context menu", async () => {
let choose: (action: string) => void = () => {
throw new Error("Menu not opened");
};
state.choose.mockImplementationOnce(
() =>
new Promise<string>((resolve) => {
choose = resolve;
}),
);
await renderMarkdown("[Readme](docs/readme.md)");
await openContextMenu();
expect(offeredActions()).toContain("open");
await act(async () => {
state.allowed = false;
choose("open");
});
expect(state.openEditor).not.toHaveBeenCalled();
});
it("does not reveal a file after revocation during its workspace lookup", async () => {
let finishLookup: () => void = () => {
throw new Error("Lookup not started");
};
state.search.mockImplementationOnce(
() =>
new Promise((resolve) => {
finishLookup = () => resolve(AsyncResult.success({ entries: [] }));
}),
);
state.choose.mockResolvedValue("reveal");
await renderMarkdown("[Readme](readme.md)");
await openContextMenu();
expect(state.search).toHaveBeenCalledOnce();
await act(async () => {
state.allowed = false;
finishLookup();
});
expect(state.openEditor).not.toHaveBeenCalled();
});
it.each([false, true])(
"keeps PR links usable without offering metadata edits (linked=%s)",
async (linked) => {
state.allowed = false;
state.linkedPullRequest = linked ? linkedPullRequest : null;
state.choose.mockResolvedValue("open-external");
await renderMarkdown(`[Review](${linkedPullRequest.url})`);
await openContextMenu();
expect(offeredActions()).toEqual(["open-external", "copy-link"]);
expect(state.openExternal).toHaveBeenCalledWith(linkedPullRequest.url);
expect(state.updateMetadata).not.toHaveBeenCalled();
},
);
it.each(["link-to-thread", "unlink-from-thread"])(
"rechecks %s after a native context menu returns",
async (action) => {
state.linkedPullRequest = action === "unlink-from-thread" ? linkedPullRequest : null;
let choose: (action: string) => void = () => {
throw new Error("Menu not opened");
};
state.choose.mockImplementationOnce(
() =>
new Promise<string>((resolve) => {
choose = resolve;
}),
);
await renderMarkdown(`[Review](${linkedPullRequest.url})`);
await openContextMenu();
expect(offeredActions()).toContain(action);
await act(async () => {
state.allowed = false;
choose(action);
});
expect(state.updateMetadata).not.toHaveBeenCalled();
await act(async () => {
state.allowed = true;
for (const listener of state.listeners) listener();
});
state.choose.mockResolvedValue(action);
await openContextMenu();
expect(state.updateMetadata).toHaveBeenCalledExactlyOnceWith({
environmentId: threadRef.environmentId,
input: {
threadId: threadRef.threadId,
linkedPullRequest: action === "link-to-thread" ? linkedPullRequest : null,
},
});
},
);
+14 -5
View File
@@ -1,6 +1,6 @@
// @vitest-environment jsdom
import { EnvironmentId } from "@t3tools/contracts";
import { EnvironmentId, type AuthEnvironmentScope } from "@t3tools/contracts";
import { act, type ComponentProps, type ReactNode } from "react";
import { renderToStaticMarkup } from "react-dom/server";
import { create, type ReactTestRenderer } from "react-test-renderer";
@@ -38,10 +38,19 @@ vi.mock("./ui/tooltip", async () => {
});
vi.mock("../state/use-atom-query-runner", () => ({ useAtomQueryRunner: () => vi.fn() }));
vi.mock("../state/use-atom-command", () => ({ useAtomCommand: () => vi.fn() }));
vi.mock("../state/session", async (importOriginal) => ({
...(await importOriginal<typeof import("../state/session")>()),
usePreparedConnection: () => ({ _tag: "Loading" }),
}));
vi.mock("../state/session", async (importOriginal) => {
const actual = await importOriginal<typeof import("../state/session")>();
const { AuthStandardClientScopes } = await import("@t3tools/contracts");
const grantedScopes = new Set<AuthEnvironmentScope>(AuthStandardClientScopes);
const hasScope = (environmentId: EnvironmentId | null, scope: AuthEnvironmentScope) =>
environmentId !== null && grantedScopes.has(scope);
return {
...actual,
useEnvironmentScope: hasScope,
readEnvironmentScope: hasScope,
usePreparedConnection: () => ({ _tag: "Loading" }),
};
});
vi.mock("../state/entities", () => ({
readThreadShell: () => null,
useProjects: () => [],
+20 -8
View File
@@ -1,4 +1,5 @@
import { usePullRequestLinking } from "~/hooks/usePullRequestLinking";
import { AuthOrchestrationOperateScope } from "@t3tools/contracts";
import { useAtomValue } from "@effect/atom-react";
import {
COMPOSER_CONTEXT_CLIPBOARD_MIME,
@@ -171,7 +172,7 @@ import { readThreadShell, useProjects } from "../state/entities";
import { serverEnvironment } from "../state/server";
import { shellEnvironment } from "../state/shell";
import { assetEnvironment } from "../state/assets";
import { usePreparedConnection } from "../state/session";
import { readEnvironmentScope, usePreparedConnection, useEnvironmentScope } from "../state/session";
import { previewEnvironment } from "../state/preview";
import { useAtomCommand } from "../state/use-atom-command";
import { useAtomQueryRunner } from "../state/use-atom-query-runner";
@@ -2516,12 +2517,11 @@ function useChatMarkdownState({
});
const pullRequestLinking = usePullRequestLinking(threadRef?.environmentId);
const environmentId = threadRef?.environmentId ?? explicitEnvironmentId ?? null;
const canOperateHost = useEnvironmentScope(environmentId, AuthOrchestrationOperateScope);
const remoteOpen = useRemoteOpenResolution(environmentId);
const canUseShellActions = canUseMarkdownFileShellActions(
environmentId,
remoteOpen.state.mode,
remoteOpen.isResolved,
);
const canUseShellActions =
canOperateHost &&
canUseMarkdownFileShellActions(environmentId, remoteOpen.state.mode, remoteOpen.isResolved);
const preparedConnection = usePreparedConnection(environmentId);
const openMarkdownMedia = useCallback(
(source: string, resolvedFilePath?: string, clickedImage?: HTMLImageElement | null) => {
@@ -2591,6 +2591,13 @@ function useChatMarkdownState({
),
);
}
if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) {
return Promise.resolve(
AsyncResult.failure<void, Error>(
Cause.fail(new Error("This connection cannot reveal files on this environment.")),
),
);
}
return openInEditor({
environmentId,
input: { cwd: filePath, editor: "file-manager", reveal: true },
@@ -2687,6 +2694,7 @@ function useChatMarkdownState({
const updateThreadPullRequestLink = useCallback(
async (href: string, linked: boolean) => {
if (threadRef === undefined || (!linked && linkedThreadPullRequestFor(href) === null)) return;
if (!readEnvironmentScope(threadRef.environmentId, AuthOrchestrationOperateScope)) return;
await pullRequestLinking.changeLink(threadRef, href, linked);
},
[linkedThreadPullRequestFor, pullRequestLinking, threadRef],
@@ -2878,6 +2886,7 @@ function useChatMarkdownState({
const componentState = useMemo(
() => ({
canOperateHost,
cwd,
diffThemeName,
environmentId,
@@ -2909,6 +2918,7 @@ function useChatMarkdownState({
updateThreadPullRequestLink,
}),
[
canOperateHost,
cwd,
diffThemeName,
environmentId,
@@ -3063,6 +3073,7 @@ const CHAT_MARKDOWN_COMPONENTS = {
},
a: function MarkdownAnchor({ node, href, children, title: _title, ...props }) {
const {
canOperateHost,
cwd,
environmentId,
imageBaseDir,
@@ -3203,8 +3214,9 @@ const CHAT_MARKDOWN_COMPONENTS = {
event.stopPropagation();
const api = readLocalApi();
if (!api) return;
const threadLinkAction =
linkedThreadPullRequestFor(href) !== null
const threadLinkAction = !canOperateHost
? undefined
: linkedThreadPullRequestFor(href) !== null
? "unlink-from-thread"
: resolveThreadPullRequest(href) === null
? undefined
+161 -52
View File
@@ -48,12 +48,15 @@ import {
} from "../questionAttachments";
import { useAttachmentUploadStore } from "../lib/attachmentUploadQueue";
import {
AuthOrchestrationOperateScope,
AuthSettingsWriteScope,
type AssistantCitation,
type ChatFileAttachment,
CommandId,
DEFAULT_MODEL,
isProviderNativeSubagentThread,
type ChatAttachment as ContractChatAttachment,
EnvironmentAuthorizationError,
type EnvironmentId,
type MessageId,
type ModelSelection,
@@ -285,9 +288,10 @@ import { DeviceSetup } from "./device/DeviceSetup";
import { Dialog } from "./ui/dialog";
import { WizardPopup } from "./ui/wizard";
import { BranchToolbar, type BranchToolbarHandle } from "./BranchToolbar";
import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings";
import { makeWorkspaceFileDropHandlers } from "./chat/workspaceFileDrop";
import { isEditableFocused } from "../lib/editableFocus";
import { DEFAULT_RESOLVED_KEYBINDINGS } from "@t3tools/shared/keybindings";
import { resolveChatShortcutCommand, shortcutLabelForCommand } from "../keybindings";
import ThreadTerminalDrawer from "./ThreadTerminalDrawer";
import {
AlarmClockIcon,
@@ -555,8 +559,13 @@ import { clampFileAttachmentUploadBytes } from "@t3tools/client-runtime/state/at
import { appAtomRegistry } from "../rpc/atomRegistry";
import { fileAttachmentCapabilityBlockReason } from "./chat/composerAttachmentFiles";
import { assetEnvironment } from "../state/assets";
import { readPreparedConnection } from "../state/session";
import {
readEnvironmentScope,
readPreparedConnection,
useEnvironmentScope,
} from "../state/session";
import { useAtomCommand } from "../state/use-atom-command";
import { useOrchestrationCommand } from "../state/use-orchestration-command";
import { useAtomQueryRunner } from "../state/use-atom-query-runner";
import { Button, InlineButton } from "./ui/button";
import {
@@ -1535,6 +1544,7 @@ export default function ChatView(props: ChatViewProps) {
reserveTitleBarControlInset = true,
forceExpandedMobileComposer = false,
} = props;
const canOperateThread = useEnvironmentScope(environmentId, AuthOrchestrationOperateScope);
const draftId = routeKind === "draft" ? props.draftId : null;
const handleNewThread = useNewThreadHandler();
const { settleThread, pinThread, confirmAndUnpinThread } = useThreadActions();
@@ -1562,46 +1572,48 @@ export default function ChatView(props: ChatViewProps) {
const openTerminal = useAtomCommand(terminalEnvironment.open, "terminal open");
const writeTerminal = useAtomCommand(terminalEnvironment.write, "terminal write");
const closeTerminalMutation = useAtomCommand(terminalEnvironment.close, "terminal close");
const createThread = useAtomCommand(threadEnvironment.create, { reportFailure: false });
const deleteThread = useAtomCommand(threadEnvironment.delete, { reportFailure: false });
const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, {
const createThread = useOrchestrationCommand(threadEnvironment.create, { reportFailure: false });
const deleteThread = useOrchestrationCommand(threadEnvironment.delete, { reportFailure: false });
const updateThreadMetadata = useOrchestrationCommand(threadEnvironment.updateMetadata, {
reportFailure: false,
});
const switchGitRef = useAtomCommand(vcsEnvironment.switchRef, { reportFailure: false });
const setThreadRuntimeMode = useAtomCommand(threadEnvironment.setRuntimeMode, {
const setThreadRuntimeMode = useOrchestrationCommand(threadEnvironment.setRuntimeMode, {
reportFailure: false,
});
const setThreadInteractionMode = useAtomCommand(threadEnvironment.setInteractionMode, {
const setThreadInteractionMode = useOrchestrationCommand(threadEnvironment.setInteractionMode, {
reportFailure: false,
});
const startThreadTurn = useAtomCommand(threadEnvironment.startTurn, { reportFailure: false });
const resumeThreadQueue = useAtomCommand(threadEnvironment.resumeThreadQueue, {
const startThreadTurn = useOrchestrationCommand(threadEnvironment.startTurn, {
reportFailure: false,
});
const uploadThreadFeedback = useAtomCommand(threadEnvironment.uploadFeedback, {
const resumeThreadQueue = useOrchestrationCommand(threadEnvironment.resumeThreadQueue, {
reportFailure: false,
});
const uploadThreadFeedback = useOrchestrationCommand(threadEnvironment.uploadFeedback, {
reportFailure: false,
});
const createAttachmentAssetUrl = useAtomQueryRunner(assetEnvironment.createUrl, {
reportFailure: false,
refresh: true,
});
const interruptThreadTurn = useAtomCommand(threadEnvironment.interruptTurn, {
const interruptThreadTurn = useOrchestrationCommand(threadEnvironment.interruptTurn, {
reportFailure: false,
});
const loadEarlierThreadHistory = useAtomCommand(threadEnvironment.loadEarlierHistory, {
label: "load earlier thread history",
reportFailure: false,
});
const respondToThreadApproval = useAtomCommand(threadEnvironment.respondToApproval, {
const respondToThreadApproval = useOrchestrationCommand(threadEnvironment.respondToApproval, {
reportFailure: false,
});
const respondToThreadUserInput = useAtomCommand(threadEnvironment.respondToUserInput, {
const respondToThreadUserInput = useOrchestrationCommand(threadEnvironment.respondToUserInput, {
reportFailure: false,
});
const dismissThreadUserInput = useAtomCommand(threadEnvironment.dismissUserInput, {
reportFailure: false,
});
const revertThreadCheckpoint = useAtomCommand(threadEnvironment.revertCheckpoint, {
const revertThreadCheckpoint = useOrchestrationCommand(threadEnvironment.revertCheckpoint, {
reportFailure: false,
});
const forkThreadFromRun = useAtomCommand(threadEnvironment.forkFromRun, {
@@ -3228,6 +3240,7 @@ export default function ChatView(props: ChatViewProps) {
providerStatuses.find((status) => status.instanceId === activeRuntime?.providerInstanceId) ??
activeProviderStatus;
const supportsConversationRollback =
canOperateThread &&
conversationProviderStatus !== null &&
conversationProviderStatus.supportsConversationRollback !== false;
const phase = derivePhase(activeRuntime);
@@ -4065,6 +4078,9 @@ export default function ChatView(props: ChatViewProps) {
resourceKey: `git-status:${activeThreadKey ?? ""}:${gitStatusCwd ?? ""}`,
});
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
const scriptKeybindings =
useAtomValue(serverEnvironment.configValueAtom(environmentId))?.keybindings ??
DEFAULT_RESOLVED_KEYBINDINGS;
const availableEditors = useAtomValue(primaryServerAvailableEditorsAtom);
const remoteOpenState = useRemoteOpenState(activeThread?.environmentId ?? environmentId);
const showOpenInPicker = shouldShowOpenInPicker({
@@ -4497,12 +4513,14 @@ export default function ChatView(props: ChatViewProps) {
const focusComposer = useCallback(() => {
composerRef.current?.focusAtEnd();
}, [composerRef]);
const canInterruptRunningThread = deriveCanInterruptRunningThread(
activeThread !== undefined,
activeRuntime,
);
const canInterruptRunningThread =
canOperateThread && deriveCanInterruptRunningThread(activeThread !== undefined, activeRuntime);
const onInterrupt = useCallback(async () => {
if (!activeThread) return;
if (
!activeThread ||
!readEnvironmentScope(activeThread.environmentId, AuthOrchestrationOperateScope)
)
return;
const result = await interruptThreadTurn({
environmentId,
input: { threadId: activeThread.id },
@@ -4997,9 +5015,37 @@ export default function ChatView(props: ChatViewProps) {
projectCwd: string;
previousScripts: ReadonlyArray<ProjectScript>;
nextScripts: ReadonlyArray<ProjectScript>;
keybinding?: string | null;
keybinding: NewProjectScriptInput["keybinding"];
keybindingCommand: KeybindingCommand | null;
}): Promise<AtomCommandResult<void, unknown>> => {
const previousKeybinding = keybindingValueForCommand(
appAtomRegistry.get(serverEnvironment.configValueAtom(environmentId))?.keybindings ?? [],
input.keybindingCommand,
);
const isDeletingScript = !input.nextScripts.some(
(script) => commandForProjectScript(script.id) === input.keybindingCommand,
);
const changesKeybinding =
isElectron &&
input.keybinding !== undefined &&
(input.keybinding?.trim() || null) !== previousKeybinding &&
(!isDeletingScript || readEnvironmentScope(environmentId, AuthSettingsWriteScope));
if (changesKeybinding && !readEnvironmentScope(environmentId, AuthSettingsWriteScope)) {
return AsyncResult.failure(
Cause.fail(
new EnvironmentAuthorizationError({
requiredScope: AuthSettingsWriteScope,
message: "This connection cannot change keyboard shortcuts.",
}),
),
);
}
const keybindingRule = changesKeybinding
? decodeProjectScriptKeybindingRule({
keybinding: input.keybinding,
command: input.keybindingCommand,
})
: null;
const updateResult = mapAtomCommandResult(
await updateProjectScriptSettings({
environmentId,
@@ -5028,10 +5074,19 @@ export default function ChatView(props: ChatViewProps) {
return updateResult;
}
const keybindingRule = decodeProjectScriptKeybindingRule({
keybinding: input.keybinding,
command: input.keybindingCommand,
});
if (!changesKeybinding) return updateResult;
if (!readEnvironmentScope(environmentId, AuthSettingsWriteScope)) {
return AsyncResult.failure(
Cause.fail(
new EnvironmentAuthorizationError({
requiredScope: AuthSettingsWriteScope,
message: isDeletingScript
? "The script was deleted, but its keyboard shortcut could not be removed because permission changed."
: "The script was saved, but this connection can no longer change keyboard shortcuts.",
}),
),
);
}
if (!isElectron) return updateResult;
@@ -6991,7 +7046,7 @@ export default function ChatView(props: ChatViewProps) {
]);
const activeThreadSettled =
supportsSettlement && activeThreadShell?.settledOverride === "settled";
const unsettleThreadMutation = useAtomCommand(threadEnvironment.unsettle, {
const unsettleThreadMutation = useOrchestrationCommand(threadEnvironment.unsettle, {
reportFailure: false,
});
// Keyed by thread, not a boolean: the pending state must follow the thread
@@ -7000,7 +7055,11 @@ export default function ChatView(props: ChatViewProps) {
const [unsettlingThreadKey, setUnsettlingThreadKey] = useState<string | null>(null);
const isUnsettling = unsettlingThreadKey !== null && unsettlingThreadKey === activeThreadKey;
const handleUnsettleActiveThread = useCallback(async () => {
if (!activeThreadRef) return;
if (
!activeThreadRef ||
!readEnvironmentScope(activeThreadRef.environmentId, AuthOrchestrationOperateScope)
)
return;
const threadKey = scopedThreadKey(activeThreadRef);
setUnsettlingThreadKey(threadKey);
try {
@@ -7022,13 +7081,17 @@ export default function ChatView(props: ChatViewProps) {
setUnsettlingThreadKey((current) => (current === threadKey ? null : current));
}
}, [activeThreadRef, unsettleThreadMutation]);
const unsnoozeThreadMutation = useAtomCommand(threadEnvironment.unsnooze, {
const unsnoozeThreadMutation = useOrchestrationCommand(threadEnvironment.unsnooze, {
reportFailure: false,
});
const [unsnoozingThreadKey, setUnsnoozingThreadKey] = useState<string | null>(null);
const isUnsnoozing = unsnoozingThreadKey !== null && unsnoozingThreadKey === activeThreadKey;
const handleUnsnoozeActiveThread = useCallback(async () => {
if (!activeThreadRef) return;
if (
!activeThreadRef ||
!readEnvironmentScope(activeThreadRef.environmentId, AuthOrchestrationOperateScope)
)
return;
const threadKey = scopedThreadKey(activeThreadRef);
setUnsnoozingThreadKey(threadKey);
try {
@@ -7175,7 +7238,8 @@ export default function ChatView(props: ChatViewProps) {
const isStoppingBackgroundWork =
stoppingBackgroundWorkKey === `${environmentId}:${activeThreadId}`;
const handleStopBackgroundWork = useCallback(async () => {
if (!activeThread) return;
if (!activeThread || !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope))
return;
const requestKey = `${environmentId}:${activeThread.id}`;
setStoppingBackgroundWorkKey(requestKey);
const result = await interruptThreadTurn({
@@ -7377,7 +7441,7 @@ export default function ChatView(props: ChatViewProps) {
<Button
size="xs"
variant="ghost"
disabled={isStoppingBackgroundWork}
disabled={!canOperateThread || isStoppingBackgroundWork}
onClick={() => void handleStopBackgroundWork()}
>
{isStoppingBackgroundWork ? "Stopping..." : "Stop"}
@@ -7387,6 +7451,7 @@ export default function ChatView(props: ChatViewProps) {
}, [
activeBackgroundTasks,
activeThread,
canOperateThread,
handleStopBackgroundWork,
isStoppingBackgroundWork,
onOpenRelatedThread,
@@ -7423,7 +7488,7 @@ export default function ChatView(props: ChatViewProps) {
<Button
size="xs"
variant="ghost"
disabled={isSnoozed ? isUnsnoozing : isUnsettling}
disabled={!canOperateThread || (isSnoozed ? isUnsnoozing : isUnsettling)}
onClick={() =>
void (isSnoozed ? handleUnsnoozeActiveThread() : handleUnsettleActiveThread())
}
@@ -7442,6 +7507,7 @@ export default function ChatView(props: ChatViewProps) {
activeThread?.id,
activeThreadSettled,
activeThreadSnoozed,
canOperateThread,
handleUnsnoozeActiveThread,
handleUnsettleActiveThread,
isUnsnoozing,
@@ -7463,6 +7529,7 @@ export default function ChatView(props: ChatViewProps) {
(item.text.trim().toLowerCase() !== "/compact" || item.attachments.length > 0),
);
const compactThreadUnavailable =
!canOperateThread ||
!activeThread ||
!activeThreadHasCompactableConversation ||
!activeProject ||
@@ -7479,11 +7546,13 @@ export default function ChatView(props: ChatViewProps) {
showPlanFollowUpPrompt;
const compactDisabled = compactThreadUnavailable;
const compactDisabledReason = compactDisabled
? !activeProject
? "Choose a project before compacting"
: !manualCompactionProviderAvailable
? "Compaction is unavailable for this provider"
: "Compacting is unavailable right now"
? !canOperateThread
? "This connection cannot change threads."
: !activeProject
? "Choose a project before compacting"
: !manualCompactionProviderAvailable
? "Compaction is unavailable for this provider"
: "Compacting is unavailable right now"
: null;
const resumeCompactionBannerItem = useMemo<ComposerBannerStackItem | null>(() => {
if (
@@ -7813,7 +7882,7 @@ export default function ChatView(props: ChatViewProps) {
}
}
const command = resolveShortcutCommand(event, keybindings, {
const command = resolveChatShortcutCommand(event, keybindings, scriptKeybindings, {
context: shortcutContext,
});
if (!command) return;
@@ -7826,6 +7895,7 @@ export default function ChatView(props: ChatViewProps) {
}
if (command === "thread.settle") {
if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) return;
event.preventDefault();
event.stopPropagation();
if (!isServerThread || !activeThreadRef || !supportsSettlement) return;
@@ -7849,6 +7919,7 @@ export default function ChatView(props: ChatViewProps) {
}
if (command === "thread.pin") {
if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) return;
event.preventDefault();
event.stopPropagation();
if (!isServerThread || !activeThreadRef || !supportsPinning) return;
@@ -8069,6 +8140,7 @@ export default function ChatView(props: ChatViewProps) {
splitTerminal,
splitPanelTerminal,
keybindings,
scriptKeybindings,
handleUnsettleActiveThread,
isServerThread,
onInterrupt,
@@ -8143,7 +8215,13 @@ export default function ChatView(props: ChatViewProps) {
const onRevertToTurnCount = useCallback(
async (turnCount: number, messageId: MessageId, restoreFiles?: boolean) => {
const localApi = readLocalApi();
if (!localApi || !activeThread || isRevertingCheckpoint) return;
if (
!localApi ||
!activeThread ||
isRevertingCheckpoint ||
!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)
)
return;
const sourceMessage = serverProjection?.messages.find((message) => message.id === messageId);
const message = sourceMessage
? {
@@ -8514,6 +8592,7 @@ export default function ChatView(props: ChatViewProps) {
);
};
if (
!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope) ||
!activeThread ||
isSendBusy ||
isConnecting ||
@@ -9141,6 +9220,23 @@ export default function ChatView(props: ChatViewProps) {
void dockTransition.catch(() => resolveDockStarted?.());
await dockStarted;
}
const attachmentCapabilitiesBeforeDispatch = readLiveAttachmentCapabilities();
if (
!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope) ||
attachmentCapabilitiesBeforeDispatch.fileBlockReason !== null
) {
sendInFlightRef.current = false;
setThreadError(
threadIdForSend,
attachmentCapabilitiesBeforeDispatch.fileBlockReason ??
"This connection cannot change threads.",
);
setDockedDraftHeroThreadKey((currentThreadKey) =>
currentThreadKey === activeThreadKey ? null : currentThreadKey,
);
return;
}
beginLocalDispatch({
preparingWorktree: multipleModelSelections !== null || Boolean(baseBranchForWorktree),
// Only a draft has a background submission to hide behind its hero.
@@ -9815,7 +9911,8 @@ export default function ChatView(props: ChatViewProps) {
const onRespondToApproval = useCallback(
async (requestId: RuntimeRequestId, decision: ProviderApprovalDecision) => {
if (!activeThreadId) return;
if (!activeThreadId || !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope))
return;
if (
pendingApprovals.find((approval) => approval.requestId === requestId)
?.responseCapability !== "live"
@@ -9848,7 +9945,8 @@ export default function ChatView(props: ChatViewProps) {
const onRespondToUserInput = useCallback(
async (requestId: RuntimeRequestId, answers: Record<string, unknown>) => {
if (!activeThreadId) return;
if (!activeThreadId || !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope))
return;
const pendingInput = pendingUserInputs.find((input) => input.requestId === requestId);
if (!pendingInput || pendingInput.responseCapability === "not_resumable") return;
const responseKey = JSON.stringify([environmentId, activeThreadId, requestId]);
@@ -10079,7 +10177,14 @@ export default function ChatView(props: ChatViewProps) {
context?: ReturnType<typeof buildMessageContext>;
interactionMode: "default" | "plan";
}) {
if (!activeThread || !isServerThread || isSendBusy || isConnecting || sendInFlightRef.current) {
if (
!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope) ||
!activeThread ||
!isServerThread ||
isSendBusy ||
isConnecting ||
sendInFlightRef.current
) {
return false;
}
@@ -10213,6 +10318,7 @@ export default function ChatView(props: ChatViewProps) {
const onImplementPlanInNewThread = useCallback(async () => {
if (
!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope) ||
!activeThread ||
!activeProject ||
!activeProposedPlan ||
@@ -11264,6 +11370,7 @@ export default function ChatView(props: ChatViewProps) {
) : null}
{!composerMounted ? null : (
<ChatComposer
canOperateThread={canOperateThread}
reportedModelSelection={reportedModelSelection}
multipleModelSelections={multipleModelSelections}
supportsMultipleModels={
@@ -11301,17 +11408,19 @@ export default function ChatView(props: ChatViewProps) {
canResume={resumableRunId !== null || hasHeldQueuedRuns}
isRevertingCheckpoint={isRevertingCheckpoint}
sendDisabledReason={
isEnvironmentChanging
? "Preparing machine"
: isRevertingCheckpoint
? "Rewinding conversation"
: feedbackUploading
? "Sending feedback"
: threadDetailLoading
? "Messages loading"
: worktreeSetupBlocksSend
? "Preparing worktree"
: projectCloneSendBlockReason
!canOperateThread
? "This connection cannot change threads."
: isEnvironmentChanging
? "Preparing machine"
: isRevertingCheckpoint
? "Rewinding conversation"
: feedbackUploading
? "Sending feedback"
: threadDetailLoading
? "Messages loading"
: worktreeSetupBlocksSend
? "Preparing worktree"
: projectCloneSendBlockReason
}
isPreparingWorktree={isPreparingWorktree}
queuedRunsControl={
@@ -0,0 +1,119 @@
import { RegistryContext } from "@effect/atom-react";
import {
AuthOrchestrationOperateScope,
EnvironmentId,
type AuthEnvironmentScope,
type AuthSessionState,
} from "@t3tools/contracts";
import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
import { act, create, type ReactTestRenderer } from "react-test-renderer";
import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
type SessionResult = AsyncResult.AsyncResult<AuthSessionState, Error>;
const state = vi.hoisted(() => ({
registry: null as AtomRegistry.AtomRegistry | null,
sessions: new Map<EnvironmentId, Atom.Writable<SessionResult>>(),
run: vi.fn(),
toast: vi.fn(),
}));
vi.mock("../connection/runtime", () => ({ connectionAtomRuntime: undefined }));
vi.mock("@t3tools/client-runtime/state/session", () => ({
createEnvironmentSessionAtoms: () => ({
sessionStateAtom: (id: EnvironmentId) => state.sessions.get(id)!,
}),
}));
vi.mock("../rpc/atomRegistry", () => ({
get appAtomRegistry() {
return state.registry;
},
}));
vi.mock("../state/shell", () => ({ shellEnvironment: { openInEditor: "openInEditor" } }));
vi.mock("../state/use-atom-command", () => ({ useAtomCommand: () => state.run }));
vi.mock("../hooks/useLocalStorage", () => ({
getLocalStorageItem: () => "vscode",
setLocalStorageItem: vi.fn(),
useLocalStorage: vi.fn(),
}));
vi.mock("./ui/button", () => ({ Button: "button" }));
vi.mock("./ui/toast", () => ({
toastManager: { add: state.toast },
stackedThreadToast: (value: unknown) => value,
}));
import { KeybindingsConfigWarning } from "./KeybindingsConfigWarning";
const environmentId = EnvironmentId.make("warning-environment");
let renderer: ReactTestRenderer | undefined;
const session = (scopes: readonly AuthEnvironmentScope[]): AuthSessionState => ({
authenticated: true,
scopes,
auth: {
policy: "remote-reachable",
bootstrapMethods: ["one-time-token"],
sessionMethods: ["bearer-access-token"],
sessionCookieName: "t3_session",
},
});
beforeEach(() => {
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
state.registry = AtomRegistry.make();
state.sessions.set(
environmentId,
Atom.make<SessionResult>(AsyncResult.success(session([AuthOrchestrationOperateScope]))).pipe(
Atom.keepAlive,
),
);
state.run.mockReset().mockResolvedValue(AsyncResult.success(undefined));
state.toast.mockReset();
});
afterEach(async () => {
await act(async () => renderer?.unmount());
renderer = undefined;
state.registry?.dispose();
state.sessions.clear();
vi.unstubAllGlobals();
});
it("updates a visible warning on revocation and blocks its retained action until regrant", async () => {
await act(async () => {
renderer = create(
<RegistryContext.Provider value={state.registry!}>
<KeybindingsConfigWarning
environmentId={environmentId}
configPath="/t3/keybindings.json"
availableEditors={["vscode"]}
message="Invalid shortcut"
/>
</RegistryContext.Provider>,
);
});
const open = renderer!.root.findByType("button").props.onClick;
expect(renderer!.root.findByType("button").props.disabled).toBe(false);
await act(async () => {
state.registry!.set(state.sessions.get(environmentId)!, AsyncResult.success(session([])));
await open();
});
expect(renderer!.root.findByType("button").props.disabled).toBe(true);
expect(state.run).not.toHaveBeenCalled();
expect(state.toast).toHaveBeenCalledWith(
expect.objectContaining({
title: "Unable to open keybindings file",
}),
);
await act(async () => {
state.registry!.set(
state.sessions.get(environmentId)!,
AsyncResult.success(session([AuthOrchestrationOperateScope])),
);
});
expect(renderer!.root.findByType("button").props.disabled).toBe(false);
await act(async () => open());
expect(state.run).toHaveBeenCalledExactlyOnceWith({
environmentId,
input: { cwd: "/t3/keybindings.json", editor: "vscode" },
});
});
@@ -0,0 +1,54 @@
import {
AuthOrchestrationOperateScope,
type EditorId,
type EnvironmentId,
} from "@t3tools/contracts";
import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
import { useOpenInPreferredEditor } from "../editorPreferences";
import { useEnvironmentScope } from "../state/session";
import { Button } from "./ui/button";
import { stackedThreadToast, toastManager } from "./ui/toast";
export function KeybindingsConfigWarning({
message,
environmentId,
configPath,
availableEditors,
}: {
message: string;
environmentId: EnvironmentId | null;
configPath: string | null;
availableEditors: readonly EditorId[];
}) {
const canOpenEditor = useEnvironmentScope(environmentId, AuthOrchestrationOperateScope);
const openInEditor = useOpenInPreferredEditor(environmentId, availableEditors);
return (
<>
{message}
<span className="mt-2 flex justify-end">
<Button
size="xs"
variant="outline"
disabled={!canOpenEditor || !configPath || availableEditors.length === 0}
onClick={async () => {
if (!configPath) return;
const result = await openInEditor(configPath);
if (result._tag === "Success") return;
const error = squashAtomCommandFailure(result);
toastManager.add(
stackedThreadToast({
type: "error",
title: "Unable to open keybindings file",
description: error instanceof Error ? error.message : "Unknown error opening file.",
}),
);
}}
>
Open keybindings.json
</Button>
</span>
</>
);
}
+102 -14
View File
@@ -45,7 +45,9 @@ import { SortableContext, useSortable, verticalListSortingStrategy } from "@dnd-
import { restrictToFirstScrollableAncestor, restrictToVerticalAxis } from "@dnd-kit/modifiers";
import { CSS } from "@dnd-kit/utilities";
import {
AuthOrchestrationOperateScope,
type ContextMenuItem,
type EnvironmentId,
ProjectId,
type ScopedThreadRef,
type ResolvedKeybindingsConfig,
@@ -96,7 +98,12 @@ import { useThreadRunningTerminalIds } from "../state/terminalSessions";
import { useThreadDiscoveredPorts } from "../portDiscoveryState";
import { openDiscoveredPort } from "./preview/openDiscoveredPort";
import { useAtomCommand } from "../state/use-atom-command";
import {
ORCHESTRATION_OPERATE_DENIED_MESSAGE,
useOrchestrationCommand,
} from "../state/use-orchestration-command";
import { previewEnvironment } from "../state/preview";
import { readEnvironmentScope, useEnvironmentScope } from "../state/session";
import {
legacyProjectCwdPreferenceKey,
resolveProjectExpanded,
@@ -357,6 +364,18 @@ interface SidebarThreadRowProps {
onFileDropThreads: (threadRef: ScopedThreadRef, files: File[]) => void;
}
function checkTaskPermission(environmentId: EnvironmentId): boolean {
if (readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) return true;
toastManager.add(
stackedThreadToast({
type: "error",
title: "Action unavailable",
description: ORCHESTRATION_OPERATE_DENIED_MESSAGE,
}),
);
return false;
}
const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowProps) {
const {
orderedProjectThreadKeys,
@@ -385,6 +404,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
onFileDropThreads,
thread,
} = props;
const canOperateThread = useEnvironmentScope(thread.environmentId, AuthOrchestrationOperateScope);
const threadRef = scopeThreadRef(thread.environmentId, thread.id);
const threadKey = scopedThreadKey(threadRef);
const [isFileDragOver, setIsFileDragOver] = useState(false);
@@ -485,10 +505,11 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
: null;
const prStatus = prStatusIndicator(pr, linkedPullRequestStatus?.sourceControlProvider);
const terminalStatus = terminalStatusFromRunningIds(runningTerminalIds);
const isConfirmingArchive = confirmingArchiveThreadKey === threadKey && !isThreadRunning;
const isConfirmingArchive =
canOperateThread && confirmingArchiveThreadKey === threadKey && !isThreadRunning;
const threadMetaClassName = isConfirmingArchive
? "pointer-events-none opacity-0"
: !isThreadRunning
: canOperateThread && !isThreadRunning
? "pointer-events-none transition-opacity duration-150 max-sm:pr-6 group-hover/menu-sub-item:opacity-0 group-focus-within/menu-sub-item:opacity-0"
: "pointer-events-none";
const clearConfirmingArchive = useCallback(() => {
@@ -517,6 +538,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
);
const handleRowDoubleClick = useCallback(
(event: React.MouseEvent) => {
if (!readEnvironmentScope(thread.environmentId, AuthOrchestrationOperateScope)) return;
// Already renaming this row: a double-click on the row chrome (outside the
// input) must not restart and discard the in-progress edit.
if (renamingThreadKey === threadKey) return;
@@ -531,7 +553,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
event.preventDefault();
startThreadRename(threadKey, thread.title);
},
[isMobile, renamingThreadKey, startThreadRename, threadKey, thread.title],
[isMobile, renamingThreadKey, startThreadRename, threadKey, thread.environmentId, thread.title],
);
const handleRowKeyDown = useCallback(
(event: React.KeyboardEvent) => {
@@ -685,12 +707,13 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
(event: React.MouseEvent<HTMLButtonElement>) => {
event.preventDefault();
event.stopPropagation();
if (!checkTaskPermission(thread.environmentId)) return;
setConfirmingArchiveThreadKey(threadKey);
requestAnimationFrame(() => {
confirmArchiveButtonRefs.current.get(threadKey)?.focus();
});
},
[confirmArchiveButtonRefs, setConfirmingArchiveThreadKey, threadKey],
[confirmArchiveButtonRefs, setConfirmingArchiveThreadKey, threadKey, thread.environmentId],
);
const handleArchiveImmediateClick = useCallback(
(event: React.MouseEvent<HTMLButtonElement>) => {
@@ -775,7 +798,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
</a>
) : null}
{threadStatus && <ThreadStatusLabel status={threadStatus} />}
{renamingThreadKey === threadKey ? (
{canOperateThread && renamingThreadKey === threadKey ? (
<input
ref={handleRenameInputRef}
className="min-w-0 flex-1 truncate rounded border border-ring bg-transparent px-0.5 text-sm outline-none"
@@ -861,7 +884,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
>
Confirm
</button>
) : !isThreadRunning ? (
) : canOperateThread && !isThreadRunning ? (
appSettingsConfirmThreadArchive ? (
<div className="pointer-events-none absolute top-1/2 right-0.5 -translate-y-1/2 opacity-0 transition-opacity duration-150 max-sm:pointer-events-auto max-sm:opacity-100 group-hover/menu-sub-item:pointer-events-auto group-hover/menu-sub-item:opacity-100 group-focus-within/menu-sub-item:pointer-events-auto group-focus-within/menu-sub-item:opacity-100">
<button
@@ -1191,13 +1214,13 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
(settings) => settings.confirmThreadArchive,
);
const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
const deleteProject = useAtomCommand(projectEnvironment.delete, {
const deleteProject = useOrchestrationCommand(projectEnvironment.delete, {
reportFailure: false,
});
const updateProject = useAtomCommand(projectEnvironment.update, {
const updateProject = useOrchestrationCommand(projectEnvironment.update, {
reportFailure: false,
});
const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, {
const updateThreadMetadata = useOrchestrationCommand(threadEnvironment.updateMetadata, {
reportFailure: false,
});
const updateSettings = useUpdateClientSettings();
@@ -1293,6 +1316,10 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
null,
);
const [projectRenameTitle, setProjectRenameTitle] = useState("");
const canRenameProject = useEnvironmentScope(
projectRenameTarget?.environmentId ?? null,
AuthOrchestrationOperateScope,
);
const [projectGroupingTarget, setProjectGroupingTarget] =
useState<SidebarProjectGroupMember | null>(null);
const [projectGroupingSelection, setProjectGroupingSelection] = useState<
@@ -1501,6 +1528,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
);
const openProjectRenameDialog = useCallback((member: SidebarProjectGroupMember) => {
if (!checkTaskPermission(member.environmentId)) return;
setProjectRenameTarget(member);
setProjectRenameTitle(member.title);
}, []);
@@ -1551,6 +1579,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
const handleRemoveProject = useCallback(
async (member: SidebarProjectGroupMember) => {
if (!checkTaskPermission(member.environmentId)) return;
const api = readLocalApi();
if (!api) {
return;
@@ -1573,6 +1602,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
await new Promise<void>((resolve) => {
window.setTimeout(resolve, 180);
});
if (!checkTaskPermission(member.environmentId)) return;
const latestProjectThreads = Array.from(
sidebarThreadByKeyRef.current.values(),
@@ -1765,12 +1795,17 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
const clicked = await api.contextMenu.show(
[
buildTargetedItem("rename", "Rename"),
buildTargetedItem("rename", "Rename", {
isDisabled: (member) =>
!readEnvironmentScope(member.environmentId, AuthOrchestrationOperateScope),
}),
buildTargetedItem("grouping", "Group into..."),
buildTargetedItem("copy-path", "Copy Path"),
{ id: "project-settings", label: "Project settings", icon: "settings" },
buildTargetedItem("delete", "Remove", {
destructive: true,
isDisabled: (member) =>
!readEnvironmentScope(member.environmentId, AuthOrchestrationOperateScope),
}),
],
{
@@ -1907,9 +1942,16 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
const hasRunningThread = selectedThreadEntries.some(
({ thread }) => !threadRuntimeCanArchive(thread.runtime),
);
const canOperateSelection = selectedThreadEntries.every(({ threadRef }) =>
readEnvironmentScope(threadRef.environmentId, AuthOrchestrationOperateScope),
);
const clicked = await api.contextMenu.show(
buildMultiSelectThreadContextMenuItems({ count, hasRunningThread }),
buildMultiSelectThreadContextMenuItems({ count, hasRunningThread }).map((item) =>
item.id === "archive" || item.id === "delete"
? { ...item, disabled: item.disabled || !canOperateSelection }
: item,
),
position,
);
@@ -1921,6 +1963,15 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
return;
}
if (
(clicked === "archive" || clicked === "delete") &&
!selectedThreadEntries.every(({ threadRef }) =>
checkTaskPermission(threadRef.environmentId),
)
) {
return;
}
if (clicked === "archive") {
if (appSettingsConfirmThreadArchive) {
const confirmed = await api.dialogs.confirm(
@@ -1928,6 +1979,13 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
);
if (!confirmed) return;
}
if (
!selectedThreadEntries.every(({ threadRef }) =>
checkTaskPermission(threadRef.environmentId),
)
) {
return;
}
const archiveOutcome = await archiveSelectedThreadEntries({
entries: selectedThreadEntries,
@@ -1974,6 +2032,13 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
);
if (!confirmed) return;
}
if (
!selectedThreadEntries.every(({ threadRef }) =>
checkTaskPermission(threadRef.environmentId),
)
) {
return;
}
const { deletedThreadKeys, firstFailure } = await deleteSelectedThreadEntries({
entries: selectedThreadEntries,
@@ -2090,6 +2155,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
const attemptArchiveThread = useCallback(
async (threadRef: ScopedThreadRef) => {
if (!checkTaskPermission(threadRef.environmentId)) return;
const result = await archiveThread(threadRef);
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
const error = squashAtomCommandFailure(result);
@@ -2111,6 +2177,8 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
}, []);
const startThreadRename = useCallback((threadKey: string, title: string) => {
const threadRef = parseScopedThreadKey(threadKey);
if (!threadRef || !checkTaskPermission(threadRef.environmentId)) return;
setRenamingThreadKey(threadKey);
setRenamingTitle(title);
renamingCommittedRef.current = false;
@@ -2250,17 +2318,27 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
);
const threadWorkspacePath =
thread.worktreePath ?? threadProject?.workspaceRoot ?? project.workspaceRoot ?? null;
const canOperateThread = readEnvironmentScope(
thread.environmentId,
AuthOrchestrationOperateScope,
);
const clicked = await api.contextMenu.show(
[
...(thread.branch
? [{ id: "new-thread-on-branch", label: `New thread on ${thread.branch}` }]
: []),
{ id: "rename", label: "Rename thread" },
{ id: "rename", label: "Rename thread", disabled: !canOperateThread },
{ id: "mark-unread", label: "Mark unread" },
{ id: "copy-path", label: "Copy Path" },
{ id: "copy-thread-id", label: "Copy Thread ID" },
{ id: "project-settings", label: "Project settings" },
{ id: "delete", label: "Delete", destructive: true, icon: "trash" },
{
id: "delete",
label: "Delete",
destructive: true,
icon: "trash",
disabled: !canOperateThread,
},
],
position,
);
@@ -2326,6 +2404,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
return;
}
if (clicked !== "delete") return;
if (!checkTaskPermission(threadRef.environmentId)) return;
if (appSettingsConfirmThreadDelete) {
const confirmed = await api.dialogs.confirm(
[
@@ -2338,6 +2417,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
return;
}
}
if (!checkTaskPermission(threadRef.environmentId)) return;
const result = await deleteThread(threadRef);
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
const error = squashAtomCommandFailure(result);
@@ -2533,6 +2613,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
<span className="text-xs font-medium text-foreground">Project title</span>
<Input
aria-label="Project title"
disabled={!canRenameProject}
value={projectRenameTitle}
onChange={(event) => setProjectRenameTitle(event.target.value)}
onKeyDown={(event) => {
@@ -2548,12 +2629,19 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
Environment: {projectRenameTarget.environmentLabel}
</p>
) : null}
{!canRenameProject ? (
<p className="text-xs text-muted-foreground">
This connection cannot change projects.
</p>
) : null}
</DialogPanel>
<DialogFooter>
<Button variant="outline" onClick={closeProjectRenameDialog}>
Cancel
</Button>
<Button onClick={() => void submitProjectRename()}>Save</Button>
<Button disabled={!canRenameProject} onClick={() => void submitProjectRename()}>
Save
</Button>
</DialogFooter>
</DialogPopup>
</Dialog>
@@ -1,9 +1,13 @@
import { ThreadDetailsControl } from "./chat/ThreadDetailsControl";
import type {
ProjectScript,
ResolvedKeybindingsConfig,
T3ProjectFileScript,
import {
AuthSettingsWriteScope,
type EnvironmentId,
type ProjectScript,
type T3ProjectFileScript,
type ResolvedKeybindingsConfig,
} from "@t3tools/contracts";
import { useAtomValue } from "@effect/atom-react";
import { DEFAULT_RESOLVED_KEYBINDINGS } from "@t3tools/shared/keybindings";
import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
@@ -13,6 +17,8 @@ import React, { useCallback, useMemo, useState } from "react";
import { commandForProjectScript, primaryProjectScript } from "~/projectScripts";
import { shortcutLabelForCommand } from "~/keybindings";
import { serverEnvironment } from "~/state/server";
import { readEnvironmentScope } from "~/state/session";
import {
EMPTY_PROJECT_SCRIPT_INPUT,
editorRequestForScript,
@@ -55,10 +61,10 @@ interface ProjectScriptsControlProps {
displayMode?: "toolbar" | "panel";
presentation?: "toolbar" | "menu";
onRequestMenuClose?: () => void;
environmentId: EnvironmentId;
scripts: ReadonlyArray<ProjectScript>;
/** Scripts declared in the project's checked-in t3.json, offered for import. */
fileScripts?: ReadonlyArray<T3ProjectFileScript>;
keybindings: ResolvedKeybindingsConfig;
preferredScriptId?: string | null;
onRunScript: (script: ProjectScript) => void;
onAddScript: (input: NewProjectScriptInput) => Promise<ProjectScriptActionResult>;
@@ -73,9 +79,9 @@ export default function ProjectScriptsControl({
displayMode = "toolbar",
presentation = "toolbar",
onRequestMenuClose,
environmentId,
scripts,
fileScripts = NO_FILE_SCRIPTS,
keybindings,
preferredScriptId = null,
onRunScript,
onAddScript,
@@ -85,6 +91,9 @@ export default function ProjectScriptsControl({
const isPanel = displayMode === "panel";
const ActionGroup = isPanel ? "div" : Group;
const panelAnchorRef = React.useRef<HTMLDivElement | null>(null);
const keybindings =
useAtomValue(serverEnvironment.configValueAtom(environmentId))?.keybindings ??
DEFAULT_RESOLVED_KEYBINDINGS;
const [actionsMenuOpen, setActionsMenuOpen] = useState({
presentation,
scripts: false,
@@ -138,7 +147,7 @@ export default function ProjectScriptsControl({
icon: fileScript.icon ?? "play",
runOnWorktreeCreate: fileScript.runOnWorktreeCreate ?? false,
waitForSetup: fileScript.runOnWorktreeCreate === true && fileScript.async === false,
keybinding: null,
...(readEnvironmentScope(environmentId, AuthSettingsWriteScope) ? { keybinding: null } : {}),
previewUrl: fileScript.previewUrl ?? null,
autoOpenPreview: fileScript.previewUrl ? (fileScript.autoOpenPreview ?? false) : false,
};
@@ -459,6 +468,7 @@ export default function ProjectScriptsControl({
)}
<ProjectScriptEditorDialog
environmentId={environmentId}
request={editorRequest}
scripts={scripts}
onSubmit={submitScript}
@@ -1,6 +1,8 @@
import type { Dispatch, ReactElement, SetStateAction } from "react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
import {
AuthProvidersManageScope,
type AuthEnvironmentScope,
type EnvironmentId,
ProviderDriverKind,
ProviderInstanceId,
@@ -16,6 +18,7 @@ import type {
const testState = vi.hoisted(() => ({
groups: [] as LocalEnvironmentUpdateGroup[],
permittedEnvironmentIds: new Set<EnvironmentId>(),
updateProvider: vi.fn(),
}));
@@ -90,6 +93,15 @@ vi.mock("~/state/server", () => ({
serverEnvironment: { updateProvider: Symbol("updateProvider") },
}));
vi.mock("~/state/session", () => ({
readEnvironmentScope: (environmentId: EnvironmentId, scope: AuthEnvironmentScope) =>
scope === AuthProvidersManageScope && testState.permittedEnvironmentIds.has(environmentId),
useEnvironmentScope: (environmentId: EnvironmentId | null, scope: AuthEnvironmentScope) =>
environmentId !== null &&
scope === AuthProvidersManageScope &&
testState.permittedEnvironmentIds.has(environmentId),
}));
vi.mock("~/state/use-atom-command", () => ({
useAtomCommand: () => testState.updateProvider,
}));
@@ -176,6 +188,8 @@ describe("ProviderUpdateEnvironmentRows", () => {
beforeEach(() => {
vi.useFakeTimers();
hooks.reset();
testState.permittedEnvironmentIds.clear();
testState.permittedEnvironmentIds.add(environmentId);
testState.updateProvider.mockReset();
const candidate = provider() as ProviderUpdateCandidate;
testState.groups = [
@@ -1,6 +1,10 @@
import { CheckIcon } from "lucide-react";
import { type ReactNode, useCallback, useMemo, useRef, useState } from "react";
import type { EnvironmentId, ServerProvider } from "@t3tools/contracts";
import {
AuthProvidersManageScope,
type EnvironmentId,
type ServerProvider,
} from "@t3tools/contracts";
import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
@@ -9,6 +13,7 @@ import {
import { cn } from "~/lib/utils";
import { serverEnvironment } from "~/state/server";
import { readEnvironmentScope, useEnvironmentScope } from "~/state/session";
import { useAtomCommand } from "~/state/use-atom-command";
import { useLocalEnvironmentUpdateGroups } from "./ProviderUpdateLaunchNotification.environments";
import {
@@ -115,6 +120,7 @@ function EnvironmentUpdateRow({
readonly status: ProviderUpdateRowStatus;
readonly onUpdate: () => void;
}) {
const canManageProviders = useEnvironmentScope(group.environmentId, AuthProvidersManageScope);
let trailing: ReactNode;
switch (status.kind) {
case "loading":
@@ -126,14 +132,14 @@ function EnvironmentUpdateRow({
case "failed":
case "unchanged":
trailing = (
<Button size="xs" variant="outline" onClick={onUpdate}>
<Button size="xs" variant="outline" disabled={!canManageProviders} onClick={onUpdate}>
Retry
</Button>
);
break;
default:
trailing = (
<Button size="xs" variant="outline" onClick={onUpdate}>
<Button size="xs" variant="outline" disabled={!canManageProviders} onClick={onUpdate}>
Update
</Button>
);
@@ -145,6 +151,11 @@ function EnvironmentUpdateRow({
<div className="flex min-w-0 flex-col">
<span className="truncate font-medium text-foreground">{group.label}</span>
<span className={cn("truncate text-xs", rowToneClass(status.kind))}>{status.text}</span>
{!canManageProviders ? (
<span className="text-xs text-muted-foreground">
This connection cannot manage provider accounts.
</span>
) : null}
</div>
<div className="shrink-0">{trailing}</div>
</div>
@@ -211,6 +222,7 @@ export function ProviderUpdateEnvironmentRows({
const handleUpdate = useCallback(
async (environmentId: EnvironmentId) => {
if (!readEnvironmentScope(environmentId, AuthProvidersManageScope)) return;
const group = groupByEnvironment.get(environmentId);
if (!group || group.candidates.length === 0) {
return;
@@ -2,10 +2,15 @@ import { useNavigate } from "@tanstack/react-router";
import { useAtomValue } from "@effect/atom-react";
import { DownloadIcon } from "lucide-react";
import { useCallback, useEffect, useMemo, useRef } from "react";
import { type ServerProvider, type ProviderInstanceId } from "@t3tools/contracts";
import {
AuthProvidersManageScope,
type ServerProvider,
type ProviderInstanceId,
} from "@t3tools/contracts";
import { primaryServerProvidersAtom, serverEnvironment } from "../state/server";
import { usePrimaryEnvironment } from "../state/environments";
import { readEnvironmentScope, useEnvironmentScope } from "../state/session";
import { useDismissedProviderUpdateNotificationKeys } from "../providerUpdateDismissal";
import { ProviderInstanceIcon } from "./chat/ProviderInstanceIcon";
import {
@@ -27,7 +32,12 @@ const seenProviderUpdateNotificationKeys = new Set<string>();
type ProviderUpdateToastId = ReturnType<typeof toastManager.add>;
type ActiveProviderUpdateToast =
| { readonly kind: "prompt"; readonly key: string; readonly toastId: ProviderUpdateToastId }
| {
readonly kind: "prompt";
readonly key: string;
readonly toastId: ProviderUpdateToastId;
readonly canManageProviders: boolean;
}
| {
readonly kind: "update";
readonly key: string;
@@ -100,6 +110,10 @@ export function ProviderUpdatePrimaryNotification() {
const navigate = useNavigate();
const providers = useAtomValue(primaryServerProvidersAtom);
const primaryEnvironment = usePrimaryEnvironment();
const canManageProviders = useEnvironmentScope(
primaryEnvironment?.environmentId ?? null,
AuthProvidersManageScope,
);
const updateProvider = useAtomCommand(serverEnvironment.updateProvider, {
reportFailure: false,
});
@@ -178,11 +192,15 @@ export function ProviderUpdatePrimaryNotification() {
activeToastRef.current = null;
}
const updateExistingPrompt =
activeToast?.kind === "prompt" &&
activeToast.key === notificationKey &&
activeToast.canManageProviders !== canManageProviders;
if (
!notificationKey ||
dismissedNotificationKeys.has(notificationKey) ||
seenProviderUpdateNotificationKeys.has(notificationKey) ||
activeToastRef.current
(seenProviderUpdateNotificationKeys.has(notificationKey) && !updateExistingPrompt) ||
(activeToastRef.current && !updateExistingPrompt)
) {
return;
}
@@ -199,7 +217,12 @@ export function ProviderUpdatePrimaryNotification() {
};
const runUpdates = () => {
if (updateStarted || oneClickProviders.length === 0 || !primaryEnvironment) {
if (
updateStarted ||
oneClickProviders.length === 0 ||
!primaryEnvironment ||
!readEnvironmentScope(primaryEnvironment.environmentId, AuthProvidersManageScope)
) {
return;
}
updateStarted = true;
@@ -219,6 +242,19 @@ export function ProviderUpdatePrimaryNotification() {
void (async () => {
const results = [];
for (const provider of oneClickProviders) {
if (!readEnvironmentScope(primaryEnvironment.environmentId, AuthProvidersManageScope)) {
if (activeToastRef.current === activeUpdate) {
addProviderUpdateToast({
view: getProviderUpdateRejectedToastView(
providerCount,
"This connection cannot manage provider accounts.",
),
openSettings: openProviderSettings,
});
activeToastRef.current = null;
}
return;
}
results.push(
await updateProvider({
environmentId: primaryEnvironment.environmentId,
@@ -260,44 +296,52 @@ export function ProviderUpdatePrimaryNotification() {
})();
};
toastId = toastManager.add(
stackedThreadToast({
type: initialView.type,
title: initialView.title,
description: initialView.description,
timeout: 0,
actionProps:
oneClickProviders.length > 0
? {
children: "Update",
onClick: runUpdates,
}
: {
const toastOptions = stackedThreadToast({
type: initialView.type,
title: initialView.title,
description: canManageProviders
? initialView.description
: "This connection cannot manage provider accounts. View provider settings for update details.",
timeout: 0,
actionProps:
oneClickProviders.length > 0
? {
children: "Update",
disabled: !canManageProviders,
onClick: runUpdates,
}
: {
children: "Settings",
onClick: openSettings,
},
actionVariant: "outline",
data: {
leadingIcon:
updateProviders.length === 1 ? (
<ProviderUpdateToastIcon provider={updateProviders[0]!} />
) : undefined,
hideCopyButton: true,
onClose: dismissPrompt,
...(oneClickProviders.length > 0
? {
secondaryActionProps: {
children: "Settings",
onClick: openSettings,
},
actionVariant: "outline",
data: {
leadingIcon:
updateProviders.length === 1 ? (
<ProviderUpdateToastIcon provider={updateProviders[0]!} />
) : undefined,
hideCopyButton: true,
onClose: dismissPrompt,
...(oneClickProviders.length > 0
? {
secondaryActionProps: {
children: "Settings",
onClick: openSettings,
},
secondaryActionVariant: "outline" as const,
}
: {}),
},
}),
);
activeToastRef.current = { kind: "prompt", key: notificationKey, toastId };
secondaryActionVariant: "outline" as const,
}
: {}),
},
});
if (updateExistingPrompt && activeToast?.kind === "prompt") {
toastId = activeToast.toastId;
toastManager.update(toastId, toastOptions);
} else {
toastId = toastManager.add(toastOptions);
}
activeToastRef.current = { kind: "prompt", key: notificationKey, toastId, canManageProviders };
}, [
canManageProviders,
updateProvider,
dismissNotificationKey,
dismissedNotificationKeys,
@@ -1,8 +1,9 @@
import { act, type ReactElement } from "react";
import { create, type ReactTestRenderer } from "react-test-renderer";
import { renderToStaticMarkup } from "react-dom/server";
import type { EnvironmentId, ServerInstallation } from "@t3tools/contracts";
import { AuthSessionState, type EnvironmentId, type ServerInstallation } from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as Schema from "effect/Schema";
import { AsyncResult } from "effect/reactivity";
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
@@ -11,6 +12,8 @@ const testState = vi.hoisted(() => ({
toast: vi.fn(),
clipboard: vi.fn(),
continueThreadsAfterServerUpdate: false,
session: null as AsyncResult.AsyncResult<AuthSessionState, Error> | null,
sessionAtom: Symbol("session"),
}));
vi.mock("~/hooks/useCopyToClipboard", () => ({
@@ -27,6 +30,13 @@ vi.mock("~/hooks/useSettings", () => ({
selector: (settings: { continueThreadsAfterServerUpdate: boolean }) => unknown,
) => selector({ continueThreadsAfterServerUpdate: testState.continueThreadsAfterServerUpdate }),
}));
vi.mock("@effect/atom-react", () => ({ useAtomValue: () => testState.session }));
vi.mock("~/rpc/atomRegistry", () => ({
appAtomRegistry: { get: () => testState.session },
}));
vi.mock("~/state/session", () => ({
environmentSession: { sessionStateAtom: () => testState.sessionAtom },
}));
vi.mock("~/state/server", () => ({
serverEnvironment: { updateServer: Symbol("updateServer") },
}));
@@ -50,6 +60,8 @@ import {
type ServerUpdateTarget,
} from "./ServerUpdateAction";
const decodeSessionState = Schema.decodeUnknownSync(AuthSessionState);
type ActionElement = ReactElement<{
readonly onClick?: () => void;
}>;
@@ -68,12 +80,86 @@ async function flushPromises(): Promise<void> {
await Promise.resolve();
}
const legacyAuth = {
policy: "remote-reachable",
bootstrapMethods: ["one-time-token"],
sessionMethods: ["bearer-access-token"],
sessionCookieName: "t3_session",
} as const;
const currentSession = {
authenticated: true,
scopes: ["environment:maintain"],
auth: {
...legacyAuth,
serverUpdateScope: "environment:maintain",
},
} as const satisfies AuthSessionState;
describe("ServerUpdateAction", () => {
beforeEach(() => {
testState.updateServer.mockReset();
testState.toast.mockReset();
testState.clipboard.mockReset();
testState.continueThreadsAfterServerUpdate = false;
testState.session = AsyncResult.success(currentSession);
});
it.each([
{ serverUpdateScope: undefined, scopes: ["orchestration:operate"], allowed: true },
{ serverUpdateScope: undefined, scopes: ["orchestration:read"], allowed: false },
{
serverUpdateScope: "environment:maintain",
scopes: ["orchestration:operate"],
allowed: false,
},
{
serverUpdateScope: "environment:maintain",
scopes: ["environment:maintain"],
allowed: true,
},
] as const)(
"uses the advertised update scope $serverUpdateScope with grant $scopes",
async ({ serverUpdateScope, scopes, allowed }) => {
testState.session = AsyncResult.success(
decodeSessionState({
...currentSession,
scopes,
auth: {
...legacyAuth,
...(serverUpdateScope === undefined ? {} : { serverUpdateScope }),
},
}),
);
testState.updateServer.mockResolvedValue(
AsyncResult.success({ targetVersion: "0.0.31", method: "boot-service" as const }),
);
renderAction().props.onClick?.();
await flushPromises();
expect(testState.updateServer).toHaveBeenCalledTimes(allowed ? 1 : 0);
},
);
it("keeps a known grant usable while the session refreshes", async () => {
testState.session = AsyncResult.waiting(AsyncResult.success(currentSession));
testState.updateServer.mockResolvedValue(
AsyncResult.success({ targetVersion: "0.0.31", method: "boot-service" as const }),
);
renderAction().props.onClick?.();
await flushPromises();
expect(testState.updateServer).toHaveBeenCalledOnce();
});
it("does not dispatch an update after maintenance access is removed", async () => {
const action = renderAction();
testState.session = AsyncResult.success({ ...currentSession, scopes: [] });
action.props.onClick?.();
await flushPromises();
expect(testState.updateServer).not.toHaveBeenCalled();
});
it.each([
+36 -3
View File
@@ -1,3 +1,7 @@
import { useAtomValue } from "@effect/atom-react";
import { AuthOrchestrationOperateScope, type AuthSessionState } from "@t3tools/contracts";
import type { AsyncResult } from "effect/reactivity";
import { environmentSession } from "~/state/session";
import type {
EnvironmentId,
ServerInstallation,
@@ -15,6 +19,7 @@ import { requestConfirmDialog } from "~/confirmDialog";
import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
import { useEnvironmentSettings } from "~/hooks/useSettings";
import { serverEnvironment, updateOutdatedServer } from "~/state/server";
import { appAtomRegistry } from "~/rpc/atomRegistry";
import { useAtomCommand } from "~/state/use-atom-command";
import { manualServerUpdateCommand } from "~/versionSkew";
import { Button } from "./ui/button";
@@ -60,7 +65,11 @@ function useServerUpdate() {
const updateServer = useAtomCommand(serverEnvironment.updateServer, { reportFailure: false });
return async (target: ServerUpdateTarget, failureTitle = "Server update failed") => {
const { environmentId, serverLabel, selfUpdate, targetVersion } = target;
if (pendingUpdateEnvironmentIds.has(environmentId)) return;
if (
!canUpdateServer(appAtomRegistry.get(environmentSession.sessionStateAtom(environmentId))) ||
pendingUpdateEnvironmentIds.has(environmentId)
)
return;
pendingUpdateEnvironmentIds.add(environmentId);
try {
const result = await updateServer({
@@ -151,6 +160,17 @@ export function ServerUpdatesAction({
);
}
function canUpdateServer(result: AsyncResult.AsyncResult<AuthSessionState, unknown>): boolean {
if (result._tag !== "Success" || !result.value.authenticated) return false;
const session = result.value;
// Only self-update bridges the old authorization protocol. Upgraded servers
// advertise the new scope even when this client's grant predates it.
return (
session.scopes?.includes(session.auth.serverUpdateScope ?? AuthOrchestrationOperateScope) ===
true
);
}
/**
* One-row status for an in-flight server update: "Downloading…" then
* "Restarting…". The update is a wait, not a warning: a single pulsing dot
@@ -204,6 +224,8 @@ export function ServerUpdateAction({
appearance = "button",
}: Omit<ServerUpdateTarget, "continueThreadsAfterServerUpdate"> & UpdateButtonProps) {
const isDesktopAppUpdate = selfUpdate === "desktop-managed";
const sessionStateAtom = environmentSession.sessionStateAtom(environmentId);
const canUpdate = canUpdateServer(useAtomValue(sessionStateAtom));
const continueThreadsAfterServerUpdate = useEnvironmentSettings(
environmentId,
(settings) => settings.continueThreadsAfterServerUpdate,
@@ -232,7 +254,10 @@ export function ServerUpdateAction({
});
const handleUpdate = async () => {
if (pendingUpdateEnvironmentIds.has(environmentId)) {
if (
!canUpdateServer(appAtomRegistry.get(sessionStateAtom)) ||
pendingUpdateEnvironmentIds.has(environmentId)
) {
return;
}
if (isDesktopAppUpdate) {
@@ -247,6 +272,7 @@ export function ServerUpdateAction({
return;
}
}
if (!canUpdateServer(appAtomRegistry.get(sessionStateAtom))) return;
await update({
environmentId,
serverLabel,
@@ -289,6 +315,7 @@ export function ServerUpdateAction({
variant="ghost-muted"
className={className}
aria-label={`${actionLabel} for ${serverLabel}`}
disabled={manualCommand === null && !canUpdate}
onClick={onClick}
/>
}
@@ -301,7 +328,13 @@ export function ServerUpdateAction({
}
return (
<Button size={size} variant={variant} className={className} onClick={onClick}>
<Button
size={size}
variant={variant}
className={className}
disabled={manualCommand === null && !canUpdate}
onClick={onClick}
>
{actionLabel}
</Button>
);
+26 -1
View File
@@ -38,6 +38,7 @@ import type {
SnapShotSource,
} from "@t3tools/contracts";
import {
AuthOrchestrationOperateScope,
ProviderDriverKind,
ProviderInstanceId,
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
@@ -1130,6 +1131,7 @@ import { useDelayedStatus } from "../../hooks/useDelayedStatus";
import { useMediaQuery } from "../../hooks/useMediaQuery";
import { usePanelAnimationSettings } from "../../panelAnimations";
import { useAtomCommand } from "../../state/use-atom-command";
import { readEnvironmentScope } from "../../state/session";
import { serverEnvironment } from "../../state/server";
import type { ReviewCommentContext } from "../../reviewCommentContext";
@@ -1348,6 +1350,7 @@ const ComposerFooterModeControls = memo(function ComposerFooterModeControls(prop
const ComposerFooterPrimaryActions = memo(function ComposerFooterPrimaryActions(props: {
compact: boolean;
canOperateThread: boolean;
activeContextWindow: ContextWindowSnapshot | null;
reserveContextWindowMeter: boolean;
activeThreadModelDisplayName: string | null;
@@ -1397,6 +1400,7 @@ const ComposerFooterPrimaryActions = memo(function ComposerFooterPrimaryActions(
) : null}
<ComposerPrimaryActions
compact={props.compact}
canOperateThread={props.canOperateThread}
pendingAction={props.pendingAction}
isRunning={props.isRunning}
canInterrupt={props.canInterrupt}
@@ -1499,6 +1503,7 @@ export interface ChatComposerHandle {
export interface ChatComposerProps {
composerDraftTarget: ScopedThreadRef | DraftId;
environmentId: EnvironmentId;
canOperateThread: boolean;
attachmentUploadsCapabilityKnown: boolean;
supportsAttachmentUploads: boolean;
supportsQuestionAttachments: boolean;
@@ -1685,6 +1690,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
const {
composerDraftTarget,
environmentId,
canOperateThread,
attachmentUploadsCapabilityKnown,
supportsAttachmentUploads,
supportsQuestionAttachments,
@@ -2001,6 +2007,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
}
return;
}
if (!canOperateThread) return;
const invalidFiles =
maxFileAttachmentBytes === null
? composerFiles
@@ -2027,6 +2034,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
}, [
attachmentUploadsCapabilityKnown,
attachmentDraftTarget,
canOperateThread,
composerFiles,
composerImages,
environmentId,
@@ -4147,7 +4155,11 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
dispatchMode?: ComposerDispatchMode,
submissionIntent?: ComposerSubmissionIntent,
) => {
if (noProviderAvailable || isSendDisabled) {
if (
noProviderAvailable ||
isSendDisabled ||
!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)
) {
event?.preventDefault();
return;
}
@@ -4210,6 +4222,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
activePendingProgress,
attachmentTargetKey,
blurMobileComposerAfterSend,
environmentId,
isSendDisabled,
noProviderAvailable,
onSend,
@@ -4245,6 +4258,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
}, [phase, settings.followUpBehavior, submitComposer]);
const compactThreadContext = useCallback(() => {
if (
!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope) ||
compactDisabled ||
noProviderAvailable ||
activePendingApproval !== null ||
@@ -4261,6 +4275,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
activePendingApproval,
activeThreadId,
compactDisabled,
composerDraftTarget,
environmentId,
isConnecting,
isSendBusy,
noProviderAvailable,
@@ -6650,6 +6666,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
<ComposerBanner.Actions>
<ComposerPendingApprovalActions
requestId={activePendingApproval.requestId}
disabled={!canOperateThread}
isResponding={respondingRequestIds.includes(
activePendingApproval.requestId,
)}
@@ -6662,6 +6679,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
) : !isComposerCollapsedMobile && pendingUserInputs.length > 0 ? (
<ComposerPendingUserInputPanel
pendingUserInputs={pendingUserInputs}
disabled={!canOperateThread}
respondingRequestIds={
activePendingIsResponding && activePendingUserInput
? [...respondingRequestIds, activePendingUserInput.requestId]
@@ -6682,6 +6700,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
<div data-chat-composer-collapsed-controls="true">
<ComposerPendingUserInputPanel
pendingUserInputs={pendingUserInputs}
disabled={!canOperateThread}
respondingRequestIds={
activePendingIsResponding && activePendingUserInput
? [...respondingRequestIds, activePendingUserInput.requestId]
@@ -6723,6 +6742,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
{activePendingProgress?.activeQuestion?.multiSelect ? (
<ComposerPrimaryActions
compact
canOperateThread={canOperateThread}
pendingAction={pendingPrimaryAction}
isRunning={false}
canInterrupt={false}
@@ -7079,6 +7099,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
draftTarget: attachmentDraftTarget,
})
}
disabled={!canOperateThread}
aria-label={`Retry upload for ${image.name}`}
/>
}
@@ -7178,6 +7199,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
draftTarget: attachmentDraftTarget,
})
}
disabled={!canOperateThread}
aria-label={`Retry upload for ${file.name}`}
/>
}
@@ -7256,6 +7278,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
draftTarget: attachmentDraftTarget,
})
}
disabled={!canOperateThread}
aria-label={`Retry upload for ${file.name}`}
/>
}
@@ -7408,6 +7431,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
>
<ComposerPrimaryActions
compact
canOperateThread={canOperateThread}
pendingAction={pendingPrimaryAction}
isRunning={false}
canInterrupt={false}
@@ -7513,6 +7537,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
) : null}
<ComposerFooterPrimaryActions
compact={isComposerResting || isComposerPrimaryActionsCompact}
canOperateThread={canOperateThread}
activeContextWindow={
settings.contextWindowMeterEnabled ? activeContextWindow : null
}
@@ -14,6 +14,7 @@ interface ComposerPendingApprovalActionsProps {
requestId: RuntimeRequestId;
isResponding: boolean;
canRespond: boolean;
disabled?: boolean;
options?: ReadonlyArray<ProviderApprovalOption> | undefined;
onRespondToApproval: (
requestId: RuntimeRequestId,
@@ -32,6 +33,7 @@ export const ComposerPendingApprovalActions = memo(function ComposerPendingAppro
requestId,
isResponding,
canRespond,
disabled = false,
options = DEFAULT_APPROVAL_OPTIONS,
onRespondToApproval,
}: ComposerPendingApprovalActionsProps) {
@@ -50,9 +52,13 @@ export const ComposerPendingApprovalActions = memo(function ComposerPendingAppro
key={option.decision}
size="xs"
variant={option.decision === "accept" ? "default" : "outline"}
disabled={isResponding || !canRespond}
disabled={disabled || isResponding || !canRespond}
aria-description={option.warning}
onClick={() => void onRespondToApproval(requestId, option.decision)}
onClick={() => {
if (!disabled && !isResponding) {
void onRespondToApproval(requestId, option.decision);
}
}}
>
{option.warning ? <TriangleAlertIcon className="size-3 shrink-0" /> : null}
<span className="max-w-40 truncate">{option.label}</span>
@@ -70,7 +76,7 @@ export const ComposerPendingApprovalActions = memo(function ComposerPendingAppro
{moreOptions.length > 0 ? (
<Menu>
<MenuTrigger
disabled={isResponding}
disabled={disabled || isResponding}
render={<Button size="icon-xs" variant="outline" aria-label="More approval options" />}
>
<EllipsisIcon />
@@ -80,9 +86,12 @@ export const ComposerPendingApprovalActions = memo(function ComposerPendingAppro
const item = (
<MenuItem
key={option.decision}
disabled={isResponding}
disabled={disabled || isResponding}
aria-description={option.warning}
onClick={() => void onRespondToApproval(requestId, option.decision)}
onClick={() => {
if (!disabled && !isResponding)
void onRespondToApproval(requestId, option.decision);
}}
variant="ghost"
className="mb-1 last:mb-0"
>
@@ -0,0 +1,93 @@
import { RuntimeRequestId } from "@t3tools/contracts";
import { act, type ReactNode } from "react";
import { create, type ReactTestRenderer } from "react-test-renderer";
import { expect, it, vi } from "vite-plus/test";
vi.mock("../ui/collapsible", () => {
const Children = ({ children }: { children: ReactNode }) => <>{children}</>;
return {
Collapsible: Children,
CollapsiblePanel: Children,
CollapsibleTrigger: Children,
};
});
import { ComposerPendingUserInputPanel } from "./ComposerPendingUserInputPanel";
it("cancels an answer's pending auto-submit on revocation and resumes after a new grant", async () => {
vi.useFakeTimers();
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
vi.stubGlobal("window", {
setTimeout: globalThis.setTimeout,
clearTimeout: globalThis.clearTimeout,
});
vi.stubGlobal("document", { addEventListener: vi.fn(), removeEventListener: vi.fn() });
const onToggleOption = vi.fn();
const onAdvance = vi.fn();
const onDismiss = vi.fn();
const prompt = {
requestId: RuntimeRequestId.make("scoped-answer"),
createdAt: "2026-09-05T00:00:00.000Z",
dismissible: false,
responseCapability: "live" as const,
questions: [
{
id: "approach",
header: "Approach",
question: "Which approach?",
options: [{ label: "Incremental", description: "One module at a time" }],
multiSelect: false,
},
],
};
const panel = (disabled: boolean) => (
<ComposerPendingUserInputPanel
pendingUserInputs={[prompt]}
disabled={disabled}
respondingRequestIds={[]}
answers={{}}
questionIndex={0}
onToggleOption={onToggleOption}
onAdvance={onAdvance}
onDismiss={onDismiss}
/>
);
let renderer: ReactTestRenderer | undefined;
const chooseOption = () => {
const option = renderer!.root
.findAllByType("button")
.find((button) =>
button.findAllByType("span").some((span) => span.children.includes("Incremental")),
);
expect(option).toBeDefined();
option!.props.onClick();
};
try {
await act(async () => {
renderer = create(panel(false));
});
await act(async () => chooseOption());
expect(onToggleOption).toHaveBeenCalledWith("approach", "Incremental");
expect(onAdvance).not.toHaveBeenCalled();
await act(async () => renderer!.update(panel(true)));
await act(async () => {
chooseOption();
vi.runAllTimers();
});
expect(onToggleOption).toHaveBeenCalledTimes(1);
expect(onAdvance).not.toHaveBeenCalled();
await act(async () => renderer!.update(panel(false)));
await act(async () => {
chooseOption();
vi.runAllTimers();
});
expect(onToggleOption).toHaveBeenCalledTimes(2);
expect(onAdvance).toHaveBeenCalledTimes(1);
} finally {
await act(async () => renderer?.unmount());
vi.unstubAllGlobals();
vi.useRealTimers();
}
});
@@ -12,6 +12,7 @@ import { ComposerBanner } from "./ComposerBanner";
interface PendingUserInputPanelProps {
pendingUserInputs: PendingUserInput[];
disabled?: boolean;
respondingRequestIds: RuntimeRequestId[];
answers: Record<string, PendingUserInputDraftAnswer>;
questionIndex: number;
@@ -22,6 +23,7 @@ interface PendingUserInputPanelProps {
export const ComposerPendingUserInputPanel = memo(function ComposerPendingUserInputPanel({
pendingUserInputs,
disabled = false,
respondingRequestIds,
answers,
questionIndex,
@@ -37,6 +39,7 @@ export const ComposerPendingUserInputPanel = memo(function ComposerPendingUserIn
<ComposerPendingUserInputCard
key={activePrompt.requestId}
prompt={activePrompt}
disabled={disabled}
isResponding={respondingRequestIds.includes(activePrompt.requestId)}
answers={answers}
questionIndex={questionIndex}
@@ -49,6 +52,7 @@ export const ComposerPendingUserInputPanel = memo(function ComposerPendingUserIn
const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard({
prompt,
disabled,
isResponding,
answers,
questionIndex,
@@ -57,6 +61,7 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
onDismiss,
}: {
prompt: PendingUserInput;
disabled: boolean;
isResponding: boolean;
answers: Record<string, PendingUserInputDraftAnswer>;
questionIndex: number;
@@ -66,7 +71,7 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
}) {
// Message-mode requests remain answerable after their provider turn ends.
const canRespond = prompt.responseCapability !== "not_resumable";
const responseDisabled = isResponding || !canRespond;
const responseDisabled = disabled || isResponding || !canRespond;
const progress = derivePendingUserInputProgress(prompt.questions, answers, questionIndex);
const activeQuestion = progress.activeQuestion;
const autoAdvanceTimerRef = useRef<number | null>(null);
@@ -88,6 +93,13 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
onAdvanceRef.current = onAdvance;
}, [onAdvance]);
useEffect(() => {
if (disabled && autoAdvanceTimerRef.current !== null) {
window.clearTimeout(autoAdvanceTimerRef.current);
autoAdvanceTimerRef.current = null;
}
}, [disabled]);
useEffect(() => {
if (!activeQuestion || activeQuestion.multiSelect || !optimisticSingleSelect) {
return;
@@ -120,6 +132,7 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
const handleOptionSelection = useCallback(
(questionId: string, optionValue: string) => {
if (disabled || isResponding) return;
if (activeQuestion?.multiSelect) {
onToggleOption(questionId, optionValue);
return;
@@ -134,7 +147,7 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
onAdvanceRef.current();
}, 200);
},
[activeQuestion, onToggleOption],
[activeQuestion, disabled, isResponding, onToggleOption],
);
// Keyboard shortcut: number keys 1-9 select corresponding options when focus is
@@ -252,8 +265,8 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
isSelected
? "bg-muted/55 text-foreground"
: "bg-transparent text-foreground/85 hover:bg-muted/30",
isResponding && "opacity-50 cursor-not-allowed",
!isResponding && "cursor-pointer",
(disabled || isResponding) && "opacity-50 cursor-not-allowed",
!disabled && !isResponding && "cursor-pointer",
);
const content = (
<>
@@ -280,7 +293,7 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
<button
key={`${activeQuestion.id}:${optionValue}`}
type="button"
disabled={isResponding}
disabled={disabled || isResponding}
onClick={() => {
handleOptionSelection(activeQuestion.id, optionValue);
}}
@@ -21,6 +21,7 @@ function renderPendingActions(isRunning: boolean) {
return renderToStaticMarkup(
createElement(ComposerPrimaryActions, {
compact: true,
canOperateThread: true,
pendingAction: {
questionIndex: 0,
isLastQuestion: true,
@@ -49,6 +50,7 @@ function renderSendButton(sendDisabledReason: string | null = null) {
return renderToStaticMarkup(
createElement(ComposerPrimaryActions, {
compact: true,
canOperateThread: true,
pendingAction: null,
isRunning: false,
canInterrupt: false,
@@ -26,6 +26,7 @@ interface PendingActionState {
interface ComposerPrimaryActionsProps {
compact: boolean;
canOperateThread: boolean;
pendingAction: PendingActionState | null;
/** The turn is running: sending steers or queues instead of starting a turn. */
isRunning: boolean;
@@ -80,6 +81,7 @@ const preventPointerFocus: PointerEventHandler<HTMLElement> = (event) => {
export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
compact,
canOperateThread,
pendingAction,
isRunning,
canInterrupt,
@@ -115,7 +117,7 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
alternateModifier: shortcutModifiers.metaKey || shortcutModifiers.ctrlKey,
}) === "queue";
const alternateAction = alternateComposerDispatchAction(followUpBehavior);
const isSendDisabled = sendDisabledReason !== null;
const isSendDisabled = !canOperateThread || sendDisabledReason !== null;
const stageBackdropVariant = useSidebarStageBackdropVariant(
environmentIdentificationMode === "artwork",
);
@@ -131,7 +133,10 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
insidePendingAction ? "size-8 sm:size-7" : "size-8 sm:h-8 sm:w-8",
)}
{...pointerFocusProps}
onClick={onInterrupt}
disabled={!canOperateThread}
onClick={() => {
if (canOperateThread) onInterrupt();
}}
aria-label="Stop generation"
/>
}
@@ -177,6 +182,7 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
className={cn(messageActionPillClassName, "h-8 sm:h-7", compact ? "px-3" : "px-4")}
{...pointerFocusProps}
disabled={
!canOperateThread ||
isEnvironmentUnavailable ||
pendingAction.isResponding ||
(pendingAction.isLastQuestion ? !pendingAction.isComplete : !pendingAction.canAdvance)
@@ -237,7 +243,9 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
<MenuPopup align="end" side="top" {...composerFloatingLayerProps}>
<MenuItem
disabled={isSendBusy || isSendDisabled || isConnecting || isEnvironmentUnavailable}
onClick={() => void onImplementPlanInNewThread()}
onClick={() => {
if (canOperateThread) onImplementPlanInNewThread();
}}
>
Implement in a new thread
</MenuItem>
@@ -0,0 +1,226 @@
import { AuthOrchestrationOperateScope, EnvironmentId, type EditorId } from "@t3tools/contracts";
import { DEFAULT_RESOLVED_KEYBINDINGS } from "@t3tools/shared/keybindings";
import { AsyncResult } from "effect/reactivity";
import { cloneElement, useState, type ReactElement, type ReactNode } from "react";
import { act, create, type ReactTestRenderer } from "react-test-renderer";
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
import type { RemoteOpenState } from "../../remoteOpen";
const state = vi.hoisted(() => ({
allowed: new Set<string>(),
remote: { mode: "local-exec" } as RemoteOpenState,
run: vi.fn(),
openUrl: vi.fn(),
setPreferred: vi.fn(),
markHintSeen: vi.fn(),
keydown: null as ((event: KeyboardEvent) => void) | null,
listeners: new Set<() => void>(),
}));
vi.mock("../../state/session", async () => {
const { useSyncExternalStore } = await import("react");
const readEnvironmentScope = (environmentId: string, scope: string) =>
scope === AuthOrchestrationOperateScope && state.allowed.has(environmentId);
return {
readEnvironmentScope,
useEnvironmentScope: (environmentId: string, scope: string) =>
useSyncExternalStore(
(listener) => {
state.listeners.add(listener);
return () => state.listeners.delete(listener);
},
() => readEnvironmentScope(environmentId, scope),
),
};
});
vi.mock("../../state/shell", () => ({ shellEnvironment: { openInEditor: "openInEditor" } }));
vi.mock("../../state/use-atom-command", () => ({ useAtomCommand: () => state.run }));
vi.mock("../../state/environments", () => ({ useEnvironment: () => ({ label: "Test host" }) }));
vi.mock("../../editorPreferences", () => ({
usePreferredEditor: (available: readonly EditorId[]) => [
available[0] ?? null,
state.setPreferred,
],
}));
vi.mock("../../remoteOpen", () => ({
useRemoteOpenState: () => state.remote,
useRemoteCapableEditors: () => editors,
useRemoteOpenHint: () => [false, state.markHintSeen],
openRemoteEditorUrl: state.openUrl,
}));
vi.mock("../../keybindings", () => ({
isOpenFavoriteEditorShortcut: () => true,
shortcutLabelForCommand: () => "Ctrl+O",
}));
vi.mock("../ui/button", () => ({ Button: "button" }));
vi.mock("../ui/group", () => ({ Group: "div", GroupSeparator: "span" }));
vi.mock("../ui/menu", () => ({
Menu: ({
open,
onOpenChange,
children,
}: {
open?: boolean;
onOpenChange?: (open: boolean) => void;
children: ReactNode;
}) => {
const [uncontrolledOpen, setUncontrolledOpen] = useState(false);
const visible = open ?? uncontrolledOpen;
return (
<div
data-menu-open={visible}
onDoubleClick={() => {
setUncontrolledOpen(!visible);
onOpenChange?.(!visible);
}}
>
{children}
</div>
);
},
MenuTrigger: ({
render,
children,
disabled,
}: {
render: ReactElement<{ disabled?: boolean }>;
children: ReactNode;
disabled?: boolean;
}) => cloneElement(render, disabled === undefined ? {} : { disabled }, children),
MenuPopup: "section",
MenuItem: "button",
MenuItemLabel: "span",
MenuShortcut: "span",
}));
import { OpenInPicker } from "./OpenInPicker";
const primary = EnvironmentId.make("primary");
const selected = EnvironmentId.make("selected");
const editors: readonly EditorId[] = ["vscode"];
let renderer: ReactTestRenderer | undefined;
beforeEach(() => {
state.allowed.clear();
state.remote = { mode: "local-exec" };
state.run.mockReset().mockResolvedValue(AsyncResult.success(undefined));
state.openUrl.mockReset().mockResolvedValue(true);
state.setPreferred.mockReset();
state.markHintSeen.mockReset();
state.keydown = null;
state.listeners.clear();
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
vi.stubGlobal("navigator", { platform: "Linux" });
vi.stubGlobal("window", {
addEventListener: (_type: string, callback: (event: KeyboardEvent) => void) => {
state.keydown = callback;
},
removeEventListener: (_type: string, callback: (event: KeyboardEvent) => void) => {
if (state.keydown === callback) state.keydown = null;
},
});
});
afterEach(async () => {
await act(async () => renderer?.unmount());
renderer = undefined;
vi.unstubAllGlobals();
});
async function renderPicker() {
await act(async () => {
for (const listener of state.listeners) listener();
const node = (
<OpenInPicker
environmentId={selected}
keybindings={DEFAULT_RESOLVED_KEYBINDINGS}
availableEditors={editors}
openInCwd="/work/project"
compact
/>
);
if (renderer) renderer.update(node);
else renderer = create(node);
});
}
function primaryButton() {
return renderer!.root.findByProps({ "aria-label": "Open file in preferred editor" });
}
function keyboardEvent() {
return { preventDefault: vi.fn() } as unknown as KeyboardEvent;
}
describe("host editor access", () => {
it("uses the selected grant for both the button and a retained shortcut", async () => {
state.allowed.add(selected);
await renderPicker();
const open = primaryButton().props.onClick;
const keydown = state.keydown!;
state.allowed.delete(selected);
state.allowed.add(primary);
const event = keyboardEvent();
await act(async () => {
open();
keydown(event);
});
expect(state.run).not.toHaveBeenCalled();
expect(state.setPreferred).not.toHaveBeenCalled();
expect(event.preventDefault).not.toHaveBeenCalled();
await renderPicker();
expect(primaryButton().props.disabled).toBe(true);
expect(renderer!.root.findByProps({ "aria-label": "Choose editor" }).props.disabled).toBe(true);
expect(state.keydown).toBeNull();
});
it("closes an open picker on revocation and launches only after a fresh grant", async () => {
state.allowed.add(selected);
await renderPicker();
await act(async () => {
renderer!.root.findByProps({ "data-menu-open": false }).props.onDoubleClick();
});
expect(renderer!.root.findByProps({ "data-menu-open": true })).toBeDefined();
state.allowed.delete(selected);
await renderPicker();
expect(renderer!.root.findByProps({ "data-menu-open": false })).toBeDefined();
state.allowed.add(selected);
await renderPicker();
expect(renderer!.root.findByProps({ "data-menu-open": false })).toBeDefined();
await act(async () => primaryButton().props.onClick());
expect(state.run).toHaveBeenCalledExactlyOnceWith({
environmentId: selected,
input: { cwd: "/work/project", editor: "vscode" },
});
});
});
describe("client editor links", () => {
it("opens an SSH editor URL without host operate permission", async () => {
state.remote = { mode: "remote-links", host: { kind: "ssh-alias", host: "test-host" } };
await renderPicker();
expect(primaryButton().props.disabled).toBe(false);
await act(async () => primaryButton().props.onClick());
expect(state.openUrl).toHaveBeenCalledExactlyOnceWith(
"vscode://vscode-remote/ssh-remote+test-host/work/project",
);
expect(state.run).not.toHaveBeenCalled();
expect(state.markHintSeen).toHaveBeenCalledOnce();
expect(state.setPreferred).toHaveBeenCalledExactlyOnceWith("vscode");
});
it("does not change preferences when the client rejects the SSH URL", async () => {
state.remote = { mode: "remote-links", host: { kind: "ssh-alias", host: "test-host" } };
state.openUrl.mockResolvedValue(false);
await renderPicker();
const event = keyboardEvent();
await act(async () => state.keydown!(event));
expect(state.openUrl).toHaveBeenCalledOnce();
expect(event.preventDefault).toHaveBeenCalledOnce();
expect(state.run).not.toHaveBeenCalled();
expect(state.setPreferred).not.toHaveBeenCalled();
expect(state.markHintSeen).not.toHaveBeenCalled();
});
});
+30 -6
View File
@@ -1,5 +1,6 @@
import { ThreadDetailsControl } from "./ThreadDetailsControl";
import {
AuthOrchestrationOperateScope,
buildRemoteOpenUrl,
EditorId,
type EnvironmentId,
@@ -66,6 +67,8 @@ import {
THREAD_DETAILS_PANEL_SPLIT_GROUP_CLASS,
THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS,
} from "./threadDetailsPanelStyles";
import { readEnvironmentScope, useEnvironmentScope } from "~/state/session";
import { useComposerMenuState } from "./useComposerMenuState";
type OpenInOption = {
label: string;
@@ -223,6 +226,10 @@ export const OpenInPicker = memo(function OpenInPicker({
const panelAnchorRef = useRef<HTMLDivElement | null>(null);
const openInEditorMutation = useAtomCommand(shellEnvironment.openInEditor, "open in editor");
const remote = useRemoteOpenState(environmentId);
const canOperateHost = useEnvironmentScope(environmentId, AuthOrchestrationOperateScope);
const isHostEditorDenied = remote.mode === "local-exec" && !canOperateHost;
const canOpenEditor = remote.mode !== "remote-unavailable" && !isHostEditorDenied;
const [menuOpen, setMenuOpen] = useComposerMenuState(isHostEditorDenied);
const remoteCapableEditors = useRemoteCapableEditors();
const [remoteHintSeen, markRemoteHintSeen] = useRemoteOpenHint();
const environmentLabel = useEnvironment(environmentId)?.label ?? "this machine";
@@ -258,6 +265,7 @@ export const OpenInPicker = memo(function OpenInPicker({
});
return;
}
if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) return;
const result = openInEditorMutation({
environmentId,
input: {
@@ -285,18 +293,32 @@ export const OpenInPicker = memo(function OpenInPicker({
);
useEffect(() => {
if (!enableShortcut) return;
if (!enableShortcut || !canOpenEditor) return;
const handler = (e: globalThis.KeyboardEvent) => {
if (!isOpenFavoriteEditorShortcut(e, keybindings)) return;
if (!openInCwd) return;
if (!preferredEditor) return;
if (
remote.mode === "local-exec" &&
!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)
)
return;
e.preventDefault();
void openInEditor(preferredEditor);
};
window.addEventListener("keydown", handler);
return () => window.removeEventListener("keydown", handler);
}, [enableShortcut, keybindings, openInCwd, openInEditor, preferredEditor]);
}, [
canOpenEditor,
enableShortcut,
environmentId,
keybindings,
openInCwd,
openInEditor,
preferredEditor,
remote.mode,
]);
const primaryLabel = isPanel ? `Open in ${primaryOption?.label ?? "editor"}` : "Open";
const editorItems = (
@@ -315,6 +337,7 @@ export const OpenInPicker = memo(function OpenInPicker({
{options.map(({ label, Icon, value, kind }) => (
<MenuItem
density={presentation === "menu" ? "touch" : "default"}
disabled={!openInCwd || !canOpenEditor}
key={value}
onClick={() => openInEditor(value)}
>
@@ -341,7 +364,7 @@ export const OpenInPicker = memo(function OpenInPicker({
<MenuItem
density={presentation === "menu" ? "touch" : "default"}
disabled={!openInCwd || remote.mode === "remote-unavailable"}
disabled={!openInCwd || !canOpenEditor}
onClick={() => openInEditor(preferredEditor)}
>
<primaryOption.Icon className={cn("size-4", getOpenInIconClass(primaryOption.kind))} />
@@ -352,7 +375,7 @@ export const OpenInPicker = memo(function OpenInPicker({
</MenuItem>
)}
<MenuSub>
<MenuSubTrigger density="touch">
<MenuSubTrigger density="touch" disabled={isHostEditorDenied}>
<SquareArrowOutUpRightIcon className="size-4" />
<MenuItemLabel>Open in…</MenuItemLabel>
</MenuSubTrigger>
@@ -376,7 +399,7 @@ export const OpenInPicker = memo(function OpenInPicker({
variant={isPanel ? "ghost" : "outline"}
part="primary"
panel={isPanel}
disabled={!preferredEditor || !openInCwd || remote.mode === "remote-unavailable"}
disabled={!preferredEditor || !openInCwd || !canOpenEditor}
onClick={() => openInEditor(preferredEditor)}
>
{primaryOption?.Icon ? (
@@ -409,8 +432,9 @@ export const OpenInPicker = memo(function OpenInPicker({
) : (
<GroupSeparator {...(!compact ? { className: "hidden @3xl/header-actions:block" } : {})} />
)}
<Menu>
<Menu open={menuOpen} onOpenChange={setMenuOpen}>
<MenuTrigger
disabled={isHostEditorDenied}
render={
<ThreadDetailsControl
aria-label="Choose editor"
@@ -0,0 +1,84 @@
import { EnvironmentId, ThreadId, ScheduledTaskId, type ScheduledTask } from "@t3tools/contracts";
import { act, create, type ReactTestRenderer } from "react-test-renderer";
import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
const state = vi.hoisted(() => ({ allowed: true, toggle: vi.fn(), run: vi.fn() }));
vi.mock("../../state/session", () => ({
useEnvironmentScope: () => state.allowed,
readEnvironmentScope: () => state.allowed,
}));
vi.mock("@effect/atom-react", () => ({ useAtomValue: () => state.allowed }));
vi.mock("@tanstack/react-router", () => ({ useNavigate: () => vi.fn() }));
vi.mock("../settings/ScheduledTasksSettings", () => ({
relativeLabel: () => "later",
scheduleLabel: () => "daily",
}));
vi.mock("../../state/server", () => ({
serverEnvironment: {
scheduledTasksLive: () => null,
setScheduledTaskEnabled: "toggle",
runScheduledTaskNow: { permissionAtom: () => null },
},
}));
vi.mock("../../state/use-atom-command", () => ({
useAtomCommand: (command: string) => (command === "toggle" ? state.toggle : state.run),
}));
vi.mock("../../state/query", () => ({
useEnvironmentQuery: () => ({ data: { tasks: [task] }, error: null }),
}));
vi.mock("../ui/tooltip", () => ({
Tooltip: ({ children }: { children: React.ReactNode }) => children,
TooltipTrigger: ({ render }: { render: React.ReactNode }) => render,
TooltipPopup: () => null,
}));
vi.mock("../ui/toast", () => ({
toastManager: { add: vi.fn() },
stackedThreadToast: (x: unknown) => x,
}));
import { ThreadAutomationsPanel } from "./ThreadAutomationsPanel";
const environmentId = EnvironmentId.make("remote");
const threadId = ThreadId.make("thread");
const task = {
id: ScheduledTaskId.make("task"),
threadId,
title: "Daily review",
enabled: true,
schedule: { type: "interval", everyMs: 60000 },
lastRunStatus: "never",
} as ScheduledTask;
let renderer: ReactTestRenderer;
beforeEach(() => {
state.allowed = true;
state.toggle.mockReset().mockResolvedValue({ _tag: "Success" });
state.run.mockReset().mockResolvedValue({ _tag: "Success" });
});
afterEach(async () => {
if (renderer) await act(async () => renderer.unmount());
});
it.each([true, false])("runs scheduled work only with task permission (%s)", async (allowed) => {
state.allowed = allowed;
await act(async () => {
renderer = create(<ThreadAutomationsPanel environmentId={environmentId} threadId={threadId} />);
});
const run = renderer.root.findAllByProps({ "aria-label": "Run Daily review now" })[0]!;
await act(async () => {
await run.props.onClick();
});
expect(state.run).toHaveBeenCalledTimes(allowed ? 1 : 0);
});
it("rejects a retained toggle after task permission is revoked", async () => {
await act(async () => {
renderer = create(<ThreadAutomationsPanel environmentId={environmentId} threadId={threadId} />);
});
const toggle = renderer.root
.findAllByProps({ "aria-label": "Pause Daily review" })
.find((node) => node.props.onCheckedChange)!;
state.allowed = false;
await act(async () => {
await toggle.props.onCheckedChange(false);
});
expect(state.toggle).not.toHaveBeenCalled();
});
@@ -1,8 +1,14 @@
import { useAtomValue } from "@effect/atom-react";
import { ThreadDetailsControl } from "./ThreadDetailsControl";
import { useNavigate } from "@tanstack/react-router";
import { CalendarClockIcon, PencilIcon, PlayIcon, Settings2Icon } from "lucide-react";
import { useState } from "react";
import type { EnvironmentId, ScheduledTask, ThreadId } from "@t3tools/contracts";
import {
AuthOrchestrationOperateScope,
type EnvironmentId,
type ScheduledTask,
type ThreadId,
} from "@t3tools/contracts";
import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
@@ -15,6 +21,7 @@ import { useEnvironmentQuery } from "../../state/query";
import { serverEnvironment } from "../../state/server";
import { useAtomCommand } from "../../state/use-atom-command";
import { readEnvironmentScope } from "../../state/session";
import { Switch } from "../ui/switch";
import { stackedThreadToast, toastManager } from "../ui/toast";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
@@ -40,6 +47,9 @@ export function ThreadAutomationsPanel(props: {
readonly environmentId: EnvironmentId;
readonly threadId: ThreadId;
}) {
const canOperate = useAtomValue(
serverEnvironment.runScheduledTaskNow.permissionAtom(props.environmentId),
);
const tasksQuery = useEnvironmentQuery(
serverEnvironment.scheduledTasksLive({ environmentId: props.environmentId, input: {} }),
);
@@ -71,7 +81,11 @@ export function ThreadAutomationsPanel(props: {
};
const toggleEnabled = async (task: ScheduledTask, enabled: boolean) => {
if (busyTaskId !== null) return;
if (
busyTaskId !== null ||
!readEnvironmentScope(props.environmentId, AuthOrchestrationOperateScope)
)
return;
setBusyTaskId(task.id);
// Partial update: only the enabled flag changes, so a toggle can never
// revert concurrent edits made to the task elsewhere.
@@ -86,7 +100,11 @@ export function ThreadAutomationsPanel(props: {
};
const runNow = async (task: ScheduledTask) => {
if (busyTaskId !== null) return;
if (
busyTaskId !== null ||
!readEnvironmentScope(props.environmentId, AuthOrchestrationOperateScope)
)
return;
setBusyTaskId(task.id);
const result = await runTaskNow({
environmentId: props.environmentId,
@@ -196,7 +214,9 @@ export function ThreadAutomationsPanel(props: {
variant="ghost"
part="icon"
aria-label={`Run ${task.title} now`}
disabled={busyTaskId !== null || task.lastRunStatus === "running"}
disabled={
!canOperate || busyTaskId !== null || task.lastRunStatus === "running"
}
onClick={() => void runNow(task)}
>
<PlayIcon className="size-3.5" />
@@ -208,7 +228,7 @@ export function ThreadAutomationsPanel(props: {
)}
<Switch
checked={task.enabled}
disabled={busyTaskId !== null}
disabled={!canOperate || busyTaskId !== null}
aria-label={task.enabled ? `Pause ${task.title}` : `Resume ${task.title}`}
onCheckedChange={(enabled) => void toggleEnabled(task, enabled)}
/>
@@ -170,8 +170,8 @@ export function ThreadDetailsPanel(props: ThreadDetailsPanelProps) {
{density !== "essential" && props.showOpenInPicker ? (
<OpenInPicker
environmentId={props.environmentId}
keybindings={props.keybindings}
environmentId={props.environmentId}
availableEditors={props.availableEditors}
openInCwd={props.gitCwd}
displayMode="panel"
@@ -180,10 +180,10 @@ export function ThreadDetailsPanel(props: ThreadDetailsPanelProps) {
{props.activeProjectScripts ? (
<ProjectScriptsControl
environmentId={props.environmentId}
displayMode="panel"
scripts={props.activeProjectScripts}
fileScripts={fileScripts}
keybindings={props.keybindings}
preferredScriptId={props.preferredScriptId}
onRunScript={props.onRunProjectScript}
onAddScript={props.onAddProjectScript}
@@ -581,14 +581,16 @@ export const TraitsPicker = memo(function TraitsPicker({
isComposerOwned,
size = "sm",
hidden = false,
disabled = false,
...persistence
}: TraitsMenuContentProps &
TraitsPersistence & {
size?: ComposerControlSize;
hidden?: boolean;
disabled?: boolean;
}) {
const composerFloatingLayerProps = useComposerMenuProps();
const [isMenuOpen, setIsMenuOpen] = useComposerMenuState(hidden);
const [isMenuOpen, setIsMenuOpen] = useComposerMenuState(hidden || disabled);
const { descriptors, primarySelectDescriptor, ultrathinkPromptControlled } =
getTraitsSectionVisibility({
provider,
@@ -627,7 +629,7 @@ export const TraitsPicker = memo(function TraitsPicker({
<Menu
open={isMenuOpen}
onOpenChange={(open) => {
setIsMenuOpen(open);
setIsMenuOpen(open && !disabled);
}}
>
<Tooltip>
@@ -636,6 +638,7 @@ export const TraitsPicker = memo(function TraitsPicker({
<MenuTrigger
render={
<ComposerControl
disabled={disabled}
aria-label={triggerLabel}
data-composer-shortcut={isComposerOwned ? "composer.effort" : undefined}
size={size}
@@ -1,5 +1,12 @@
import { useAuth } from "@clerk/react";
import { AuthAdministrativeScopes, AuthRelayWriteScope } from "@t3tools/contracts";
import { useAtomValue } from "@effect/atom-react";
import {
AuthAdministrativeScopes,
AuthRelayReadScope,
AuthRelayWriteScope,
type AuthSessionState,
} from "@t3tools/contracts";
import { AsyncResult, Atom } from "effect/reactivity";
import { useEffect, useRef, useState } from "react";
import {
@@ -9,9 +16,13 @@ import {
} from "~/cloud/connectOnboarding";
import { hasCloudPublicConfig } from "~/cloud/publicConfig";
import { useCloudLinkController } from "~/cloud/useCloudLinkController";
import { usePrimarySessionState } from "~/environments/primary";
import { useLocalStorage } from "~/hooks/useLocalStorage";
import { useEnvironments, usePrimaryEnvironment } from "~/state/environments";
import {
useEnvironments,
usePrimaryEnvironment,
usePrimaryEnvironmentId,
} from "~/state/environments";
import { environmentSession, readEnvironmentScope, useEnvironmentScope } from "~/state/session";
import { CloudEnvironmentConnectRows } from "./CloudEnvironmentConnectList";
import { Button } from "../ui/button";
import { Checkbox } from "../ui/checkbox";
@@ -37,6 +48,8 @@ export function ConnectOnboardingDialog() {
type OnboardingStep = "publish" | "devices";
const EMPTY_SESSION_STATE_ATOM = Atom.make(AsyncResult.initial<AuthSessionState>());
function ConfiguredConnectOnboardingDialog() {
// Mirrors ManagedRelayAuthProvider: a pending Clerk session must not read as
// signed-out, or its later activation would look like a fresh sign-in.
@@ -47,22 +60,22 @@ function ConfiguredConnectOnboardingDialog() {
ConnectOnboardingOptOutSchema,
);
const desktopBridge = window.desktopBridge;
const primarySessionState = usePrimarySessionState();
const currentSessionScopes = desktopBridge
? AuthAdministrativeScopes
: primarySessionState.data?.authenticated
? (primarySessionState.data.scopes ?? null)
: null;
const canManageRelay = currentSessionScopes?.includes(AuthRelayWriteScope) ?? false;
const { isReady: environmentsReady } = useEnvironments();
const primaryEnvironmentId = usePrimaryEnvironmentId();
const primarySessionState = useAtomValue(
primaryEnvironmentId === null
? EMPTY_SESSION_STATE_ATOM
: environmentSession.sessionStateAtom(primaryEnvironmentId),
);
const canReadRelay = useEnvironmentScope(primaryEnvironmentId, AuthRelayReadScope);
const canWriteRelay = useEnvironmentScope(primaryEnvironmentId, AuthRelayWriteScope);
const canManageRelay = canReadRelay && canWriteRelay;
// The publish step is only offered when we know the answer; opening the
// wizard before the session state resolves would let the step set change
// mid-flight. A failed session read still opens the wizard — it just means
// no publish step.
const sessionScopesKnown =
Boolean(desktopBridge) ||
primarySessionState.data !== null ||
primarySessionState.error !== null;
primaryEnvironmentId === null ? environmentsReady : primarySessionState._tag !== "Initial";
const controller = useCloudLinkController();
const showPublishStep = canManageRelay && controller.linkState.target !== null;
@@ -80,6 +93,12 @@ function ConfiguredConnectOnboardingDialog() {
const prefilledFromLinkStateRef = useRef(false);
const observedAccountRef = useRef<string | null | undefined>(undefined);
useEffect(() => {
if (step === "publish" && sessionScopesKnown && !showPublishStep && !isApplying) {
setStep("devices");
}
}, [isApplying, sessionScopesKnown, showPublishStep, step]);
const optOutAccounts = optOutState.optOutAccounts;
// Every sign-in or account switch that completes during this session
@@ -176,6 +195,16 @@ function ConfiguredConnectOnboardingDialog() {
};
const applyPublishSelection = async () => {
if (isApplying) return;
if (
primaryEnvironmentId === null ||
!readEnvironmentScope(primaryEnvironmentId, AuthRelayReadScope) ||
!readEnvironmentScope(primaryEnvironmentId, AuthRelayWriteScope)
) {
setStep("devices");
return;
}
if (linkStateData === null || controller.linkState.error !== null) return;
// The wizard only ever enables — with both toggles off there is nothing to
// apply, and an existing link must not be torn down from onboarding.
if (!exposeEnvironment && !publishAgentActivity) {
@@ -225,6 +254,13 @@ function ConfiguredConnectOnboardingDialog() {
isStepDisabled={() => isApplying}
onStepChange={(index) => {
const next = steps[index];
if (
next === "publish" &&
(primaryEnvironmentId === null ||
!readEnvironmentScope(primaryEnvironmentId, AuthRelayReadScope) ||
!readEnvironmentScope(primaryEnvironmentId, AuthRelayWriteScope))
)
return;
if (next) setStep(next);
}}
/>
@@ -235,10 +271,24 @@ function ConfiguredConnectOnboardingDialog() {
<PublishStep
exposeEnvironment={exposeEnvironment}
publishAgentActivity={publishAgentActivity}
disabled={isApplying}
operationError={controller.operationError}
onExposeEnvironmentChange={setExposeEnvironment}
onPublishAgentActivityChange={setPublishAgentActivity}
disabled={isApplying || !canManageRelay || linkStateData === null}
operationError={controller.operationError ?? controller.linkState.error}
onExposeEnvironmentChange={(enabled) => {
if (
primaryEnvironmentId !== null &&
readEnvironmentScope(primaryEnvironmentId, AuthRelayReadScope) &&
readEnvironmentScope(primaryEnvironmentId, AuthRelayWriteScope)
)
setExposeEnvironment(enabled);
}}
onPublishAgentActivityChange={(enabled) => {
if (
primaryEnvironmentId !== null &&
readEnvironmentScope(primaryEnvironmentId, AuthRelayReadScope) &&
readEnvironmentScope(primaryEnvironmentId, AuthRelayWriteScope)
)
setPublishAgentActivity(enabled);
}}
/>
) : (
<DevicesStep />
@@ -261,7 +311,7 @@ function ConfiguredConnectOnboardingDialog() {
Not now
</Button>
<Button
disabled={isApplying || (controller.linkState.isPending && linkStateData === null)}
disabled={isApplying || !canManageRelay || linkStateData === null}
onClick={() => void applyPublishSelection()}
>
{isApplying ? "Enabling…" : "Continue"}
@@ -2,6 +2,7 @@ import { DeviceHostUpdates } from "./DeviceHostUpdates";
import type { DevicePlatform, DeviceServiceState, EnvironmentId } from "@t3tools/contracts";
import { Check } from "lucide-react";
import { Check as CheckGlyph, CircleAlert } from "lucide";
import { AuthSettingsWriteScope } from "@t3tools/contracts";
import { useState } from "react";
import { Button } from "~/components/ui/button";
@@ -12,6 +13,7 @@ import { Spinner } from "~/components/ui/spinner";
import { Switch } from "~/components/ui/switch";
import { deviceEnvironment } from "~/state/device";
import { useAtomCommand } from "~/state/use-atom-command";
import { readEnvironmentScope, useEnvironmentScope } from "~/state/session";
import { cn } from "~/lib/utils";
const platformName = (platform: DevicePlatform) => (platform === "ios" ? "iOS" : "Android");
@@ -57,6 +59,7 @@ export function DeviceSetup(props: {
readonly state: DeviceServiceState;
readonly onComplete?: () => void;
}) {
const canConfigure = useEnvironmentScope(props.environmentId, AuthSettingsWriteScope);
const configure = useAtomCommand(deviceEnvironment.configure);
const list = useAtomCommand(deviceEnvironment.list, { reportFailure: false });
const [pending, setPending] = useState<"hub" | "check" | "agent" | "complete" | null>(null);
@@ -71,6 +74,7 @@ export function DeviceSetup(props: {
kind: NonNullable<typeof pending>,
input: { enabled?: boolean; agentAccessEnabled?: boolean; onboardingCompleted?: boolean },
) => {
if (!readEnvironmentScope(props.environmentId, AuthSettingsWriteScope)) return;
setPending(kind);
try {
const result = await configure({ environmentId: props.environmentId, input });
@@ -103,7 +107,7 @@ export function DeviceSetup(props: {
<p className="text-muted-foreground">{deviceHubDescription}</p>
<Switch
checked={enabled}
disabled={busy || pending !== null}
disabled={!canConfigure || busy || pending !== null}
aria-label="Enable device hub"
onCheckedChange={(checked) =>
void update("hub", {
@@ -144,7 +148,7 @@ export function DeviceSetup(props: {
<p className="text-muted-foreground">{agentDeviceDescription}</p>
<Switch
checked={props.state.agentAccessEnabled}
disabled={!enabled || busy || pending !== null}
disabled={!canConfigure || !enabled || busy || pending !== null}
aria-label="Allow agents to control devices"
onCheckedChange={(checked) =>
void update("agent", { agentAccessEnabled: Boolean(checked) })
@@ -185,7 +189,7 @@ export function DeviceSetup(props: {
</Button>
) : (
<Button
disabled={props.state.hostStatus !== "ready" || pending !== null}
disabled={!canConfigure || props.state.hostStatus !== "ready" || pending !== null}
onClick={() => void update("complete", { onboardingCompleted: true })}
>
{pending === "complete" ? "Saving…" : "Done"}
@@ -0,0 +1,403 @@
import { RegistryContext } from "@effect/atom-react";
import {
AuthOrchestrationOperateScope,
AuthOrchestrationReadScope,
EnvironmentId,
ProjectId,
type AgentSessionProjectCandidate,
type AuthEnvironmentScope,
type AuthSessionState,
} from "@t3tools/contracts";
import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
import { act, create, type ReactTestInstance, type ReactTestRenderer } from "react-test-renderer";
import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
type SessionResult = AsyncResult.AsyncResult<AuthSessionState, Error>;
type Project = { id: ProjectId; environmentId: EnvironmentId; workspaceRoot: string };
type CreateProjectInput = {
environmentId: EnvironmentId;
input: { projectId: ProjectId; workspaceRoot: string };
};
const state = vi.hoisted(() => ({
selectedEnvironment: "primary",
registry: null as AtomRegistry.AtomRegistry | null,
sessions: new Map<EnvironmentId, Atom.Writable<SessionResult>>(),
projects: null as Atom.Writable<ReadonlyArray<Project>> | null,
providers: null as Atom.Atom<ReadonlyArray<never>> | null,
config: null as Atom.Atom<null> | null,
candidates: [] as AgentSessionProjectCandidate[],
createProject: vi.fn(),
importThreads: vi.fn(),
refreshProviders: vi.fn(),
connectPairing: vi.fn(),
completeOnboarding: vi.fn(),
onDone: vi.fn(),
scan: vi.fn(),
refreshScan: vi.fn(),
}));
vi.mock("../../connection/runtime", () => ({ connectionAtomRuntime: undefined }));
vi.mock("@t3tools/client-runtime/state/session", () => ({
createEnvironmentSessionAtoms: () => ({
sessionStateAtom: (id: EnvironmentId) => state.sessions.get(id)!,
}),
}));
vi.mock("../../rpc/atomRegistry", () => ({
get appAtomRegistry() {
return state.registry;
},
}));
vi.mock("@clerk/react", () => ({ useAuth: () => ({ isLoaded: true, isSignedIn: false }) }));
vi.mock("../../hooks/useTheme", () => ({ mountOnboardingTheme: () => () => {} }));
vi.mock("../../hooks/useLocalStorage", () => ({ useLocalStorage: () => [false, () => {}] }));
vi.mock("../../hooks/useCopyToClipboard", () => ({
useCopyToClipboard: () => ({ copyToClipboard: vi.fn(), copied: false }),
}));
vi.mock("../../cloud/publicConfig", () => ({ hasCloudPublicConfig: () => false }));
vi.mock("../clerk/useT3ConnectAuthPrompt", () => ({ useT3ConnectAuthPrompt: vi.fn() }));
vi.mock("../../onboarding/firstRun", () => ({
useCompleteOnboarding: () => state.completeOnboarding,
}));
vi.mock("../../env", () => ({ isElectron: false }));
vi.mock("../../state/environments", () => {
const environment = (environmentId: string) => ({
environmentId,
label: environmentId,
connection: { phase: "connected" },
entry: { target: { _tag: "DirectConnectionTarget" } },
});
const primary = environment("primary");
return {
usePrimaryEnvironment: () => primary,
useEnvironments: () => ({ environments: [environment(state.selectedEnvironment)] }),
};
});
vi.mock("../../state/server", () => ({
serverEnvironment: {
providersValueAtom: () => state.providers,
configValueAtom: () => state.config,
refreshProviders: "refreshProviders",
},
}));
vi.mock("../../state/entities", async () => {
const { useAtomValue } = await import("@effect/atom-react");
return {
useProjects: () => useAtomValue(state.projects!),
readProjects: () => state.registry!.get(state.projects!),
};
});
vi.mock("../../state/projects", () => ({ projectEnvironment: { create: "createProject" } }));
vi.mock("../../state/agentSessions", () => ({
agentSessionScan: (query: { environmentId: EnvironmentId }) => query,
agentSessionImport: "importThreads",
}));
vi.mock("../../onboarding/useProjectScans", () => ({
useProjectScans: (ids: EnvironmentId[]) =>
ids.map((environmentId) => {
state.scan({ environmentId });
return {
environmentId,
data: { candidates: state.candidates, truncated: false },
isPending: false,
error: null,
refresh: state.refreshScan,
};
}),
}));
vi.mock("../ui/dialog", () => ({
Dialog: "div",
DialogPopup: "div",
DialogTitle: "div",
DialogHeader: "div",
}));
vi.mock("../ui/wizard", () => ({
WizardPanel: "div",
WizardSteps: "div",
WizardPopup: "div",
WizardHeader: "div",
}));
vi.mock("../ui/scroll-area", () => ({ ScrollArea: "div" }));
vi.mock("../ui/tooltip", () => ({ Tooltip: "div", TooltipTrigger: "span", TooltipPopup: "span" }));
vi.mock("../../connection/onboarding", () => ({ connectPairing: "connectPairing" }));
vi.mock("../../state/use-atom-command", () => ({
useAtomCommand: (
command: "createProject" | "importThreads" | "refreshProviders" | "connectPairing",
) => state[command],
}));
vi.mock("../../state/terminal", () => ({ terminalEnvironment: {} }));
vi.mock("../ThreadTerminalDrawer", () => ({ TerminalViewport: "div" }));
vi.mock("../cloud/CloudEnvironmentConnectList", () => ({ CloudEnvironmentConnectRows: "div" }));
vi.mock("../settings/ChatGptWelcomeCoordinator", () => ({ ChatGptWelcomeCoordinator: () => null }));
vi.mock("../settings/CodexSetupSection", () => ({
CodexSetupSection: () => null,
AddManagedCodexAccountDialog: () => null,
}));
vi.mock("../settings/providerDriverMeta", () => ({ getDriverOption: () => ({ label: "Agent" }) }));
vi.mock("../settings/providerStatus", () => ({
getProviderSummary: () => ({ headline: "Checking", detail: null }),
}));
vi.mock("../ui/button", () => ({ Button: "button" }));
vi.mock("../ui/input", () => ({ Input: "input" }));
vi.mock("../ui/checkbox", () => ({ Checkbox: "input" }));
vi.mock("../ui/collapsible", () => ({
Collapsible: "div",
CollapsiblePanel: "div",
CollapsibleTrigger: "button",
}));
vi.mock("../ui/toast", () => ({ toastManager: { add: vi.fn(), close: vi.fn(), update: vi.fn() } }));
import { WelcomeWizard } from "./WelcomeWizard";
const primaryId = EnvironmentId.make("primary");
const remoteId = EnvironmentId.make("remote");
const permissionMessage = "This connection cannot import projects or thread history.";
let renderer: ReactTestRenderer | undefined;
function session(scopes: ReadonlyArray<AuthEnvironmentScope>): AuthSessionState {
return {
authenticated: true,
scopes: [AuthOrchestrationReadScope, ...scopes],
auth: {
policy: "remote-reachable",
bootstrapMethods: ["one-time-token"],
sessionMethods: ["bearer-access-token"],
sessionCookieName: "t3_session",
},
};
}
function setGrant(environmentId: EnvironmentId, allowed: boolean) {
state.registry!.set(
state.sessions.get(environmentId)!,
AsyncResult.success(session(allowed ? [AuthOrchestrationOperateScope] : [])),
);
}
function candidate(path: string): AgentSessionProjectCandidate {
return {
path,
title: path.split("/").at(-1)!,
sources: ["codex"],
threadCount: 10,
lastActiveAt: new Date(Date.now() - 60_000).toISOString(),
alreadyImported: false,
};
}
function recordProject({ environmentId, input }: CreateProjectInput) {
state.registry!.set(state.projects!, [
...state.registry!.get(state.projects!),
{ id: input.projectId, environmentId, workspaceRoot: input.workspaceRoot },
]);
return AsyncResult.success(undefined);
}
function deferred<T>() {
let resolve!: (value: T) => void;
const promise = new Promise<T>((complete) => {
resolve = complete;
});
return { promise, resolve };
}
function text(node: ReactTestInstance | string): string {
return typeof node === "string" ? node : node.children.map(text).join("");
}
function button(label: string) {
const found = renderer!.root.findAllByType("button").find((node) => text(node) === label);
if (!found) throw new Error(`Missing button: ${label}`);
return found;
}
async function click(label: string) {
const target = button(label);
expect(target.props.disabled).not.toBe(true);
await act(async () => target.props.onClick());
}
async function mountImport(remote = false) {
state.selectedEnvironment = remote ? "remote" : "primary";
await act(async () => {
renderer = create(
<RegistryContext.Provider value={state.registry!}>
<WelcomeWizard localAvailable={!remote} onDone={state.onDone} />
</RegistryContext.Provider>,
);
});
await click("Continue");
await click("Continue");
expect(text(renderer!.root)).toContain("Choose your projects");
}
beforeEach(() => {
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
vi.stubGlobal("document", { activeElement: null, body: {}, getElementById: () => null });
state.registry = AtomRegistry.make();
for (const id of [primaryId, remoteId]) {
state.sessions.set(
id,
Atom.make<SessionResult>(AsyncResult.success(session([AuthOrchestrationOperateScope]))).pipe(
Atom.keepAlive,
),
);
}
state.projects = Atom.make<ReadonlyArray<Project>>([]).pipe(Atom.keepAlive);
state.providers = Atom.make<ReadonlyArray<never>>([]).pipe(Atom.keepAlive);
state.config = Atom.make(null).pipe(Atom.keepAlive);
state.candidates = [candidate("/projects/first"), candidate("/projects/second")];
state.createProject
.mockReset()
.mockImplementation(async (input: CreateProjectInput) => recordProject(input));
state.importThreads
.mockReset()
.mockResolvedValue(AsyncResult.success({ importedCount: 1, skippedCount: 0 }));
state.refreshProviders.mockReset().mockResolvedValue(AsyncResult.success(undefined));
state.connectPairing.mockReset().mockResolvedValue(AsyncResult.success(remoteId));
state.completeOnboarding.mockReset().mockResolvedValue(undefined);
state.onDone.mockReset();
state.scan.mockReset();
state.refreshScan.mockReset();
});
afterEach(async () => {
await act(async () => renderer?.unmount());
renderer = undefined;
state.registry?.dispose();
state.sessions.clear();
vi.unstubAllGlobals();
});
it("keeps scanning, choosing and skipping available to a paired read-only environment", async () => {
setGrant(remoteId, false);
await mountImport(true);
expect(state.scan).toHaveBeenCalledWith(expect.objectContaining({ environmentId: remoteId }));
expect(text(renderer!.root)).toContain("/projects/first");
expect(button("Import 2 projects").props.disabled).toBe(true);
expect(text(renderer!.root)).toContain(permissionMessage);
await click("Do not import projects");
expect(state.createProject).not.toHaveBeenCalled();
expect(state.importThreads).not.toHaveBeenCalled();
expect(state.completeOnboarding).toHaveBeenCalledOnce();
expect(state.onDone).toHaveBeenCalledOnce();
});
it("waits for the selected grant and enables import when it arrives", async () => {
state.registry!.set(state.sessions.get(primaryId)!, AsyncResult.initial());
await mountImport();
expect(button("Import 2 projects").props.disabled).toBe(true);
await act(async () => setGrant(primaryId, true));
await click("Import 2 projects");
expect(state.createProject).toHaveBeenCalledTimes(2);
expect(state.importThreads).toHaveBeenCalledTimes(2);
expect(state.onDone).toHaveBeenCalledWith(expect.objectContaining({ environmentId: primaryId }));
});
it("preserves selections and denies a retained action using the paired environment's fresh grant", async () => {
await mountImport(true);
await act(async () => {
renderer!.root.findAllByType("input")[1]!.props.onCheckedChange(false);
});
const retainedImport = button("Import 1 project").props.onClick;
await act(async () => {
setGrant(remoteId, false);
retainedImport();
});
expect(button("Import 1 project").props.disabled).toBe(true);
expect(renderer!.root.findAllByType("input")[1]!.props.checked).toBe(false);
expect(text(renderer!.root)).toContain(permissionMessage);
expect(state.createProject).not.toHaveBeenCalled();
expect(state.importThreads).not.toHaveBeenCalled();
expect(state.onDone).not.toHaveBeenCalled();
await act(async () => setGrant(remoteId, true));
expect(text(renderer!.root)).not.toContain(permissionMessage);
await click("Import 1 project");
expect(state.createProject).toHaveBeenCalledExactlyOnceWith(
expect.objectContaining({ environmentId: remoteId }),
);
expect(state.importThreads).toHaveBeenCalledExactlyOnceWith(
expect.objectContaining({ environmentId: remoteId }),
);
});
it("rechecks after project creation and can retry its history without recreating the project", async () => {
const creation = deferred<void>();
state.createProject.mockImplementationOnce(async (input: CreateProjectInput) => {
await creation.promise;
return recordProject(input);
});
await mountImport();
await click("Import 2 projects");
expect(state.createProject).toHaveBeenCalledOnce();
await act(async () => {
setGrant(primaryId, false);
creation.resolve();
await creation.promise;
});
expect(state.importThreads).not.toHaveBeenCalled();
expect(state.createProject).toHaveBeenCalledOnce();
expect(state.onDone).not.toHaveBeenCalled();
expect(text(renderer!.root)).toContain(permissionMessage);
await act(async () => setGrant(primaryId, true));
await click("Import 2 projects");
expect(state.createProject).toHaveBeenCalledTimes(2);
expect(state.importThreads).toHaveBeenCalledTimes(2);
expect(state.onDone).toHaveBeenCalledOnce();
});
it.each([false, true])(
"rechecks after history import before the next project write (existing: %s)",
async (existing) => {
if (existing) {
const projectId = ProjectId.make("second-existing");
state.candidates[1] = { ...state.candidates[1]!, projectId };
state.registry!.set(state.projects!, [
{ id: projectId, environmentId: primaryId, workspaceRoot: "/projects/second" },
]);
}
const imported = deferred<{ importedCount: number; skippedCount: number }>();
state.importThreads.mockImplementationOnce(async () =>
AsyncResult.success(await imported.promise),
);
await mountImport();
await click("Import 2 projects");
expect(state.createProject).toHaveBeenCalledOnce();
expect(state.importThreads).toHaveBeenCalledOnce();
await act(async () => {
setGrant(primaryId, false);
imported.resolve({ importedCount: 1, skippedCount: 0 });
await imported.promise;
});
expect(state.createProject).toHaveBeenCalledOnce();
expect(state.importThreads).toHaveBeenCalledOnce();
expect(state.onDone).not.toHaveBeenCalled();
expect(text(renderer!.root)).toContain(permissionMessage);
await act(async () => setGrant(primaryId, true));
await click("Import 2 projects");
expect(state.createProject).toHaveBeenCalledTimes(existing ? 1 : 2);
expect(state.importThreads).toHaveBeenCalledTimes(2);
expect(state.onDone).toHaveBeenCalledOnce();
},
);
it("completes accepted imports when permission is revoked after the final server write", async () => {
state.candidates = state.candidates.slice(0, 1);
const imported = deferred<{ importedCount: number; skippedCount: number }>();
state.importThreads.mockImplementationOnce(async () =>
AsyncResult.success(await imported.promise),
);
await mountImport();
await click("Import 1 project");
await act(async () => {
setGrant(primaryId, false);
imported.resolve({ importedCount: 1, skippedCount: 0 });
await imported.promise;
});
expect(state.createProject).toHaveBeenCalledOnce();
expect(state.importThreads).toHaveBeenCalledOnce();
expect(state.completeOnboarding).toHaveBeenCalledOnce();
expect(state.onDone).toHaveBeenCalledOnce();
});
@@ -12,6 +12,12 @@ const mocks = vi.hoisted(() => ({
toast: vi.fn(),
projects: [] as Array<{ id: string; environmentId: string; workspaceRoot: string }>,
}));
vi.mock("../../state/session", () => ({
useEnvironmentScope: () => true,
useEnvironmentsWithScope: (environments: Array<{ environmentId: string }>) =>
new Set(environments.map((entry) => entry.environmentId)),
readEnvironmentScope: () => true,
}));
vi.mock("../../state/agentSessions", () => ({ agentSessionImport: "import" }));
vi.mock("../../state/projects", () => ({ projectEnvironment: { create: "create" } }));
vi.mock("../../state/use-atom-command", () => ({
@@ -17,6 +17,7 @@ import {
import {
CommandId,
defaultInstanceIdForDriver,
AuthOrchestrationOperateScope,
ProviderDriverKind,
ThreadId,
} from "@t3tools/contracts";
@@ -60,6 +61,7 @@ import { isOnboardingRelayEnvironment } from "../../onboarding/targetEnvironment
import { useProjectScans } from "../../onboarding/useProjectScans";
import { projectEnvironment } from "../../state/projects";
import { serverEnvironment } from "../../state/server";
import { readEnvironmentScope, useEnvironmentsWithScope } from "../../state/session";
import { terminalEnvironment } from "../../state/terminal";
import { useAtomCommand } from "../../state/use-atom-command";
import { connectPairing } from "../../connection/onboarding";
@@ -1145,6 +1147,8 @@ function AgentInstallTerminal({
// ── Step 4: import ───────────────────────────────────────────
const IMPORT_PERMISSION_MESSAGE = "This connection cannot import projects or thread history.";
function ImportStep({
scans,
isImporting,
@@ -1161,6 +1165,7 @@ function ImportStep({
) => Promise<boolean>;
}) {
const { environments } = useEnvironments();
const writableEnvironments = useEnvironmentsWithScope(scans, AuthOrchestrationOperateScope);
const createProject = useAtomCommand(projectEnvironment.create, { reportFailure: false });
const importThreads = useAtomCommand(agentSessionImport, { reportFailure: false });
const projects = useProjects();
@@ -1222,6 +1227,16 @@ function ImportStep({
);
const selected = candidates.filter((candidate) => selectedKeys.has(candidate.key));
const canImport = selected.every((candidate) =>
writableEnvironments.has(candidate.environmentId),
);
const [importError, setImportError] = useState("");
const visibleImportError = !canImport
? IMPORT_PERMISSION_MESSAGE
: importError === IMPORT_PERMISSION_MESSAGE
? ""
: importError;
const finishAfterImport = () => {
const projectRef = resolveOnboardingLandingProject(
lastImportSelectionRef.current,
@@ -1238,6 +1253,18 @@ function ImportStep({
const runImport = async (selection: typeof candidates) => {
if (isImporting) return;
const hasAccess = () =>
selection.every((candidate) =>
readEnvironmentScope(candidate.environmentId, AuthOrchestrationOperateScope),
);
const stopForDeniedAccess = () => {
setIsImporting(false);
setImportError(IMPORT_PERMISSION_MESSAGE);
};
if (!hasAccess()) {
stopForDeniedAccess();
return;
}
if (selection.length === 0) {
void onDone();
return;
@@ -1269,6 +1296,10 @@ function ImportStep({
) {
return;
}
if (!hasAccess()) {
stopForDeniedAccess();
return;
}
if (importedProjects.has(candidate.key)) continue;
let projectId = resolveOnboardingProjectId(readProjects(), environmentId, candidate);
if (projectId === null) {
@@ -1308,6 +1339,10 @@ function ImportStep({
}
}
if (!hasAccess()) {
stopForDeniedAccess();
return;
}
const threadImportResult = await importThreads({
environmentId,
input: { projectId, expectedWorkspaceRoot: candidate.path },
@@ -1457,13 +1492,16 @@ function ImportStep({
})}
</div>
</ScrollArea>
{visibleImportError ? (
<p className="mt-3 text-sm text-destructive">{visibleImportError}</p>
) : null}
<div className="mt-6 flex flex-wrap items-center justify-end gap-3">
<Button variant="ghost-muted" disabled={isImporting} onClick={finishAfterImport}>
Do not import projects
</Button>
<Button
autoFocus
disabled={isImporting || selected.length === 0}
disabled={!canImport || isImporting || selected.length === 0}
onClick={() => void runImport(selected)}
>
{isImporting
@@ -0,0 +1,340 @@
import {
AuthOrchestrationOperateScope,
AuthSettingsWriteScope,
EnvironmentId,
type AuthEnvironmentScope,
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import { AsyncResult } from "effect/reactivity";
import { act, create, type ReactTestRenderer } from "react-test-renderer";
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
const permissions = vi.hoisted(() => ({ canWriteSettings: false, canEditProject: true }));
vi.mock("~/state/session", () => ({
readEnvironmentScope: (_id: EnvironmentId, scope: AuthEnvironmentScope) =>
scope === AuthOrchestrationOperateScope
? permissions.canEditProject
: permissions.canWriteSettings,
useEnvironmentScope: (_id: EnvironmentId, scope: AuthEnvironmentScope) =>
scope === AuthOrchestrationOperateScope
? permissions.canEditProject
: permissions.canWriteSettings,
}));
vi.mock("./ui/dialog", () => ({
Dialog: "div",
DialogDescription: "div",
DialogFooter: "div",
DialogHeader: "div",
DialogPanel: "div",
DialogPopup: "div",
DialogTitle: "div",
}));
vi.mock("./ui/alert-dialog", () => ({
AlertDialog: "div",
AlertDialogClose: "button",
AlertDialogDescription: "div",
AlertDialogFooter: "div",
AlertDialogHeader: "div",
AlertDialogPopup: "div",
AlertDialogTitle: "div",
}));
vi.mock("./ui/popover", () => ({
Popover: "div",
PopoverPopup: "div",
PopoverTrigger: "button",
}));
vi.mock("./ui/button", () => ({ Button: "button" }));
vi.mock("./ui/input", () => ({ Input: "input" }));
vi.mock("./ui/label", () => ({ Label: "label" }));
vi.mock("./ui/switch", () => ({ Switch: "input" }));
vi.mock("./ui/textarea", () => ({ Textarea: "textarea" }));
import {
ProjectScriptEditorDialog,
type NewProjectScriptInput,
type ProjectScriptEditorRequest,
} from "./projectScriptEditor";
const request: ProjectScriptEditorRequest = {
scriptId: "test",
initial: {
name: "Test",
command: "vp test",
icon: "test",
runOnWorktreeCreate: false,
waitForSetup: false,
keybinding: "mod+k",
previewUrl: null,
autoOpenPreview: false,
},
};
describe("ProjectScriptEditorDialog", () => {
let renderer: ReactTestRenderer | undefined;
beforeEach(() => {
permissions.canWriteSettings = false;
permissions.canEditProject = true;
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
});
afterEach(async () => {
await act(() => renderer?.unmount());
vi.unstubAllGlobals();
});
async function openEditor(
onSubmit = vi.fn().mockResolvedValue(AsyncResult.success(undefined)),
editorRequest = request,
actions = { onDelete: vi.fn(), onClose: vi.fn() },
editScope:
| typeof AuthOrchestrationOperateScope
| typeof AuthSettingsWriteScope = AuthOrchestrationOperateScope,
) {
await act(() => {
renderer = create(
<ProjectScriptEditorDialog
environmentId={EnvironmentId.make("script-editor-test")}
editScope={editScope}
request={editorRequest}
scripts={[]}
onSubmit={onSubmit}
onDelete={actions.onDelete}
onClose={actions.onClose}
/>,
);
});
return renderer!.root;
}
it.each([null, "test"])(
"saves a settings action without task access (id: %s)",
async (scriptId) => {
permissions.canEditProject = false;
permissions.canWriteSettings = true;
const onSubmit = vi.fn().mockResolvedValue(AsyncResult.success(undefined));
const root = await openEditor(
onSubmit,
{ ...request, scriptId },
undefined,
AuthSettingsWriteScope,
);
const submit = root.findByType("form").props.onSubmit;
permissions.canWriteSettings = false;
await act(async () => {
await submit({ preventDefault() {} });
});
expect(onSubmit).not.toHaveBeenCalled();
permissions.canWriteSettings = true;
await act(async () => {
await submit({ preventDefault() {} });
});
expect(onSubmit).toHaveBeenCalledExactlyOnceWith(
scriptId,
expect.objectContaining({ command: "vp test" }),
);
},
);
it("rechecks settings access before deleting a settings action", async () => {
permissions.canEditProject = false;
permissions.canWriteSettings = true;
const actions = { onDelete: vi.fn(), onClose: vi.fn() };
const root = await openEditor(undefined, request, actions, AuthSettingsWriteScope);
await act(() => {
root.findByProps({ variant: "destructive-outline" }).props.onClick();
});
const confirmDelete = root.findByProps({ variant: "destructive" }).props.onClick;
permissions.canWriteSettings = false;
await act(() => confirmDelete());
expect(actions.onDelete).not.toHaveBeenCalled();
permissions.canWriteSettings = true;
await act(() => confirmDelete());
expect(actions.onDelete).toHaveBeenCalledExactlyOnceWith(request.scriptId);
});
it("clears an old shortcut when adding an action with no shortcut", async () => {
permissions.canWriteSettings = true;
let persistedKeybinding: string | null = "mod+k";
const onSubmit = vi.fn(async (_id: string | null, input: NewProjectScriptInput) => {
if (input.keybinding !== undefined) persistedKeybinding = input.keybinding;
return AsyncResult.success(undefined);
});
const root = await openEditor(onSubmit, {
scriptId: null,
initial: { ...request.initial, keybinding: null },
});
await act(async () => {
await root.findByType("form").props.onSubmit({ preventDefault() {} });
});
expect(persistedKeybinding).toBeNull();
expect(onSubmit).toHaveBeenCalledWith(null, expect.objectContaining({ keybinding: null }));
});
it.each([false, true])(
"re-adds a deleted action while preserving its shortcut without settings access (revoked: %s)",
async (revokeBeforeSubmit) => {
permissions.canWriteSettings = revokeBeforeSubmit;
const persisted = { name: null as string | null, keybinding: "mod+k" as string | null };
const onSubmit = vi.fn(async (_id: string | null, input: NewProjectScriptInput) => {
if (input.keybinding !== undefined && !permissions.canWriteSettings) {
return AsyncResult.failure(
Cause.fail(new Error("This connection cannot change keyboard shortcuts.")),
);
}
persisted.name = input.name;
if (input.keybinding !== undefined) persisted.keybinding = input.keybinding;
return AsyncResult.success(undefined);
});
const root = await openEditor(onSubmit, {
scriptId: null,
initial: { ...request.initial, keybinding: null },
});
permissions.canWriteSettings = false;
await act(async () => {
await root.findByType("form").props.onSubmit({ preventDefault() {} });
});
expect(persisted).toEqual({ name: "Test", keybinding: "mod+k" });
expect(onSubmit).toHaveBeenCalledOnce();
},
);
it.each([false, true])(
"requires settings access to override a retained shortcut when re-adding an action (revoked: %s)",
async (revokeBeforeSubmit) => {
permissions.canWriteSettings = true;
vi.stubGlobal("navigator", { platform: "Linux" });
const persisted = { name: null as string | null, keybinding: "mod+k" as string | null };
const onSubmit = vi.fn(async (_id: string | null, input: NewProjectScriptInput) => {
persisted.name = input.name;
if (input.keybinding !== undefined) persisted.keybinding = input.keybinding;
return AsyncResult.success(undefined);
});
const root = await openEditor(onSubmit, {
scriptId: null,
initial: { ...request.initial, keybinding: null },
});
await act(() => {
root.findByProps({ id: "script-keybinding" }).props.onKeyDown({
key: "j",
ctrlKey: true,
metaKey: false,
altKey: false,
shiftKey: false,
preventDefault() {},
});
});
if (revokeBeforeSubmit) permissions.canWriteSettings = false;
await act(async () => {
await root.findByType("form").props.onSubmit({ preventDefault() {} });
});
expect(persisted).toEqual(
revokeBeforeSubmit
? { name: null, keybinding: "mod+k" }
: { name: "Test", keybinding: "mod+j" },
);
},
);
it.each([false, true])(
"preserves a concurrent shortcut change when saving only the script (settings access: %s)",
async (canWriteSettings) => {
permissions.canWriteSettings = canWriteSettings;
const persisted = { name: request.initial.name, keybinding: request.initial.keybinding };
const onSubmit = vi.fn(async (_id: string | null, input: NewProjectScriptInput) => {
persisted.name = input.name;
if (input.keybinding !== undefined) persisted.keybinding = input.keybinding;
return AsyncResult.success(undefined);
});
const root = await openEditor(onSubmit);
// A second client changes the shortcut after this dialog snapshots it.
persisted.keybinding = "mod+j";
await act(() => {
root.findByProps({ id: "script-name" }).props.onChange({ target: { value: "Renamed" } });
});
await act(async () => {
await root.findByType("form").props.onSubmit({ preventDefault() {} });
});
expect(persisted).toEqual({ name: "Renamed", keybinding: "mod+j" });
expect(onSubmit).toHaveBeenCalledOnce();
},
);
it.each([false, true])(
"enforces settings access when submitting an explicit shortcut clear (revoked: %s)",
async (revokeBeforeSubmit) => {
permissions.canWriteSettings = true;
const onSubmit = vi.fn().mockResolvedValue(AsyncResult.success(undefined));
const root = await openEditor(onSubmit);
await act(() => {
root.findByProps({ id: "script-keybinding" }).props.onKeyDown({
key: "Backspace",
preventDefault() {},
});
});
if (revokeBeforeSubmit) permissions.canWriteSettings = false;
await act(async () => {
await root.findByType("form").props.onSubmit({ preventDefault() {} });
});
if (revokeBeforeSubmit) {
expect(onSubmit).not.toHaveBeenCalled();
} else {
expect(onSubmit).toHaveBeenCalledWith(
"test",
expect.objectContaining({ keybinding: null }),
);
}
},
);
it.each([false, true])(
"requires project access to save even with settings access (revoked: %s)",
async (revokeBeforeSubmit) => {
permissions.canEditProject = revokeBeforeSubmit;
permissions.canWriteSettings = true;
const onSubmit = vi.fn().mockResolvedValue(AsyncResult.success(undefined));
const root = await openEditor(onSubmit);
const submit = root.findByType("form").props.onSubmit;
permissions.canEditProject = false;
await act(async () => {
await submit({ preventDefault() {} });
});
expect(onSubmit).not.toHaveBeenCalled();
permissions.canEditProject = true;
await act(async () => {
await submit({ preventDefault() {} });
});
expect(onSubmit).toHaveBeenCalledOnce();
},
);
it("rechecks project access before deleting from an already open confirmation", async () => {
const actions = { onDelete: vi.fn(), onClose: vi.fn() };
const root = await openEditor(undefined, request, actions);
await act(() => {
root.findByProps({ variant: "destructive-outline" }).props.onClick();
});
const confirmDelete = root.findByProps({ variant: "destructive" }).props.onClick;
permissions.canEditProject = false;
await act(() => confirmDelete());
expect(actions.onDelete).not.toHaveBeenCalled();
expect(actions.onClose).not.toHaveBeenCalled();
permissions.canEditProject = true;
await act(() => confirmDelete());
expect(actions.onDelete).toHaveBeenCalledExactlyOnceWith(request.scriptId);
expect(actions.onClose).toHaveBeenCalledOnce();
});
});
@@ -1,9 +1,14 @@
import { EnvironmentId } from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import { AsyncResult } from "effect/reactivity";
import { act, StrictMode, type ReactNode } from "react";
import { create, type ReactTestRenderer } from "react-test-renderer";
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
vi.mock("~/state/session", () => ({
readEnvironmentScope: () => true,
useEnvironmentScope: () => true,
}));
vi.mock("./ui/dialog", () => ({
Dialog: ({ open, children }: { open: boolean; children: ReactNode }) => (open ? children : null),
DialogDescription: "p",
@@ -58,6 +63,7 @@ function editor(nextRequest: ProjectScriptEditorRequest) {
return (
<StrictMode>
<ProjectScriptEditorDialog
environmentId={EnvironmentId.make("test")}
request={nextRequest}
scripts={[]}
onSubmit={onSubmit}
+46 -14
View File
@@ -1,7 +1,10 @@
import type {
ProjectScript,
ProjectScriptIcon,
ResolvedKeybindingsConfig,
import {
AuthOrchestrationOperateScope,
AuthSettingsWriteScope,
type EnvironmentId,
type ProjectScript,
type ProjectScriptIcon,
type ResolvedKeybindingsConfig,
} from "@t3tools/contracts";
import {
isAtomCommandInterrupted,
@@ -31,6 +34,8 @@ import {
} from "~/lib/projectScriptKeybindings";
import { keybindingFromKeyboardEvent } from "~/components/settings/KeybindingsSettings.logic";
import { commandForProjectScript, nextProjectScriptId } from "~/projectScripts";
import { readEnvironmentScope, useEnvironmentScope } from "~/state/session";
import { useComposerMenuState } from "./chat/useComposerMenuState";
import {
AlertDialog,
AlertDialogClose,
@@ -87,7 +92,8 @@ export interface NewProjectScriptInput {
runOnWorktreeCreate: boolean;
/** Setup scripts only: hold the agent until the script exits. */
waitForSetup: boolean;
keybinding: string | null;
/** Omit to preserve the current shortcut when the form did not edit it. */
keybinding?: string | null;
/** Optional URL to open in the in-app preview when this script runs. */
previewUrl: string | null;
/** When true, automatically open the preview panel pointed at `previewUrl`. */
@@ -140,12 +146,16 @@ export function editorRequestForScript(
* being edited via `request`; the dialog owns the form state and validation.
*/
export function ProjectScriptEditorDialog({
environmentId,
editScope = AuthOrchestrationOperateScope,
request,
scripts,
onSubmit,
onDelete,
onClose,
}: {
environmentId: EnvironmentId;
editScope?: typeof AuthOrchestrationOperateScope | typeof AuthSettingsWriteScope;
request: ProjectScriptEditorRequest | null;
/** Existing scripts, used to derive a unique id for new scripts. */
scripts: ReadonlyArray<ProjectScript>;
@@ -156,18 +166,20 @@ export function ProjectScriptEditorDialog({
onDelete: (scriptId: string) => void;
onClose: () => void;
}) {
const canEditActions = useEnvironmentScope(environmentId, editScope);
const canWriteSettings = useEnvironmentScope(environmentId, AuthSettingsWriteScope);
const formId = React.useId();
const [name, setName] = useState("");
const [command, setCommand] = useState("");
const [icon, setIcon] = useState<ProjectScriptIcon>("play");
const [iconPickerOpen, setIconPickerOpen] = useState(false);
const [iconPickerOpen, setIconPickerOpen] = useComposerMenuState(!canEditActions);
const [runOnWorktreeCreate, setRunOnWorktreeCreate] = useState(false);
const [waitForSetup, setWaitForSetup] = useState(false);
const [keybinding, setKeybinding] = useState("");
const [previewUrl, setPreviewUrl] = useState("");
const [autoOpenPreview, setAutoOpenPreview] = useState(false);
const [validationError, setValidationError] = useState<string | null>(null);
const [deleteConfirmOpen, setDeleteConfirmOpen] = useState(false);
const [deleteConfirmOpen, setDeleteConfirmOpen] = useComposerMenuState(!canEditActions);
const [savingRequest, setSavingRequest] = useState<ProjectScriptEditorRequest | null>(null);
const pendingSubmissionRef = useRef<{ request: ProjectScriptEditorRequest } | null>(null);
@@ -199,7 +211,7 @@ export function ProjectScriptEditorDialog({
setAutoOpenPreview(request.initial.autoOpenPreview);
setValidationError(request.error ?? null);
setSavingRequest(null);
}, [request]);
}, [request, setIconPickerOpen]);
const close = () => {
pendingSubmissionRef.current = null;
@@ -209,6 +221,8 @@ export function ProjectScriptEditorDialog({
};
const captureKeybinding = (event: KeyboardEvent<HTMLInputElement>) => {
if (!readEnvironmentScope(environmentId, editScope)) return;
if (!readEnvironmentScope(environmentId, AuthSettingsWriteScope)) return;
if (event.key === "Tab") return;
event.preventDefault();
if (event.key === "Backspace" || event.key === "Delete") {
@@ -223,6 +237,17 @@ export function ProjectScriptEditorDialog({
const submit = async (event: FormEvent) => {
event.preventDefault();
if (!request || pendingSubmissionRef.current !== null) return;
if (!readEnvironmentScope(environmentId, editScope)) {
setValidationError("This connection cannot change project actions.");
return;
}
const changesKeybinding =
(keybinding.trim() || null) !== (request.initial.keybinding?.trim() || null);
const canChangeKeybinding = readEnvironmentScope(environmentId, AuthSettingsWriteScope);
if (changesKeybinding && !canChangeKeybinding) {
setValidationError("This connection cannot change keyboard shortcuts.");
return;
}
const trimmedName = name.trim();
const trimmedCommand = command.trim();
if (trimmedName.length === 0) {
@@ -254,7 +279,9 @@ export function ProjectScriptEditorDialog({
icon,
runOnWorktreeCreate,
waitForSetup: runOnWorktreeCreate && waitForSetup,
keybinding: keybindingRule?.key ?? null,
...((request.scriptId === null && canChangeKeybinding) || changesKeybinding
? { keybinding: keybindingRule?.key ?? null }
: {}),
previewUrl: trimmedPreviewUrl.length > 0 ? trimmedPreviewUrl : null,
autoOpenPreview: trimmedPreviewUrl.length > 0 ? autoOpenPreview : false,
} satisfies NewProjectScriptInput;
@@ -309,7 +336,7 @@ export function ProjectScriptEditorDialog({
</DialogHeader>
<DialogPanel>
<form id={formId} onSubmit={submit}>
<fieldset className="space-y-4" disabled={isSaving}>
<fieldset className="space-y-4" disabled={isSaving || !canEditActions}>
<div className="space-y-1.5">
<Label htmlFor="script-name">Name</Label>
<div className="flex items-center gap-2">
@@ -364,6 +391,7 @@ export function ProjectScriptEditorDialog({
<div className="space-y-1.5">
<Label htmlFor="script-keybinding">Keybinding</Label>
<Input
disabled={!canWriteSettings}
id="script-keybinding"
placeholder="Press shortcut"
value={keybinding}
@@ -437,7 +465,7 @@ export function ProjectScriptEditorDialog({
type="button"
variant="destructive-outline"
className="mr-auto"
disabled={isSaving}
disabled={isSaving || !canEditActions}
onClick={() => setDeleteConfirmOpen(true)}
>
Delete
@@ -446,14 +474,14 @@ export function ProjectScriptEditorDialog({
<Button type="button" variant="outline" onClick={close}>
Cancel
</Button>
<Button form={formId} type="submit" disabled={isSaving}>
<Button form={formId} type="submit" disabled={isSaving || !canEditActions}>
{isSaving ? "Saving…" : isEditing ? "Save changes" : "Save action"}
</Button>
</DialogFooter>
</DialogPopup>
</Dialog>
<AlertDialog open={deleteConfirmOpen} onOpenChange={setDeleteConfirmOpen}>
<AlertDialog open={deleteConfirmOpen && canEditActions} onOpenChange={setDeleteConfirmOpen}>
<AlertDialogPopup>
<AlertDialogHeader>
<AlertDialogTitle>Delete action "{name}"?</AlertDialogTitle>
@@ -463,9 +491,13 @@ export function ProjectScriptEditorDialog({
<AlertDialogClose render={<Button variant="outline" />}>Cancel</AlertDialogClose>
<Button
variant="destructive"
disabled={isSaving}
disabled={isSaving || !canEditActions}
onClick={() => {
if (!request?.scriptId) return;
if (!readEnvironmentScope(environmentId, editScope)) {
setValidationError("This connection cannot change project actions.");
return;
}
setDeleteConfirmOpen(false);
close();
onDelete(request.scriptId);
@@ -14,6 +14,7 @@ const state = vi.hoisted(() => ({
result: null as { readonly agents: ReadonlyArray<AcpRegistrySearchAgent> } | null,
error: null as string | null,
isPending: false,
canManage: true,
refresh: vi.fn(),
search: vi.fn(() => atoms.search),
prepare: vi.fn(),
@@ -53,6 +54,11 @@ vi.mock("../../state/server", () => ({
},
}));
vi.mock("../../state/session", () => ({
useEnvironmentScope: () => state.canManage,
readEnvironmentScope: () => state.canManage,
}));
vi.mock("../../state/query", () => ({
useEnvironmentQuery: () => ({
data: state.result,
@@ -119,6 +125,7 @@ function findByAriaLabel(
describe("AcpRegistrySearchStep", () => {
beforeEach(() => {
state.canManage = true;
vi.useFakeTimers();
hooks.reset();
state.result = null;
@@ -265,6 +272,16 @@ describe("AcpRegistrySearchStep", () => {
});
});
it("rechecks the grant before preparing an agent", async () => {
state.result = { agents: [gemini] };
const onPrepared = vi.fn();
const add = findByAriaLabel(render({ onPrepared }), "Add Gemini CLI");
state.canManage = false;
await (add.props.onClick as () => void)();
expect(state.prepare).not.toHaveBeenCalled();
expect(onPrepared).not.toHaveBeenCalled();
});
it("ignores a stale prepare completion", async () => {
let resolveFirst!: (value: { readonly _tag: "Success"; readonly value: unknown }) => void;
let resolveSecond!: (value: { readonly _tag: "Success"; readonly value: unknown }) => void;
@@ -1,3 +1,5 @@
import { AuthProvidersManageScope } from "@t3tools/contracts";
import { readEnvironmentScope, useEnvironmentScope } from "../../state/session";
import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
@@ -64,6 +66,7 @@ export function AcpRegistrySearchStep({
// An empty registry query is the compact compatible catalog. Start there so
// entering this step is useful before the user knows what to search for.
const [submittedQuery, setSubmittedQuery] = useState("");
const canManageProviders = useEnvironmentScope(environmentId, AuthProvidersManageScope);
const [preparingId, setPreparingId] = useState<string | null>(null);
const [prepareError, setPrepareError] = useState<string | null>(null);
const prepareGeneration = useRef(0);
@@ -105,6 +108,7 @@ export function AcpRegistrySearchStep({
};
const handlePrepare = async (agent: AcpRegistrySearchAgent) => {
if (!readEnvironmentScope(environmentId, AuthProvidersManageScope)) return;
const generation = ++prepareGeneration.current;
setPrepareError(null);
setPreparingId(agent.id);
@@ -271,7 +275,7 @@ export function AcpRegistrySearchStep({
) : null}
<Button
aria-label={`${alreadyAdded ? "Already added" : isPreparing ? progressLabel : "Add"} ${agent.name}`}
disabled={alreadyAdded || preparingId !== null}
disabled={!canManageProviders || alreadyAdded || preparingId !== null}
onClick={() => void handlePrepare(agent)}
size="xs"
variant={isPreparing ? "secondary" : "outline"}
@@ -32,6 +32,12 @@ const commands = vi.hoisted(() => ({
logout: vi.fn(),
}));
const grants = vi.hoisted(() => ({ scopes: new Set<string>() }));
vi.mock("~/state/session", async (original) => ({
...(await original<typeof import("~/state/session")>()),
useEnvironmentScope: (_id: unknown, scope: string) => grants.scopes.has(scope),
readEnvironmentScope: (_id: unknown, scope: string) => grants.scopes.has(scope),
}));
const dialogs = vi.hoisted(() => ({ confirm: vi.fn() }));
vi.mock("react", async (importOriginal) => {
@@ -105,14 +111,14 @@ const provider = {
skills: [],
} satisfies ServerProvider;
function render(): ReactElement<Record<string, unknown>> {
function render(readOnly = false): ReactElement<Record<string, unknown>> {
hooks.beginRender();
return AcpSessionManagementSection({
environmentId,
instanceId,
provider,
projects: [{ id: projectId, title: "Antigravity", workspaceRoot: session.cwd }],
readOnly: false,
readOnly,
}) as ReactElement<Record<string, unknown>>;
}
@@ -139,55 +145,56 @@ async function flushPromises(): Promise<void> {
await Promise.resolve();
}
describe("AcpSessionManagementSection", () => {
beforeEach(() => {
hooks.reset();
commands.list.mockReset().mockResolvedValue({
_tag: "Success",
value: {
sessions: [session],
nextCursor: null,
canLoad: true,
canResume: true,
canDelete: true,
},
});
commands.import.mockReset().mockResolvedValue({
_tag: "Success",
value: { threadId: ThreadId.make("thread-imported"), imported: true },
});
commands.delete.mockReset().mockResolvedValue({
_tag: "Success",
value: { deleted: true },
});
commands.listProviders.mockReset().mockResolvedValue({
_tag: "Success",
value: {
providers: [
{
providerId: "google",
supported: ["openai"],
required: false,
current: { apiType: "openai", baseUrl: "https://api.example.test/v1" },
},
],
},
});
commands.setProvider.mockReset().mockResolvedValue({
_tag: "Success",
value: { configured: true },
});
commands.disableProvider.mockReset().mockResolvedValue({
_tag: "Success",
value: { disabled: true },
});
commands.logout.mockReset().mockResolvedValue({
_tag: "Success",
value: { loggedOut: true },
});
dialogs.confirm.mockReset().mockResolvedValue(true);
beforeEach(() => {
hooks.reset();
grants.scopes = new Set(["orchestration:read", "orchestration:operate", "providers:manage"]);
commands.list.mockReset().mockResolvedValue({
_tag: "Success",
value: {
sessions: [session],
nextCursor: null,
canLoad: true,
canResume: true,
canDelete: true,
},
});
commands.import.mockReset().mockResolvedValue({
_tag: "Success",
value: { threadId: ThreadId.make("thread-imported"), imported: true },
});
commands.delete.mockReset().mockResolvedValue({
_tag: "Success",
value: { deleted: true },
});
commands.listProviders.mockReset().mockResolvedValue({
_tag: "Success",
value: {
providers: [
{
providerId: "google",
supported: ["openai"],
required: false,
current: { apiType: "openai", baseUrl: "https://api.example.test/v1" },
},
],
},
});
commands.setProvider.mockReset().mockResolvedValue({
_tag: "Success",
value: { configured: true },
});
commands.disableProvider.mockReset().mockResolvedValue({
_tag: "Success",
value: { disabled: true },
});
commands.logout.mockReset().mockResolvedValue({
_tag: "Success",
value: { loggedOut: true },
});
dialogs.confirm.mockReset().mockResolvedValue(true);
});
describe("AcpSessionManagementSection", () => {
it("lists and imports native sessions through the owning environment", async () => {
const initial = render();
(findByLabel(initial, "List sessions").props.onClick as (() => void) | undefined)?.();
@@ -292,3 +299,33 @@ describe("AcpSessionManagementSection", () => {
});
});
});
it("imports with task access even when provider configuration is read-only", async () => {
grants.scopes.delete("providers:manage");
(findByLabel(render(true), "List sessions").props.onClick as () => void)();
await flushPromises();
(findByLabel(render(true), "Import").props.onClick as () => void)();
await flushPromises();
expect(commands.import).toHaveBeenCalledOnce();
});
it("does not import with provider management alone", async () => {
grants.scopes.delete("orchestration:operate");
(findByLabel(render(), "List sessions").props.onClick as () => void)();
await flushPromises();
(findByLabel(render(), "Import").props.onClick as () => void)();
await flushPromises();
expect(commands.import).not.toHaveBeenCalled();
});
it("rechecks task access after confirming deletion", async () => {
(findByLabel(render(), "List sessions").props.onClick as () => void)();
await flushPromises();
dialogs.confirm.mockImplementationOnce(async () => {
grants.scopes.delete("orchestration:operate");
return true;
});
(findByLabel(render(), "Delete").props.onClick as () => void)();
await flushPromises();
expect(commands.delete).not.toHaveBeenCalled();
});
@@ -1,3 +1,9 @@
import {
AuthOrchestrationOperateScope,
AuthProvidersManageScope,
AuthOrchestrationReadScope,
} from "@t3tools/contracts";
import { useEnvironmentScope, readEnvironmentScope } from "~/state/session";
import type {
AcpRegistryConfigurableProvider,
AcpRegistrySession,
@@ -45,6 +51,8 @@ export function AcpSessionManagementSection(props: {
readonly projects: ReadonlyArray<AcpSessionProject>;
readonly readOnly: boolean;
}) {
const canOperate = useEnvironmentScope(props.environmentId, AuthOrchestrationOperateScope);
const canRead = useEnvironmentScope(props.environmentId, AuthOrchestrationReadScope);
const [projectId, setProjectId] = useState<ProjectId | null>(props.projects[0]?.id ?? null);
const [sessions, setSessions] = useState<ReadonlyArray<AcpRegistrySession>>([]);
const [nextCursor, setNextCursor] = useState<string | null>(null);
@@ -117,7 +125,12 @@ export function AcpSessionManagementSection(props: {
};
const importNativeSession = async (session: AcpRegistrySession) => {
if (projectId === null || importingSessionId !== null) return;
if (
!readEnvironmentScope(props.environmentId, AuthOrchestrationOperateScope) ||
projectId === null ||
importingSessionId !== null
)
return;
setImportingSessionId(session.sessionId);
const result = await importSession({
environmentId: props.environmentId,
@@ -154,7 +167,8 @@ export function AcpSessionManagementSection(props: {
`Permanently delete native ACP session "${session.title ?? session.sessionId}"?`,
{ variant: "destructive" },
);
if (!confirmed) return;
if (!confirmed || !readEnvironmentScope(props.environmentId, AuthOrchestrationOperateScope))
return;
setDeletingSessionId(session.sessionId);
const result = await deleteSession({
environmentId: props.environmentId,
@@ -199,7 +213,12 @@ export function AcpSessionManagementSection(props: {
};
const saveProvider = async (provider: AcpRegistryConfigurableProvider) => {
if (projectId === null || savingProviderId !== null) return;
if (
!readEnvironmentScope(props.environmentId, AuthProvidersManageScope) ||
projectId === null ||
savingProviderId !== null
)
return;
const draft = providerDrafts[provider.providerId];
if (draft === undefined || draft.apiType.length === 0 || draft.baseUrl.length === 0) return;
let headers: Record<string, string> | undefined;
@@ -251,7 +270,7 @@ export function AcpSessionManagementSection(props: {
`Disable ACP provider "${provider.providerId}"?`,
{ variant: "destructive" },
);
if (!confirmed) return;
if (!confirmed || !readEnvironmentScope(props.environmentId, AuthProvidersManageScope)) return;
setSavingProviderId(provider.providerId);
const result = await disableProvider({
environmentId: props.environmentId,
@@ -267,7 +286,7 @@ export function AcpSessionManagementSection(props: {
};
const logoutProvider = async () => {
if (loggingOut) return;
if (loggingOut || !readEnvironmentScope(props.environmentId, AuthProvidersManageScope)) return;
setLoggingOut(true);
const result = await logout({
environmentId: props.environmentId,
@@ -310,7 +329,7 @@ export function AcpSessionManagementSection(props: {
<>
<Select
value={projectId ?? ""}
disabled={props.readOnly || projectOperationPending}
disabled={!canRead || projectOperationPending}
onValueChange={(value) => {
if (value === null) return;
setProjectId(value as ProjectId);
@@ -337,7 +356,7 @@ export function AcpSessionManagementSection(props: {
type="button"
size="sm"
variant="outline"
disabled={props.readOnly || loading || projectId === null}
disabled={!canRead || loading || projectId === null}
onClick={() => void loadSessions()}
>
{loading ? "Loading" : sessions.length === 0 ? "List sessions" : "Refresh"}
@@ -370,7 +389,7 @@ export function AcpSessionManagementSection(props: {
size="xs"
variant="ghost-muted"
disabled={
props.readOnly ||
!canOperate ||
!canImport ||
session.importedThreadId !== null ||
importingSessionId !== null
@@ -389,7 +408,7 @@ export function AcpSessionManagementSection(props: {
size="xs"
variant="ghost-muted"
disabled={
props.readOnly ||
!canOperate ||
session.importedThreadId !== null ||
deletingSessionId !== null
}
@@ -410,7 +429,7 @@ export function AcpSessionManagementSection(props: {
size="xs"
variant="ghost-muted"
className="w-fit"
disabled={props.readOnly || loading}
disabled={!canRead || loading}
onClick={() => void loadSessions(nextCursor)}
>
{loading ? "Loading" : "Load more"}
@@ -433,7 +452,7 @@ export function AcpSessionManagementSection(props: {
type="button"
size="xs"
variant="outline"
disabled={props.readOnly || loadingProviders || projectId === null}
disabled={!canRead || loadingProviders || projectId === null}
onClick={() => void loadProviders()}
>
{loadingProviders ? "Loading" : providers.length === 0 ? "List providers" : "Refresh"}
@@ -443,7 +462,7 @@ export function AcpSessionManagementSection(props: {
{!canList && props.projects.length > 1 ? (
<Select
value={projectId ?? ""}
disabled={props.readOnly || projectOperationPending}
disabled={!canRead || projectOperationPending}
onValueChange={(value) => {
if (value === null) return;
setProjectId(value as ProjectId);
@@ -1,3 +1,5 @@
import { AuthProvidersManageScope } from "@t3tools/contracts";
import { readEnvironmentScope, useEnvironmentScope } from "../../state/session";
import { useAtomValue } from "@effect/atom-react";
import {
ProviderDriverKind,
@@ -31,6 +33,7 @@ export function AddCodexAccountDialog({
| undefined;
readonly renderSetup: (instanceId: ProviderInstanceId, provider: ServerProvider) => ReactNode;
}) {
const canManageProviders = useEnvironmentScope(environmentId, AuthProvidersManageScope);
const settings = useEnvironmentSettings(environmentId);
const providers = useAtomValue(serverEnvironment.providersValueAtom(environmentId));
const update = useAtomCommand(serverEnvironment.updateSettings, "Add ChatGPT account");
@@ -47,7 +50,8 @@ export function AddCodexAccountDialog({
}, [connected]);
const createAccount = async () => {
if (pending || !name.trim()) return;
if (pending || !name.trim() || !readEnvironmentScope(environmentId, AuthProvidersManageScope))
return;
setPending(true);
// The ID is routing identity; the name is editable and need not be unique.
const id = ProviderInstanceId.make(`codex_${randomUUID()}`);
@@ -131,7 +135,11 @@ export function AddCodexAccountDialog({
<Button variant="outline" disabled={pending} onClick={onClose}>
Cancel
</Button>
<Button type="submit" form="add-codex-account" disabled={pending || !name.trim()}>
<Button
type="submit"
form="add-codex-account"
disabled={pending || !name.trim() || !canManageProviders}
>
{pending ? "Adding account…" : "Continue"}
</Button>
</>
@@ -4,6 +4,13 @@ import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
import { visitElements } from "../../test/reactElementTree";
import { reactHookHarness as hooks } from "../../test/reactHookHarness";
const actions = vi.hoisted(() => ({
update: vi.fn(),
toast: vi.fn(),
onOpenChange: vi.fn(),
canManageProviders: true,
}));
const settingsHooks = vi.hoisted(() => ({
read: vi.fn(() => ({ providerInstances: {} })),
mutate: vi.fn(),
@@ -35,6 +42,15 @@ vi.mock("../../hooks/useSettings", () => ({
usePersistEnvironmentProviderInstanceMutation: settingsHooks.useMutation,
}));
vi.mock("../../state/session", async (importOriginal) => {
const actual = await importOriginal<typeof import("../../state/session")>();
const hasScope = (environmentId: EnvironmentId, scope: string) =>
environmentId === "remote-device" && scope === "providers:manage" && actions.canManageProviders;
return { ...actual, useEnvironmentScope: hasScope, readEnvironmentScope: hasScope };
});
vi.mock("../ui/toast", () => ({ toastManager: { add: actions.toast } }));
import { AddProviderInstanceDialog } from "./AddProviderInstanceDialog";
const remoteEnvironmentId = EnvironmentId.make("remote-device");
@@ -81,9 +97,45 @@ async function selectPreparedAcp() {
);
}
function renderDialog() {
hooks.beginRender();
return AddProviderInstanceDialog({
open: true,
environmentId: remoteEnvironmentId,
environmentLabel: "Remote device",
onOpenChange: actions.onOpenChange,
});
}
function button(dialog: unknown, label: string) {
const element = visitElements(
dialog,
(entry) => entry.props.children === label && typeof entry.props.onClick === "function",
);
if (!element) throw new Error(`Missing button: ${label}`);
return element;
}
function prepareInstance() {
let dialog = renderDialog();
(button(dialog, "Configure manually").props.onClick as () => void)();
dialog = renderDialog();
const label = visitElements(dialog, (entry) => entry.props.placeholder === "e.g. Work");
if (!label) throw new Error("Missing instance label input.");
(label.props.onChange as (event: { target: { value: string } }) => void)({
target: { value: "Work" },
});
dialog = renderDialog();
(button(dialog, "Next").props.onClick as () => void)();
return renderDialog();
}
describe("AddProviderInstanceDialog environment routing", () => {
beforeEach(() => {
hooks.reset();
actions.canManageProviders = true;
actions.toast.mockReset();
actions.onOpenChange.mockReset();
settingsHooks.read.mockReset().mockReturnValue({ providerInstances: {} });
settingsHooks.mutate.mockReset().mockResolvedValue({ _tag: "Success", value: {} });
settingsHooks.useMutation.mockReset().mockReturnValue(settingsHooks.mutate);
@@ -321,4 +373,53 @@ describe("AddProviderInstanceDialog environment routing", () => {
expect(onOpenChange).not.toHaveBeenCalled();
});
it("adds an instance with the selected environment's provider grant alone", async () => {
const dialog = prepareInstance();
(button(dialog, "Add instance").props.onClick as () => void)();
await Promise.resolve();
expect(settingsHooks.mutate).toHaveBeenCalledWith({
operation: "create",
instanceId: "codex_work",
instance: {
driver: "codex",
enabled: true,
displayName: "Work",
config: { setupMode: "existing" },
},
});
expect(actions.toast).toHaveBeenCalledWith(
expect.objectContaining({ type: "success", title: "Provider instance added" }),
);
expect(actions.onOpenChange).toHaveBeenCalledWith(false);
});
it("rejects a queued save after the provider grant is revoked", () => {
const dialog = prepareInstance();
const save = button(dialog, "Add instance").props.onClick as () => void;
actions.canManageProviders = false;
save();
expect(settingsHooks.mutate).not.toHaveBeenCalled();
expect(actions.toast).not.toHaveBeenCalled();
expect(actions.onOpenChange).not.toHaveBeenCalled();
expect(button(renderDialog(), "Add instance").props.disabled).toBe(true);
});
it("keeps a denied draft available when the provider grant arrives", async () => {
actions.canManageProviders = false;
let dialog = prepareInstance();
(button(dialog, "Add instance").props.onClick as () => void)();
expect(settingsHooks.mutate).not.toHaveBeenCalled();
expect(actions.toast).not.toHaveBeenCalled();
actions.canManageProviders = true;
dialog = renderDialog();
expect(button(dialog, "Add instance").props.disabled).toBe(false);
(button(dialog, "Add instance").props.onClick as () => void)();
await Promise.resolve();
expect(settingsHooks.mutate).toHaveBeenCalledOnce();
expect(actions.onOpenChange).toHaveBeenCalledWith(false);
});
});
@@ -9,6 +9,7 @@ import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"
import {
DEFAULT_UNIFIED_SETTINGS,
type AcpRegistrySearchAgent,
AuthProvidersManageScope,
ProviderInstanceId,
ProviderDriverKind,
type EnvironmentId,
@@ -24,6 +25,7 @@ import * as Equal from "effect/Equal";
import { cn } from "../../lib/utils";
import { normalizeProviderAccentColor } from "../../providerInstances";
import { readEnvironmentScope, useEnvironmentScope } from "../../state/session";
import { Button } from "../ui/button";
import { ChatGptConnectionButton } from "./ChatGptConnectionButton";
import { Dialog } from "../ui/dialog";
@@ -113,6 +115,7 @@ export function AddProviderInstanceDialog({
}: AddProviderInstanceDialogProps) {
const settings = useEnvironmentSettings(environmentId);
const persistProviderInstance = usePersistEnvironmentProviderInstanceMutation(environmentId);
const canManageProviders = useEnvironmentScope(environmentId, AuthProvidersManageScope);
const [wizardStep, setWizardStep] = useState(0);
const [addingChatGptAccount, setAddingChatGptAccount] = useState(false);
@@ -308,6 +311,7 @@ export function AddProviderInstanceDialog({
};
const handleSave = async () => {
if (!readEnvironmentScope(environmentId, AuthProvidersManageScope)) return;
if (isSaving || createdInstanceId) return;
setHasAttemptedSubmit(true);
if (instanceIdError !== null || (isAcpRegistry && acpSelectionError !== null)) return;
@@ -694,7 +698,11 @@ export function AddProviderInstanceDialog({
Next
</Button>
) : (
<Button size="sm" disabled={isSaving} onClick={() => void handleSave()}>
<Button
size="sm"
disabled={isSaving || !canManageProviders}
onClick={() => void handleSave()}
>
{isSaving
? "Adding..."
: isAcpRegistry && !isLocalAcp
@@ -1,3 +1,5 @@
import { AuthProvidersManageScope } from "@t3tools/contracts";
import { useEnvironmentScope } from "../../state/session";
import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
@@ -167,6 +169,7 @@ export function AddManagedCodexAccountDialog({
| ((instanceId: ProviderInstanceId, displayName: string) => void)
| undefined;
}) {
const canManageProviders = useEnvironmentScope(environmentId, AuthProvidersManageScope);
return (
<AddCodexAccountDialog
environmentId={environmentId}
@@ -180,6 +183,7 @@ export function AddManagedCodexAccountDialog({
provider={provider}
mode="managed"
enabled
readOnly={!canManageProviders}
autoStart
onAutoStartConsumed={noop}
onModeChange={noop}
@@ -2,6 +2,7 @@ import type { AdvertisedEndpoint, DesktopWslState } from "@t3tools/contracts";
import { describe, expect, it, vi } from "vite-plus/test";
import {
applyWslEnableSelection,
canRevokeOtherClients,
isQrShareableEndpoint,
isWslSettingsRowVisible,
selectQrEndpointOption,
@@ -183,3 +184,15 @@ describe("selectQrEndpointOption", () => {
expect(selectQrEndpointOption([], "anything", "anything")).toBeNull();
});
});
describe("canRevokeOtherClients", () => {
it("permits revocation when a write-only grant cannot list clients", () => {
expect(canRevokeOtherClients(null)).toBe(true);
});
it("disables revocation only when a loaded list has no other clients", () => {
expect(canRevokeOtherClients([])).toBe(false);
expect(canRevokeOtherClients([{ current: true }])).toBe(false);
expect(canRevokeOtherClients([{ current: true }, { current: false }])).toBe(true);
});
});
@@ -1,5 +1,12 @@
import type { AdvertisedEndpoint, DesktopBridge, DesktopWslState } from "@t3tools/contracts";
/** A missing access list says nothing about whether other clients exist. */
export function canRevokeOtherClients(
clientSessions: ReadonlyArray<{ readonly current: boolean }> | null,
): boolean {
return clientSessions === null || clientSessions.some((session) => !session.current);
}
type WslEnableBridge = Pick<DesktopBridge, "setWslBackendEnabled" | "setWslDistro" | "setWslOnly">;
/**
@@ -23,7 +23,9 @@ import {
import {
AuthAccessReadScope,
AuthAccessWriteScope,
AuthAdministrativeScopes,
AuthSettingsWriteScope,
AuthProvidersManageScope,
AuthEnvironmentMaintainScope,
AuthOrchestrationOperateScope,
AuthOrchestrationReadScope,
AuthRelayReadScope,
@@ -64,6 +66,7 @@ import { formatElapsedDurationLabel, formatExpiresInLabel } from "../../timestam
import { resolveDesktopPairingUrl, resolveHostedPairingUrl } from "./pairingUrls";
import {
applyWslEnableSelection,
canRevokeOtherClients,
isQrShareableEndpoint,
isWslSettingsRowVisible,
selectQrEndpointOption,
@@ -162,6 +165,7 @@ import {
connectPairing as connectPairingAtom,
connectSshEnvironment as connectSshEnvironmentAtom,
} from "~/connection/onboarding";
import { readEnvironmentScope, useEnvironmentScope } from "~/state/session";
import { useEnvironmentQuery } from "~/state/query";
import {
desktopNetworkAccessStateAtom,
@@ -174,6 +178,7 @@ import {
useEnvironments,
usePrimaryEnvironment,
useRelayEnvironmentDiscovery,
usePrimaryEnvironmentId,
} from "~/state/environments";
import { APP_VERSION } from "~/branding";
import { requestConfirmDialog } from "~/confirmDialog";
@@ -234,6 +239,21 @@ const PAIRING_SCOPE_OPTIONS: ReadonlyArray<{
title: "Operate tasks",
description: "Start tasks and perform changes in the environment.",
},
{
scope: AuthSettingsWriteScope,
title: "Change environment settings",
description: "Edit environment preferences and keybindings.",
},
{
scope: AuthProvidersManageScope,
title: "Manage providers",
description: "Configure, install, sign in to, and update providers and usage sources.",
},
{
scope: AuthEnvironmentMaintainScope,
title: "Maintain environment",
description: "Update the server and control environment processes.",
},
{
scope: AuthTerminalOperateScope,
title: "Use terminals",
@@ -600,6 +620,7 @@ type PairingLinkListRowProps = {
presentation?: AccessSectionPresentation;
revokingPairingLinkId: string | null;
onRevoke: (id: string) => void;
canRevoke: boolean;
};
const PairingLinkListRow = memo(function PairingLinkListRow({
@@ -611,6 +632,7 @@ const PairingLinkListRow = memo(function PairingLinkListRow({
presentation = "current",
revokingPairingLinkId,
onRevoke,
canRevoke,
}: PairingLinkListRowProps) {
const nowMs = useRelativeTimeTick(1_000);
const expiresAtMs = useMemo(
@@ -877,7 +899,7 @@ const PairingLinkListRow = memo(function PairingLinkListRow({
<Button
size="xs"
variant="destructive-outline"
disabled={revokingPairingLinkId === pairingLink.id}
disabled={!canRevoke || revokingPairingLinkId === pairingLink.id}
onClick={() => void onRevoke(pairingLink.id)}
>
{revokingPairingLinkId === pairingLink.id ? "Revoking…" : "Revoke"}
@@ -982,6 +1004,7 @@ type ConnectedClientListRowProps = {
presentation?: AccessSectionPresentation;
revokingClientSessionId: string | null;
onRevokeSession: (sessionId: ServerClientSessionRecord["sessionId"]) => void;
canRevoke: boolean;
};
const ConnectedClientListRow = memo(function ConnectedClientListRow({
@@ -989,6 +1012,7 @@ const ConnectedClientListRow = memo(function ConnectedClientListRow({
presentation = "current",
revokingClientSessionId,
onRevokeSession,
canRevoke,
}: ConnectedClientListRowProps) {
const nowMs = useRelativeTimeTick(1_000);
const isLive = clientSession.current || clientSession.connected;
@@ -1045,7 +1069,7 @@ const ConnectedClientListRow = memo(function ConnectedClientListRow({
<Button
size="xs"
variant="destructive-outline"
disabled={revokingClientSessionId === clientSession.sessionId}
disabled={!canRevoke || revokingClientSessionId === clientSession.sessionId}
onClick={() => void onRevokeSession(clientSession.sessionId)}
>
{revokingClientSessionId === clientSession.sessionId ? "Revoking…" : "Revoke"}
@@ -1059,9 +1083,10 @@ const ConnectedClientListRow = memo(function ConnectedClientListRow({
type AuthorizedClientsHeaderActionProps = {
onPairingLinkCreated: (result: AuthPairingCredentialResult) => void;
clientSessions: ReadonlyArray<ServerClientSessionRecord>;
clientSessions: ReadonlyArray<ServerClientSessionRecord> | null;
isRevokingOtherClients: boolean;
onRevokeOtherClients: () => void;
delegatableScopes: ReadonlyArray<AuthEnvironmentScope>;
};
const AuthorizedClientsHeaderAction = memo(function AuthorizedClientsHeaderAction({
@@ -1069,24 +1094,36 @@ const AuthorizedClientsHeaderAction = memo(function AuthorizedClientsHeaderActio
clientSessions,
isRevokingOtherClients,
onRevokeOtherClients,
delegatableScopes,
}: AuthorizedClientsHeaderActionProps) {
const primaryEnvironmentId = usePrimaryEnvironmentId();
const [dialogOpen, setDialogOpen] = useState(false);
const [pairingLabel, setPairingLabel] = useState("");
const [pairingScopes, setPairingScopes] = useState<ReadonlyArray<AuthEnvironmentScope>>([
...AuthStandardClientScopes,
]);
const selectedScopes = pairingScopes.filter((scope) => delegatableScopes.includes(scope));
const [isCreatingPairingLink, setIsCreatingPairingLink] = useState(false);
const handleCreatePairingLink = useCallback(async () => {
if (
primaryEnvironmentId === null ||
selectedScopes.length === 0 ||
!readEnvironmentScope(primaryEnvironmentId, AuthAccessWriteScope) ||
!selectedScopes.every((scope) => readEnvironmentScope(primaryEnvironmentId, scope))
)
return;
setIsCreatingPairingLink(true);
try {
const created = await createServerPairingCredential({
label: pairingLabel,
scopes: pairingScopes,
scopes: selectedScopes,
});
onPairingLinkCreated(created);
setPairingLabel("");
setPairingScopes([...AuthStandardClientScopes]);
setPairingScopes(
AuthStandardClientScopes.filter((scope) => delegatableScopes.includes(scope)),
);
setDialogOpen(false);
} catch (error) {
const message = error instanceof Error ? error.message : "Failed to create pairing URL.";
@@ -1100,7 +1137,7 @@ const AuthorizedClientsHeaderAction = memo(function AuthorizedClientsHeaderActio
} finally {
setIsCreatingPairingLink(false);
}
}, [onPairingLinkCreated, pairingLabel, pairingScopes]);
}, [delegatableScopes, onPairingLinkCreated, pairingLabel, primaryEnvironmentId, selectedScopes]);
const togglePairingScope = useCallback((scope: AuthEnvironmentScope, checked: boolean) => {
setPairingScopes((current) =>
@@ -1113,9 +1150,7 @@ const AuthorizedClientsHeaderAction = memo(function AuthorizedClientsHeaderActio
<Button
size="xs"
variant="destructive-outline"
disabled={
isRevokingOtherClients || clientSessions.every((clientSession) => clientSession.current)
}
disabled={isRevokingOtherClients || !canRevokeOtherClients(clientSessions)}
onClick={() => void onRevokeOtherClients()}
>
{isRevokingOtherClients ? "Revoking…" : "Revoke others"}
@@ -1126,7 +1161,9 @@ const AuthorizedClientsHeaderAction = memo(function AuthorizedClientsHeaderActio
setDialogOpen(open);
if (!open) {
setPairingLabel("");
setPairingScopes([...AuthStandardClientScopes]);
setPairingScopes(
AuthStandardClientScopes.filter((scope) => delegatableScopes.includes(scope)),
);
}
}}
>
@@ -1172,7 +1209,13 @@ const AuthorizedClientsHeaderAction = memo(function AuthorizedClientsHeaderActio
size="xs"
variant="outline"
disabled={isCreatingPairingLink}
onClick={() => setPairingScopes([AuthOrchestrationReadScope])}
onClick={() =>
setPairingScopes(
delegatableScopes.includes(AuthOrchestrationReadScope)
? [AuthOrchestrationReadScope]
: [],
)
}
>
Read only
</Button>
@@ -1180,36 +1223,44 @@ const AuthorizedClientsHeaderAction = memo(function AuthorizedClientsHeaderActio
size="xs"
variant="outline"
disabled={isCreatingPairingLink}
onClick={() => setPairingScopes([...AuthStandardClientScopes])}
onClick={() =>
setPairingScopes(
AuthStandardClientScopes.filter((scope) =>
delegatableScopes.includes(scope),
),
)
}
>
Standard
</Button>
</div>
</div>
<div className="divide-y divide-border/60 rounded-lg border border-input bg-muted/25">
{PAIRING_SCOPE_OPTIONS.map(({ scope, title, description }) => (
<label
key={scope}
className="flex cursor-pointer items-start gap-3 px-3 py-2.5 transition-colors hover:bg-muted/40"
>
<Checkbox
className="mt-0.5"
checked={pairingScopes.includes(scope)}
disabled={isCreatingPairingLink}
onCheckedChange={(checked) => togglePairingScope(scope, checked === true)}
/>
<span className="min-w-0">
<span className="block text-xs font-medium text-foreground">{title}</span>
<span className="block text-xs leading-snug text-muted-foreground">
{description}
{PAIRING_SCOPE_OPTIONS.filter(({ scope }) => delegatableScopes.includes(scope)).map(
({ scope, title, description }) => (
<label
key={scope}
className="flex cursor-pointer items-start gap-3 px-3 py-2.5 transition-colors hover:bg-muted/40"
>
<Checkbox
className="mt-0.5"
checked={pairingScopes.includes(scope)}
disabled={isCreatingPairingLink}
onCheckedChange={(checked) => togglePairingScope(scope, checked === true)}
/>
<span className="min-w-0">
<span className="block text-xs font-medium text-foreground">{title}</span>
<span className="block text-xs leading-snug text-muted-foreground">
{description}
</span>
</span>
</span>
</label>
))}
</label>
),
)}
</div>
{pairingScopes.length === 0 ? (
{selectedScopes.length === 0 ? (
<p className="text-xs text-destructive">Select at least one permission.</p>
) : pairingScopes.includes(AuthAccessWriteScope) ? (
) : selectedScopes.includes(AuthAccessWriteScope) ? (
<p className="text-xs text-warning">
This client can create or revoke access for other devices.
</p>
@@ -1225,7 +1276,7 @@ const AuthorizedClientsHeaderAction = memo(function AuthorizedClientsHeaderActio
Cancel
</Button>
<Button
disabled={isCreatingPairingLink || pairingScopes.length === 0}
disabled={isCreatingPairingLink || selectedScopes.length === 0}
onClick={() => void handleCreatePairingLink()}
>
{isCreatingPairingLink ? "Creating…" : "Create link"}
@@ -1250,6 +1301,7 @@ type PairingClientsListProps = {
revokingClientSessionId: string | null;
onRevokePairingLink: (id: string) => void;
onRevokeClientSession: (sessionId: ServerClientSessionRecord["sessionId"]) => void;
canRevoke: boolean;
};
const PairingClientsList = memo(function PairingClientsList({
@@ -1265,6 +1317,7 @@ const PairingClientsList = memo(function PairingClientsList({
revokingClientSessionId,
onRevokePairingLink,
onRevokeClientSession,
canRevoke,
}: PairingClientsListProps) {
return (
<>
@@ -1279,6 +1332,7 @@ const PairingClientsList = memo(function PairingClientsList({
presentation={presentation}
revokingPairingLinkId={revokingPairingLinkId}
onRevoke={onRevokePairingLink}
canRevoke={canRevoke}
/>
))}
@@ -1289,6 +1343,7 @@ const PairingClientsList = memo(function PairingClientsList({
presentation={presentation}
revokingClientSessionId={revokingClientSessionId}
onRevokeSession={onRevokeClientSession}
canRevoke={canRevoke}
/>
))}
@@ -1793,6 +1848,7 @@ function CloudLinkSwitch({
}
function ConfiguredCloudLinkRow({ canManageRelay }: { readonly canManageRelay: boolean }) {
const primaryEnvironmentId = usePrimaryEnvironmentId();
const {
isSignedIn,
linkState: primaryCloudLinkState,
@@ -1813,6 +1869,11 @@ function ConfiguredCloudLinkRow({ canManageRelay }: { readonly canManageRelay: b
const isBusy = isUpdating || isUpdatingPreference;
const updateManagedTunnel = async (enabled: boolean) => {
if (
primaryEnvironmentId === null ||
!readEnvironmentScope(primaryEnvironmentId, AuthRelayWriteScope)
)
return;
setIsUpdating(true);
const ok = await reconcileCloudState({ managedTunnel: enabled, publish: publishAgentActivity });
if (ok) {
@@ -1836,6 +1897,11 @@ function ConfiguredCloudLinkRow({ canManageRelay }: { readonly canManageRelay: b
};
const updatePublishAgentActivity = async (enabled: boolean) => {
if (
primaryEnvironmentId === null ||
!readEnvironmentScope(primaryEnvironmentId, AuthRelayWriteScope)
)
return;
setIsUpdatingPreference(true);
const ok = await reconcileCloudState({ managedTunnel: managedTunnelActive, publish: enabled });
if (ok) {
@@ -1883,7 +1949,13 @@ function ConfiguredCloudLinkRow({ canManageRelay }: { readonly canManageRelay: b
control={
<CloudLinkSwitch
checked={managedTunnelActive}
disabled={!canManageRelay || !isSignedIn || primaryCloudLinkState.isPending || isBusy}
disabled={
!canManageRelay ||
!isSignedIn ||
primaryCloudLinkState.data === null ||
primaryCloudLinkState.isPending ||
isBusy
}
disabledReason={disabledReason}
onCheckedChange={(enabled) => void updateManagedTunnel(enabled)}
/>
@@ -1897,7 +1969,13 @@ function ConfiguredCloudLinkRow({ canManageRelay }: { readonly canManageRelay: b
<CloudLinkSwitch
ariaLabel="Publish agent activity to mobile clients"
checked={publishAgentActivity}
disabled={!canManageRelay || !isSignedIn || primaryCloudLinkState.isPending || isBusy}
disabled={
!canManageRelay ||
!isSignedIn ||
primaryCloudLinkState.data === null ||
primaryCloudLinkState.isPending ||
isBusy
}
disabledReason={disabledReason}
onCheckedChange={(enabled) => void updatePublishAgentActivity(enabled)}
/>
@@ -1922,8 +2000,23 @@ function ConfiguredCloudLinkRow({ canManageRelay }: { readonly canManageRelay: b
);
}
function CloudLinkRow({ canManageRelay }: { readonly canManageRelay: boolean }) {
return hasCloudPublicConfig() ? <ConfiguredCloudLinkRow canManageRelay={canManageRelay} /> : null;
function CloudLinkRow({
canReadRelay,
canManageRelay,
}: {
readonly canReadRelay: boolean;
readonly canManageRelay: boolean;
}) {
if (!hasCloudPublicConfig()) return null;
if (!canReadRelay) {
return (
<SettingsRow
title="T3 Connect"
description="To edit these settings, pair this connection with both View relay and Manage relay permissions."
/>
);
}
return <ConfiguredCloudLinkRow canManageRelay={canManageRelay} />;
}
function EmptyRemoteEnvironments({ cloudEnabled = true }: { readonly cloudEnabled?: boolean }) {
@@ -1981,11 +2074,9 @@ export function ConnectionsSettings() {
});
const primaryEnvironmentId = primaryEnvironment?.environmentId ?? null;
const primarySessionState = usePrimarySessionState();
const currentSessionScopes = desktopBridge
? AuthAdministrativeScopes
: primarySessionState.data?.authenticated
? (primarySessionState.data.scopes ?? null)
: null;
const currentSessionScopes = primarySessionState.data?.authenticated
? (primarySessionState.data.scopes ?? null)
: null;
const currentAuthPolicy = desktopBridge ? null : (primarySessionState.data?.auth.policy ?? null);
// Catalog order is the order the machines were added; rows never jump when
// one is switched off.
@@ -2165,12 +2256,14 @@ export function ConnectionsSettings() {
const setDefaultAdvertisedEndpointKey = useUiStateStore(
(state) => state.setDefaultAdvertisedEndpointKey,
);
const canManageLocalBackend =
!isLocalEnvironmentDisabled() &&
(currentSessionScopes?.includes(AuthAccessWriteScope) ?? false);
const canManageRelay = currentSessionScopes?.includes(AuthRelayWriteScope) ?? false;
const canReadAccess = useEnvironmentScope(primaryEnvironmentId, AuthAccessReadScope);
const canWriteAccess = useEnvironmentScope(primaryEnvironmentId, AuthAccessWriteScope);
const canReadRelay = useEnvironmentScope(primaryEnvironmentId, AuthRelayReadScope);
const canMaintain = useEnvironmentScope(primaryEnvironmentId, AuthEnvironmentMaintainScope);
const canManageRelay = useEnvironmentScope(primaryEnvironmentId, AuthRelayWriteScope);
const canManageLocalBackend = !isLocalEnvironmentDisabled() && canMaintain;
const authAccessChanges = useEnvironmentQuery(
canManageLocalBackend && primaryEnvironmentId !== null
canReadAccess && primaryEnvironmentId !== null
? authEnvironment.accessChanges({
environmentId: primaryEnvironmentId,
input: null,
@@ -2273,7 +2366,12 @@ export function ConnectionsSettings() {
const handleDesktopServerExposureChange = useCallback(
async (checked: boolean) => {
if (!desktopBridge) return;
if (
!desktopBridge ||
primaryEnvironmentId === null ||
!readEnvironmentScope(primaryEnvironmentId, AuthEnvironmentMaintainScope)
)
return;
setIsUpdatingDesktopServerExposure(true);
setDesktopServerExposureMutationError(null);
try {
@@ -2296,7 +2394,7 @@ export function ConnectionsSettings() {
setIsUpdatingDesktopServerExposure(false);
}
},
[desktopBridge],
[desktopBridge, primaryEnvironmentId],
);
const handleConfirmDesktopServerExposureChange = useCallback(() => {
@@ -2306,7 +2404,12 @@ export function ConnectionsSettings() {
}, [handleDesktopServerExposureChange, pendingDesktopServerExposureMode]);
const handleConfirmTailscaleServeSetup = useCallback(async () => {
if (!desktopBridge) return;
if (
!desktopBridge ||
primaryEnvironmentId === null ||
!readEnvironmentScope(primaryEnvironmentId, AuthEnvironmentMaintainScope)
)
return;
if (!isTailscaleServePortValid) return;
setIsUpdatingTailscaleServe(true);
setDesktopServerExposureMutationError(null);
@@ -2331,7 +2434,7 @@ export function ConnectionsSettings() {
} finally {
setIsUpdatingTailscaleServe(false);
}
}, [desktopBridge, isTailscaleServePortValid, parsedTailscaleServePort]);
}, [desktopBridge, isTailscaleServePortValid, parsedTailscaleServePort, primaryEnvironmentId]);
const handleStartTailscaleServeSetup = useCallback(
(endpoint: AdvertisedEndpoint) => {
@@ -2344,7 +2447,12 @@ export function ConnectionsSettings() {
);
const handleConfirmTailscaleServeDisable = useCallback(async () => {
if (!desktopBridge) return;
if (
!desktopBridge ||
primaryEnvironmentId === null ||
!readEnvironmentScope(primaryEnvironmentId, AuthEnvironmentMaintainScope)
)
return;
setIsUpdatingTailscaleServe(true);
setDesktopServerExposureMutationError(null);
try {
@@ -2367,34 +2475,47 @@ export function ConnectionsSettings() {
} finally {
setIsUpdatingTailscaleServe(false);
}
}, [desktopBridge, desktopServerExposureState?.tailscaleServePort]);
}, [desktopBridge, desktopServerExposureState, primaryEnvironmentId]);
const handleStartTailscaleServeDisable = useCallback((_endpoint: AdvertisedEndpoint) => {
setDisableTailscaleServeDialogOpen(true);
}, []);
const handleRevokeDesktopPairingLink = useCallback(async (id: string) => {
setRevokingDesktopPairingLinkId(id);
setDesktopAccessManagementMutationError(null);
try {
await revokeServerPairingLink(id);
} catch (error) {
const message = error instanceof Error ? error.message : "Failed to revoke pairing link.";
setDesktopAccessManagementMutationError(message);
toastManager.add(
stackedThreadToast({
type: "error",
title: "Could not revoke pairing link",
description: message,
}),
);
} finally {
setRevokingDesktopPairingLinkId(null);
}
}, []);
const handleRevokeDesktopPairingLink = useCallback(
async (id: string) => {
if (
primaryEnvironmentId === null ||
!readEnvironmentScope(primaryEnvironmentId, AuthAccessWriteScope)
)
return;
setRevokingDesktopPairingLinkId(id);
setDesktopAccessManagementMutationError(null);
try {
await revokeServerPairingLink(id);
} catch (error) {
const message = error instanceof Error ? error.message : "Failed to revoke pairing link.";
setDesktopAccessManagementMutationError(message);
toastManager.add(
stackedThreadToast({
type: "error",
title: "Could not revoke pairing link",
description: message,
}),
);
} finally {
setRevokingDesktopPairingLinkId(null);
}
},
[primaryEnvironmentId],
);
const handleRevokeDesktopClientSession = useCallback(
async (sessionId: ServerClientSessionRecord["sessionId"]) => {
if (
primaryEnvironmentId === null ||
!readEnvironmentScope(primaryEnvironmentId, AuthAccessWriteScope)
)
return;
setRevokingDesktopClientSessionId(sessionId);
setDesktopAccessManagementMutationError(null);
try {
@@ -2413,10 +2534,15 @@ export function ConnectionsSettings() {
setRevokingDesktopClientSessionId(null);
}
},
[],
[primaryEnvironmentId],
);
const handleRevokeOtherDesktopClients = useCallback(async () => {
if (
primaryEnvironmentId === null ||
!readEnvironmentScope(primaryEnvironmentId, AuthAccessWriteScope)
)
return;
setIsRevokingOtherDesktopClients(true);
setDesktopAccessManagementMutationError(null);
try {
@@ -2439,7 +2565,7 @@ export function ConnectionsSettings() {
} finally {
setIsRevokingOtherDesktopClients(false);
}
}, []);
}, [primaryEnvironmentId]);
// Shared by manual SSH submission and discovered-host selection.
const connectSavedBackendSshTarget = useCallback(
@@ -2743,8 +2869,6 @@ export function ConnectionsSettings() {
: visibleDesktopNetworkAdvertisedEndpoints,
[tailscaleHttpsEndpoint, visibleDesktopNetworkAdvertisedEndpoints],
);
const isLocalBackendRemotelyReachable =
isLocalBackendNetworkAccessible || tailscaleHttpsEndpoint?.status === "available";
const defaultDesktopNetworkAdvertisedEndpoint = useMemo(
() =>
selectPairingEndpoint(visibleDesktopNetworkAdvertisedEndpoints, defaultAdvertisedEndpointKey),
@@ -3074,7 +3198,12 @@ export function ConnectionsSettings() {
// entry catches up (registers/unregisters) without a reload.
const applyWslSettingChange = useCallback(
async (apply: () => Promise<DesktopWslState>) => {
if (!desktopBridge) return;
if (
!desktopBridge ||
primaryEnvironmentId === null ||
!readEnvironmentScope(primaryEnvironmentId, AuthEnvironmentMaintainScope)
)
return;
setIsUpdatingWslBackend(true);
setDesktopWslMutationError(null);
try {
@@ -3099,7 +3228,7 @@ export function ConnectionsSettings() {
setIsUpdatingWslBackend(false);
}
},
[desktopBridge],
[desktopBridge, primaryEnvironmentId],
);
// Reload the keep-alive WSL state atom. Clearing the mutation error before
@@ -3428,6 +3557,7 @@ export function ConnectionsSettings() {
revokingClientSessionId={revokingDesktopClientSessionId}
onRevokePairingLink={handleRevokeDesktopPairingLink}
onRevokeClientSession={handleRevokeDesktopClientSession}
canRevoke={canWriteAccess}
/>
</>
);
@@ -3467,35 +3597,42 @@ export function ConnectionsSettings() {
<SettingsRow
title={searchableSetting("network-access").title}
description={
currentAuthPolicy === "remote-reachable"
? "Remote access is already configured. Change network exposure where the server starts."
: "Only this machine can connect. Restart with a non-loopback host for remote pairing."
desktopBridge
? "This connection cannot view or change network exposure."
: currentAuthPolicy === "remote-reachable"
? "Remote access is already configured. Change network exposure where the server starts."
: currentAuthPolicy === "loopback-browser"
? "Only this machine can connect. Restart with a non-loopback host for remote pairing."
: "Network exposure information is unavailable."
}
control={
<Tooltip>
<TooltipTrigger
render={
<span className="inline-flex">
<Switch
checked={isLocalBackendNetworkAccessible}
disabled
aria-label="Enable network access"
/>
</span>
}
/>
<TooltipPopup side="top">
Network exposure changes restart the backend and must be controlled where the server
process is launched.
</TooltipPopup>
</Tooltip>
!desktopBridge &&
(currentAuthPolicy === "remote-reachable" || currentAuthPolicy === "loopback-browser") ? (
<Tooltip>
<TooltipTrigger
render={
<span className="inline-flex">
<Switch
checked={isLocalBackendNetworkAccessible}
disabled
aria-label="Enable network access"
/>
</span>
}
/>
<TooltipPopup side="top">
Network exposure changes restart the backend and must be controlled where the server
process is launched.
</TooltipPopup>
</Tooltip>
) : undefined
}
/>
);
const primarySettings = (
<>
{desktopBridge || canManageLocalBackend ? (
{primaryEnvironmentId !== null ? (
<>
<SettingsSection
{...searchableSetting("connections-environment")}
@@ -3591,17 +3728,21 @@ export function ConnectionsSettings() {
{renderEndpointRows("endpoint-rail")}
{renderTailscaleRow()}
{renderWslRow()}
<CloudLinkRow canManageRelay={canManageRelay} />
{canReadRelay || canManageRelay ? (
<CloudLinkRow canReadRelay={canReadRelay} canManageRelay={canManageRelay} />
) : null}
</>
) : canManageLocalBackend ? (
<>
{renderDisabledNetworkAccessRow()}
<CloudLinkRow canManageRelay={canManageRelay} />
{canReadRelay || canManageRelay ? (
<CloudLinkRow canReadRelay={canReadRelay} canManageRelay={canManageRelay} />
) : null}
</>
) : null}
</SettingsSection>
{isLocalBackendRemotelyReachable ? (
{canReadAccess || canWriteAccess ? (
<FoldedSettingsSection
id="authorized-clients"
title="Authorized clients"
@@ -3610,12 +3751,21 @@ export function ConnectionsSettings() {
visibleDesktopPairingLinks,
)}
control={
<AuthorizedClientsHeaderAction
onPairingLinkCreated={handlePairingLinkCreated}
clientSessions={desktopClientSessions}
isRevokingOtherClients={isRevokingOtherDesktopClients}
onRevokeOtherClients={handleRevokeOtherDesktopClients}
/>
canWriteAccess ? (
<AuthorizedClientsHeaderAction
delegatableScopes={currentSessionScopes ?? []}
onPairingLinkCreated={handlePairingLinkCreated}
clientSessions={
canReadAccess &&
authAccessChanges.error === null &&
authAccessChanges.data?.type === "snapshot"
? desktopClientSessions
: null
}
isRevokingOtherClients={isRevokingOtherDesktopClients}
onRevokeOtherClients={handleRevokeOtherDesktopClients}
/>
) : undefined
}
>
<ScrollArea
@@ -3624,12 +3774,18 @@ export function ConnectionsSettings() {
className="max-h-[22.5rem]"
data-testid="authorized-clients-scroll-area"
>
{renderAuthorizedClients("current")}
{canReadAccess ? (
renderAuthorizedClients("current")
) : (
<p className="px-4 py-3 text-xs text-muted-foreground">
This connection can create access links but cannot view authorized clients.
</p>
)}
</ScrollArea>
</FoldedSettingsSection>
) : null}
<AlertDialog
open={isDesktopServerExposureDialogOpen}
open={isDesktopServerExposureDialogOpen && canManageLocalBackend}
onOpenChange={(open) => {
if (isUpdatingDesktopServerExposure) return;
setIsDesktopServerExposureDialogOpen(open);
@@ -3662,7 +3818,9 @@ export function ConnectionsSettings() {
variant="default"
onClick={handleConfirmDesktopServerExposureChange}
disabled={
pendingDesktopServerExposureMode === null || isUpdatingDesktopServerExposure
!canManageLocalBackend ||
pendingDesktopServerExposureMode === null ||
isUpdatingDesktopServerExposure
}
>
{isUpdatingDesktopServerExposure && <Spinner size="sm" />}
@@ -3678,7 +3836,7 @@ export function ConnectionsSettings() {
</AlertDialogPopup>
</AlertDialog>
<AlertDialog
open={isWslConfirmDialogOpen}
open={isWslConfirmDialogOpen && canManageLocalBackend}
onOpenChange={(open) => {
if (isUpdatingWslBackend) return;
if (!open) setPendingWslChange(null);
@@ -3725,7 +3883,7 @@ export function ConnectionsSettings() {
<Button
variant="outline"
onClick={() => handleConfirmEnableWsl("wsl-only")}
disabled={isUpdatingWslBackend}
disabled={isUpdatingWslBackend || !canManageLocalBackend}
>
{isUpdatingWslBackend ? (
<>
@@ -3739,7 +3897,7 @@ export function ConnectionsSettings() {
<Button
variant="default"
onClick={() => handleConfirmEnableWsl("both")}
disabled={isUpdatingWslBackend}
disabled={isUpdatingWslBackend || !canManageLocalBackend}
>
{isUpdatingWslBackend ? (
<>
@@ -3760,7 +3918,7 @@ export function ConnectionsSettings() {
: "default"
}
onClick={handleConfirmWslChange}
disabled={isUpdatingWslBackend}
disabled={isUpdatingWslBackend || !canManageLocalBackend}
>
{isUpdatingWslBackend ? (
<>
@@ -3786,7 +3944,7 @@ export function ConnectionsSettings() {
</AlertDialogPopup>
</AlertDialog>
<AlertDialog
open={disableTailscaleServeDialogOpen}
open={disableTailscaleServeDialogOpen && canManageLocalBackend}
onOpenChange={(open) => {
if (isUpdatingTailscaleServe) return;
setDisableTailscaleServeDialogOpen(open);
@@ -3809,7 +3967,7 @@ export function ConnectionsSettings() {
<Button
variant="destructive"
onClick={() => void handleConfirmTailscaleServeDisable()}
disabled={isUpdatingTailscaleServe}
disabled={isUpdatingTailscaleServe || !canManageLocalBackend}
>
{isUpdatingTailscaleServe ? (
<>
@@ -3899,10 +4057,12 @@ export function ConnectionsSettings() {
) : (
<SettingsSection {...searchableSetting("connections-environment")}>
<SettingsRow
title="Administrative access"
description="Pairing links and client-session management require the access:write scope for this backend."
title="No environment selected"
description="Connect an environment to view its settings and access."
/>
<CloudLinkRow canManageRelay={canManageRelay} />
{canReadRelay || canManageRelay ? (
<CloudLinkRow canReadRelay={canReadRelay} canManageRelay={canManageRelay} />
) : null}
</SettingsSection>
)}
</>
Loaded 100 of 162 files, more files were not shown because too many files have changed in this diff. Show more