TypeScript
feat(auth): separate environment administration permissions (#9786)
Julius Marminge28ce9d1c1751
diff --git a/AGENTS.md b/AGENTS.mdindex ef6dbcff766..3d1c49d5190 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -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.diff --git a/apps/mobile/src/features/agent-awareness/liveActivityPreferences.test.ts b/apps/mobile/src/features/agent-awareness/liveActivityPreferences.test.tsindex 74d06207da9..dd17b610bfa 100644--- a/apps/mobile/src/features/agent-awareness/liveActivityPreferences.test.ts+++ b/apps/mobile/src/features/agent-awareness/liveActivityPreferences.test.ts@@ -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));+ });});diff --git a/apps/mobile/src/features/agent-awareness/liveActivityPreferences.ts b/apps/mobile/src/features/agent-awareness/liveActivityPreferences.tsindex 1b30769e7bc..826edaf839b 100644--- a/apps/mobile/src/features/agent-awareness/liveActivityPreferences.ts+++ b/apps/mobile/src/features/agent-awareness/liveActivityPreferences.ts@@ -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("setLiveActivityUpdatesEnreadonly 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("setLiveActivityUpdatesEnyield* 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("setLiveActivityUpdatesEnyield* 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}.`,diff --git a/apps/mobile/src/features/archive/ArchivedThreadsScreen.tsx b/apps/mobile/src/features/archive/ArchivedThreadsScreen.tsxindex f0cebef2cee..eacd5544ea0 100644--- a/apps/mobile/src/features/archive/ArchivedThreadsScreen.tsx+++ b/apps/mobile/src/features/archive/ArchivedThreadsScreen.tsx@@ -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 (<ThreadSwipeableresetKey={`${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>);}diff --git a/apps/mobile/src/features/home/useThreadListActions.test.ts b/apps/mobile/src/features/home/useThreadListActions.test.tsnew file mode 100644index 00000000000..4fffe5f36c1--- /dev/null+++ b/apps/mobile/src/features/home/useThreadListActions.test.ts@@ -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);+ });+});diff --git a/apps/mobile/src/features/home/useThreadListActions.ts b/apps/mobile/src/features/home/useThreadListActions.tsindex 38a24e8b165..964c12a7189 100644--- a/apps/mobile/src/features/home/useThreadListActions.ts+++ b/apps/mobile/src/features/home/useThreadListActions.ts@@ -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/useArchivedThreimport { 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 },diff --git a/apps/mobile/src/features/settings/SettingsEnvironmentDetailRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsEnvironmentDetailRouteScreen.tsxindex f25d7844f04..1065a860a5e 100644--- a/apps/mobile/src/features/settings/SettingsEnvironmentDetailRouteScreen.tsx+++ b/apps/mobile/src/features/settings/SettingsEnvironmentDetailRouteScreen.tsx@@ -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: Environmtext: "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<SettingsActionRowicon="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<SettingsActionRowicon="arrow.up.circle"label={`Update ${provider.displayName ?? provider.driver}`}- disabled={disabled}+ disabled={busy || !canManageProviders}loading={pending === provider.instanceId}onPress={() => requestProviderUpdate(provider)}/>diff --git a/apps/mobile/src/features/settings/SettingsNotificationsRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsNotificationsRouteScreen.tsxindex 293841e9571..25c2e03d46f 100644--- a/apps/mobile/src/features/settings/SettingsNotificationsRouteScreen.tsx+++ b/apps/mobile/src/features/settings/SettingsNotificationsRouteScreen.tsx@@ -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,diff --git a/apps/mobile/src/features/settings/SettingsRouteScreen.logic.test.ts b/apps/mobile/src/features/settings/SettingsRouteScreen.logic.test.tsindex 3e0ead2ce52..41400a50c32 100644--- a/apps/mobile/src/features/settings/SettingsRouteScreen.logic.test.ts+++ b/apps/mobile/src/features/settings/SettingsRouteScreen.logic.test.ts@@ -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", () => {diff --git a/apps/mobile/src/features/settings/SettingsRouteScreen.logic.ts b/apps/mobile/src/features/settings/SettingsRouteScreen.logic.tsindex 6cdf8a3e1f8..efa618e814a 100644--- a/apps/mobile/src/features/settings/SettingsRouteScreen.logic.ts+++ b/apps/mobile/src/features/settings/SettingsRouteScreen.logic.ts@@ -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;diff --git a/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsxindex e8593ff407f..e9cc8563f2a 100644--- a/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx+++ b/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx@@ -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}/><FormFieldlabel="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({<ControlPillMenuactions={[{ 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;diff --git a/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsxindex 885f269251c..ae4f43b5fb3 100644--- a/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx+++ b/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx@@ -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}diff --git a/apps/mobile/src/features/settings/SettingsThreadsRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsThreadsRouteScreen.tsxindex 386cdfba062..047f28e5fb9 100644--- a/apps/mobile/src/features/settings/SettingsThreadsRouteScreen.tsx+++ b/apps/mobile/src/features/settings/SettingsThreadsRouteScreen.tsx@@ -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.sidebarAutoSettleAfterDfunction 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}diff --git a/apps/mobile/src/features/settings/components/SettingsProjectOverridesSection.tsx b/apps/mobile/src/features/settings/components/SettingsProjectOverridesSection.tsxindex b89ab845434..81b21b7b666 100644--- a/apps/mobile/src/features/settings/components/SettingsProjectOverridesSection.tsx+++ b/apps/mobile/src/features/settings/components/SettingsProjectOverridesSection.tsx@@ -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: {<PressableaccessibilityRole="button"accessibilityLabel="Use environment defaults"+ disabled={props.disabled}onPress={props.onClear}className="px-2 py-2 active:opacity-70">diff --git a/apps/mobile/src/features/settings/environment-maintenance.test.ts b/apps/mobile/src/features/settings/environment-maintenance.test.tsindex 878f7151189..fb90d33b473 100644--- a/apps/mobile/src/features/settings/environment-maintenance.test.ts+++ b/apps/mobile/src/features/settings/environment-maintenance.test.ts@@ -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);diff --git a/apps/mobile/src/features/settings/environment-maintenance.ts b/apps/mobile/src/features/settings/environment-maintenance.tsindex f441066d717..02e149a4231 100644--- a/apps/mobile/src/features/settings/environment-maintenance.ts+++ b/apps/mobile/src/features/settings/environment-maintenance.ts@@ -16,7 +16,8 @@ export function canMaintainEnvironment(session: AuthSessionState | null, connectreturn (connected &&session?.authenticated === true &&- session.scopes?.includes(AuthOrchestrationOperateScope) === true+ session.scopes?.includes(session.auth.serverUpdateScope ?? AuthOrchestrationOperateScope) ===+ true);}diff --git a/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsxindex b926db7326e..181c257cbc1 100644--- a/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx+++ b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx@@ -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-shaimport { 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 ? (<PressableaccessibilityRole="button"@@ -1794,6 +1813,7 @@ export function NewTaskDraftScreen(props: {{voicePresentation.showsSend ? (<ComposerActionButtonaccessibilityLabel={+ taskPermissionReason ??attachmentBlockReason ??(cloneBlocksStart? projectClone === null || projectClone.phase === "running"diff --git a/apps/mobile/src/features/threads/PendingApprovalCard.tsx b/apps/mobile/src/features/threads/PendingApprovalCard.tsxindex 9348945ff04..fcdb9e3563f 100644--- a/apps/mobile/src/features/threads/PendingApprovalCard.tsx+++ b/apps/mobile/src/features/threads/PendingApprovalCard.tsx@@ -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>);}diff --git a/apps/mobile/src/features/threads/PendingUserInputCard.tsx b/apps/mobile/src/features/threads/PendingUserInputCard.tsxindex bd3cb03b17b..9c2ba094256 100644--- a/apps/mobile/src/features/threads/PendingUserInputCard.tsx+++ b/apps/mobile/src/features/threads/PendingUserInputCard.tsx@@ -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 (diff --git a/apps/mobile/src/features/threads/ThreadComposer.tsx b/apps/mobile/src/features/threads/ThreadComposer.tsxindex 5ea142d08b4..298bc07479d 100644--- a/apps/mobile/src/features/threads/ThreadComposer.tsx+++ b/apps/mobile/src/features/threads/ThreadComposer.tsx@@ -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: ThreadComposeraccessibilityLabel="Stop agent"icon="stop.fill"variant="danger"+ disabled={!props.canOperateThread}onPress={props.onStopThread}/>) : (@@ -1150,6 +1153,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposeraccessibilityLabel="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} />diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsxindex 1d3beebe924..ea635357830 100644--- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx+++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx@@ -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}diff --git a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx b/apps/mobile/src/features/threads/ThreadRouteScreen.tsxindex b7ebc569ced..02e8724fd3c 100644--- a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx+++ b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx@@ -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)}diff --git a/apps/mobile/src/features/threads/thread-list-v2-items.tsx b/apps/mobile/src/features/threads/thread-list-v2-items.tsxindex 92ffbcd23f5..4bc4328a578 100644--- a/apps/mobile/src/features/threads/thread-list-v2-items.tsx+++ b/apps/mobile/src/features/threads/thread-list-v2-items.tsx@@ -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/ProviderIcoimport { 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 && (diff --git a/apps/mobile/src/features/usage/UsageLimitsSection.test.ts b/apps/mobile/src/features/usage/UsageLimitsSection.test.tsindex f8d769355f7..32f0f3b32a0 100644--- a/apps/mobile/src/features/usage/UsageLimitsSection.test.ts+++ b/apps/mobile/src/features/usage/UsageLimitsSection.test.ts@@ -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++;diff --git a/apps/mobile/src/features/usage/UsageLimitsSection.tsx b/apps/mobile/src/features/usage/UsageLimitsSection.tsxindex 144c9d18e8e..0fb8fb9f269 100644--- a/apps/mobile/src/features/usage/UsageLimitsSection.tsx+++ b/apps/mobile/src/features/usage/UsageLimitsSection.tsx@@ -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 ? (<PressableaccessibilityRole="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>);diff --git a/apps/mobile/src/lib/attachmentUpload.test.ts b/apps/mobile/src/lib/attachmentUpload.test.tsindex df68a2de301..b57f9a89cb9 100644--- a/apps/mobile/src/lib/attachmentUpload.test.ts+++ b/apps/mobile/src/lib/attachmentUpload.test.ts@@ -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] });diff --git a/apps/mobile/src/lib/attachmentUpload.ts b/apps/mobile/src/lib/attachmentUpload.tsindex 50b6cf1cee1..a5affef8031 100644--- a/apps/mobile/src/lib/attachmentUpload.ts+++ b/apps/mobile/src/lib/attachmentUpload.ts@@ -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,diff --git a/apps/mobile/src/state/attachments.test.ts b/apps/mobile/src/state/attachments.test.tsnew file mode 100644index 00000000000..5f727e3304f--- /dev/null+++ b/apps/mobile/src/state/attachments.test.ts@@ -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();+ });+});diff --git a/apps/mobile/src/state/attachments.ts b/apps/mobile/src/state/attachments.tsindex 3377a96c1ec..b6ad84789f4 100644--- a/apps/mobile/src/state/attachments.ts+++ b/apps/mobile/src/state/attachments.ts@@ -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),+};diff --git a/apps/mobile/src/state/composer-attachment-uploads.ts b/apps/mobile/src/state/composer-attachment-uploads.tsindex 52bcd1bc678..eab5305ed26 100644--- a/apps/mobile/src/state/composer-attachment-uploads.ts+++ b/apps/mobile/src/state/composer-attachment-uploads.ts@@ -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]);}diff --git a/apps/mobile/src/state/session.test.ts b/apps/mobile/src/state/session.test.tsnew file mode 100644index 00000000000..d1ee156235d--- /dev/null+++ b/apps/mobile/src/state/session.test.ts@@ -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);+});diff --git a/apps/mobile/src/state/session.ts b/apps/mobile/src/state/session.tsindex 18086c60185..dffff631d8a 100644--- a/apps/mobile/src/state/session.ts+++ b/apps/mobile/src/state/session.ts@@ -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"),);diff --git a/apps/mobile/src/state/thread-task-permissions.test.ts b/apps/mobile/src/state/thread-task-permissions.test.tsnew file mode 100644index 00000000000..2fc2fecacc9--- /dev/null+++ b/apps/mobile/src/state/thread-task-permissions.test.ts@@ -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" } },+ });+ });+});diff --git a/apps/mobile/src/state/use-selected-thread-requests.test.tsx b/apps/mobile/src/state/use-selected-thread-requests.test.tsxindex 293b5d0ce1a..9c8ab5a5990 100644--- a/apps/mobile/src/state/use-selected-thread-requests.test.tsx+++ b/apps/mobile/src/state/use-selected-thread-requests.test.tsx@@ -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", () => ({diff --git a/apps/mobile/src/state/use-selected-thread-requests.ts b/apps/mobile/src/state/use-selected-thread-requests.tsindex b33a0d7e432..0c32c6a37c1 100644--- a/apps/mobile/src/state/use-selected-thread-requests.ts+++ b/apps/mobile/src/state/use-selected-thread-requests.ts@@ -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;}diff --git a/apps/mobile/src/state/use-thread-composer-state.ts b/apps/mobile/src/state/use-thread-composer-state.tsindex 0db48453529..12a9999c8a0 100644--- a/apps/mobile/src/state/use-thread-composer-state.ts+++ b/apps/mobile/src/state/use-thread-composer-state.ts@@ -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;diff --git a/apps/mobile/src/state/use-thread-outbox-drain.permissions.test.ts b/apps/mobile/src/state/use-thread-outbox-drain.permissions.test.tsnew file mode 100644index 00000000000..dd347c4e424--- /dev/null+++ b/apps/mobile/src/state/use-thread-outbox-drain.permissions.test.ts@@ -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]);+ },+ );+});diff --git a/apps/mobile/src/state/use-thread-outbox-drain.test.ts b/apps/mobile/src/state/use-thread-outbox-drain.test.tsindex ce725e82de7..bb2abf326ee 100644--- a/apps/mobile/src/state/use-thread-outbox-drain.test.ts+++ b/apps/mobile/src/state/use-thread-outbox-drain.test.ts@@ -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({diff --git a/apps/mobile/src/state/use-thread-outbox-drain.ts b/apps/mobile/src/state/use-thread-outbox-drain.tsindex 85c6cecb8f7..66744fa0c92 100644--- a/apps/mobile/src/state/use-thread-outbox-drain.ts+++ b/apps/mobile/src/state/use-thread-outbox-drain.ts@@ -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,diff --git a/apps/server/src/auth/EnvironmentAuth.test.ts b/apps/server/src/auth/EnvironmentAuth.test.tsindex 61ebba5775f..71ee138ddc3 100644--- a/apps/server/src/auth/EnvironmentAuth.test.ts+++ b/apps/server/src/auth/EnvironmentAuth.test.ts@@ -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())),);diff --git a/apps/server/src/auth/EnvironmentAuthAdmin.test.ts b/apps/server/src/auth/EnvironmentAuthAdmin.test.tsindex 204e61c189d..350ed0305c3 100644--- a/apps/server/src/auth/EnvironmentAuthAdmin.test.ts+++ b/apps/server/src/auth/EnvironmentAuthAdmin.test.ts@@ -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);diff --git a/apps/server/src/auth/EnvironmentAuthPolicy.test.ts b/apps/server/src/auth/EnvironmentAuthPolicy.test.tsindex 13f3336787b..eff221a34bd 100644--- a/apps/server/src/auth/EnvironmentAuthPolicy.test.ts+++ b/apps/server/src/auth/EnvironmentAuthPolicy.test.ts@@ -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(diff --git a/apps/server/src/auth/EnvironmentAuthPolicy.ts b/apps/server/src/auth/EnvironmentAuthPolicy.tsindex 0c3327d95f0..e1119efdf6d 100644--- a/apps/server/src/auth/EnvironmentAuthPolicy.ts+++ b/apps/server/src/auth/EnvironmentAuthPolicy.ts@@ -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,diff --git a/apps/server/src/auth/McpOAuth.test.ts b/apps/server/src/auth/McpOAuth.test.tsindex 7af90bff807..f1a616c4927 100644--- a/apps/server/src/auth/McpOAuth.test.ts+++ b/apps/server/src/auth/McpOAuth.test.ts@@ -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 forconst 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(diff --git a/apps/server/src/auth/PairingGrantStore.test.ts b/apps/server/src/auth/PairingGrantStore.test.tsindex db29e3c34ca..5b6a4900567 100644--- a/apps/server/src/auth/PairingGrantStore.test.ts+++ b/apps/server/src/auth/PairingGrantStore.test.ts@@ -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");diff --git a/apps/server/src/auth/RpcAuthorization.test.ts b/apps/server/src/auth/RpcAuthorization.test.tsindex 3615cb58557..cc369509939 100644--- a/apps/server/src/auth/RpcAuthorization.test.ts+++ b/apps/server/src/auth/RpcAuthorization.test.ts@@ -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),+ );+});diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.tsindex 3cce8fbe0b2..355668e1b19 100644--- a/apps/server/src/auth/RpcAuthorization.ts+++ b/apps/server/src/auth/RpcAuthorization.ts@@ -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. */diff --git a/apps/server/src/auth/SessionStore.test.ts b/apps/server/src/auth/SessionStore.test.tsindex 330d55ba43d..f7d3e7e1f5a 100644--- a/apps/server/src/auth/SessionStore.test.ts+++ b/apps/server/src/auth/SessionStore.test.ts@@ -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()))),);diff --git a/apps/server/src/auth/http.ts b/apps/server/src/auth/http.tsindex ae6ec007622..1a74467edfc 100644--- a/apps/server/src/auth/http.ts+++ b/apps/server/src/auth/http.ts@@ -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,diff --git a/apps/server/src/observability/RpcInstrumentation.test.ts b/apps/server/src/observability/RpcInstrumentation.test.tsindex 32baf29d068..4ac5c52ee03 100644--- a/apps/server/src/observability/RpcInstrumentation.test.ts+++ b/apps/server/src/observability/RpcInstrumentation.test.ts@@ -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]),),),);diff --git a/apps/server/src/provider/ProviderRegistry.test.ts b/apps/server/src/provider/ProviderRegistry.test.tsindex bf3e9906b16..3e461f5f1a5 100644--- a/apps/server/src/provider/ProviderRegistry.test.ts+++ b/apps/server/src/provider/ProviderRegistry.test.ts@@ -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");diff --git a/apps/server/src/provider/ProviderRegistry.ts b/apps/server/src/provider/ProviderRegistry.tsindex 898bb955e5e..65c56525d32 100644--- a/apps/server/src/provider/ProviderRegistry.ts+++ b/apps/server/src/provider/ProviderRegistry.ts@@ -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) {diff --git a/apps/server/src/serverSettings.test.ts b/apps/server/src/serverSettings.test.tsindex 44ce0767e4b..051f0533161 100644--- a/apps/server/src/serverSettings.test.ts+++ b/apps/server/src/serverSettings.test.ts@@ -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;diff --git a/apps/web/src/cloud/primaryCloudLinkState.ts b/apps/web/src/cloud/primaryCloudLinkState.tsindex 8d9b919db05..5b524469706 100644--- a/apps/web/src/cloud/primaryCloudLinkState.ts+++ b/apps/web/src/cloud/primaryCloudLinkState.ts@@ -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,diff --git a/apps/web/src/cloud/useCloudLinkController.test.tsx b/apps/web/src/cloud/useCloudLinkController.test.tsxnew file mode 100644index 00000000000..5ee48b5f722--- /dev/null+++ b/apps/web/src/cloud/useCloudLinkController.test.tsx@@ -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();+ });+});diff --git a/apps/web/src/cloud/useCloudLinkController.ts b/apps/web/src/cloud/useCloudLinkController.tsindex 73015959996..e39feb69776 100644--- a/apps/web/src/cloud/useCloudLinkController.ts+++ b/apps/web/src/cloud/useCloudLinkController.ts@@ -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,diff --git a/apps/web/src/components/ChatMarkdown.permissions.test.tsx b/apps/web/src/components/ChatMarkdown.permissions.test.tsxnew file mode 100644index 00000000000..750d013e0ce--- /dev/null+++ b/apps/web/src/components/ChatMarkdown.permissions.test.tsx@@ -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,+ },+ });+ },+);diff --git a/apps/web/src/components/ChatMarkdown.test.tsx b/apps/web/src/components/ChatMarkdown.test.tsxindex 7f655acb1cc..b1ceb33062c 100644--- a/apps/web/src/components/ChatMarkdown.test.tsx+++ b/apps/web/src/components/ChatMarkdown.test.tsx@@ -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: () => [],diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsxindex 5389cae83d6..de85ab8b071 100644--- a/apps/web/src/components/ChatMarkdown.tsx+++ b/apps/web/src/components/ChatMarkdown.tsx@@ -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? undefineddiff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsxindex e705a42d597..bc383266d5c 100644--- a/apps/web/src/components/ChatView.tsx+++ b/apps/web/src/components/ChatView.tsx@@ -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/atimport { 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 = useOrchestrationCommand(threadEnvironment.setInteractionMode, {reportFailure: false,});- const setThreadInteractionMode = useAtomCommand(threadEnvironment.setInteractionMode, {+ const startThreadTurn = useOrchestrationCommand(threadEnvironment.startTurn, {reportFailure: false,});- const startThreadTurn = useAtomCommand(threadEnvironment.startTurn, { reportFailure: false });- const resumeThreadQueue = useAtomCommand(threadEnvironment.resumeThreadQueue, {+ const resumeThreadQueue = useOrchestrationCommand(threadEnvironment.resumeThreadQueue, {reportFailure: false,});- const uploadThreadFeedback = useAtomCommand(threadEnvironment.uploadFeedback, {+ 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) {<Buttonsize="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) {<Buttonsize="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={diff --git a/apps/web/src/components/KeybindingsConfigWarning.test.tsx b/apps/web/src/components/KeybindingsConfigWarning.test.tsxnew file mode 100644index 00000000000..3059b46b2bd--- /dev/null+++ b/apps/web/src/components/KeybindingsConfigWarning.test.tsx@@ -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" },+ });+});diff --git a/apps/web/src/components/KeybindingsConfigWarning.tsx b/apps/web/src/components/KeybindingsConfigWarning.tsxnew file mode 100644index 00000000000..07a19cf4b00--- /dev/null+++ b/apps/web/src/components/KeybindingsConfigWarning.tsx@@ -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>+ </>+ );+}diff --git a/apps/web/src/components/LegacySidebar.tsx b/apps/web/src/components/LegacySidebar.tsxindex 3e1356f988a..55db8a49c9d 100644--- a/apps/web/src/components/LegacySidebar.tsx+++ b/apps/web/src/components/LegacySidebar.tsx@@ -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: SidebarThreadRowPonFileDropThreads,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: SidebarThreadRowPevent.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 ? (<inputref={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: SidebarProjecnull,);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: SidebarProjecconst 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: SidebarProjecawait 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: SidebarProjecconst 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: SidebarProjecconst 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: SidebarProjecreturn;}+ 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: SidebarProjecconst 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: SidebarProjecreturn;}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: SidebarProjecreturn;}}+ 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><Inputaria-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: SidebarProjecEnvironment: {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>diff --git a/apps/web/src/components/ProjectScriptsControl.tsx b/apps/web/src/components/ProjectScriptsControl.tsxindex 5bffde323eb..b1f6bf6d6bd 100644--- a/apps/web/src/components/ProjectScriptsControl.tsx+++ b/apps/web/src/components/ProjectScriptsControl.tsx@@ -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}diff --git a/apps/web/src/components/ProviderUpdateEnvironmentRows.test.tsx b/apps/web/src/components/ProviderUpdateEnvironmentRows.test.tsxindex 6760fb57b94..6f6fcb4ef0c 100644--- a/apps/web/src/components/ProviderUpdateEnvironmentRows.test.tsx+++ b/apps/web/src/components/ProviderUpdateEnvironmentRows.test.tsx@@ -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 = [diff --git a/apps/web/src/components/ProviderUpdateEnvironmentRows.tsx b/apps/web/src/components/ProviderUpdateEnvironmentRows.tsxindex 27df0460f50..2cd406045d1 100644--- a/apps/web/src/components/ProviderUpdateEnvironmentRows.tsx+++ b/apps/web/src/components/ProviderUpdateEnvironmentRows.tsx@@ -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;diff --git a/apps/web/src/components/ProviderUpdatePrimaryNotification.tsx b/apps/web/src/components/ProviderUpdatePrimaryNotification.tsxindex 3fca1d748ca..98b3e71dac2 100644--- a/apps/web/src/components/ProviderUpdatePrimaryNotification.tsx+++ b/apps/web/src/components/ProviderUpdatePrimaryNotification.tsx@@ -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,diff --git a/apps/web/src/components/ServerUpdateAction.test.tsx b/apps/web/src/components/ServerUpdateAction.test.tsxindex b065ef8c834..385e12af7df 100644--- a/apps/web/src/components/ServerUpdateAction.test.tsx+++ b/apps/web/src/components/ServerUpdateAction.test.tsx@@ -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([diff --git a/apps/web/src/components/ServerUpdateAction.tsx b/apps/web/src/components/ServerUpdateAction.tsxindex d828e929f93..01336191579 100644--- a/apps/web/src/components/ServerUpdateAction.tsx+++ b/apps/web/src/components/ServerUpdateAction.tsx@@ -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>);diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsxindex ee9c313cbec..b3be7790bce 100644--- a/apps/web/src/components/chat/ChatComposer.tsx+++ b/apps/web/src/components/chat/ChatComposer.tsx@@ -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(propconst 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}<ComposerPrimaryActionscompact={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><ComposerPendingApprovalActionsrequestId={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 ? (<ComposerPendingUserInputPanelpendingUserInputs={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"><ComposerPendingUserInputPanelpendingUserInputs={pendingUserInputs}+ disabled={!canOperateThread}respondingRequestIds={activePendingIsResponding && activePendingUserInput? [...respondingRequestIds, activePendingUserInput.requestId]@@ -6723,6 +6742,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps){activePendingProgress?.activeQuestion?.multiSelect ? (<ComposerPrimaryActionscompact+ 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)><ComposerPrimaryActionscompact+ canOperateThread={canOperateThread}pendingAction={pendingPrimaryAction}isRunning={false}canInterrupt={false}@@ -7513,6 +7537,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)) : null}<ComposerFooterPrimaryActionscompact={isComposerResting || isComposerPrimaryActionsCompact}+ canOperateThread={canOperateThread}activeContextWindow={settings.contextWindowMeterEnabled ? activeContextWindow : null}diff --git a/apps/web/src/components/chat/ComposerPendingApprovalActions.tsx b/apps/web/src/components/chat/ComposerPendingApprovalActions.tsxindex 73be3c744be..7957e274c50 100644--- a/apps/web/src/components/chat/ComposerPendingApprovalActions.tsx+++ b/apps/web/src/components/chat/ComposerPendingApprovalActions.tsx@@ -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 ComposerPendingApprorequestId,isResponding,canRespond,+ disabled = false,options = DEFAULT_APPROVAL_OPTIONS,onRespondToApproval,}: ComposerPendingApprovalActionsProps) {@@ -50,9 +52,13 @@ export const ComposerPendingApprovalActions = memo(function ComposerPendingApprokey={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 ComposerPendingApproconst item = (<MenuItemkey={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">diff --git a/apps/web/src/components/chat/ComposerPendingUserInputPanel.permissions.test.tsx b/apps/web/src/components/chat/ComposerPendingUserInputPanel.permissions.test.tsxnew file mode 100644index 00000000000..f81ed670260--- /dev/null+++ b/apps/web/src/components/chat/ComposerPendingUserInputPanel.permissions.test.tsx@@ -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();+ }+});diff --git a/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx b/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsxindex 28124ce74aa..483eeb57a6e 100644--- a/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx+++ b/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx@@ -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<ComposerPendingUserInputCardkey={activePrompt.requestId}prompt={activePrompt}+ disabled={disabled}isResponding={respondingRequestIds.includes(activePrompt.requestId)}answers={answers}questionIndex={questionIndex}@@ -49,6 +52,7 @@ export const ComposerPendingUserInputPanel = memo(function ComposerPendingUserInconst 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(<buttonkey={`${activeQuestion.id}:${optionValue}`}type="button"- disabled={isResponding}+ disabled={disabled || isResponding}onClick={() => {handleOptionSelection(activeQuestion.id, optionValue);}}diff --git a/apps/web/src/components/chat/ComposerPrimaryActions.test.tsx b/apps/web/src/components/chat/ComposerPrimaryActions.test.tsxindex 8573842d266..d951f1e21fe 100644--- a/apps/web/src/components/chat/ComposerPrimaryActions.test.tsx+++ b/apps/web/src/components/chat/ComposerPrimaryActions.test.tsx@@ -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,diff --git a/apps/web/src/components/chat/ComposerPrimaryActions.tsx b/apps/web/src/components/chat/ComposerPrimaryActions.tsxindex 81bce817fe4..af4fc8a8234 100644--- a/apps/web/src/components/chat/ComposerPrimaryActions.tsx+++ b/apps/web/src/components/chat/ComposerPrimaryActions.tsx@@ -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}><MenuItemdisabled={isSendBusy || isSendDisabled || isConnecting || isEnvironmentUnavailable}- onClick={() => void onImplementPlanInNewThread()}+ onClick={() => {+ if (canOperateThread) onImplementPlanInNewThread();+ }}>Implement in a new thread</MenuItem>diff --git a/apps/web/src/components/chat/OpenInPicker.test.tsx b/apps/web/src/components/chat/OpenInPicker.test.tsxnew file mode 100644index 00000000000..f7ad7c700cf--- /dev/null+++ b/apps/web/src/components/chat/OpenInPicker.test.tsx@@ -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();+ });+});diff --git a/apps/web/src/components/chat/OpenInPicker.tsx b/apps/web/src/components/chat/OpenInPicker.tsxindex 09d4b92eb9c..302d09b8244 100644--- a/apps/web/src/components/chat/OpenInPicker.tsx+++ b/apps/web/src/components/chat/OpenInPicker.tsx@@ -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 }) => (<MenuItemdensity={presentation === "menu" ? "touch" : "default"}+ disabled={!openInCwd || !canOpenEditor}key={value}onClick={() => openInEditor(value)}>@@ -341,7 +364,7 @@ export const OpenInPicker = memo(function OpenInPicker({<MenuItemdensity={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={<ThreadDetailsControlaria-label="Choose editor"diff --git a/apps/web/src/components/chat/ThreadAutomationsPanel.permissions.test.tsx b/apps/web/src/components/chat/ThreadAutomationsPanel.permissions.test.tsxnew file mode 100644index 00000000000..d91f6b35ac8--- /dev/null+++ b/apps/web/src/components/chat/ThreadAutomationsPanel.permissions.test.tsx@@ -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();+});diff --git a/apps/web/src/components/chat/ThreadAutomationsPanel.tsx b/apps/web/src/components/chat/ThreadAutomationsPanel.tsxindex cd1202d1e42..eec45fd6374 100644--- a/apps/web/src/components/chat/ThreadAutomationsPanel.tsx+++ b/apps/web/src/components/chat/ThreadAutomationsPanel.tsx@@ -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: {)}<Switchchecked={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)}/>diff --git a/apps/web/src/components/chat/ThreadDetailsPanel.tsx b/apps/web/src/components/chat/ThreadDetailsPanel.tsxindex 5b79f0c00f5..b4a70929722 100644--- a/apps/web/src/components/chat/ThreadDetailsPanel.tsx+++ b/apps/web/src/components/chat/ThreadDetailsPanel.tsx@@ -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}diff --git a/apps/web/src/components/chat/TraitsPicker.tsx b/apps/web/src/components/chat/TraitsPicker.tsxindex ff42d096b37..cfd900e8338 100644--- a/apps/web/src/components/chat/TraitsPicker.tsx+++ b/apps/web/src/components/chat/TraitsPicker.tsx@@ -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({<Menuopen={isMenuOpen}onOpenChange={(open) => {- setIsMenuOpen(open);+ setIsMenuOpen(open && !disabled);}}><Tooltip>@@ -636,6 +638,7 @@ export const TraitsPicker = memo(function TraitsPicker({<MenuTriggerrender={<ComposerControl+ disabled={disabled}aria-label={triggerLabel}data-composer-shortcut={isComposerOwned ? "composer.effort" : undefined}size={size}diff --git a/apps/web/src/components/cloud/ConnectOnboardingDialog.tsx b/apps/web/src/components/cloud/ConnectOnboardingDialog.tsxindex b605ba3facd..afe71469799 100644--- a/apps/web/src/components/cloud/ConnectOnboardingDialog.tsx+++ b/apps/web/src/components/cloud/ConnectOnboardingDialog.tsx@@ -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() {<PublishStepexposeEnvironment={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"}diff --git a/apps/web/src/components/device/DeviceSetup.tsx b/apps/web/src/components/device/DeviceSetup.tsxindex d4ebfe89f90..67c30525861 100644--- a/apps/web/src/components/device/DeviceSetup.tsx+++ b/apps/web/src/components/device/DeviceSetup.tsx@@ -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><Switchchecked={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><Switchchecked={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"}diff --git a/apps/web/src/components/onboarding/WelcomeWizard.import.test.tsx b/apps/web/src/components/onboarding/WelcomeWizard.import.test.tsxnew file mode 100644index 00000000000..a9403887d9e--- /dev/null+++ b/apps/web/src/components/onboarding/WelcomeWizard.import.test.tsx@@ -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();+});diff --git a/apps/web/src/components/onboarding/WelcomeWizard.test.tsx b/apps/web/src/components/onboarding/WelcomeWizard.test.tsxindex b36a8e81523..9c357213c36 100644--- a/apps/web/src/components/onboarding/WelcomeWizard.test.tsx+++ b/apps/web/src/components/onboarding/WelcomeWizard.test.tsx@@ -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", () => ({diff --git a/apps/web/src/components/onboarding/WelcomeWizard.tsx b/apps/web/src/components/onboarding/WelcomeWizard.tsxindex f8f37c603a4..bb4055d8468 100644--- a/apps/web/src/components/onboarding/WelcomeWizard.tsx+++ b/apps/web/src/components/onboarding/WelcomeWizard.tsx@@ -17,6 +17,7 @@ import {import {CommandId,defaultInstanceIdForDriver,+ AuthOrchestrationOperateScope,ProviderDriverKind,ThreadId,} from "@t3tools/contracts";@@ -60,6 +61,7 @@ import { isOnboardingRelayEnvironment } from "../../onboarding/targetEnvironmentimport { 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><ButtonautoFocus- disabled={isImporting || selected.length === 0}+ disabled={!canImport || isImporting || selected.length === 0}onClick={() => void runImport(selected)}>{isImportingdiff --git a/apps/web/src/components/projectScriptEditor.permissions.test.tsx b/apps/web/src/components/projectScriptEditor.permissions.test.tsxnew file mode 100644index 00000000000..eccdb0cf834--- /dev/null+++ b/apps/web/src/components/projectScriptEditor.permissions.test.tsx@@ -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();+ });+});diff --git a/apps/web/src/components/projectScriptEditor.test.tsx b/apps/web/src/components/projectScriptEditor.test.tsxindex 27c98a02456..71a3f7c7980 100644--- a/apps/web/src/components/projectScriptEditor.test.tsx+++ b/apps/web/src/components/projectScriptEditor.test.tsx@@ -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}diff --git a/apps/web/src/components/projectScriptEditor.tsx b/apps/web/src/components/projectScriptEditor.tsxindex b3708f5721f..a8a7e5e900e 100644--- a/apps/web/src/components/projectScriptEditor.tsx+++ b/apps/web/src/components/projectScriptEditor.tsx@@ -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><Buttonvariant="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);diff --git a/apps/web/src/components/settings/AcpRegistrySearchStep.test.tsx b/apps/web/src/components/settings/AcpRegistrySearchStep.test.tsxindex 06d5704c415..03da36f8f89 100644--- a/apps/web/src/components/settings/AcpRegistrySearchStep.test.tsx+++ b/apps/web/src/components/settings/AcpRegistrySearchStep.test.tsx@@ -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;diff --git a/apps/web/src/components/settings/AcpRegistrySearchStep.tsx b/apps/web/src/components/settings/AcpRegistrySearchStep.tsxindex 55178f481a5..70118c30268 100644--- a/apps/web/src/components/settings/AcpRegistrySearchStep.tsx+++ b/apps/web/src/components/settings/AcpRegistrySearchStep.tsx@@ -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}<Buttonaria-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"}diff --git a/apps/web/src/components/settings/AcpSessionManagementSection.test.tsx b/apps/web/src/components/settings/AcpSessionManagementSection.test.tsxindex 17c673efa59..e9dd834bd45 100644--- a/apps/web/src/components/settings/AcpSessionManagementSection.test.tsx+++ b/apps/web/src/components/settings/AcpSessionManagementSection.test.tsx@@ -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();+});diff --git a/apps/web/src/components/settings/AcpSessionManagementSection.tsx b/apps/web/src/components/settings/AcpSessionManagementSection.tsxindex bb25420b6db..f793d4101b3 100644--- a/apps/web/src/components/settings/AcpSessionManagementSection.tsx+++ b/apps/web/src/components/settings/AcpSessionManagementSection.tsx@@ -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: {<><Selectvalue={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 ? (<Selectvalue={projectId ?? ""}- disabled={props.readOnly || projectOperationPending}+ disabled={!canRead || projectOperationPending}onValueChange={(value) => {if (value === null) return;setProjectId(value as ProjectId);diff --git a/apps/web/src/components/settings/AddCodexAccountDialog.tsx b/apps/web/src/components/settings/AddCodexAccountDialog.tsxindex 802e5d912c2..e9551945235 100644--- a/apps/web/src/components/settings/AddCodexAccountDialog.tsx+++ b/apps/web/src/components/settings/AddCodexAccountDialog.tsx@@ -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></>diff --git a/apps/web/src/components/settings/AddProviderInstanceDialog.environment.test.tsx b/apps/web/src/components/settings/AddProviderInstanceDialog.environment.test.tsxindex d112af1fed0..d643cfe2776 100644--- a/apps/web/src/components/settings/AddProviderInstanceDialog.environment.test.tsx+++ b/apps/web/src/components/settings/AddProviderInstanceDialog.environment.test.tsx@@ -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);+ });});diff --git a/apps/web/src/components/settings/AddProviderInstanceDialog.tsx b/apps/web/src/components/settings/AddProviderInstanceDialog.tsxindex 0d137c89dec..b329d6ef134 100644--- a/apps/web/src/components/settings/AddProviderInstanceDialog.tsx+++ b/apps/web/src/components/settings/AddProviderInstanceDialog.tsx@@ -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 && !isLocalAcpdiff --git a/apps/web/src/components/settings/CodexSetupSection.tsx b/apps/web/src/components/settings/CodexSetupSection.tsxindex 32aa640b1e7..415882dbacd 100644--- a/apps/web/src/components/settings/CodexSetupSection.tsx+++ b/apps/web/src/components/settings/CodexSetupSection.tsx@@ -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 (<AddCodexAccountDialogenvironmentId={environmentId}@@ -180,6 +183,7 @@ export function AddManagedCodexAccountDialog({provider={provider}mode="managed"enabled+ readOnly={!canManageProviders}autoStartonAutoStartConsumed={noop}onModeChange={noop}diff --git a/apps/web/src/components/settings/ConnectionsSettings.logic.test.ts b/apps/web/src/components/settings/ConnectionsSettings.logic.test.tsindex 74283796a8e..79a29fa6985 100644--- a/apps/web/src/components/settings/ConnectionsSettings.logic.test.ts+++ b/apps/web/src/components/settings/ConnectionsSettings.logic.test.ts@@ -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);+ });+});diff --git a/apps/web/src/components/settings/ConnectionsSettings.logic.ts b/apps/web/src/components/settings/ConnectionsSettings.logic.tsindex d683efab3a4..4dcabbb4b40 100644--- a/apps/web/src/components/settings/ConnectionsSettings.logic.ts+++ b/apps/web/src/components/settings/ConnectionsSettings.logic.ts@@ -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">;/**diff --git a/apps/web/src/components/settings/ConnectionsSettings.tsx b/apps/web/src/components/settings/ConnectionsSettings.tsxindex f915ca4457d..4877d39ff77 100644--- a/apps/web/src/components/settings/ConnectionsSettings.tsx+++ b/apps/web/src/components/settings/ConnectionsSettings.tsx@@ -23,7 +23,9 @@ import {import {AuthAccessReadScope,AuthAccessWriteScope,- AuthAdministrativeScopes,+ AuthSettingsWriteScope,+ AuthProvidersManageScope,+ AuthEnvironmentMaintainScope,AuthOrchestrationOperateScope,AuthOrchestrationReadScope,AuthRelayReadScope,@@ -64,6 +66,7 @@ import { formatElapsedDurationLabel, formatExpiresInLabel } from "../../timestamimport { 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({<Buttonsize="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({<Buttonsize="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 AuthorizedClientsHeaderActioclientSessions,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<Buttonsize="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 AuthorizedClientsHeaderActiosetDialogOpen(open);if (!open) {setPairingLabel("");- setPairingScopes([...AuthStandardClientScopes]);+ setPairingScopes(+ AuthStandardClientScopes.filter((scope) => delegatableScopes.includes(scope)),+ );}}}>@@ -1172,7 +1209,13 @@ const AuthorizedClientsHeaderAction = memo(function AuthorizedClientsHeaderActiosize="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 AuthorizedClientsHeaderActiosize="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 AuthorizedClientsHeaderActioCancel</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: bconst 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: bcontrol={<CloudLinkSwitchchecked={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<CloudLinkSwitchariaLabel="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() {<SettingsRowtitle={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 ? (<FoldedSettingsSectionid="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() {<Buttonvariant="outline"onClick={() => handleConfirmEnableWsl("wsl-only")}- disabled={isUpdatingWslBackend}+ disabled={isUpdatingWslBackend || !canManageLocalBackend}>{isUpdatingWslBackend ? (<>@@ -3739,7 +3897,7 @@ export function ConnectionsSettings() {<Buttonvariant="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() {<Buttonvariant="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>)}</>diff --git a/apps/web/src/components/settings/DeviceHostsSettings.tsx b/apps/web/src/components/settings/DeviceHostsSettings.tsxindex 1885c2aa110..781f549f5d3 100644--- a/apps/web/src/components/settings/DeviceHostsSettings.tsx+++ b/apps/web/src/components/settings/DeviceHostsSettings.tsx@@ -1,4 +1,6 @@import { DeviceToolVersions } from "../device/DeviceToolVersions";+import { AuthSettingsWriteScope } from "@t3tools/contracts";+import { readEnvironmentScope, useEnvironmentScope } from "../../state/session";import { Tooltip, TooltipTrigger, TooltipPopup } from "../ui/tooltip";import { AppleIcon, AndroidIcon } from "../Icons";import { Spinner } from "../ui/spinner";@@ -22,6 +24,7 @@ import { deviceHostConnectionKey } from "./deviceHostConnectionChecks";export function DeviceHostsSettings(props: { environmentId: EnvironmentId | null }) {const { scope, environments, connectedEnvironments } = useSettingsScope();+ const canConfigure = useEnvironmentScope(props.environmentId, AuthSettingsWriteScope);const projectScope = scope.kind === "project" || scope.kind === "checkout";const update = useAtomCommand(serverEnvironment.updateSettings, { reportFailure: false });const [editing, setEditing] = useState<SshDeviceHostConfig | null>(null);@@ -42,6 +45,9 @@ export function DeviceHostsSettings(props: { environmentId: EnvironmentId | nullif (environment.connection.phase !== "connected" || !environment.serverConfig) {throw new Error("Environment disconnected");}+ if (!readEnvironmentScope(environment.environmentId, AuthSettingsWriteScope)) {+ throw new Error("This connection cannot change device settings.");+ }return update({environmentId: environment.environmentId,input: {@@ -85,7 +91,9 @@ export function DeviceHostsSettings(props: { environmentId: EnvironmentId | null<Buttonsize="sm"variant="outline"- disabled={projectScope || busy || !props.environmentId || editing !== null}+ disabled={+ !canConfigure || projectScope || busy || !props.environmentId || editing !== null+ }onClick={() => {setOriginalHost(null);setEditing({ id: randomUUID(), label: "", target: "" });@@ -113,7 +121,7 @@ export function DeviceHostsSettings(props: { environmentId: EnvironmentId | nullenvironmentLabel={environment.label}environmentId={environment.environmentId}hosts={environment.serverConfig?.settings.deviceHosts ?? []}- busy={projectScope || busy}+ busy={!canConfigure || projectScope || busy}checks={checks}testConnection={async (host) => {const results = await testConnection(host);diff --git a/apps/web/src/components/settings/DiagnosticsSettings.tsx b/apps/web/src/components/settings/DiagnosticsSettings.tsxindex 3acc22b5d1a..18abfa37e1a 100644--- a/apps/web/src/components/settings/DiagnosticsSettings.tsx+++ b/apps/web/src/components/settings/DiagnosticsSettings.tsx@@ -1,4 +1,7 @@import { ProcessSignalActions } from "./ProcessSignalActions";+import { AuthOrchestrationOperateScope } from "@t3tools/contracts";+import { readEnvironmentScope, useEnvironmentScope } from "../../state/session";+import { AuthEnvironmentMaintainScope } from "@t3tools/contracts";import { RefreshIcon } from "~/components/ui/refresh-icon";import { AlertTriangleIcon, CopyIcon, FolderOpenIcon, InfoIcon } from "lucide-react";import { ChevronDown, ChevronRight } from "lucide";@@ -17,7 +20,7 @@ import * as Option from "effect/Option";import { cn } from "../../lib/utils";import { ensureLocalApi } from "../../localApi";-import { resolveAndPersistPreferredEditor } from "../../editorPreferences";+import { useOpenInPreferredEditor } from "../../editorPreferences";import { formatRelativeTimeLabel, getRelativeTimeState } from "../../timestampFormat";import { useEnvironmentQuery } from "../../state/query";import { serverEnvironment } from "../../state/server";@@ -296,11 +299,13 @@ function ProcessNameCell({function ProcessDiagnosticsTable({processes,+ canMaintainEnvironment,signalingPid,onSignal,emptyLabel,}: {processes: ReadonlyArray<ServerProcessDiagnosticsEntry>;+ canMaintainEnvironment: boolean;signalingPid: number | null;onSignal: (pid: number, signal: ServerProcessSignal) => void;emptyLabel?: string;@@ -408,7 +413,7 @@ function ProcessDiagnosticsTable({</td><td className="p-2 align-middle sm:pr-4"><ProcessSignalActions- disabled={signalingPid === process.pid}+ disabled={!canMaintainEnvironment || signalingPid === process.pid}onSignal={(signal) => onSignal(process.pid, signal)}/></td>@@ -710,14 +715,14 @@ export function DiagnosticsSettingsPanel() {// The boundary only mounts this page when the selection resolves to one// connected environment, so the representative is the one to inspect.const environmentId = environment?.environmentId ?? null;+ const canMaintainEnvironment = useEnvironmentScope(environmentId, AuthEnvironmentMaintainScope);const observability = environment?.serverConfig?.observability;const availableEditors = environment?.serverConfig?.availableEditors;+ const canOpenHostEditor = useEnvironmentScope(environmentId, AuthOrchestrationOperateScope);const signalServerProcess = useAtomCommand(serverEnvironment.signalProcess, {reportFailure: false,});- const openInEditor = useAtomCommand(shellEnvironment.openInEditor, {- reportFailure: false,- });+ const openInEditor = useOpenInPreferredEditor(environmentId, availableEditors ?? []);const [resourceWindowMs, setResourceWindowMs] = useState(15 * 60_000);const selectedResourceWindow =RESOURCE_HISTORY_WINDOWS.find((option) => option.windowMs === resourceWindowMs) ??@@ -773,26 +778,17 @@ export function DiagnosticsSettingsPanel() {const logsDirectoryPath = observability?.logsDirectoryPath ?? null;if (!logsDirectoryPath) return;- const editor = resolveAndPersistPreferredEditor(availableEditors ?? []);- if (!editor) {- setOpenLogsDirectoryError("No available editors found.");- return;- }- if (environmentId === null) {- setOpenLogsDirectoryError("No environment is selected.");+ if (+ environmentId === null ||+ !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)+ ) {return;}setIsOpeningLogsDirectory(true);setOpenLogsDirectoryError(null);void (async () => {- const result = await openInEditor({- environmentId,- input: {- cwd: logsDirectoryPath,- editor,- },- });+ const result = await openInEditor(logsDirectoryPath);setIsOpeningLogsDirectory(false);if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {const error = squashAtomCommandFailure(result);@@ -801,7 +797,7 @@ export function DiagnosticsSettingsPanel() {);}})();- }, [availableEditors, environmentId, observability?.logsDirectoryPath, openInEditor]);+ }, [environmentId, observability?.logsDirectoryPath, openInEditor]);const isInitialLoading = isPending && data === null;const isProcessInitialLoading = isProcessPending && processData === null;@@ -809,7 +805,12 @@ export function DiagnosticsSettingsPanel() {async (pid: number, signal: ServerProcessSignal) => {const targetEnvironmentId = environmentIdRef.current;const process = processDataRef.current?.processes.find((entry) => entry.pid === pid);- if (targetEnvironmentId === null || process === undefined) return;+ if (+ targetEnvironmentId === null ||+ process === undefined ||+ !readEnvironmentScope(targetEnvironmentId, AuthEnvironmentMaintainScope)+ )+ return;if (signalingPidRef.current !== null) return;signalingPidRef.current = pid;setSignalingPid(pid);@@ -838,7 +839,12 @@ export function DiagnosticsSettingsPanel() {return;}}- if (environmentIdRef.current !== targetEnvironmentId) {+ const currentEnvironmentId = environmentIdRef.current;+ if (+ currentEnvironmentId === null ||+ currentEnvironmentId !== targetEnvironmentId ||+ !readEnvironmentScope(currentEnvironmentId, AuthEnvironmentMaintainScope)+ ) {clearSignaling();return;}@@ -956,6 +962,7 @@ export function DiagnosticsSettingsPanel() {) : null}<ProcessDiagnosticsTableprocesses={processData?.processes ?? []}+ canMaintainEnvironment={canMaintainEnvironment}signalingPid={signalingPid}onSignal={signalProcess}emptyLabel={@@ -1041,7 +1048,11 @@ export function DiagnosticsSettingsPanel() {<Buttonsize="icon-xs"variant="ghost-muted"- disabled={!observability?.logsDirectoryPath || isOpeningLogsDirectory}+ disabled={+ !canOpenHostEditor ||+ !observability?.logsDirectoryPath ||+ isOpeningLogsDirectory+ }onClick={openLogsDirectory}aria-label="Open logs folder">diff --git a/apps/web/src/components/settings/EnvironmentIconPicker.test.ts b/apps/web/src/components/settings/EnvironmentIconPicker.test.tsindex 429b853ddae..25fd930e3b6 100644--- a/apps/web/src/components/settings/EnvironmentIconPicker.test.ts+++ b/apps/web/src/components/settings/EnvironmentIconPicker.test.ts@@ -30,10 +30,10 @@ describe("resolveEnvironmentIconPickerLock", () => {).toMatch(/cannot change/);});- it("stays open while access is still resolving so a slow session does not flicker", () => {+ it("waits for a settings grant before allowing changes", () => {expect(resolveEnvironmentIconPickerLock({ serverConfig: config(true), operateAccess: "pending" }),- ).toBeNull();+ ).toMatch(/cannot change/);expect(resolveEnvironmentIconPickerLock({ serverConfig: config(true), operateAccess: "granted" }),).toBeNull();diff --git a/apps/web/src/components/settings/EnvironmentIconPicker.tsx b/apps/web/src/components/settings/EnvironmentIconPicker.tsxindex 0add490159a..1bbacc27392 100644--- a/apps/web/src/components/settings/EnvironmentIconPicker.tsx+++ b/apps/web/src/components/settings/EnvironmentIconPicker.tsx@@ -1,4 +1,5 @@import {+ AuthSettingsWriteScope,ENVIRONMENT_MACHINE_KINDS,isEnvironmentMachineKind,resolveEnvironmentMachineKind,@@ -6,11 +7,8 @@ import {type ServerConfig,} from "@t3tools/contracts";-import { isElectron } from "../../env";-import { usePrimarySessionState } from "../../environments/primary";import { useUpdateEnvironmentSettings } from "../../hooks/useSettings";-import { usePrimaryEnvironmentId } from "../../state/environments";-import { useEnvironmentSessionState } from "../../state/session";+import { useEnvironmentScope } from "../../state/session";import { ENVIRONMENT_MACHINE_KIND_LABELS, EnvironmentMachineIcon } from "../EnvironmentMachineIcon";import {MenuItem,@@ -21,10 +19,6 @@ import {MenuSubPopup,MenuSubTrigger,} from "../ui/menu";-import {- resolvePrimaryOperateAccess,- resolveRemoteOperateAccess,-} from "./ProviderSettingsPanel.logic";/*** Why the picker is inert, in the order the user can do something about it.@@ -40,37 +34,12 @@ export function resolveEnvironmentIconPickerLock(input: {if (input.serverConfig.environment.capabilities.environmentIcon !== true) {return "This environment's server is too old to keep an icon. Update it to choose one.";}- if (input.operateAccess === "denied") {+ if (input.operateAccess !== "granted") {return "Your session on this environment cannot change its settings.";}return null;}-// Same split the provider settings use: the desktop app owns its primary-// server outright, a browser session on the primary checks its cookie-// session's scopes, and a remote checks the scopes its own server reports.-function useEnvironmentOperateAccess(environmentId: EnvironmentId) {- const isPrimary = usePrimaryEnvironmentId() === environmentId;- const primarySession = usePrimarySessionState();- const remoteSession = useEnvironmentSessionState(environmentId);- if (isPrimary) {- return isElectron- ? "granted"- : resolvePrimaryOperateAccess({- isPrimary: true,- hasDesktopBridge: false,- session: primarySession.data,- isPending: primarySession.isPending,- hasError: primarySession.error !== null,- });- }- return resolveRemoteOperateAccess({- session: remoteSession.data,- isPending: remoteSession.isPending,- hasError: remoteSession.hasError,- });-}-/*** "Icon" submenu for an environment's row menu. Lists the machine kinds with* the server's own detection marked, so the user can tell whether detection@@ -86,7 +55,9 @@ export function EnvironmentIconMenu({readonly serverConfig: ServerConfig | null;}) {const updateSettings = useUpdateEnvironmentSettings(environmentId);- const operateAccess = useEnvironmentOperateAccess(environmentId);+ const operateAccess = useEnvironmentScope(environmentId, AuthSettingsWriteScope)+ ? "granted"+ : "denied";const lock = resolveEnvironmentIconPickerLock({ serverConfig, operateAccess });// With no detection the server falls back to "server", so picking that// kind clears the override the same way picking the detected kind does.diff --git a/apps/web/src/components/settings/IntegrationsSettings.test.tsx b/apps/web/src/components/settings/IntegrationsSettings.test.tsxindex 15b19029e81..bdcfb2ca9db 100644--- a/apps/web/src/components/settings/IntegrationsSettings.test.tsx+++ b/apps/web/src/components/settings/IntegrationsSettings.test.tsx@@ -17,6 +17,16 @@ const { listBrowserImportSources } = vi.hoisted(() => ({listBrowserImportSources: vi.fn().mockResolvedValue([]),}));+vi.mock("../ui/tooltip", () => ({+ Tooltip: ({ children }: { children: ReactNode }) => children,+ TooltipTrigger: ({ render, children }: { render: ReactNode; children: ReactNode }) => (+ <>+ {render}+ {children}+ </>+ ),+ TooltipPopup: () => null,+}));vi.mock("../preview/previewBridge", () => ({previewBridge: { listBrowserImportSources },}));@@ -24,6 +34,8 @@ vi.mock("../../env", () => ({ isElectron: true }));vi.mock("../../state/environments", () => ({useEnvironments: () => ({ environments: [], isReady: true }),usePrimaryEnvironment: () => null,+ // Settings rows resolve the primary grant before rendering server controls.+ usePrimaryEnvironmentId: () => null,}));vi.mock("../../hooks/useSettings", async (importOriginal) => ({...(await importOriginal<typeof import("../../hooks/useSettings")>()),diff --git a/apps/web/src/components/settings/IntegrationsSettings.tsx b/apps/web/src/components/settings/IntegrationsSettings.tsxindex e007e026956..a0c0a79bebc 100644--- a/apps/web/src/components/settings/IntegrationsSettings.tsx+++ b/apps/web/src/components/settings/IntegrationsSettings.tsx@@ -12,6 +12,7 @@ import { DeviceHostsSettings } from "./DeviceHostsSettings";* @module IntegrationsSettings*/import {+ AuthSettingsWriteScope,BrowserImportFailureReason,BROWSER_PROFILE_MAX_COUNT,type BrowserLinkTarget,@@ -49,6 +50,7 @@ import { previewBridge } from "~/components/preview/previewBridge";import { cn, randomUUID } from "~/lib/utils";import { useEnvironments, usePrimaryEnvironment } from "~/state/environments";import { deviceEnvironment, useDeviceState } from "~/state/device";+import { readEnvironmentScope, useEnvironmentScope } from "~/state/session";import { useAtomCommand } from "~/state/use-atom-command";import { previewEnvironment } from "~/state/preview";import { useServerConfigs } from "~/state/entities";@@ -647,6 +649,7 @@ function DeviceIntegrationControls({enabled: boolean;agentAccessEnabled: boolean;}) {+ const canConfigure = useEnvironmentScope(environmentId, AuthSettingsWriteScope);const { state, loaded } = useDeviceState(environmentId);const { scope, environments, connectedEnvironments } = useSettingsScope();const updateSettings = useUpdateScopedSettings();@@ -679,7 +682,7 @@ function DeviceIntegrationControls({kind: NonNullable<typeof pending>,input: { enabled?: boolean; agentAccessEnabled?: boolean },) => {- if (!environmentId) return;+ if (!environmentId || !readEnvironmentScope(environmentId, AuthSettingsWriteScope)) return;setPending(kind);try {const results = await Promise.allSettled(@@ -687,6 +690,9 @@ function DeviceIntegrationControls({if (environment.connection.phase !== "connected" || !environment.serverConfig) {throw new Error("Environment disconnected");}+ if (!readEnvironmentScope(environment.environmentId, AuthSettingsWriteScope)) {+ throw new Error("This connection cannot change device settings.");+ }return configure({environmentId: environment.environmentId,input: { ...input, ...(input.enabled ? { onboardingCompleted: true } : {}) },@@ -786,7 +792,14 @@ function DeviceIntegrationControls({<ScopedSwitchsettingKeys={["enableDeviceSupport"]}checked={enabled}- disabled={projectScope || !loaded || !environmentId || busy || pending !== null}+ disabled={+ !canConfigure ||+ projectScope ||+ !loaded ||+ !environmentId ||+ busy ||+ pending !== null+ }aria-label="Device hub"onCheckedChange={(checked) =>void update("hub", {@@ -851,6 +864,7 @@ function DeviceIntegrationControls({settingKeys={["enableAgentDeviceAccess"]}checked={agentAccessEnabled}disabled={+ !canConfigure ||connectedEnvironments.length === 0 ||(!projectScope && (!loaded || !anyHubEnabled || busy)) ||pending !== nulldiff --git a/apps/web/src/components/settings/KeybindingsSettings.environment.test.tsx b/apps/web/src/components/settings/KeybindingsSettings.environment.test.tsxnew file mode 100644index 00000000000..a33720e5834--- /dev/null+++ b/apps/web/src/components/settings/KeybindingsSettings.environment.test.tsx@@ -0,0 +1,143 @@+import type { EnvironmentId } from "@t3tools/contracts";+import { beforeEach, describe, expect, it, vi } from "vite-plus/test";++import { visitElements } from "../../test/reactElementTree";+import { reactHookHarness as hooks } from "../../test/reactHookHarness";++const state = vi.hoisted(() => ({+ canOperate: false,+ canWriteSettings: true,+ openEditor: vi.fn(),+ upsert: vi.fn(),+ remove: vi.fn(),+}));++vi.mock("react", async (importOriginal) => {+ const actual = await importOriginal<typeof import("react")>();+ const { reactHookHarness } = await import("../../test/reactHookHarness");+ return {+ ...actual,+ useCallback: reactHookHarness.useCallback,+ useEffect: () => undefined,+ useMemo: reactHookHarness.useMemo,+ useRef: reactHookHarness.useRef,+ useState: reactHookHarness.useState,+ };+});++vi.mock("react/compiler-runtime", async () => {+ const { reactHookHarness } = await import("../../test/reactHookHarness");+ return { c: reactHookHarness.useMemoCache };+});++vi.mock("@effect/atom-react", () => ({+ useAtomValue: (atom: string) => (atom === "config-path" ? "/fixture/keybindings.json" : []),+}));++vi.mock("@tanstack/react-router", () => ({ useLocation: () => "" }));+vi.mock("../ProjectFavicon", () => ({ ProjectFavicon: () => null }));+vi.mock("../../state/server", () => ({+ primaryServerKeybindingsAtom: "keybindings",+ primaryServerKeybindingsConfigPathAtom: "config-path",+ primaryServerAvailableEditorsAtom: "editors",+ serverEnvironment: { upsertKeybinding: state.upsert, removeKeybinding: state.remove },+}));++vi.mock("../../state/environments", () => ({+ usePrimaryEnvironment: () => ({ environmentId: "primary-settings" }),+}));++vi.mock("./SettingsScopeContext", () => ({+ useSettingsScope: () => {+ const environment = {+ environmentId: "primary-settings",+ serverConfig: {+ keybindings: [],+ keybindingsConfigPath: "/fixture/keybindings.json",+ availableEditors: [],+ },+ };+ return { environment, connectedEnvironments: [environment] };+ },+}));++vi.mock("../../state/session", () => {+ const hasScope = (environmentId: EnvironmentId | null, scope: string) =>+ environmentId === "primary-settings" &&+ (scope === "orchestration:operate"+ ? state.canOperate+ : scope === "settings:write" && state.canWriteSettings);+ return {+ useEnvironmentScope: hasScope,+ readEnvironmentScope: hasScope,+ useEnvironmentsWithScope: () => new Set(state.canWriteSettings ? ["primary-settings"] : []),+ };+});++vi.mock("../../state/use-atom-command", () => ({+ useAtomCommand: (command: unknown) => command,+}));++vi.mock("../../editorPreferences", () => ({+ useOpenInPreferredEditor: (environmentId: EnvironmentId) => (path: string) =>+ state.openEditor({ environmentId, path }),+}));++import { KeybindingsSettingsPanel } from "./KeybindingsSettings";++function renderPanel() {+ hooks.beginRender();+ return KeybindingsSettingsPanel();+}++function openButton(panel: unknown) {+ const button = visitElements(+ panel,+ (element) => element.props["aria-label"] === "Open keybindings.json",+ );+ if (!button) throw new Error("Missing Open keybindings.json action.");+ return button;+}++describe("KeybindingsSettings editor permission", () => {+ beforeEach(() => {+ hooks.reset();+ state.canOperate = false;+ state.canWriteSettings = true;+ state.openEditor.mockReset().mockResolvedValue({ _tag: "Success", value: undefined });+ state.upsert.mockReset().mockResolvedValue({ _tag: "Success", value: undefined });+ state.remove.mockReset().mockResolvedValue({ _tag: "Success", value: undefined });+ });++ it("rejects editor launches when settings writes are the only write grant", () => {+ const button = openButton(renderPanel());+ (button.props.onClick as () => void)();++ expect(state.openEditor).not.toHaveBeenCalled();+ expect(button.props.disabled).toBe(true);+ });++ it("opens the primary environment's file after operate is granted without settings writes", () => {+ state.canWriteSettings = false;+ renderPanel();+ state.canOperate = true;+ const button = openButton(renderPanel());+ expect(button.props.disabled).toBe(false);+ (button.props.onClick as () => void)();++ expect(state.openEditor).toHaveBeenCalledWith({+ environmentId: "primary-settings",+ path: "/fixture/keybindings.json",+ });+ });++ it("rejects a queued editor launch after operate is revoked", () => {+ state.canOperate = true;+ const open = openButton(renderPanel()).props.onClick as () => void;+ state.canOperate = false;+ open();++ expect(state.openEditor).not.toHaveBeenCalled();+ expect(openButton(renderPanel()).props.disabled).toBe(true);+ });+});diff --git a/apps/web/src/components/settings/KeybindingsSettings.tsx b/apps/web/src/components/settings/KeybindingsSettings.tsxindex b2660f8943e..156a3d0f800 100644--- a/apps/web/src/components/settings/KeybindingsSettings.tsx+++ b/apps/web/src/components/settings/KeybindingsSettings.tsx@@ -1,3 +1,5 @@+import { useEnvironmentScope } from "../../state/session";+import { useEnvironmentsWithScope, readEnvironmentScope } from "../../state/session";import {ChevronDownIcon,CircleXIcon,@@ -22,6 +24,8 @@ import {useState,} from "react";import {+ AuthOrchestrationOperateScope,+ AuthSettingsWriteScope,type KeybindingCommand,type KeybindingWhenNode,type ServerRemoveKeybindingInput,@@ -1281,6 +1285,14 @@ export function KeybindingsSettingsPanel() {// fan out to every connected environment in the selection, so one// shortcut change reaches each machine the user runs T3 Code on.const { environment: primaryEnvironment, connectedEnvironments } = useSettingsScope();+ const canOpenKeybindingsFile = useEnvironmentScope(+ primaryEnvironment?.environmentId ?? null,+ AuthOrchestrationOperateScope,+ );+ const writableIds = useEnvironmentsWithScope(connectedEnvironments, AuthSettingsWriteScope);+ const canWriteSettings =+ connectedEnvironments.length > 0 &&+ connectedEnvironments.every((target) => writableIds.has(target.environmentId));const serverKeybindings = primaryEnvironment?.serverConfig?.keybindings;const keybindings = useMemo(() => mergeWithDefaultKeybindings(serverKeybindings ?? []),@@ -1351,7 +1363,12 @@ export function KeybindingsSettingsPanel() {}, []);const openKeybindingsFile = useCallback(() => {- if (!keybindingsConfigPath) return;+ if (+ !keybindingsConfigPath ||+ !primaryEnvironment ||+ !readEnvironmentScope(primaryEnvironment.environmentId, AuthOrchestrationOperateScope)+ )+ return;void (async () => {const result = await openInPreferredEditor(keybindingsConfigPath);if (result._tag === "Success" || isAtomCommandInterrupted(result)) {@@ -1365,11 +1382,17 @@ export function KeybindingsSettingsPanel() {type: "error",});})();- }, [keybindingsConfigPath, openInPreferredEditor]);+ }, [keybindingsConfigPath, openInPreferredEditor, primaryEnvironment]);const saveKeybinding = useCallback((input: ServerUpsertKeybindingInput) => {- if (!primaryEnvironment) return;+ if (+ !primaryEnvironment ||+ !connectedEnvironments.every((target) =>+ readEnvironmentScope(target.environmentId, AuthSettingsWriteScope),+ )+ )+ return;setSavingCommand(input.command);const payload: ServerUpsertKeybindingInput = {command: input.command,@@ -1404,7 +1427,13 @@ export function KeybindingsSettingsPanel() {const removeKeybinding = useCallback((row: KeybindingRow) => {- if (!primaryEnvironment) return;+ if (+ !primaryEnvironment ||+ !connectedEnvironments.every((target) =>+ readEnvironmentScope(target.environmentId, AuthSettingsWriteScope),+ )+ )+ return;setSavingCommand(row.command);void (async () => {const results = await Promise.all(@@ -1468,7 +1497,7 @@ export function KeybindingsSettingsPanel() {<Buttontype="button"variant="outline"- disabled={isAddingBinding}+ disabled={isAddingBinding || !canWriteSettings}onClick={() => setIsAddingBinding(true)}><PlusIcon aria-hidden className="size-4" />@@ -1481,7 +1510,7 @@ export function KeybindingsSettingsPanel() {type="button"variant="outline"size="icon"- disabled={!keybindingsConfigPath}+ disabled={!keybindingsConfigPath || !canOpenKeybindingsFile}onClick={openKeybindingsFile}aria-label="Open keybindings.json">@@ -1494,33 +1523,40 @@ export function KeybindingsSettingsPanel() {</div></SettingsSection>- {isAddingBinding ? (- <SettingsGroup>- <NewKeybindingSettingsRow- commandOptions={commandOptions}- allRows={rows}- variables={whenVariables}- isSaving={savingCommand !== null}- onSave={saveKeybinding}- onCancel={cancelAdd}- />- </SettingsGroup>+ {!canWriteSettings ? (+ <p className="text-xs text-muted-foreground">+ This connection can view keybindings but cannot change them.+ </p>) : null}+ <div inert={!canWriteSettings}>+ {isAddingBinding ? (+ <SettingsGroup>+ <NewKeybindingSettingsRow+ commandOptions={commandOptions}+ allRows={rows}+ variables={whenVariables}+ isSaving={savingCommand !== null}+ onSave={saveKeybinding}+ onCancel={cancelAdd}+ />+ </SettingsGroup>+ ) : null}- {groups.length > 0 ? (- <KeybindingsGroups- groups={groups}- anchorIds={anchorIds}- savingCommand={savingCommand}- {...rowActions}- />- ) : (- <SettingsGroup>- <div className="px-4 py-12 text-center text-sm text-muted-foreground">- No keybindings match your search.- </div>- </SettingsGroup>- )}+ {groups.length > 0 ? (+ <KeybindingsGroups+ groups={groups}+ anchorIds={anchorIds}+ savingCommand={savingCommand}+ {...rowActions}+ />+ ) : (+ <SettingsGroup>+ <div className="px-4 py-12 text-center text-sm text-muted-foreground">+ No keybindings match your search.+ </div>+ </SettingsGroup>+ )}+ </div></SettingsPageContainer>);}diff --git a/apps/web/src/components/settings/ProjectActionsSettings.tsx b/apps/web/src/components/settings/ProjectActionsSettings.tsxindex f9b7b44ec0c..1392da91607 100644--- a/apps/web/src/components/settings/ProjectActionsSettings.tsx+++ b/apps/web/src/components/settings/ProjectActionsSettings.tsx@@ -1,3 +1,5 @@+import { useScopedSettingsWriteAllowed } from "./useScopedSettings";+import { AuthSettingsWriteScope } from "@t3tools/contracts";import { EnvironmentId, type T3ProjectFileScript } from "@t3tools/contracts";import {isAtomCommandInterrupted,@@ -52,6 +54,7 @@ export function ProjectActionsSettings() {(candidate) =>JSON.stringify(candidate.settings.defaultProjectScripts) !== JSON.stringify(scripts),);+ const canWriteSettings = useScopedSettingsWriteAllowed();const [request, setRequest] = useState<ProjectScriptEditorRequest | null>(null);const memberById = new Map(isProjectScope ? scope.members.map((member) => [member.id, member]) : [],@@ -148,7 +151,7 @@ export function ProjectActionsSettings() {id="import-scripts"size="xs"variant="ghost"- disabled={saving}+ disabled={saving || !canWriteSettings}type="button"/>}@@ -184,7 +187,7 @@ export function ProjectActionsSettings() {<Buttonsize="xs"variant="outline"- disabled={saving || targets.length === 0}+ disabled={saving || !canWriteSettings || targets.length === 0}onClick={() => setRequest({ scriptId: null, initial: EMPTY_PROJECT_SCRIPT_INPUT })}><PlusIcon className="size-3.5" />@@ -202,7 +205,7 @@ export function ProjectActionsSettings() {<ProjectActionsListscripts={scripts}keybindings={keybindings}- disabled={saving}+ disabled={saving || !canWriteSettings}onEdit={(script) => setRequest(editorRequestForScript(script, keybindings))}/>)}@@ -213,15 +216,19 @@ export function ProjectActionsSettings() {className="text-warning"/>) : null}- <ProjectScriptEditorDialog- request={request}- scripts={scripts}- onSubmit={submit}- onDelete={(id) =>- void persist((current) => current.filter((script) => script.id !== id), id, null)- }- onClose={() => setRequest(null)}- />+ {target && (+ <ProjectScriptEditorDialog+ environmentId={target.environmentId}+ editScope={AuthSettingsWriteScope}+ request={request}+ scripts={scripts}+ onSubmit={submit}+ onDelete={(id) =>+ void persist((current) => current.filter((script) => script.id !== id), id, null)+ }+ onClose={() => setRequest(null)}+ />+ )}</SettingsSection>);}diff --git a/apps/web/src/components/settings/ProjectSettingsPanel.test.tsx b/apps/web/src/components/settings/ProjectSettingsPanel.test.tsxnew file mode 100644index 00000000000..939bc4a0437--- /dev/null+++ b/apps/web/src/components/settings/ProjectSettingsPanel.test.tsx@@ -0,0 +1,476 @@+import { RegistryContext } from "@effect/atom-react";+import type {+ DeleteProjectInput,+ UpdateProjectInput,+} from "@t3tools/client-runtime/state/projects";+import {+ AuthOrchestrationOperateScope,+ AuthSettingsWriteScope,+ DEFAULT_SERVER_SETTINGS,+ EnvironmentId,+ ProjectId,+ ProviderDriverKind,+ ProviderInstanceId,+ type AuthEnvironmentScope,+ type AuthSessionState,+ type ResolvedKeybindingsConfig,+ type ServerProvider,+} from "@t3tools/contracts";+import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings";+import { DEFAULT_RESOLVED_KEYBINDINGS } from "@t3tools/shared/keybindings";+import * as Cause from "effect/Cause";+import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";+import { cloneElement, 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 { Project } from "../../types";++type SessionResult = AsyncResult.AsyncResult<AuthSessionState, Error>;+const state = vi.hoisted(() => ({+ registry: null as AtomRegistry.AtomRegistry | null,+ sessions: new Map<EnvironmentId, Atom.Writable<SessionResult>>(),+ providers: null as Atom.Atom<ReadonlyArray<ServerProvider>> | null,+ config: null as Atom.Atom<{ keybindings: ResolvedKeybindingsConfig }> | null,+ projects: [] as Project[],+ update:+ vi.fn<+ (request: {+ environmentId: EnvironmentId;+ input: UpdateProjectInput;+ }) => Promise<AsyncResult.Success<void>>+ >(),+ delete:+ vi.fn<+ (request: {+ environmentId: EnvironmentId;+ input: DeleteProjectInput;+ }) => Promise<AsyncResult.Success<void>>+ >(),+ confirm: vi.fn<() => Promise<boolean>>(),+ updateSettings: vi.fn(),+ upsertKeybinding: vi.fn(),+ removeKeybinding: vi.fn(),+ updateClientSettings: vi.fn(),+ releaseUploads: vi.fn(),+ clearDraft: vi.fn(),+ copy: vi.fn(),+ navigate: 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/environments", () => ({+ useEnvironments: () => ({ environments }),+ usePrimaryEnvironmentId: () => primaryId,+}));+vi.mock("~/state/entities", () => ({+ useProjects: () => state.projects,+ useThreadShells: () => [],+}));+vi.mock("~/state/projects", () => ({+ projectEnvironment: { update: "update", delete: "delete" },+}));+vi.mock("~/state/server", () => ({+ EMPTY_SERVER_PROVIDERS: [],+ serverEnvironment: {+ providersValueAtom: () => state.providers!,+ configValueAtom: () => state.config!,+ updateSettings: "updateSettings",+ upsertKeybinding: "upsertKeybinding",+ removeKeybinding: "removeKeybinding",+ },+}));+vi.mock("~/state/use-atom-command", () => ({+ useAtomCommand: (+ command: "update" | "delete" | "updateSettings" | "upsertKeybinding" | "removeKeybinding",+ ) => state[command],+}));+vi.mock("~/hooks/useSettings", () => ({+ useClientSettings: () => DEFAULT_CLIENT_SETTINGS,+ useUpdateClientSettings: () => state.updateClientSettings,+ usePrimarySettings: () => DEFAULT_SERVER_SETTINGS,+ useEnvironmentSettings: () => DEFAULT_SERVER_SETTINGS,+}));+vi.mock("~/hooks/useT3ProjectFileScripts", () => ({+ useT3ProjectFileState: () => ({+ status: "valid",+ file: null,+ scripts: [{ name: "Imported", command: "vp test" }],+ }),+}));+vi.mock("~/hooks/useCopyToClipboard", () => ({+ useCopyToClipboard: () => ({ copyToClipboard: state.copy }),+}));+vi.mock("~/localApi", () => ({ readLocalApi: () => ({ dialogs: { confirm: state.confirm } }) }));+vi.mock("~/composerDraftStore", () => ({+ useComposerDraftStore: {+ getState: () => ({+ getDraftThreadByProjectRef: () => null,+ clearProjectDraftThreadId: state.clearDraft,+ }),+ },+}));+vi.mock("~/lib/composerDraftUploads", () => ({ releaseProjectDraftUploads: state.releaseUploads }));+vi.mock("~/env", () => ({ isElectron: true }));+vi.mock("@tanstack/react-router", () => ({+ useNavigate: () => state.navigate,+ useLocation: () => "/settings/projects",+}));+vi.mock("../ui/toast", () => ({+ toastManager: { add: vi.fn() },+ stackedThreadToast: (value: unknown) => value,+}));+vi.mock("../ui/button", () => ({ Button: "button" }));+vi.mock("../ui/input", () => ({ Input: "input" }));+vi.mock("../ui/switch", () => ({ Switch: "input" }));+vi.mock("../ui/select", () => ({+ Select: "select",+ SelectItem: "option",+ SelectPopup: "div",+ SelectTrigger: "button",+ SelectValue: "span",+}));+vi.mock("../ui/menu", () => ({+ Menu: "div",+ MenuGroup: "div",+ MenuGroupLabel: "div",+ MenuItem: "button",+ MenuPopup: "div",+ MenuSeparator: "hr",+ MenuTrigger: ({ render, children }: { render: ReactElement; children: ReactNode }) =>+ cloneElement(render, {}, children),+}));+vi.mock("../ui/tooltip", () => ({+ Tooltip: "div",+ TooltipPopup: "span",+ TooltipTrigger: ({ render }: { render: ReactNode }) => render,+}));+vi.mock("./settingsLayout", () => ({+ SETTINGS_PICKER_TRIGGER_CLASSNAME: "",+ SettingsPageContainer: "div",+ SettingsSection: ({+ children,+ headerAction,+ }: {+ children: ReactNode;+ headerAction?: ReactNode;+ }) => (+ <section>+ {headerAction}+ {children}+ </section>+ ),+ SettingsRow: ({ control, resetAction }: { control?: ReactNode; resetAction?: ReactNode }) => (+ <div>+ {resetAction}+ {control}+ </div>+ ),+ SettingResetButton: ({+ label,+ ...props+ }: {+ label: string;+ disabled?: boolean;+ onClick: () => void;+ }) => <button {...props} aria-label={`Reset ${label} to default`} />,+}));+vi.mock("./ProjectDefaultsSettings", () => ({ ProjectDefaultsSettings: () => null }));+vi.mock("./ProjectActionsSettings", () => ({ ProjectActionsSettings: () => null }));+vi.mock("../ProjectFavicon", () => ({ ProjectFavicon: () => null }));+vi.mock("../chat/ProviderModelPicker", () => ({ ProviderModelPicker: "model-picker" }));+vi.mock("../chat/TraitsPicker", () => ({ TraitsPicker: "traits-picker" }));+vi.mock("./ProjectFaviconPickerDialog", () => ({+ canPickExternalProjectFavicon: () => false,+ ProjectFaviconPickerDialog: "favicon-picker",+}));+vi.mock("./ProjectIconPickerDialog", () => ({ ProjectIconPickerDialog: "icon-picker" }));+vi.mock("../projectScriptEditor", async (importOriginal) => ({+ ...(await importOriginal<typeof import("../projectScriptEditor")>()),+ ProjectScriptEditorDialog: "script-editor",+}));++import { buildSidebarProjectSnapshots } from "../../sidebarProjectGrouping";+import { ProjectFaviconPickerDialog } from "./ProjectFaviconPickerDialog";+import { ProjectSettingsPanel } from "./ProjectSettingsPanel";++const primaryId = EnvironmentId.make("primary");+const remoteId = EnvironmentId.make("remote");+const instanceId = ProviderInstanceId.make("codex");+const environments = [primaryId, remoteId].map((environmentId) => ({+ environmentId,+ label: environmentId,+ connection: { phase: "connected" },+ serverConfig: { keybindings: DEFAULT_RESOLVED_KEYBINDINGS },+}));+const session = (scopes: ReadonlyArray<AuthEnvironmentScope>): AuthSessionState => ({+ authenticated: true,+ scopes,+ auth: {+ policy: "remote-reachable",+ bootstrapMethods: ["one-time-token"],+ sessionMethods: ["bearer-access-token"],+ sessionCookieName: "t3_session",+ },+});+const writable = () => AsyncResult.success(session([AuthOrchestrationOperateScope]));++function deferred<T>() {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((complete) => {+ resolve = complete;+ });+ return { promise, resolve };+}++let renderer: ReactTestRenderer | undefined;++beforeEach(() => {+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+ vi.clearAllMocks();+ state.registry = AtomRegistry.make();+ state.sessions.clear();+ for (const id of [primaryId, remoteId])+ state.sessions.set(id, Atom.make<SessionResult>(writable()).pipe(Atom.keepAlive));+ state.projects = [primaryId, remoteId].map((environmentId) => ({+ id: ProjectId.make(`project-${environmentId}`),+ environmentId,+ title: "Shared repo",+ workspaceRoot: `/work/${environmentId}`,+ repositoryIdentity: {+ canonicalKey: "github.com/example/shared-repo",+ locator: {+ source: "git-remote",+ remoteName: "origin",+ remoteUrl: "https://github.com/example/shared-repo.git",+ },+ },+ defaultModelSelection: { instanceId, model: "gpt-5-codex" },+ createdAt: "2026-01-01T00:00:00.000Z",+ updatedAt: "2026-01-01T00:00:00.000Z",+ scripts: [],+ }));+ state.providers = Atom.make<ReadonlyArray<ServerProvider>>([+ {+ instanceId,+ driver: ProviderDriverKind.make("codex"),+ enabled: true,+ installed: true,+ version: null,+ status: "ready",+ auth: { status: "authenticated" },+ checkedAt: "2026-01-01T00:00:00.000Z",+ models: [],+ slashCommands: [],+ skills: [],+ },+ ]);+ state.config = Atom.make({ keybindings: DEFAULT_RESOLVED_KEYBINDINGS });+ state.update.mockImplementation(async ({ environmentId, input }) => {+ const { projectId, ...updates } = input;+ const patch = Object.fromEntries(+ Object.entries(updates).filter(([, value]) => value !== undefined),+ ) as Partial<Project>;+ state.projects = state.projects.map((project) =>+ project.environmentId === environmentId && project.id === projectId+ ? { ...project, ...patch }+ : project,+ );+ return AsyncResult.success(undefined);+ });+ state.delete.mockResolvedValue(AsyncResult.success(undefined));+ state.updateSettings.mockResolvedValue(AsyncResult.success(undefined));+ state.confirm.mockResolvedValue(true);+});++afterEach(async () => {+ await act(() => renderer?.unmount());+ renderer = undefined;+ state.registry?.dispose();+ vi.unstubAllGlobals();+});++function group() {+ return buildSidebarProjectSnapshots({+ projects: state.projects,+ settings: DEFAULT_CLIENT_SETTINGS,+ primaryEnvironmentId: primaryId,+ resolveEnvironmentLabel: (id) => id,+ })[0]!;+}++async function mountPanel() {+ await act(() => {+ renderer = create(+ <RegistryContext.Provider value={state.registry!}>+ <ProjectSettingsPanel projectKey={group().projectKey} />+ </RegistryContext.Provider>,+ );+ });+ return renderer!.root;+}++function button(label: string) {+ return renderer!.root.findAllByType("button").find((node) => node.children.includes(label))!;+}++async function grant(id: EnvironmentId, result: SessionResult) {+ await act(() => state.registry!.set(state.sessions.get(id)!, result));+}++describe("project settings permissions", () => {+ it("preflights every member before any shared field update", async () => {+ await grant(remoteId, AsyncResult.success(session([AuthSettingsWriteScope])));+ const root = await mountPanel();+ const name = root.findByProps({ "aria-label": "Project name" });++ await act(async () => {+ name.props.onChange();+ name.props.onBlur({ currentTarget: { value: "Renamed" } });+ root.findByType(ProjectFaviconPickerDialog).props.onSelect("/work/icon.png");+ });++ expect(state.update).not.toHaveBeenCalled();+ expect(state.projects.every((project) => project.title === "Shared repo")).toBe(true);+ expect(name.props.disabled).toBe(true);+ expect(button("Remove all entries").props.disabled).toBe(true);+ });++ it("updates every member when all have project access without settings access", async () => {+ const root = await mountPanel();+ await act(async () => {+ const name = root.findByProps({ "aria-label": "Project name" });+ name.props.onChange();+ name.props.onBlur({ currentTarget: { value: "Renamed" } });+ });+ expect(state.update.mock.calls.map(([request]) => request.environmentId)).toEqual([+ primaryId,+ remoteId,+ ]);+ expect(state.projects.map((project) => project.title)).toEqual(["Renamed", "Renamed"]);+ });++ it("stops before the next member if its grant is revoked during an earlier update", async () => {+ const firstUpdate = deferred<AsyncResult.Success<void>>();+ state.update.mockReturnValueOnce(firstUpdate.promise);+ const root = await mountPanel();+ await act(async () => {+ const name = root.findByProps({ "aria-label": "Project name" });+ name.props.onChange();+ name.props.onBlur({ currentTarget: { value: "Renamed" } });+ });+ expect(state.update).toHaveBeenCalledOnce();++ await grant(remoteId, AsyncResult.success(session([])));+ await act(async () => {+ firstUpdate.resolve(AsyncResult.success(undefined));+ await firstUpdate.promise;+ });+ expect(state.update).toHaveBeenCalledOnce();+ expect(state.update.mock.calls[0]![0].environmentId).toBe(primaryId);+ });++ it("disables removal for a checkout whose project grant is missing", async () => {+ await grant(remoteId, AsyncResult.success(session([])));+ const root = await mountPanel();+ const denied = root.findByProps({ "aria-label": "Remove checkout /work/remote" });+ expect(denied.props.disabled).toBe(true);+ await act(async () => denied.props.onClick());+ expect(state.confirm).not.toHaveBeenCalled();+ expect(state.delete).not.toHaveBeenCalled();+ expect(root.findByProps({ "aria-label": "Remove checkout /work/primary" }).props.disabled).toBe(+ false,+ );+ });++ it("allows removing a writable checkout while denying removal of the mixed group", async () => {+ await grant(remoteId, AsyncResult.success(session([])));+ await mountPanel();+ await act(async () => button("Remove all entries").props.onClick());+ expect(state.confirm).not.toHaveBeenCalled();+ expect(state.delete).not.toHaveBeenCalled();+ await act(async () =>+ renderer!.root.findByProps({ "aria-label": "Remove checkout /work/primary" }).props.onClick(),+ );+ expect(state.delete).toHaveBeenCalledExactlyOnceWith({+ environmentId: primaryId,+ input: { projectId: state.projects[0]!.id, force: true },+ });+ expect(state.releaseUploads).toHaveBeenCalledOnce();+ expect(state.clearDraft).toHaveBeenCalledOnce();+ });++ it("rechecks every removal target after confirmation before deleting or clearing drafts", async () => {+ const confirmed = deferred<boolean>();+ state.confirm.mockReturnValueOnce(confirmed.promise);+ await mountPanel();+ await act(async () => button("Remove all entries").props.onClick());+ expect(state.confirm).toHaveBeenCalledOnce();+ await grant(remoteId, AsyncResult.success(session([])));+ await act(async () => {+ confirmed.resolve(true);+ await confirmed.promise;+ });+ expect(state.delete).not.toHaveBeenCalled();+ expect(state.releaseUploads).not.toHaveBeenCalled();+ expect(state.clearDraft).not.toHaveBeenCalled();+ });++ it("reacts to another member's revoked and restored grant and guards a stale handler", async () => {+ await grant(+ primaryId,+ AsyncResult.success(session([AuthOrchestrationOperateScope, AuthSettingsWriteScope])),+ );+ const root = await mountPanel();+ const name = () => root.findByProps({ "aria-label": "Project name" });+ const staleSave = name().props.onBlur;+ await act(async () => {+ state.registry!.set(state.sessions.get(remoteId)!, AsyncResult.success(session([])));+ name().props.onChange();+ staleSave({ currentTarget: { value: "Renamed" } });+ });+ expect(state.update).not.toHaveBeenCalled();+ expect(name().props.disabled).toBe(true);++ await grant(remoteId, writable());+ expect(name().props.disabled).toBe(false);+ await act(async () => {+ name().props.onChange();+ name().props.onBlur({ currentTarget: { value: "Renamed" } });+ });+ expect(state.projects.map((project) => project.title)).toEqual(["Renamed", "Renamed"]);+ });++ it.each([+ ["loading", () => AsyncResult.initial<AuthSessionState, Error>(), false],+ [+ "failed",+ () => AsyncResult.failure<AuthSessionState, Error>(Cause.fail(new Error("Disconnected"))),+ false,+ ],+ ["refreshing", () => AsyncResult.waiting(writable()), true],+ ] as const)(+ "uses the current grant while a member's session is %s",+ async (_state, result, allowed) => {+ await grant(remoteId, result());+ const root = await mountPanel();+ const name = root.findByProps({ "aria-label": "Project name" });+ expect(name.props.disabled).toBe(!allowed);+ await act(async () => {+ name.props.onChange();+ name.props.onBlur({ currentTarget: { value: "Renamed" } });+ });+ expect(state.update).toHaveBeenCalledTimes(allowed ? 2 : 0);+ },+ );+});diff --git a/apps/web/src/components/settings/ProjectSettingsPanel.tsx b/apps/web/src/components/settings/ProjectSettingsPanel.tsxindex 0d368abef6a..fcc83a87514 100644--- a/apps/web/src/components/settings/ProjectSettingsPanel.tsx+++ b/apps/web/src/components/settings/ProjectSettingsPanel.tsx@@ -1,3 +1,7 @@+import { useComposerMenuState } from "../chat/useComposerMenuState";+import { useOrchestrationCommand } from "../../state/use-orchestration-command";+import { AuthOrchestrationOperateScope } from "@t3tools/contracts";+import { useEnvironmentsWithScope, readEnvironmentScope } from "../../state/session";import {isAtomCommandInterrupted,mapAtomCommandResult,@@ -23,7 +27,6 @@ import {import { useEnvironments, usePrimaryEnvironmentId } from "../../state/environments";import { useThreadShells } from "../../state/entities";import { projectEnvironment } from "../../state/projects";-import { useAtomCommand } from "../../state/use-atom-command";import { ProjectFavicon } from "../ProjectFavicon";import { Alert, AlertDescription } from "../ui/alert";import { Button } from "../ui/button";@@ -171,13 +174,21 @@ function ProjectDetail({() => new Map(environments.map((environment) => [environment.environmentId, environment])),[environments],);+ const editableIds = useEnvironmentsWithScope(group.memberProjects, AuthOrchestrationOperateScope);+ const canEditGroup = group.memberProjects.every((member) =>+ editableIds.has(member.environmentId),+ );const representative =group.memberProjects.find((member) => environmentById.get(member.environmentId)?.serverConfig != null,) ?? group.memberProjects[0]!;const threads = useThreadShells();- const updateProject = useAtomCommand(projectEnvironment.update, { reportFailure: false });- const deleteProject = useAtomCommand(projectEnvironment.delete, { reportFailure: false });+ const updateProject = useOrchestrationCommand(projectEnvironment.update, {+ reportFailure: false,+ });+ const deleteProject = useOrchestrationCommand(projectEnvironment.delete, {+ reportFailure: false,+ });const projectNameEditedRef = useRef(false);const faviconPath = representative.faviconPath ?? null;@@ -204,6 +215,25 @@ function ProjectDetail({);}, []);+ const checkProjectAccess = useCallback(+ (members: ReadonlyArray<SidebarProjectGroupMember>, failureTitle: string) => {+ const denied = members.find(+ (member) => !readEnvironmentScope(member.environmentId, AuthOrchestrationOperateScope),+ );+ if (!denied) return null;+ const result = AsyncResult.failure<void, Error>(+ Cause.fail(+ new Error(+ `This connection cannot change projects in ${denied.environmentLabel ?? "this environment"}.`,+ ),+ ),+ );+ reportFailure(failureTitle, result);+ return result;+ },+ [reportFailure],+ );+// Group-shared fields live on each physical project record, so a// group-level edit fans out to every member.const updateAllMembers = useCallback(@@ -215,6 +245,8 @@ function ProjectDetail({}>,failureTitle: string,): Promise<AtomCommandResult<void, unknown>> => {+ const denied = checkProjectAccess(group.memberProjects, failureTitle);+ if (denied) return denied;const unavailable = group.memberProjects.find((member) => {const environment = environmentById.get(member.environmentId);return environment?.connection.phase !== "connected" || !environment.serverConfig;@@ -228,6 +260,8 @@ function ProjectDetail({return result;}for (const member of group.memberProjects) {+ const revoked = checkProjectAccess([member], failureTitle);+ if (revoked) return revoked;const result = mapAtomCommandResult(await updateProject({environmentId: member.environmentId,@@ -249,7 +283,7 @@ function ProjectDetail({}return AsyncResult.success(undefined);},- [environmentById, group.memberProjects, reportFailure, updateProject],+ [checkProjectAccess, environmentById, group.memberProjects, reportFailure, updateProject],);const renameGroup = useCallback(@@ -274,8 +308,8 @@ function ProjectDetail({);// ----- project icon ------ const [faviconPickerOpen, setFaviconPickerOpen] = useState(false);- const [iconPickerOpen, setIconPickerOpen] = useState(false);+ const [faviconPickerOpen, setFaviconPickerOpen] = useComposerMenuState(!canEditGroup);+ const [iconPickerOpen, setIconPickerOpen] = useComposerMenuState(!canEditGroup);const [isSavingFavicon, setIsSavingFavicon] = useState(false);const savingFaviconRef = useRef(false);const setProjectIcon = useCallback(@@ -297,6 +331,7 @@ function ProjectDetail({const removeMembers = useCallback(async (members: ReadonlyArray<SidebarProjectGroupMember>) => {+ if (checkProjectAccess(members, "Failed to remove project")) return;const api = readLocalApi();if (!api) return;@@ -336,9 +371,11 @@ function ProjectDetail({),);if (confirmed._tag === "Failure" || !confirmed.value) return;+ if (checkProjectAccess(members, "Failed to remove project")) return;const draftStore = useComposerDraftStore.getState();for (const member of members) {+ if (checkProjectAccess([member], "Failed to remove project")) return;const memberThreads = projectThreads.filter((thread) =>thread.environmentId === member.environmentId && thread.projectId === member.id,@@ -374,6 +411,7 @@ function ProjectDetail({}},[+ checkProjectAccess,deleteProject,group.displayName,group.memberProjects.length,@@ -395,6 +433,7 @@ function ProjectDetail({<Buttonsize="sm"variant="outline"+ disabled={!editableIds.has(member.environmentId)}onClick={() => void removeMembers([member])}aria-label={`Remove checkout ${member.workspaceRoot}`}>@@ -416,6 +455,13 @@ function ProjectDetail({</AlertDescription></Alert><SettingsSection id="project-overview" title="Project" hideTitle>+ {!canEditGroup ? (+ <p className="px-3 py-2 text-sm text-muted-foreground sm:px-4">+ {group.memberProjects.length > 1+ ? "Shared settings require permission to change every checkout in this group."+ : "This connection cannot change this project."}+ </p>+ ) : null}<SettingsRowtitle="Name"description="The shared name for this project group in the sidebar and thread lists."@@ -425,6 +471,7 @@ function ProjectDetail({size="sm"className="w-full sm:w-64"aria-label="Project name"+ disabled={!canEditGroup}defaultValue={group.displayName}onChange={() => {projectNameEditedRef.current = true;@@ -457,7 +504,7 @@ function ProjectDetail({) ? (<SettingResetButtonlabel="project icon"- disabled={isSavingFavicon}+ disabled={isSavingFavicon || !canEditGroup}onClick={() => void setProjectIcon({ faviconPath: null, projectIcon: null })}/>) : null@@ -470,7 +517,7 @@ function ProjectDetail({variant="outline"type="button"aria-label="Choose a project icon"- disabled={isSavingFavicon}+ disabled={isSavingFavicon || !canEditGroup}onClick={() => setIconPickerOpen(true)}>Choose icon@@ -480,7 +527,7 @@ function ProjectDetail({variant="outline"type="button"aria-label="Choose a project icon file"- disabled={isSavingFavicon}+ disabled={isSavingFavicon || !canEditGroup}onClick={() => setFaviconPickerOpen(true)}>Choose file@@ -512,6 +559,7 @@ function ProjectDetail({<Buttonsize="sm"variant="destructive-outline"+ disabled={!canEditGroup}onClick={() => void removeMembers(group.memberProjects)}><Trash2Icon />@@ -535,10 +583,10 @@ function ProjectDetail({? { onPickExternal: () => pickProjectFavicon(representative.workspaceRoot) }: {})}onSelect={(path) => void setProjectIcon({ faviconPath: path, projectIcon: null })}- open={faviconPickerOpen}+ open={faviconPickerOpen && canEditGroup}projectName={group.displayName}/>- {iconPickerOpen ? (+ {iconPickerOpen && canEditGroup ? (<Suspense fallback={null}><ProjectIconPickerDialogcurrent={projectIcon}diff --git a/apps/web/src/components/settings/ProviderInstanceCard.tsx b/apps/web/src/components/settings/ProviderInstanceCard.tsxindex 9965925ad27..381dcd864e4 100644--- a/apps/web/src/components/settings/ProviderInstanceCard.tsx+++ b/apps/web/src/components/settings/ProviderInstanceCard.tsx@@ -478,6 +478,7 @@ interface ProviderInstanceCardProps {readonly selected?: boolean | undefined;readonly onSelect?: (() => void) | undefined;readonly readOnly?: boolean | undefined;+ readonly canWriteSettings?: boolean;readonly onUpdate: (nextInstance: ProviderInstanceConfig) => void;/*** Pass `undefined` to hide the delete footer entirely. Built-in default@@ -546,6 +547,7 @@ export function ProviderInstanceCard({selected = false,onSelect,readOnly = false,+ canWriteSettings = true,onUpdate,onDelete,headerAction,@@ -1116,30 +1118,27 @@ export function ProviderInstanceCard({environment={genericEnvironment}onChange={updateGenericEnvironment}/>- {environmentId !== undefined && liveProvider?.driver === "acpRegistry" ? (- <AcpSessionManagementSection- environmentId={environmentId}- instanceId={instanceId}- provider={liveProvider}- projects={acpProjects}- readOnly={readOnly}- />- ) : null}</SettingsSection>+ {environmentId !== undefined && liveProvider?.driver === "acpRegistry" ? (+ <AcpSessionManagementSection+ environmentId={environmentId}+ instanceId={instanceId}+ provider={liveProvider}+ projects={acpProjects}+ readOnly={readOnly}+ />+ ) : null}{driverOption !== undefined ? (- <SettingsSection- title="Models"- inert={readOnly}- aria-disabled={readOnly || undefined}- className={readOnly ? "opacity-50 select-none" : undefined}- >+ <SettingsSection title="Models"><div className="px-3 py-3 sm:px-4"><p className="mb-3 text-xs text-muted-foreground">Favorites, visibility, and ordering are saved on this device. Custom models are savedon the selected environment.</p><ProviderModelsSection+ canManageCustomModels={!readOnly}+ canWritePreferences={canWriteSettings}instanceId={instanceId}driverKind={driverKind}models={modelsForDisplay}diff --git a/apps/web/src/components/settings/ProviderModelsSection.tsx b/apps/web/src/components/settings/ProviderModelsSection.tsxindex 14c55a12efb..1cb3e311147 100644--- a/apps/web/src/components/settings/ProviderModelsSection.tsx+++ b/apps/web/src/components/settings/ProviderModelsSection.tsx@@ -131,6 +131,8 @@ interface ProviderModelsSectionProps {* removed) via `onChange`.*/readonly customModels: ReadonlyArray<CustomModelDefinition>;+ readonly canManageCustomModels: boolean;+ readonly canWritePreferences?: boolean;/** Server-returned model slugs hidden from the model picker. */readonly hiddenModels: ReadonlyArray<string>;/** Model slugs favorited for this provider instance. */@@ -164,6 +166,8 @@ export function ProviderModelsSection({driverKind,models,customModels,+ canManageCustomModels,+ canWritePreferences = true,hiddenModels,favoriteModels,modelOrder,@@ -224,7 +228,7 @@ export function ProviderModelsSection({}, [displayModels]);const handleAdd = () => {- if (driverKind === "antigravity") return;+ if (!canManageCustomModels || driverKind === "antigravity") return;const normalized = normalizeCustomModelSlug(input);if (!normalized) {setError("Enter a model slug.");@@ -260,6 +264,7 @@ export function ProviderModelsSection({};const handleRemove = (slug: string) => {+ if (!canManageCustomModels) return;if (editingSlug === slug) setEditingSlug(null);onChange(customModels.filter((entry) => entry.slug !== slug));onModelOrderChange(modelOrder.filter((model) => model !== slug));@@ -268,18 +273,20 @@ export function ProviderModelsSection({};const handleSaveEdit = (next: CustomModelDefinition) => {+ if (!canManageCustomModels) return;onChange(customModels.map((entry) => (entry.slug === next.slug ? next : entry)));setEditingSlug(null);};const setHidden = (slug: string, hidden: boolean) => {- if (hidden === hiddenModelSet.has(slug)) return;+ if (!canWritePreferences || hidden === hiddenModelSet.has(slug)) return;onHiddenModelsChange(hidden ? [...hiddenModels, slug] : hiddenModels.filter((model) => model !== slug),);};const handleToggleFavorite = (slug: string) => {+ if (!canWritePreferences) return;if (favoriteModelSet.has(slug)) {onFavoriteModelsChange(favoriteModels.filter((model) => model !== slug));return;@@ -296,6 +303,7 @@ export function ProviderModelsSection({? "hidden": "visible";const handleMove = (slug: string, direction: -1 | 1) => {+ if (!canWritePreferences) return;const index = displayModels.findIndex((model) => model.slug === slug);const nextIndex = index + direction;if (index < 0 || nextIndex < 0 || nextIndex >= displayModels.length) return;@@ -314,6 +322,7 @@ export function ProviderModelsSection({<Buttonsize="icon-micro"variant="ghost-muted"+ disabled={!canWritePreferences}onClick={() => handleToggleFavorite(model.slug)}aria-label={`${isFavorite ? "Remove" : "Add"} ${model.name} ${isFavorite ? "from" : "to"@@ -348,7 +357,7 @@ export function ProviderModelsSection({<Buttonsize="icon-micro"variant="ghost-muted"- disabled={!options.canMoveUp}+ disabled={!canWritePreferences || !options.canMoveUp}onClick={() => handleMove(model.slug, -1)}aria-label={`Move ${model.name} up`}/>@@ -364,7 +373,7 @@ export function ProviderModelsSection({<Buttonsize="icon-micro"variant="ghost-muted"- disabled={!options.canMoveDown}+ disabled={!canWritePreferences || !options.canMoveDown}onClick={() => handleMove(model.slug, 1)}aria-label={`Move ${model.name} down`}/>@@ -384,10 +393,12 @@ export function ProviderModelsSection({<Buttonsize="icon-micro"variant="ghost-muted"+ disabled={!canManageCustomModels}aria-label={`Edit ${model.slug}`}- onClick={() =>- setEditingSlug((current) => (current === model.slug ? null : model.slug))- }+ onClick={() => {+ if (!canManageCustomModels) return;+ setEditingSlug((current) => (current === model.slug ? null : model.slug));+ }}/>}>@@ -401,6 +412,7 @@ export function ProviderModelsSection({<Buttonsize="icon-micro"variant="ghost-muted"+ disabled={!canManageCustomModels}aria-label={`Remove ${model.slug}`}onClick={() => handleRemove(model.slug)}/>@@ -430,7 +442,7 @@ export function ProviderModelsSection({<Switchsize="sm"checked={!isHidden}- disabled={model.isCustom}+ disabled={!canWritePreferences || model.isCustom}onCheckedChange={(checked) => setHidden(model.slug, !checked)}aria-label={`Show ${model.name} in the model picker`}/>@@ -562,7 +574,7 @@ export function ProviderModelsSection({const previous = visibleModels[index - 1];const startsGroup = previous === undefined || groupOf(previous) !== group;const editingEntry =- model.isCustom && editingSlug === model.slug+ canManageCustomModels && model.isCustom && editingSlug === model.slug? customModels.find((entry) => entry.slug === model.slug): undefined;return (@@ -593,7 +605,7 @@ export function ProviderModelsSection({})}</div>- {driverKind === "antigravity" ? null : isAdding ? (+ {driverKind === "antigravity" || !canManageCustomModels ? null : isAdding ? (<div className="mt-3 flex flex-col gap-2 sm:flex-row"><Inputid={`provider-instance-${instanceId}-custom-model`}diff --git a/apps/web/src/components/settings/ProviderSettingsPanel.environment.test.tsx b/apps/web/src/components/settings/ProviderSettingsPanel.environment.test.tsxindex dcb4ba7ef7e..bcce41229b2 100644--- a/apps/web/src/components/settings/ProviderSettingsPanel.environment.test.tsx+++ b/apps/web/src/components/settings/ProviderSettingsPanel.environment.test.tsx@@ -26,6 +26,8 @@ const commands = vi.hoisted(() => ({updateProvider: vi.fn(),uninstall: vi.fn(),acceptUrlAuth: vi.fn(),+ canManageProviders: true,+ canWriteSettings: true,}));const settingsState = vi.hoisted(() => ({@@ -118,6 +120,20 @@ vi.mock("../../environments/primary", () => ({vi.mock("../../state/session", () => ({useEnvironmentSessionState: () => ({ data: null, hasError: false, isPending: true }),+ useEnvironmentScope: (environmentId: EnvironmentId, scope: string) =>+ environmentId === "remote-device" &&+ (scope === "providers:manage"+ ? commands.canManageProviders+ : scope === "settings:write"+ ? commands.canWriteSettings+ : scope === "orchestration:read"),+ readEnvironmentScope: (environmentId: EnvironmentId, scope: string) =>+ environmentId === "remote-device" &&+ (scope === "providers:manage"+ ? commands.canManageProviders+ : scope === "settings:write"+ ? commands.canWriteSettings+ : scope === "orchestration:read"),}));vi.mock("../../state/entities", () => ({@@ -125,6 +141,7 @@ vi.mock("../../state/entities", () => ({}));import { EnvironmentProviderSettings } from "./ProviderSettingsPanel";+import { AddProviderInstanceDialog } from "./AddProviderInstanceDialog";const environmentId = EnvironmentId.make("remote-device");const codexId = ProviderInstanceId.make("codex");@@ -209,6 +226,8 @@ describe("EnvironmentProviderSettings routing", () => {settingsState.mutateProviderInstance.mockReset().mockResolvedValue({ _tag: "Success", value: {} });+ commands.canManageProviders = true;+ commands.canWriteSettings = true;commands.refresh.mockReset().mockResolvedValue({ _tag: "Success" });commands.updateProvider.mockReset().mockResolvedValue({ _tag: "Success" });commands.uninstall.mockReset().mockResolvedValue({ _tag: "Success", value: {} });@@ -355,6 +374,7 @@ describe("EnvironmentProviderSettings routing", () => {});it("keeps provider selection available while write controls are read only", () => {+ commands.canWriteSettings = false;settingsState.value = {...DEFAULT_UNIFIED_SETTINGS,providerInstances: {@@ -388,7 +408,7 @@ describe("EnvironmentProviderSettings routing", () => {const notice = visitElements(panel, (element) => element.props.title === "Limited permissions");expect(notice).not.toBeNull();- expect(visitElements(panel, isRefreshButton)).toBeNull();+ expect(visitElements(panel, isRefreshButton)).not.toBeNull();expect(visitElements(panel, isAddProviderButton)).toBeNull();});@@ -403,6 +423,24 @@ describe("EnvironmentProviderSettings routing", () => {expect(visitElements(panel, isAddProviderButton)).not.toBeNull();});+ it("removes an open add-instance dialog when the provider grant is revoked", () => {+ let panel = renderPanel();+ const add = visitElements(panel, isAddProviderButton);+ if (!add) throw new Error("Missing Add provider action.");+ (add.props.onClick as () => void)();+ panel = renderPanel();+ expect(+ visitElements(panel, (element) => element.type === AddProviderInstanceDialog),+ ).not.toBeNull();++ commands.canManageProviders = false;+ panel = renderPanel({ readOnly: true });+ expect(+ visitElements(panel, (element) => element.type === AddProviderInstanceDialog),+ ).toBeNull();+ expect(settingsState.updateSettings).not.toHaveBeenCalled();+ });+it("keeps Advanced visible when search targets the provider health interval", () => {let panel = renderPanel();expect(visitElements(panel, (element) => element.props.title === "Advanced")).not.toBeNull();diff --git a/apps/web/src/components/settings/ProviderSettingsPanel.logic.test.ts b/apps/web/src/components/settings/ProviderSettingsPanel.logic.test.tsindex c04db646a47..d32634004ed 100644--- a/apps/web/src/components/settings/ProviderSettingsPanel.logic.test.ts+++ b/apps/web/src/components/settings/ProviderSettingsPanel.logic.test.ts@@ -1,4 +1,4 @@-import { AuthOrchestrationOperateScope, EnvironmentId } from "@t3tools/contracts";+import { AuthProvidersManageScope, EnvironmentId } from "@t3tools/contracts";import { describe, expect, it } from "vite-plus/test";import {@@ -136,7 +136,7 @@ describe("provider environment access", () => {describe("primary operate access", () => {const authenticated = {authenticated: true as const,- scopes: [AuthOrchestrationOperateScope],+ scopes: [AuthProvidersManageScope],};it("keeps cached session data authoritative while SWR revalidates", () => {@@ -163,7 +163,7 @@ describe("primary operate access", () => {).toBe("pending");});- it("treats a failed session fetch as a transport problem, not a denial", () => {+ it("denies writes when the session fetch fails", () => {expect(resolvePrimaryOperateAccess({isPrimary: true,@@ -172,7 +172,7 @@ describe("primary operate access", () => {isPending: false,hasError: true,}),- ).toBe("granted");+ ).toBe("denied");});it("denies unauthenticated sessions and sessions without the operate scope", () => {@@ -205,7 +205,7 @@ describe("primary operate access", () => {).toBe("denied");});- it("grants desktop bridge and remote environments without blocking on the primary session", () => {+ it("waits for explicit grants on desktop and remote environments", () => {expect(resolvePrimaryOperateAccess({isPrimary: true,@@ -214,7 +214,7 @@ describe("primary operate access", () => {isPending: true,hasError: false,}),- ).toBe("granted");+ ).toBe("pending");expect(resolvePrimaryOperateAccess({isPrimary: false,@@ -223,15 +223,24 @@ describe("primary operate access", () => {isPending: true,hasError: false,}),- ).toBe("granted");+ ).toBe("pending");});});describe("remote operate access", () => {+ it("does not treat the old orchestration grant as provider management", () => {+ expect(+ resolveRemoteOperateAccess({+ session: { authenticated: true, scopes: ["orchestration:operate"] },+ isPending: false,+ hasError: false,+ }),+ ).toBe("denied");+ });it("derives access from the environment session's granted scopes", () => {expect(resolveRemoteOperateAccess({- session: { authenticated: true, scopes: [AuthOrchestrationOperateScope] },+ session: { authenticated: true, scopes: [AuthProvidersManageScope] },isPending: false,hasError: false,}),@@ -258,18 +267,16 @@ describe("remote operate access", () => {);expect(resolveRemoteOperateAccess({- session: { authenticated: true, scopes: [AuthOrchestrationOperateScope] },+ session: { authenticated: true, scopes: [AuthProvidersManageScope] },isPending: true,hasError: false,}),).toBe("granted");});- it("stays optimistic when the session fetch fails or an older server omits scopes", () => {- // Transport failures and pre-scope-reporting servers are not permission- // decisions; the environment RPC layer still rejects unauthorized writes.+ it("denies writes when the session fetch fails or scopes are missing", () => {expect(resolveRemoteOperateAccess({ session: null, isPending: false, hasError: true })).toBe(- "granted",+ "denied",);expect(resolveRemoteOperateAccess({@@ -277,6 +284,6 @@ describe("remote operate access", () => {isPending: false,hasError: false,}),- ).toBe("granted");+ ).toBe("denied");});});diff --git a/apps/web/src/components/settings/ProviderSettingsPanel.logic.ts b/apps/web/src/components/settings/ProviderSettingsPanel.logic.tsindex e6748ae0fc7..4e7faab872d 100644--- a/apps/web/src/components/settings/ProviderSettingsPanel.logic.ts+++ b/apps/web/src/components/settings/ProviderSettingsPanel.logic.ts@@ -1,6 +1,6 @@import type { EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";import {- AuthOrchestrationOperateScope,+ AuthProvidersManageScope,type AuthSessionState,type EnvironmentId,} from "@t3tools/contracts";@@ -74,46 +74,19 @@ export type ProviderEnvironmentAccess =*/export type ProviderOperateAccess = "granted" | "denied" | "pending";-/**- * Resolve operate access from an environment's `/api/auth/session` answer.- *- * Cached session data wins over an in-flight revalidation. The session atoms- * are SWR-backed, so they report `isPending` on every background refresh;- * treating that as unknown would flip a working panel back to loading and- * discard in-progress edits.- *- * `missingScopesAccess` decides the case where the session resolved but did- * not report scopes: the primary serves the web app itself so its server- * always reports them (absence means denial), while a remote device may run an- * older server version that predates scope reporting, where denial would lock- * out a legitimate session. The environment RPC layer stays authoritative- * either way.- */+/** Cached grants remain usable during revalidation; unknown or failed lookups grant nothing. */function resolveSessionOperateAccess(input: {readonly session: Pick<AuthSessionState, "authenticated" | "scopes"> | null;readonly isPending: boolean;readonly hasError: boolean;- readonly missingScopesAccess: "granted" | "denied";}): ProviderOperateAccess {- if (input.session === null) {- if (input.isPending) {- return "pending";- }- // A failed session fetch is a transport problem, not a permission- // decision — locking the panel read-only would misreport it. Stay- // optimistic; the environment RPC layer still rejects unauthorized writes.- return input.hasError ? "granted" : "denied";- }- if (!input.session.authenticated) {- return "denied";- }- if (input.session.scopes === undefined) {- return input.missingScopesAccess;- }- return input.session.scopes.includes(AuthOrchestrationOperateScope) ? "granted" : "denied";+ if (input.hasError) return "denied";+ if (input.session === null) return input.isPending ? "pending" : "denied";+ return input.session.authenticated && input.session.scopes?.includes(AuthProvidersManageScope)+ ? "granted"+ : "denied";}-/** Operate access for the primary environment's own browser session. */export function resolvePrimaryOperateAccess(input: {readonly isPrimary: boolean;readonly hasDesktopBridge: boolean;@@ -121,30 +94,15 @@ export function resolvePrimaryOperateAccess(input: {readonly isPending: boolean;readonly hasError: boolean;}): ProviderOperateAccess {- if (!input.isPrimary || input.hasDesktopBridge) {- return "granted";- }- return resolveSessionOperateAccess({- session: input.session,- isPending: input.isPending,- hasError: input.hasError,- missingScopesAccess: "denied",- });+ return resolveSessionOperateAccess(input);}-/**- * Operate access for a non-primary environment, derived from the scopes its- * `/api/auth/session` endpoint reports for this client's credential.- */export function resolveRemoteOperateAccess(input: {readonly session: Pick<AuthSessionState, "authenticated" | "scopes"> | null;readonly isPending: boolean;readonly hasError: boolean;}): ProviderOperateAccess {- return resolveSessionOperateAccess({- ...input,- missingScopesAccess: "granted",- });+ return resolveSessionOperateAccess(input);}export function classifyProviderEnvironmentAccess(input: {diff --git a/apps/web/src/components/settings/ProviderSettingsPanel.tsx b/apps/web/src/components/settings/ProviderSettingsPanel.tsxindex cc8fe347c12..6f46870ed76 100644--- a/apps/web/src/components/settings/ProviderSettingsPanel.tsx+++ b/apps/web/src/components/settings/ProviderSettingsPanel.tsx@@ -1,5 +1,11 @@import { SettingsGroup } from "./SettingsGroup";import { RefreshIcon } from "~/components/ui/refresh-icon";+import {+ AuthSettingsWriteScope,+ AuthProvidersManageScope,+ AuthOrchestrationReadScope,+} from "@t3tools/contracts";+import { useEnvironmentScope, readEnvironmentScope } from "../../state/session";import { useAtomValue } from "@effect/atom-react";import { connectionStatusTitle } from "@t3tools/client-runtime/connection";import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";@@ -31,8 +37,6 @@ import { PlusIcon } from "lucide-react";import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";import { isDesktopLocalConnectionTarget } from "../../connection/desktopLocal";-import { isElectron } from "../../env";-import { usePrimarySessionState } from "../../environments/primary";import {useEnvironmentSettings,usePersistEnvironmentProviderInstanceMutation,@@ -115,7 +119,6 @@ import {isProviderSettingsEnvironmentAvailable,type ProviderEnvironmentAccess,type ProviderOperateAccess,- resolvePrimaryOperateAccess,resolveRemoteOperateAccess,resolveSelectedProviderEnvironmentId,} from "./ProviderSettingsPanel.logic";@@ -465,28 +468,6 @@ function SelectedEnvironmentProviderSettings({readonly deviceTabs?: ReactNode;readonly targetInstanceId?: ProviderInstanceId | undefined;}) {- const isPrimary = environment.entry.target._tag === "PrimaryConnectionTarget";- if (isPrimary) {- // The desktop app owns its primary server outright; a browser session- // checks the scopes its cookie session was granted.- if (isElectron) {- return (- <AccessGatedProviderSettings- environment={environment}- operateAccess="granted"- deviceTabs={deviceTabs}- targetInstanceId={targetInstanceId}- />- );- }- return (- <PrimarySessionGatedProviderSettings- environment={environment}- deviceTabs={deviceTabs}- targetInstanceId={targetInstanceId}- />- );- }return (<RemoteSessionGatedProviderSettingsenvironment={environment}@@ -496,33 +477,6 @@ function SelectedEnvironmentProviderSettings({);}-function PrimarySessionGatedProviderSettings({- environment,- deviceTabs,- targetInstanceId,-}: {- readonly environment: EnvironmentPresentation;- readonly deviceTabs?: ReactNode;- readonly targetInstanceId?: ProviderInstanceId | undefined;-}) {- const primarySessionState = usePrimarySessionState();- const operateAccess = resolvePrimaryOperateAccess({- isPrimary: true,- hasDesktopBridge: false,- session: primarySessionState.data,- isPending: primarySessionState.isPending,- hasError: primarySessionState.error !== null,- });- return (- <AccessGatedProviderSettings- environment={environment}- operateAccess={operateAccess}- deviceTabs={deviceTabs}- targetInstanceId={targetInstanceId}- />- );-}-function RemoteSessionGatedProviderSettings({environment,deviceTabs,@@ -597,15 +551,15 @@ export function EnvironmentProviderSettings({readonly targetInstanceId?: ProviderInstanceId | undefined;/*** Grey out and freeze every write control when this session's credential- * lacks `orchestration:operate` on the environment. Selecting providers+ * lacks `providers:manage` on the environment. Selecting providers* still works so the real configuration stays readable; switches, forms,- * and the health interval are inert so no write is offered and then rejected.+ * are inert so no write is offered and then rejected.*/readonly readOnly?: boolean;}) {const settings = useEnvironmentSettings(environmentId);- // Provider instances hold per-machine credentials and binaries, so this- // page always edits exactly the environment it displays.+ const canWriteSettings = useEnvironmentScope(environmentId, AuthSettingsWriteScope);+ const canRefreshProviders = useEnvironmentScope(environmentId, AuthOrchestrationReadScope);const updateSettings = useUpdateEnvironmentSettings(environmentId);const persistProviderInstance = usePersistEnvironmentProviderInstanceMutation(environmentId);const updateClientSettings = useUpdateClientSettings();@@ -700,7 +654,8 @@ export function EnvironmentProviderSettings({: null;const refreshProviders = useCallback(() => {- if (refreshingRef.current) return;+ if (refreshingRef.current || !readEnvironmentScope(environmentId, AuthOrchestrationReadScope))+ return;refreshingRef.current = true;setIsRefreshingProviders(true);void (async () => {@@ -725,6 +680,7 @@ export function EnvironmentProviderSettings({candidate: Pick<ProviderSettingsUpdateCandidate, "driver" | "instanceId">,targetVersion?: string,) => {+ if (!readEnvironmentScope(environmentId, AuthProvidersManageScope)) return;// Ref-based re-entry guard, mirroring refreshProviders: a state updater// may run after this function returns, so it cannot gate the dispatch.if (updatingInstanceIdsRef.current.has(candidate.instanceId)) {@@ -1062,6 +1018,7 @@ export function EnvironmentProviderSettings({/>) : undefined}+ canWriteSettings={canWriteSettings}setup={mode === "editor" && row.driver === "antigravity" ? (<ProviderSetupSection@@ -1125,7 +1082,10 @@ export function EnvironmentProviderSettings({onUpdate={(next) => {const wasEnabled = resolveProviderInstanceEnabled(row.instance);const isDisabling = next.enabled === false && wasEnabled;- const shouldClearTextGen = isDisabling && textGenInstanceId === row.instanceId;+ const shouldClearTextGen =+ isDisabling &&+ textGenInstanceId === row.instanceId &&+ readEnvironmentScope(environmentId, AuthSettingsWriteScope);updateProviderInstance(row,next,@@ -1197,53 +1157,47 @@ export function EnvironmentProviderSettings({headerAction={<div className="flex min-w-0 items-center gap-2"><ProviderUpdatesAction />- {readOnly ? (- <span className="min-w-0 truncate text-xs text-muted-foreground">- <ProviderLastChecked lastCheckedAt={lastCheckedAt} />- </span>- ) : (- <>- <Tooltip>- <TooltipTrigger- render={- <Button- size="xs"- variant="ghost-muted"- disabled={isRefreshingProviders}- aria-busy={isRefreshingProviders}- onClick={() => void refreshProviders()}- >- <RefreshIcon refreshing={isRefreshingProviders} />- <span className="sr-only">Refresh provider status</span>- <span className="hidden min-w-0 truncate sm:inline">- {isRefreshingProviders ? (- "Refreshing providers"- ) : (- <ProviderLastChecked lastCheckedAt={lastCheckedAt} />- )}- </span>- </Button>- }- />- <TooltipPopup side="top">Refresh provider status</TooltipPopup>- </Tooltip>- <Tooltip>- <TooltipTrigger- render={- <Button- size="icon-xs"- variant="ghost-muted"- onClick={() => setIsAddInstanceDialogOpen(true)}- aria-label="Add provider"- >- <PlusIcon />- </Button>- }- />- <TooltipPopup side="top">Add provider</TooltipPopup>- </Tooltip>- </>- )}+ <Tooltip>+ <TooltipTrigger+ render={+ <Button+ size="xs"+ variant="ghost-muted"+ disabled={isRefreshingProviders || !canRefreshProviders}+ aria-busy={isRefreshingProviders}+ onClick={() => void refreshProviders()}+ >+ <RefreshIcon refreshing={isRefreshingProviders} />+ <span className="sr-only">Refresh provider status</span>+ <span className="hidden min-w-0 truncate sm:inline">+ {isRefreshingProviders ? (+ "Refreshing providers"+ ) : (+ <ProviderLastChecked lastCheckedAt={lastCheckedAt} />+ )}+ </span>+ </Button>+ }+ />+ <TooltipPopup side="top">Refresh provider status</TooltipPopup>+ </Tooltip>+ {!readOnly ? (+ <Tooltip>+ <TooltipTrigger+ render={+ <Button+ size="icon-xs"+ variant="ghost-muted"+ onClick={() => setIsAddInstanceDialogOpen(true)}+ aria-label="Add provider"+ >+ <PlusIcon />+ </Button>+ }+ />+ <TooltipPopup side="top">Add provider</TooltipPopup>+ </Tooltip>+ ) : null}</div>}>@@ -1318,7 +1272,10 @@ export function EnvironmentProviderSettings({description="Refresh provider status, versions, and models in the background. Set to 0 to disable."resetAction={providerHealthRefreshIntervalSeconds !== defaultProviderHealthRefreshIntervalSeconds ? (- <span inert={readOnly} className={readOnly ? "opacity-50" : undefined}>+ <span+ inert={!canWriteSettings}+ className={!canWriteSettings ? "opacity-50" : undefined}+ ><SettingResetButtonlabel="provider health check interval"onClick={() =>@@ -1336,11 +1293,11 @@ export function EnvironmentProviderSettings({}control={<div- inert={readOnly}- aria-disabled={readOnly || undefined}+ inert={!canWriteSettings}+ aria-disabled={!canWriteSettings || undefined}className={cn("flex shrink-0 items-center gap-2",- readOnly && "opacity-50 select-none",+ !canWriteSettings && "opacity-50 select-none",)}><NumberField@@ -1375,7 +1332,7 @@ export function EnvironmentProviderSettings({/></SettingsSection>- {isAddInstanceDialogOpen ? (+ {isAddInstanceDialogOpen && !readOnly ? (<AddProviderInstanceDialogopenenvironmentId={environmentId}diff --git a/apps/web/src/components/settings/ResourceTelemetryDiagnostics.tsx b/apps/web/src/components/settings/ResourceTelemetryDiagnostics.tsxindex 7a9965d91ec..ab721ef54f4 100644--- a/apps/web/src/components/settings/ResourceTelemetryDiagnostics.tsx+++ b/apps/web/src/components/settings/ResourceTelemetryDiagnostics.tsx@@ -1,4 +1,5 @@import { ProcessSignalActions } from "./ProcessSignalActions";+import { AuthEnvironmentMaintainScope } from "@t3tools/contracts";import { RefreshIcon } from "~/components/ui/refresh-icon";import {ActivityIcon,@@ -40,6 +41,7 @@ import {import { cn } from "../../lib/utils";import { ensureLocalApi } from "../../localApi";import { serverEnvironment } from "../../state/server";+import { readEnvironmentScope, useEnvironmentScope } from "../../state/session";import { useAtomCommand } from "../../state/use-atom-command";import { formatRelativeTime } from "../../timestampFormat";import { Button } from "../ui/button";@@ -520,10 +522,12 @@ function canSignalProcess(process: ResourceTelemetryProcess): boolean {function ProcessActions({process,+ canMaintainEnvironment,signalingKeys,onSignal,}: {process: ResourceTelemetryProcess;+ canMaintainEnvironment: boolean;signalingKeys: ReadonlySet<string>;onSignal: (process: ResourceTelemetryProcess, signal: ServerProcessSignal) => void;}) {@@ -532,16 +536,21 @@ function ProcessActions({}const isSignaling = signalingKeys.has(processIdentityKey(process));return (- <ProcessSignalActions disabled={isSignaling} onSignal={(signal) => onSignal(process, signal)} />+ <ProcessSignalActions+ disabled={!canMaintainEnvironment || isSignaling}+ onSignal={(signal) => onSignal(process, signal)}+ />);}function ProcessTable({processes,+ canMaintainEnvironment,signalingKeys,onSignal,}: {processes: ReadonlyArray<ResourceTelemetryProcess>;+ canMaintainEnvironment: boolean;signalingKeys: ReadonlySet<string>;onSignal: (process: ResourceTelemetryProcess, signal: ServerProcessSignal) => void;}) {@@ -650,6 +659,7 @@ function ProcessTable({<td className="px-2 py-2 text-right sm:pr-4"><ProcessActionsprocess={process}+ canMaintainEnvironment={canMaintainEnvironment}signalingKeys={signalingKeys}onSignal={onSignal}/>@@ -820,6 +830,7 @@ export function ResourceTelemetryDiagnostics({const [windowMs, setWindowMs] = useState(15 * 60_000);const selectedWindow =HISTORY_WINDOWS.find((option) => option.windowMs === windowMs) ?? HISTORY_WINDOWS[1];+ const canMaintainEnvironment = useEnvironmentScope(environmentId, AuthEnvironmentMaintainScope);const telemetry = useResourceTelemetry(environmentId);const retryTelemetry = telemetry.retry;const history = useResourceTelemetryHistory(@@ -848,7 +859,11 @@ export function ResourceTelemetryDiagnostics({const signalProcess = useCallback(async (process: ResourceTelemetryProcess, signal: ServerProcessSignal) => {const targetEnvironmentId = environmentIdRef.current;- if (targetEnvironmentId === null) return;+ if (+ targetEnvironmentId === null ||+ !readEnvironmentScope(targetEnvironmentId, AuthEnvironmentMaintainScope)+ )+ return;const identityKey = processIdentityKey(process);if (signalingKeysRef.current.has(identityKey)) return;const nextSignalingKeys = new Set(signalingKeysRef.current).add(identityKey);@@ -882,7 +897,10 @@ export function ResourceTelemetryDiagnostics({return;}}- if (environmentIdRef.current !== targetEnvironmentId) {+ if (+ environmentIdRef.current !== targetEnvironmentId ||+ !readEnvironmentScope(targetEnvironmentId, AuthEnvironmentMaintainScope)+ ) {clearSignaling();return;}@@ -924,6 +942,12 @@ export function ResourceTelemetryDiagnostics({);const retryCollector = useCallback(() => {+ const environmentId = environmentIdRef.current;+ if (+ environmentId === null ||+ !readEnvironmentScope(environmentId, AuthEnvironmentMaintainScope)+ )+ return;setIsRetrying(true);void retryTelemetry().catch((error: unknown) => {@@ -1253,6 +1277,7 @@ export function ResourceTelemetryDiagnostics({<div className="overflow-hidden rounded-2xl border border-border/70 bg-card shadow-xs/5"><ProcessTableprocesses={snapshot?.processes ?? []}+ canMaintainEnvironment={canMaintainEnvironment}signalingKeys={signalingKeys}onSignal={signalProcess}/>diff --git a/apps/web/src/components/settings/ScheduledTasksSettings.tsx b/apps/web/src/components/settings/ScheduledTasksSettings.tsxindex d82b6f16369..34c3896d87f 100644--- a/apps/web/src/components/settings/ScheduledTasksSettings.tsx+++ b/apps/web/src/components/settings/ScheduledTasksSettings.tsx@@ -59,6 +59,8 @@ import { EMPTY_SERVER_PROVIDERS, serverEnvironment } from "../../state/server";import { useAtomCommand } from "../../state/use-atom-command";import { WorktreeBaseBranchPicker } from "../WorktreeBaseBranchPicker";import { EnvironmentMachineIcon } from "../EnvironmentMachineIcon";+import { AuthOrchestrationOperateScope } from "@t3tools/contracts";+import { readEnvironmentScope } from "~/state/session";import { useSettingsScope } from "./SettingsScopeContext";import {WEBHOOK_SIGNATURE_DEFAULTS,@@ -246,6 +248,9 @@ export function ScheduledTasksSettings(target: {setEditor({ environmentId, task });}, []);const defaultEnvironment = environment ?? connectedEnvironments[0];+ const canCreate = useAtomValue(+ serverEnvironment.upsertScheduledTask.permissionAtom(defaultEnvironment?.environmentId ?? null),+ );return (<SettingsPageContainer><SettingsSection@@ -255,7 +260,7 @@ export function ScheduledTasksSettings(target: {<Buttonsize="xs"variant="ghost-muted"- disabled={!defaultEnvironment}+ disabled={!defaultEnvironment || !canCreate}onClick={() =>defaultEnvironment &&setEditor({ environmentId: defaultEnvironment.environmentId, task: null })@@ -404,6 +409,9 @@ function ScheduledTaskRow({readonly task: ScheduledTask;readonly onEdit: () => void;}) {+ const canOperate = useAtomValue(+ serverEnvironment.upsertScheduledTask.permissionAtom(environmentId),+ );const [busy, setBusy] = useState(false);const [deliveriesOpen, setDeliveriesOpen] = useState(false);const isWebhook = task.schedule.type === "webhook";@@ -417,7 +425,7 @@ function ScheduledTaskRow({label: "scheduled task delete",});const act = async (action: "toggle" | "run" | "delete") => {- if (busy) return;+ if (busy || !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) return;setBusy(true);const result =action === "toggle"@@ -462,7 +470,7 @@ function ScheduledTaskRow({<div className="flex items-center gap-2"><Switchchecked={task.enabled}- disabled={busy}+ disabled={busy || !canOperate}aria-label={`Enable ${task.title}`}onCheckedChange={() => void act("toggle")}/>@@ -472,7 +480,7 @@ function ScheduledTaskRow({<Buttonsize="icon-sm"variant="ghost"- disabled={busy}+ disabled={busy || !canOperate}aria-label={`Actions for ${task.title}`}/>}@@ -668,6 +676,9 @@ function WebhookEndpointField({readonly environmentId: EnvironmentId;readonly task: ScheduledTask | null;}) {+ const canRotate = useAtomValue(+ serverEnvironment.rotateScheduledTaskWebhookToken.permissionAtom(environmentId),+ );const httpBaseUrl = useEnvironmentHttpBaseUrl(environmentId);const { copyToClipboard, isCopied } = useCopyToClipboard({ target: "webhook URL" });const rotate = useAtomCommand(serverEnvironment.rotateScheduledTaskWebhookToken, {@@ -725,7 +736,7 @@ function WebhookEndpointField({size="sm"variant="outline"type="button"- disabled={rotating}+ disabled={rotating || !canRotate}onClick={() => void rotateUrl()}>Rotate@@ -787,6 +798,9 @@ function ScheduledTaskEditorDialog({const settings = useEnvironmentSettings(environmentId);const providers =useAtomValue(serverEnvironment.providersValueAtom(environmentId)) ?? EMPTY_SERVER_PROVIDERS;+ const canOperate = useAtomValue(+ serverEnvironment.upsertScheduledTask.permissionAtom(environmentId),+ );const upsertTask = useAtomCommand(serverEnvironment.upsertScheduledTask, {label: "scheduled task upsert",});@@ -840,6 +854,7 @@ function ScheduledTaskEditorDialog({const submit = async () => {if (+ !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope) ||submissionPending.current ||saving ||editingTaskMissing ||@@ -1348,7 +1363,7 @@ function ScheduledTaskEditorDialog({</DialogClose><Buttonsize="sm"- disabled={saving || editingTaskMissing || !connected || !tasksQuery.data}+ disabled={!canOperate || saving || editingTaskMissing || !connected || !tasksQuery.data}onClick={() => void submit()}>{draft.editingId ? "Save task" : "Create task"}diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsxindex 6e464e94d54..5e52b482789 100644--- a/apps/web/src/components/settings/SettingsPanels.tsx+++ b/apps/web/src/components/settings/SettingsPanels.tsx@@ -1,4 +1,5 @@import { SettingsGroup } from "./SettingsGroup";+import { useScopedSettingsWriteAllowed } from "./useScopedSettings";import { Spinner } from "~/components/ui/spinner";import { NotificationSettings } from "./NotificationSettings";import { PRIVACY_POLICY_URL } from "../../legalLinks";@@ -876,6 +877,7 @@ function BackgroundActivityAdvancedDialog({readonly open: boolean;readonly onOpenChange: (open: boolean) => void;}) {+ const canWriteSettings = useScopedSettingsWriteAllowed();const settings = useScopedSettings();const updateSettings = useUpdateScopedSettings();const resolvedBackgroundActivity = resolveServerBackgroundActivitySettings(settings);@@ -894,7 +896,7 @@ function BackgroundActivityAdvancedDialog({);return (- <Dialog open={open} onOpenChange={onOpenChange}>+ <Dialog open={open && canWriteSettings} onOpenChange={onOpenChange}><DialogPopup className="max-w-xl"><DialogHeader><DialogTitle>Background Activity</DialogTitle>@@ -903,7 +905,10 @@ function BackgroundActivityAdvancedDialog({</DialogDescription></DialogHeader><DialogPanel>- <div className="overflow-hidden rounded-xl border bg-card text-card-foreground">+ <fieldset+ disabled={!canWriteSettings}+ className="min-w-0 overflow-hidden rounded-xl border bg-card text-card-foreground"+ ><div className="flex flex-col gap-3 border-b px-4 py-3 sm:flex-row sm:items-center sm:justify-between"><div className="min-w-0 space-y-1"><div className="text-sm font-medium">Shared policy</div>@@ -1125,11 +1130,12 @@ function BackgroundActivityAdvancedDialog({</label>))}</div>- </div>+ </fieldset></DialogPanel><DialogFooter><Buttonvariant="outline"+ disabled={!canWriteSettings}onClick={() => updateSettings(resetBackgroundActivitySettings())}>Reset alldiff --git a/apps/web/src/components/settings/SnapShotSettings.test.tsx b/apps/web/src/components/settings/SnapShotSettings.test.tsxindex b8f5bed9979..a950e051172 100644--- a/apps/web/src/components/settings/SnapShotSettings.test.tsx+++ b/apps/web/src/components/settings/SnapShotSettings.test.tsx@@ -25,6 +25,10 @@ vi.mock("react/compiler-runtime", async () => {return { c: reactHookHarness.useMemoCache };});vi.mock("@effect/atom-react", () => ({ useAtomValue: () => [] }));+vi.mock("../../state/environments", () => ({+ usePrimaryEnvironmentId: () => null,+ useEnvironments: () => [],+}));vi.mock("../../state/server", () => ({ primaryServerKeybindingsAtom: {} }));vi.mock("./SettingsScopeContext", () => ({ useOptionalSettingsScope: () => null }));vi.mock("./SettingsScopeSentence", () => ({ SettingsScopeSentence: () => null }));diff --git a/apps/web/src/components/settings/settingsLayout.tsx b/apps/web/src/components/settings/settingsLayout.tsxindex 0794553cb8f..c455792eb94 100644--- a/apps/web/src/components/settings/settingsLayout.tsx+++ b/apps/web/src/components/settings/settingsLayout.tsx@@ -1,4 +1,7 @@import { SettingsGroup } from "./SettingsGroup";+import { AuthSettingsWriteScope } from "@t3tools/contracts";+import { usePrimaryEnvironmentId } from "../../state/environments";+import { useEnvironmentScope, useEnvironmentsWithScope } from "../../state/session";import { InfoIcon, Undo2Icon } from "lucide-react";import { DEFAULT_SERVER_SETTINGS, type ServerSettings } from "@t3tools/contracts";import * as Equal from "effect/Equal";@@ -27,6 +30,7 @@ import { SettingsScopeSentence } from "./SettingsScopeSentence";import {isProjectScopedSettingKey,listProjectOverrides,+ type ProjectOverrideEntry,scopedSettingsAreMixed,scopedSettingsSource,} from "./scopedSettings";@@ -281,6 +285,16 @@ export function SettingsRow({const targetRef = useSettingsSearchTarget<HTMLDivElement>(rowProps.id);const primarySettingsAvailable = usePrimarySettingsAvailable();const context = useOptionalSettingsScope();+ const primaryEnvironmentId = usePrimaryEnvironmentId();+ const primaryCanWrite = useEnvironmentScope(primaryEnvironmentId, AuthSettingsWriteScope);+ const writableIds = useEnvironmentsWithScope(+ context?.connectedEnvironments ?? [],+ AuthSettingsWriteScope,+ );+ const canWriteSettings = context+ ? context.connectedEnvironments.length > 0 &&+ context.connectedEnvironments.every((target) => writableIds.has(target.environmentId))+ : primaryCanWrite;const clearOverrides = useClearScopedSettings();const clearProjectOverrides = useClearProjectOverrides();const isProjectScope =@@ -295,7 +309,8 @@ export function SettingsRow({context && isProjectScope ? scopedSettingsSource(context.targets, scopedKeys) : null;const unavailable =serverScoped &&- !(context ? context.connectedEnvironments.length > 0 : primarySettingsAvailable);+ (!canWriteSettings ||+ !(context ? context.connectedEnvironments.length > 0 : primarySettingsAvailable));const inheritedFrom =source === "environment" && context?.scope.environmentIds.length === 1? (context.environments.find(@@ -375,9 +390,11 @@ export function SettingsRow({const renderedControl =unavailable && control? inertControl(- context- ? "Reconnect the selected environment to change this setting."- : PRIMARY_SETTINGS_UNAVAILABLE_MESSAGE,+ !canWriteSettings+ ? "This connection does not have permission to change environment settings."+ : context+ ? "Reconnect the selected environment to change this setting."+ : PRIMARY_SETTINGS_UNAVAILABLE_MESSAGE,): environmentWide && control? inertControl("Environment-wide setting. Select an environment to change it.")@@ -415,7 +432,12 @@ export function SettingsRow({environments={context.connectedEnvironments}keys={settingKeys}overridingProjects={overridingProjects}- onClearOverrides={(entries) => clearProjectOverrides(entries, scopedKeys)}+ {...(canWriteSettings+ ? {+ onClearOverrides: (entries: readonly ProjectOverrideEntry[]) =>+ clearProjectOverrides(entries, scopedKeys),+ }+ : {})}/>) : null;const renderedStatus = status;diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.tsindex 0007fa68a13..81b2d1248f1 100644--- a/apps/web/src/components/settings/settingsSearch.ts+++ b/apps/web/src/components/settings/settingsSearch.ts@@ -813,7 +813,6 @@ export const SETTINGS_SEARCH_ITEMS = [to: "/settings/connections",targetId: "connections-environment",searchTerms: ["machine glyph sidebar mac mini studio laptop desktop server cloud vm"],- localBackendManagementOnly: true,},{id: "local-environment",diff --git a/apps/web/src/components/settings/useAvailableSettingsSearchItems.ts b/apps/web/src/components/settings/useAvailableSettingsSearchItems.tsindex 3820357e59f..3c248de1c01 100644--- a/apps/web/src/components/settings/useAvailableSettingsSearchItems.ts+++ b/apps/web/src/components/settings/useAvailableSettingsSearchItems.ts@@ -1,14 +1,14 @@import { useMemo } from "react";-import { AuthAccessWriteScope } from "@t3tools/contracts";+import { AuthEnvironmentMaintainScope } from "@t3tools/contracts";import { usePrimaryCloudLinkState } from "~/cloud/primaryCloudLinkState";import { hasCloudPublicConfig } from "~/cloud/publicConfig";import { isElectron } from "~/env";import { isLocalEnvironmentDisabled } from "~/localEnvironment";import { desktopWslStateAtom } from "~/state/desktopWslState";-import { useEnvironments } from "~/state/environments";+import { useEnvironments, usePrimaryEnvironmentId } from "~/state/environments";import { useEnvironmentQuery } from "~/state/query";-import { usePrimarySessionState } from "~/environments/primary";+import { useEnvironmentScope } from "~/state/session";import { isWslSettingsRowVisible } from "./ConnectionsSettings.logic";import { isProviderSettingsEnvironmentAvailable } from "./ProviderSettingsPanel.logic";import type { SettingsScopeSearch } from "./settingsScope";@@ -19,21 +19,17 @@ import {export function useAvailableSettingsSearchItems(scopeSearch: SettingsScopeSearch = {}) {const { environments } = useEnvironments();- const primarySessionState = usePrimarySessionState();+ const primaryEnvironmentId = usePrimaryEnvironmentId();const localEnvironmentDisabled = isLocalEnvironmentDisabled();+ const canMaintain = useEnvironmentScope(primaryEnvironmentId, AuthEnvironmentMaintainScope);+ const canManageLocalBackend = !localEnvironmentDisabled && canMaintain;const desktopWsl = useEnvironmentQuery(- isElectron && !localEnvironmentDisabled ? desktopWslStateAtom : null,+ isElectron && canManageLocalBackend ? desktopWslStateAtom : null,);const cloudLinkState = usePrimaryCloudLinkState().data;// Same fallback as the Connections row: older servers imply a tunnel from `linked`.const managedTunnelActive =cloudLinkState?.managedTunnelActive ?? cloudLinkState?.linked ?? false;- const canManageLocalBackend =- !localEnvironmentDisabled &&- (isElectron ||- ((primarySessionState.data?.authenticated &&- primarySessionState.data.scopes?.includes(AuthAccessWriteScope)) ??- false));return useMemo(() =>diff --git a/apps/web/src/components/settings/useHostConnectionChecks.ts b/apps/web/src/components/settings/useHostConnectionChecks.tsindex 7d642fa62a6..f0129e4b693 100644--- a/apps/web/src/components/settings/useHostConnectionChecks.ts+++ b/apps/web/src/components/settings/useHostConnectionChecks.ts@@ -1,3 +1,5 @@+import { AuthSettingsWriteScope } from "@t3tools/contracts";+import { readEnvironmentScope } from "../../state/session";import { useRef, useState } from "react";import * as Cause from "effect/Cause";import type { SshDeviceHostConfig } from "@t3tools/contracts";@@ -25,6 +27,9 @@ export function useHostConnectionChecks(targets: ReadonlyArray<DeviceHostCheckTatargets,host,async (environmentId, input) => {+ if (!readEnvironmentScope(environmentId, AuthSettingsWriteScope)) {+ throw new Error("This connection cannot test device hosts.");+ }const result = await test({ environmentId, input });if (result._tag === "Failure") throw new Error(Cause.pretty(result.cause));return result.value;diff --git a/apps/web/src/components/settings/useProjectScriptSettings.ts b/apps/web/src/components/settings/useProjectScriptSettings.tsindex 626496aa9a8..ee10913dc14 100644--- a/apps/web/src/components/settings/useProjectScriptSettings.ts+++ b/apps/web/src/components/settings/useProjectScriptSettings.ts@@ -1,3 +1,5 @@+import { AuthSettingsWriteScope, EnvironmentAuthorizationError } from "@t3tools/contracts";+import { readEnvironmentScope } from "../../state/session";import {isAtomCommandInterrupted,mapAtomCommandResult,@@ -80,6 +82,22 @@ export function useProjectScriptSettings(toastManager.add({ type: "error", title: "Actions not saved", description: message });return AsyncResult.failure(Cause.fail(new Error(message)));}+ if (+ targets.some(+ ({ environmentId }) => !readEnvironmentScope(environmentId, AuthSettingsWriteScope),+ )+ ) {+ return reportScriptFailure(+ AsyncResult.failure(+ Cause.fail(+ new EnvironmentAuthorizationError({+ requiredScope: AuthSettingsWriteScope,+ message: "This connection cannot change environment settings.",+ }),+ ),+ ),+ );+ }savingRef.current = true;setSaving(true);try {diff --git a/apps/web/src/components/settings/useScopedSettings.ts b/apps/web/src/components/settings/useScopedSettings.tsindex ddf6b60b9aa..743eb4ec439 100644--- a/apps/web/src/components/settings/useScopedSettings.ts+++ b/apps/web/src/components/settings/useScopedSettings.ts@@ -1,3 +1,12 @@+import { AuthSettingsWriteScope } from "@t3tools/contracts";+import { useEnvironmentsWithScope } from "../../state/session";+import {+ requiredScopesForServerSettingsPatch,+ EnvironmentAuthorizationError,+} from "@t3tools/contracts";+import { readEnvironmentScope } from "../../state/session";+import * as Cause from "effect/Cause";+import { AsyncResult } from "effect/reactivity";import {DEFAULT_SERVER_SETTINGS,type ProjectScopedServerSettingKey,@@ -63,19 +72,33 @@ function useRunScopedPlan() {});return;}- void persistScopedSettingsPatch(plan, persistServer, persistClientSettingsPatch).then(- ({ failedEnvironments, savedEnvironmentCount }) => {- if (failedEnvironments.length === 0) return;- toastManager.add({- type: "error",- title:- savedEnvironmentCount > 0- ? "Setting saved on some environments"- : "Setting not saved",- description: `Could not update ${failedEnvironments.map((environment) => environment.label).join(", ")}.${savedEnvironmentCount > 0 ? " The other selected environments saved the change." : ""}`,- });+ void persistScopedSettingsPatch(+ plan,+ async (request) => {+ const missing = requiredScopesForServerSettingsPatch(request.input.patch).find(+ (scope) => !readEnvironmentScope(request.environmentId, scope),+ );+ if (missing)+ return AsyncResult.failure(+ Cause.fail(+ new EnvironmentAuthorizationError({+ requiredScope: missing,+ message: "This connection cannot change these settings.",+ }),+ ),+ );+ return persistServer(request);},- );+ persistClientSettingsPatch,+ ).then(({ failedEnvironments, savedEnvironmentCount }) => {+ if (failedEnvironments.length === 0) return;+ toastManager.add({+ type: "error",+ title:+ savedEnvironmentCount > 0 ? "Setting saved on some environments" : "Setting not saved",+ description: `Could not update ${failedEnvironments.map((environment) => environment.label).join(", ")}.${savedEnvironmentCount > 0 ? " The other selected environments saved the change." : ""}`,+ });+ });},[persistServer],);@@ -119,3 +142,12 @@ export function useClearProjectOverrides() {[context, run],);}++export function useScopedSettingsWriteAllowed() {+ const { connectedEnvironments } = useSettingsScope();+ const writable = useEnvironmentsWithScope(connectedEnvironments, AuthSettingsWriteScope);+ return (+ connectedEnvironments.length > 0 &&+ connectedEnvironments.every((target) => writable.has(target.environmentId))+ );+}diff --git a/apps/web/src/components/usage/UsageLimits.tsx b/apps/web/src/components/usage/UsageLimits.tsxindex 585bd6ccf10..a031cd0d156 100644--- a/apps/web/src/components/usage/UsageLimits.tsx+++ b/apps/web/src/components/usage/UsageLimits.tsx@@ -1,4 +1,5 @@import {+ AuthProvidersManageScope,type EnvironmentId,type ProviderConsumeResetCreditOutcome,ProviderConsumeResetCreditInput,@@ -21,6 +22,7 @@ import { Fragment, type ReactNode, useState } from "react";import { usePrimarySettings } from "../../hooks/useSettings";import { environmentPresentations } from "../../state/presentation";+import { useEnvironmentScope, readEnvironmentScope } from "../../state/session";import { serverEnvironment } from "../../state/server";import { useAtomCommand } from "../../state/use-atom-command";import { formatUpcomingTimestamp } from "../../timestampFormat";@@ -206,6 +208,7 @@ export function useResetCredit(environmentId: EnvironmentId,input: ProviderConsumeResetCreditInput,) {+ const canManageProviders = useEnvironmentScope(environmentId, AuthProvidersManageScope);const consume = useAtomCommand(serverEnvironment.consumeResetCredit, { reportFailure: false });const [confirming, setConfirming] = useState(false);const [busy, setBusy] = useState(false);@@ -213,6 +216,7 @@ export function useResetCredit(const redeem = async () => {setConfirming(false);+ if (!readEnvironmentScope(environmentId, AuthProvidersManageScope)) return;setBusy(true);setStatus(null);const result = await consume({ environmentId, input });@@ -228,7 +232,7 @@ export function useResetCredit();};- return { confirming, setConfirming, busy, status, redeem };+ return { canManageProviders, confirming, setConfirming, busy, status, redeem };}/**@@ -241,10 +245,12 @@ export function ResetCreditDialog({open,onOpenChange,onConfirm,+ disabled = false,}: {readonly open: boolean;readonly onOpenChange: (open: boolean) => void;readonly onConfirm: () => void;+ readonly disabled?: boolean;}) {return (<AlertDialog open={open} onOpenChange={onOpenChange}>@@ -258,7 +264,9 @@ export function ResetCreditDialog({</AlertDialogHeader><AlertDialogFooter><AlertDialogClose render={<Button variant="outline" />}>Cancel</AlertDialogClose>- <Button onClick={onConfirm}>Use credit</Button>+ <Button disabled={disabled} onClick={onConfirm}>+ Use credit+ </Button></AlertDialogFooter></AlertDialogPopup></AlertDialog>@@ -294,13 +302,23 @@ export function ResetCredits({readonly credits: ServerProviderResetCredits;readonly now: number;}) {- const { confirming, setConfirming, busy, status, redeem } = useResetCredit(environmentId, input);+ const { canManageProviders, confirming, setConfirming, busy, status, redeem } = useResetCredit(+ environmentId,+ input,+ );if (credits.availableCount === 0 && status === null) return null;return (<div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-muted-foreground"><span className="tabular-nums">{resetCreditsSummary(credits, now)}</span>{credits.availableCount > 0 ? (- <Button size="xs" variant="outline" disabled={busy} onClick={() => setConfirming(true)}>+ <Button+ size="xs"+ variant="outline"+ disabled={busy || !canManageProviders}+ onClick={() => {+ if (readEnvironmentScope(environmentId, AuthProvidersManageScope)) setConfirming(true);+ }}+ >{busy ? "Using…" : "Use reset"}</Button>) : null}@@ -309,6 +327,7 @@ export function ResetCredits({open={confirming}onOpenChange={setConfirming}onConfirm={() => void redeem()}+ disabled={!canManageProviders}/></div>);diff --git a/apps/web/src/components/usage/UsageLimitsPooled.tsx b/apps/web/src/components/usage/UsageLimitsPooled.tsxindex d99ce30b475..9ebe499179b 100644--- a/apps/web/src/components/usage/UsageLimitsPooled.tsx+++ b/apps/web/src/components/usage/UsageLimitsPooled.tsx@@ -204,7 +204,7 @@ function SegmentPopover({<Buttonsize="xs"variant="outline"- disabled={redeem.busy}+ disabled={redeem.busy || !redeem.canManageProviders}className="ms-auto"onClick={onRedeem}>@@ -429,6 +429,7 @@ function RedeemableSegmentPopup({open={redeem.confirming}onOpenChange={redeem.setConfirming}onConfirm={() => void redeem.redeem()}+ disabled={!redeem.canManageProviders}/>{/* The popover closed before the confirm, so the outcome needs a home outside it. */}{redeem.status ? (diff --git a/apps/web/src/components/usage/UsagePriceOverrides.tsx b/apps/web/src/components/usage/UsagePriceOverrides.tsxindex 125c7eaf0f4..50d0953ce84 100644--- a/apps/web/src/components/usage/UsagePriceOverrides.tsx+++ b/apps/web/src/components/usage/UsagePriceOverrides.tsx@@ -1,21 +1,16 @@import { useAtomValue } from "@effect/atom-react";-import type { EnvironmentId } from "@t3tools/contracts";+import { AuthSettingsWriteScope, type EnvironmentId } from "@t3tools/contracts";import { ChevronDownIcon, PlusIcon, RotateCcwIcon, XIcon } from "lucide-react";import * as Option from "effect/Option";import { AsyncResult, Atom } from "effect/reactivity";import { useRef, useState } from "react";-import { isElectron } from "../../env";import { cn } from "../../lib/utils";import { environmentPresentations } from "../../state/presentation";import { serverEnvironment } from "../../state/server";-import { environmentSession } from "../../state/session";+import { environmentSession, readEnvironmentScope } from "../../state/session";import { useAtomCommand } from "../../state/use-atom-command";import type { EnvironmentUsageStatus } from "../../state/usage";-import {- resolvePrimaryOperateAccess,- resolveRemoteOperateAccess,-} from "../settings/ProviderSettingsPanel.logic";import { Button } from "../ui/button";import {Dialog,@@ -51,15 +46,17 @@ const priceTargetsAtom = Atom.make((get): readonly UsagePriceTarget[] =>[...get(environmentPresentations.presentationsAtom)].map(([environmentId, environment]) => {const settings = get(serverEnvironment.settingsValueAtom(environmentId));const session = get(environmentSession.sessionStateAtom(environmentId));- const sessionAccess = {- session: Option.getOrNull(AsyncResult.value(session)),- isPending: session.waiting,- hasError: session._tag === "Failure",- };- const isPrimary = environment.entry.target._tag === "PrimaryConnectionTarget";- const access = isPrimary- ? resolvePrimaryOperateAccess({ ...sessionAccess, isPrimary, hasDesktopBridge: isElectron })- : resolveRemoteOperateAccess(sessionAccess);+ const sessionData = Option.getOrNull(AsyncResult.value(session));+ const access =+ session._tag === "Failure"+ ? "denied"+ : sessionData === null+ ? session.waiting+ ? "pending"+ : "denied"+ : sessionData.authenticated && sessionData.scopes?.includes(AuthSettingsWriteScope)+ ? "granted"+ : "denied";return {environmentId,label: environment.entry.target.label,@@ -262,7 +259,10 @@ export function UsagePriceOverrides({target.unavailable ?? [...changes.get(target.environmentId)!.errors.values()][0] ?? null,})),changes: new Map([...changes].map(([id, plan]) => [id, plan.changes])),- write: updateSettings,+ write: async (input) =>+ readEnvironmentScope(input.environmentId, AuthSettingsWriteScope)+ ? updateSettings(input)+ : { _tag: "Failure" },onResult: (environmentId, result) => {if (result.status === "failed") failed = true;setAttempt((previous) =>diff --git a/apps/web/src/editorPreferences.test.ts b/apps/web/src/editorPreferences.test.tsnew file mode 100644index 00000000000..2c23af4b4ff--- /dev/null+++ b/apps/web/src/editorPreferences.test.ts@@ -0,0 +1,88 @@+import {+ AuthOrchestrationOperateScope,+ EnvironmentAuthorizationError,+ EnvironmentId,+} from "@t3tools/contracts";+import * as Cause from "effect/Cause";+import { AsyncResult } from "effect/reactivity";+import { assert, beforeEach, expect, it, vi } from "vite-plus/test";++const state = vi.hoisted(() => ({+ allowed: new Set<string>(),+ run: vi.fn(),+ getPreference: vi.fn(),+ setPreference: vi.fn(),+}));++vi.mock("react", () => ({ useCallback: (callback: unknown) => callback }));+vi.mock("./state/shell", () => ({ shellEnvironment: { openInEditor: "openInEditor" } }));+vi.mock("./state/use-atom-command", () => ({ useAtomCommand: () => state.run }));+vi.mock("./state/session", () => ({+ readEnvironmentScope: (environmentId: string, scope: string) =>+ scope === AuthOrchestrationOperateScope && state.allowed.has(environmentId),+}));+vi.mock("./hooks/useLocalStorage", () => ({+ getLocalStorageItem: state.getPreference,+ setLocalStorageItem: state.setPreference,+ useLocalStorage: vi.fn(),+}));++import { useOpenInPreferredEditor } from "./editorPreferences";++const primary = EnvironmentId.make("primary");+const secondary = EnvironmentId.make("secondary");++beforeEach(() => {+ state.allowed.clear();+ state.run.mockReset().mockResolvedValue(AsyncResult.success(undefined));+ state.getPreference.mockReset().mockReturnValue(null);+ state.setPreference.mockReset();+});++it("does not use another environment's grant or change preferences when denied", async () => {+ state.allowed.add(primary);+ const open = useOpenInPreferredEditor(secondary, ["vscode"]);+ const result = await open("/work/readme.md");+ assert(result._tag === "Failure");+ const error = Cause.squash(result.cause);+ expect(error).toBeInstanceOf(EnvironmentAuthorizationError);+ expect(error).toMatchObject({ requiredScope: AuthOrchestrationOperateScope });+ expect(state.run).not.toHaveBeenCalled();+ expect(state.getPreference).not.toHaveBeenCalled();+ expect(state.setPreference).not.toHaveBeenCalled();+});++it("checks revocation and regrant when a retained editor callback is invoked", async () => {+ state.allowed.add(secondary);+ const open = useOpenInPreferredEditor(secondary, ["vscode"]);+ state.allowed.delete(secondary);+ expect((await open("/work/readme.md:5"))._tag).toBe("Failure");+ expect(state.run).not.toHaveBeenCalled();++ state.allowed.add(secondary);+ expect(await open("/work/readme.md:5")).toMatchObject({ _tag: "Success", value: "vscode" });+ expect(state.run).toHaveBeenCalledExactlyOnceWith({+ environmentId: secondary,+ input: { cwd: "/work/readme.md:5", editor: "vscode" },+ });+ expect(state.setPreference).toHaveBeenCalledTimes(1);+});++it("keeps the stored available editor for an authorized launch", async () => {+ state.allowed.add(secondary);+ state.getPreference.mockReturnValue("cursor");+ const open = useOpenInPreferredEditor(secondary, ["vscode", "cursor"]);+ expect(await open("/work")).toMatchObject({ _tag: "Success", value: "cursor" });+ expect(state.run).toHaveBeenCalledExactlyOnceWith({+ environmentId: secondary,+ input: { cwd: "/work", editor: "cursor" },+ });+ expect(state.setPreference).not.toHaveBeenCalled();+});++it("returns the existing failures for a missing environment or editor", async () => {+ state.allowed.add(secondary);+ expect((await useOpenInPreferredEditor(null, ["vscode"])("/work"))._tag).toBe("Failure");+ expect((await useOpenInPreferredEditor(secondary, [])("/work"))._tag).toBe("Failure");+ expect(state.run).not.toHaveBeenCalled();+});diff --git a/apps/web/src/editorPreferences.ts b/apps/web/src/editorPreferences.tsindex 5903f122c3f..2451aad2d5d 100644--- a/apps/web/src/editorPreferences.ts+++ b/apps/web/src/editorPreferences.ts@@ -1,4 +1,10 @@-import { EDITORS, EditorId, EnvironmentId } from "@t3tools/contracts";+import {+ AuthOrchestrationOperateScope,+ EDITORS,+ EditorId,+ EnvironmentAuthorizationError,+ EnvironmentId,+} from "@t3tools/contracts";import {mapAtomCommandResult,type AtomCommandFailure,@@ -11,6 +17,7 @@ import { getLocalStorageItem, setLocalStorageItem, useLocalStorage } from "./hooimport { useCallback, useMemo } from "react";import { shellEnvironment } from "./state/shell";import { useAtomCommand } from "./state/use-atom-command";+import { readEnvironmentScope } from "./state/session";const LAST_EDITOR_KEY = "t3code:last-editor";@@ -49,9 +56,7 @@ export function usePreferredEditor(availableEditors: ReadonlyArray<EditorId>) {return [effectiveEditor, setLastEditor] as const;}-export function resolveAndPersistPreferredEditor(- availableEditors: readonly EditorId[],-): EditorId | null {+function resolveAndPersistPreferredEditor(availableEditors: readonly EditorId[]): EditorId | null {const availableEditorIds = new Set(availableEditors);const stored = getLocalStorageItem(LAST_EDITOR_KEY, EditorId);if (stored && availableEditorIds.has(stored)) return stored;@@ -78,6 +83,7 @@ export function useOpenInPreferredEditor(| OpenInEditorError| PreferredEditorEnvironmentRequiredError| PreferredEditorUnavailableError+ | EnvironmentAuthorizationError>> => {if (environmentId === null) {@@ -89,6 +95,16 @@ export function useOpenInPreferredEditor(),);}+ if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) {+ return AsyncResult.failure(+ Cause.fail(+ new EnvironmentAuthorizationError({+ requiredScope: AuthOrchestrationOperateScope,+ message: "This connection cannot open an editor on this environment.",+ }),+ ),+ );+ }const editor = resolveAndPersistPreferredEditor(availableEditors);if (!editor) {return AsyncResult.failure(diff --git a/apps/web/src/hooks/useSettings.sync.test.tsx b/apps/web/src/hooks/useSettings.sync.test.tsxnew file mode 100644index 00000000000..fd46cd8962d--- /dev/null+++ b/apps/web/src/hooks/useSettings.sync.test.tsx@@ -0,0 +1,201 @@+import { RegistryContext } from "@effect/atom-react";+import {+ AuthSettingsWriteScope,+ DEFAULT_SERVER_SETTINGS,+ EnvironmentId,+ type AuthEnvironmentScope,+ type AuthSessionState,+ type ServerSettingsPatch,+} from "@t3tools/contracts";+import * as Cause from "effect/Cause";+import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";+import { act } from "react";+import { create, type ReactTestRenderer } from "react-test-renderer";+import { afterEach, beforeEach, describe, 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>>(),+ environments: [] as Array<{+ environmentId: EnvironmentId;+ label: string;+ connection: { phase: "connected" | "disconnected" };+ serverConfig: {+ environment: { capabilities: { threadAutoSettlement: boolean } };+ settings: typeof DEFAULT_SERVER_SETTINGS;+ };+ }>,+ persist: 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/environments", () => ({+ useEnvironments: () => ({ environments: state.environments }),+ usePrimaryEnvironment: () =>+ state.environments.find((environment) => environment.environmentId === primaryId) ?? null,+}));+vi.mock("~/state/server", () => ({+ serverEnvironment: { updateSettings: Symbol("updateSettings") },+ primaryServerSettingsAtom: undefined,+}));+vi.mock("~/state/use-atom-command", () => ({ useAtomCommand: () => state.persist }));+vi.mock("~/components/ui/toast", () => ({ toastManager: { add: state.toast } }));+vi.mock("~/themePalette", () => ({}));+vi.mock("./useTheme", () => ({}));++import { useUpdatePrimarySettings } from "./useSettings";++const primaryId = EnvironmentId.make("primary");+const remoteId = EnvironmentId.make("remote");+const patch = { sidebarAutoSettleOnMerge: false } satisfies ServerSettingsPatch;+const session = (scopes: ReadonlyArray<AuthEnvironmentScope>): AuthSessionState => ({+ authenticated: true,+ scopes,+ auth: {+ policy: "remote-reachable",+ bootstrapMethods: ["one-time-token"],+ sessionMethods: ["bearer-access-token"],+ sessionCookieName: "t3_session",+ },+});+let renderer: ReactTestRenderer | undefined;++function SettingsEditor() {+ const updateSettings = useUpdatePrimarySettings();+ return <button onClick={() => updateSettings(patch)}>Save shared setting</button>;+}++function saveSharedSettings() {+ renderer!.root.findByType("button").props.onClick();+}++async function mountEditor() {+ await act(() => {+ renderer = create(+ <RegistryContext.Provider value={state.registry!}>+ <SettingsEditor />+ </RegistryContext.Provider>,+ );+ });+}++beforeEach(() => {+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+ state.registry = AtomRegistry.make();+ state.sessions.clear();+ state.sessions.set(+ primaryId,+ Atom.make<SessionResult>(AsyncResult.success(session([AuthSettingsWriteScope]))),+ );+ state.sessions.set(remoteId, Atom.make<SessionResult>(AsyncResult.initial()));+ state.environments = [primaryId, remoteId].map((environmentId) => ({+ environmentId,+ label: environmentId,+ connection: { phase: "connected" },+ serverConfig: {+ environment: { capabilities: { threadAutoSettlement: true } },+ settings: DEFAULT_SERVER_SETTINGS,+ },+ }));+ state.persist.mockReset();+ state.persist.mockResolvedValue(AsyncResult.success(DEFAULT_SERVER_SETTINGS));+ state.toast.mockReset();+});++afterEach(async () => {+ await act(() => renderer?.unmount());+ renderer = undefined;+ state.registry?.dispose();+ vi.unstubAllGlobals();+});++describe("shared settings writes", () => {+ it("dispatches to the primary and connected remote before the remote grant finishes loading", async () => {+ await mountEditor();+ saveSharedSettings();++ expect(state.persist.mock.calls).toEqual([+ [{ environmentId: primaryId, input: { patch } }],+ [{ environmentId: remoteId, input: { patch } }],+ ]);+ expect(state.registry!.get(state.sessions.get(remoteId)!)).toMatchObject({ _tag: "Initial" });+ });++ it.each([+ ["denied", () => AsyncResult.success(session([]))],+ ["denied while refreshing", () => AsyncResult.waiting(AsyncResult.success(session([])))],+ [+ "failed",+ () => AsyncResult.failure<AuthSessionState, Error>(Cause.fail(new Error("session rejected"))),+ ],+ ] as const)("skips a remote whose grant is %s", async (_label, result) => {+ state.registry!.set(state.sessions.get(remoteId)!, result());+ await mountEditor();+ saveSharedSettings();++ expect(state.persist).toHaveBeenCalledExactlyOnceWith({+ environmentId: primaryId,+ input: { patch },+ });+ });++ it.each(["disconnected", "unsupported"] as const)(+ "skips a %s remote even with a cold grant",+ async (condition) => {+ const remote = state.environments[1]!;+ if (condition === "disconnected") remote.connection.phase = "disconnected";+ else remote.serverConfig.environment.capabilities.threadAutoSettlement = false;+ await mountEditor();+ saveSharedSettings();++ expect(state.persist).toHaveBeenCalledExactlyOnceWith({+ environmentId: primaryId,+ input: { patch },+ });+ },+ );++ it.each(["primary", "hosted"] as const)(+ "rechecks a cold remote grant that resolves to denied after the %s handler renders",+ async (mode) => {+ if (mode === "hosted") {+ state.environments = state.environments.filter(+ (environment) => environment.environmentId !== primaryId,+ );+ }+ await mountEditor();+ const previousUpdate = renderer!.root.findByType("button").props.onClick as () => void;+ await act(() => {+ state.registry!.set(state.sessions.get(remoteId)!, AsyncResult.success(session([])));+ });+ previousUpdate();++ if (mode === "primary") {+ expect(state.persist).toHaveBeenCalledExactlyOnceWith({+ environmentId: primaryId,+ input: { patch },+ });+ expect(state.toast).not.toHaveBeenCalled();+ } else {+ expect(state.persist).not.toHaveBeenCalled();+ expect(state.toast).toHaveBeenCalledExactlyOnceWith({+ type: "warning",+ title: "Setting not saved",+ description: "This connection does not have permission to change these settings.",+ });+ }+ },+ );+});diff --git a/apps/web/src/hooks/useSettings.ts b/apps/web/src/hooks/useSettings.tsindex 5448873ce40..2e089668ccc 100644--- a/apps/web/src/hooks/useSettings.ts+++ b/apps/web/src/hooks/useSettings.ts@@ -13,6 +13,8 @@ import { useCallback, useMemo, useSyncExternalStore } from "react";import { useAtomValue } from "@effect/atom-react";import {DEFAULT_SERVER_SETTINGS,+ AuthSettingsWriteScope,+ requiredScopesForServerSettingsPatch,type EnvironmentId,type ProviderInstanceMutation,ServerSettings,@@ -40,12 +42,16 @@ import {themeAllowsSidebarArtwork,} from "~/themePalette";import * as Struct from "effect/Struct";+import * as Option from "effect/Option";+import { AsyncResult, Atom } from "effect/reactivity";import { toastManager } from "~/components/ui/toast";import { isHostedStaticApp } from "~/hostedPairing";import { primaryServerSettingsAtom, serverEnvironment } from "~/state/server";import { useEnvironments, usePrimaryEnvironment } from "~/state/environments";import { useAtomCommand } from "~/state/use-atom-command";import { useTheme } from "./useTheme";+import { environmentSession, readEnvironmentScope, useEnvironmentScope } from "~/state/session";+import { appAtomRegistry } from "~/rpc/atomRegistry";const CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE = "[CLIENT_SETTINGS]";@@ -425,6 +431,31 @@ export function usePrimarySettingsAvailable(): boolean {return primaryEnvironment !== null || !isHostedStaticApp();}+/** Connected sync targets, excluding grants already known to forbid settings writes. */+function useSharedSettingsSyncTargetIds(includePending = false): ReadonlyArray<EnvironmentId> {+ const { environments } = useEnvironments();+ const writableTargetsAtom = useMemo(+ () =>+ Atom.make((get) =>+ environments.filter(supportsSharedSettingsSync).flatMap((environment) => {+ const result = get(environmentSession.sessionStateAtom(environment.environmentId));+ // A cold grant must not drop a shared edit. The server authorizes the+ // write; mismatch suggestions still wait for a confirmed grant.+ if (includePending && result._tag === "Initial") {+ return [environment.environmentId];+ }+ const session =+ result._tag === "Failure" ? null : Option.getOrNull(AsyncResult.value(result));+ return session?.authenticated && session.scopes?.includes(AuthSettingsWriteScope)+ ? [environment.environmentId]+ : [];+ }),+ ),+ [environments, includePending],+ );+ return useAtomValue(writableTargetsAtom);+}+/*** Returns an updater that routes each key to the correct backing store.*@@ -435,16 +466,31 @@ export function usePrimarySettingsAvailable(): boolean {* through client persistence.*/function useUpdateSettingsTarget(environmentId: EnvironmentId | null) {+ // Mount this session even on pages without a visible permission-gated control.+ useEnvironmentScope(environmentId, AuthSettingsWriteScope);const persistServerSettings = useAtomCommand(serverEnvironment.updateSettings,"server settings update",);const { environments } = useEnvironments();+ const sharedSettingsSyncTargetIds = useSharedSettingsSyncTargetIds(true);const updateSettings = useCallback((patch: UnifiedSettingsPatch) => {const { serverPatch, clientPatch } = splitPatch(patch);- if (Object.keys(serverPatch).length > 0) {+ const canWriteServerPatch =+ environmentId === null ||+ requiredScopesForServerSettingsPatch(serverPatch).every((scope) =>+ readEnvironmentScope(environmentId, scope),+ );+ if (Object.keys(serverPatch).length > 0 && !canWriteServerPatch) {+ toastManager.add({+ type: "warning",+ title: "Setting not saved",+ description: "This connection does not have permission to change these settings.",+ });+ }+ if (Object.keys(serverPatch).length > 0 && canWriteServerPatch) {const { sharedPatch, localPatch } = splitSharedServerPatch(serverPatch);// Dropping the write silently leaves the control looking saved.const warnUnsaved = (description = PRIMARY_SETTINGS_UNAVAILABLE_MESSAGE) =>@@ -467,13 +513,12 @@ function useUpdateSettingsTarget(environmentId: EnvironmentId | null) {const sourceSettings = environments.find((target) => target.environmentId === environmentId,)?.serverConfig?.settings;- const targets = new Set(- environments.filter(supportsSharedSettingsSync).map((target) => target.environmentId),- );+ const targets = new Set(sharedSettingsSyncTargetIds);if (environmentId) {targets.add(environmentId);}let wroteToTarget = false;+ let permissionDenied = false;for (const targetId of targets) {const target = environments.find((candidate) => candidate.environmentId === targetId);const targetPatch = filterSharedServerPatch(@@ -484,6 +529,16 @@ function useUpdateSettingsTarget(environmentId: EnvironmentId | null) {targetId === environmentId,);if (Object.keys(targetPatch).length === 0) continue;+ const session = appAtomRegistry.get(environmentSession.sessionStateAtom(targetId));+ if (+ session._tag !== "Initial" &&+ !requiredScopesForServerSettingsPatch(sharedPatch).every((scope) =>+ readEnvironmentScope(targetId, scope),+ )+ ) {+ permissionDenied = true;+ continue;+ }wroteToTarget = true;void persistServerSettings({environmentId: targetId,@@ -492,7 +547,11 @@ function useUpdateSettingsTarget(environmentId: EnvironmentId | null) {}if (!wroteToTarget) {warnUnsaved(- targets.size > 0 ? "Update older servers to save this setting." : undefined,+ permissionDenied+ ? "This connection does not have permission to change these settings."+ : targets.size > 0+ ? "Update older servers to save this setting."+ : undefined,);}}@@ -501,7 +560,7 @@ function useUpdateSettingsTarget(environmentId: EnvironmentId | null) {void persistClientSettingsPatch(clientPatch);}},- [environmentId, environments, persistServerSettings],+ [environmentId, environments, persistServerSettings, sharedSettingsSyncTargetIds],);return updateSettings;diff --git a/apps/web/src/keybindings.test.ts b/apps/web/src/keybindings.test.tsindex 58199ddf628..811d9101cbc 100644--- a/apps/web/src/keybindings.test.ts+++ b/apps/web/src/keybindings.test.ts@@ -25,6 +25,7 @@ import {isTerminalSplitShortcut,isTerminalSplitVerticalShortcut,isTerminalToggleShortcut,+ resolveChatShortcutCommand,resolveShortcutCommand,shouldShowThreadJumpHintsForModifiers,shortcutLabelForCommand,@@ -886,6 +887,102 @@ describe("cross-command precedence", () => {});});+describe("resolveChatShortcutCommand", () => {+ it("runs the active environment's script shortcut instead of the primary environment's", () => {+ const primary = compile([{ shortcut: modShortcut("r"), command: "script.setup.run" }]);+ const active = compile([{ shortcut: modShortcut("t"), command: "script.setup.run" }]);++ assert.strictEqual(+ resolveChatShortcutCommand(event({ key: "t", ctrlKey: true }), primary, active, {+ platform: "Linux",+ }),+ "script.setup.run",+ );+ assert.isNull(+ resolveChatShortcutCommand(event({ key: "r", ctrlKey: true }), primary, active, {+ platform: "Linux",+ }),+ );+ });++ it("resolves shared chords to the active environment's script ID", () => {+ const primary = compile([{ shortcut: modShortcut("r"), command: "script.setup.run" }]);+ const active = compile([{ shortcut: modShortcut("r"), command: "script.deploy.run" }]);++ assert.strictEqual(+ resolveChatShortcutCommand(event({ key: "r", metaKey: true }), primary, active, {+ platform: "MacIntel",+ }),+ "script.deploy.run",+ );+ });++ it("does not run primary scripts before the active environment's bindings arrive", () => {+ const primary = compile([{ shortcut: modShortcut("r"), command: "script.setup.run" }]);++ assert.isNull(+ resolveChatShortcutCommand(event({ key: "r", ctrlKey: true }), primary, [], {+ platform: "Linux",+ }),+ );+ });++ it("keeps primary app commands ahead of conflicting active script shortcuts", () => {+ const primary = compile([{ shortcut: modShortcut("k"), command: "commandPalette.toggle" }]);+ const active = compile([{ shortcut: modShortcut("k"), command: "script.setup.run" }]);++ assert.strictEqual(+ resolveChatShortcutCommand(event({ key: "k", ctrlKey: true }), primary, active, {+ platform: "Linux",+ }),+ "commandPalette.toggle",+ );+ });++ it("keeps app shortcuts on the primary environment when the active environment remaps them", () => {+ const primary = compile([{ shortcut: modShortcut("j"), command: "terminal.toggle" }]);+ const active = compile([{ shortcut: modShortcut("t"), command: "terminal.toggle" }]);++ assert.strictEqual(+ resolveChatShortcutCommand(event({ key: "j", ctrlKey: true }), primary, active, {+ platform: "Linux",+ }),+ "terminal.toggle",+ );+ assert.isNull(+ resolveChatShortcutCommand(event({ key: "t", ctrlKey: true }), primary, active, {+ platform: "Linux",+ }),+ );+ });++ it.each([false, true])(+ "preserves active binding precedence with terminalFocus=%s",+ (terminalFocus) => {+ const primary = compile([{ shortcut: modShortcut("r"), command: "script.setup.run" }]);+ const active = compile([+ { shortcut: modShortcut("r"), command: "script.deploy.run" },+ {+ shortcut: modShortcut("r"),+ command: "terminal.new",+ whenAst: whenIdentifier("terminalFocus"),+ },+ ]);+ const options = { platform: "Linux", context: { terminalFocus } };+ const shortcut = event({ key: "r", ctrlKey: true });++ assert.strictEqual(+ resolveChatShortcutCommand(shortcut, primary, active, options),+ terminalFocus ? null : "script.deploy.run",+ );+ assert.strictEqual(+ resolveChatShortcutCommand(shortcut, active, active, options),+ resolveShortcutCommand(shortcut, active, options),+ );+ },+ );+});+describe("resolveShortcutCommand", () => {it("resolves a custom stop-thread shortcut", () => {const keybindings = compile([{ shortcut: modShortcut("escape"), command: "thread.stop" }]);diff --git a/apps/web/src/keybindings.ts b/apps/web/src/keybindings.tsindex 7864eabf755..92affc39e52 100644--- a/apps/web/src/keybindings.ts+++ b/apps/web/src/keybindings.ts@@ -18,6 +18,7 @@ import {type ShortcutModifierStateLike,} from "@t3tools/shared/keybindings";import { isElectron } from "./env";+import { projectScriptIdFromCommand } from "./projectScripts";export type { ShortcutEventLike, ShortcutModifierStateLike } from "@t3tools/shared/keybindings";export { shortcutKeyFromEvent } from "@t3tools/shared/keybindings";@@ -169,6 +170,24 @@ export function resolveShortcutCommand(return null;}+/** App shortcuts use the primary environment; script shortcuts belong to the active project. */+export function resolveChatShortcutCommand(+ event: ShortcutEventLike,+ primaryKeybindings: ResolvedKeybindingsConfig,+ activeKeybindings: ResolvedKeybindingsConfig,+ options?: ShortcutMatchOptions,+): KeybindingCommand | null {+ const primaryCommand = resolveShortcutCommand(event, primaryKeybindings, options);+ if (primaryCommand !== null && projectScriptIdFromCommand(primaryCommand) === null) {+ return primaryCommand;+ }++ const activeCommand = resolveShortcutCommand(event, activeKeybindings, options);+ return activeCommand !== null && projectScriptIdFromCommand(activeCommand) !== null+ ? activeCommand+ : null;+}+export function formatShortcutKeyLabel(key: string): string {if (key === " ") return "Space";if (key.length === 1) return key.toUpperCase();diff --git a/apps/web/src/lib/attachmentUploadQueue.test.ts b/apps/web/src/lib/attachmentUploadQueue.test.tsindex ea217616452..a92129a23e0 100644--- a/apps/web/src/lib/attachmentUploadQueue.test.ts+++ b/apps/web/src/lib/attachmentUploadQueue.test.ts@@ -18,6 +18,7 @@ const mocks = vi.hoisted(() => ({executeAtomQuery: vi.fn(),removeUpload: Symbol("remove-upload"),runAtomCommand: vi.fn(),+ readEnvironmentScope: vi.fn(),readPreparedConnection: vi.fn(),}));@@ -48,6 +49,7 @@ vi.mock("../state/attachments", () => ({}));vi.mock("../state/session", () => ({+ readEnvironmentScope: mocks.readEnvironmentScope,readPreparedConnection: mocks.readPreparedConnection,}));@@ -172,6 +174,7 @@ describe("attachmentUploadQueue", () => {mocks.executeAtomQuery.mockReset();mocks.executeAtomQuery.mockResolvedValue({ _tag: "Success", value: {} });mocks.runAtomCommand.mockReset();+ mocks.readEnvironmentScope.mockReset().mockReturnValue(true);mocks.readPreparedConnection.mockReset();mocks.readPreparedConnection.mockReturnValue({ httpBaseUrl: "https://environment.test/" });mocks.runAtomCommand.mockImplementation(@@ -266,6 +269,114 @@ describe("attachmentUploadQueue", () => {expect(readAttachmentUpload(image.id)).toBeUndefined();});+ it("keeps an attachment local until its own environment grants write access", async () => {+ const image = makeImage("permission-gain");+ mocks.readEnvironmentScope.mockImplementation(+ (environmentId) => environmentId === firstEnvironment,+ );++ startAttachmentUpload({ environmentId: secondEnvironment, image });+ expect(mocks.runAtomCommand).not.toHaveBeenCalled();+ expect(TestXmlHttpRequest.requests).toHaveLength(0);+ expect(readAttachmentUpload(image.id)).toBeUndefined();+ expect(image.file).not.toBeNull();++ mocks.readEnvironmentScope.mockReturnValue(true);+ startAttachmentUpload({ environmentId: secondEnvironment, image });+ await Promise.resolve();+ const settled = awaitAttachmentUploads([image.id]);+ TestXmlHttpRequest.requests[0]!.complete();+ await settled;++ expect(readAttachmentUpload(image.id)).toMatchObject({+ status: "ready",+ environmentId: secondEnvironment,+ });+ });++ it("does not transfer bytes or retry when access is revoked while minting an upload", async () => {+ const image = makeImage("revoke-before-bytes");+ let finishMint: (() => void) | undefined;+ mocks.runAtomCommand.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ finishMint = () =>+ resolve({+ _tag: "Success",+ value: {+ attachmentId: "pending-revoked",+ relativeUrl: "/api/attachments/upload/pending-revoked",+ expiresAt: 1,+ },+ });+ }),+ );+ startAttachmentUpload({ environmentId: firstEnvironment, image });+ const settled = awaitAttachmentUploads([image.id]);+ mocks.readEnvironmentScope.mockReturnValue(false);+ finishMint!();+ await settled;++ expect(TestXmlHttpRequest.requests).toHaveLength(0);+ expect(readAttachmentUpload(image.id)).toMatchObject({+ status: "failed",+ reason: "This connection cannot upload attachments.",+ attachmentId: "pending-revoked",+ });+ retryAttachmentUpload({ environmentId: firstEnvironment, image });+ expect(readAttachmentUpload(image.id)?.status).toBe("failed");+ releaseAttachmentUpload(image.id);+ expect(readAttachmentUpload(image.id)).toBeUndefined();+ expect(mocks.runAtomCommand).toHaveBeenCalledTimes(1);+ });++ it("does not mint queued uploads after access is revoked", async () => {+ const images = Array.from({ length: 4 }, (_, index) => makeImage(`queued-${index}`));+ for (const image of images) {+ startAttachmentUpload({ environmentId: firstEnvironment, image });+ }+ await Promise.resolve();+ expect(TestXmlHttpRequest.requests).toHaveLength(3);+ const settled = awaitAttachmentUploads(images.map((image) => image.id));+ mocks.readEnvironmentScope.mockReturnValue(false);+ for (const request of TestXmlHttpRequest.requests) {+ request.complete();+ }+ await settled;++ expect(mocks.runAtomCommand).toHaveBeenCalledTimes(3);+ expect(TestXmlHttpRequest.requests).toHaveLength(3);+ expect(readAttachmentUpload(images[3]!.id)).toMatchObject({+ status: "failed",+ reason: "This connection cannot upload attachments.",+ });+ });++ it("does not delete a persisted upload using another environment's grant", () => {+ mocks.readEnvironmentScope.mockImplementation(+ (environmentId) => environmentId === firstEnvironment,+ );+ releasePersistedAttachmentUpload({+ id: "local-file",+ environmentId: secondEnvironment,+ attachmentId: "persisted-file",+ });+ expect(mocks.runAtomCommand).not.toHaveBeenCalled();++ mocks.readEnvironmentScope.mockReturnValue(true);+ releasePersistedAttachmentUpload({+ id: "local-file",+ environmentId: secondEnvironment,+ attachmentId: "persisted-file",+ });+ expect(mocks.runAtomCommand).toHaveBeenCalledWith(+ expect.anything(),+ mocks.removeUpload,+ { environmentId: secondEnvironment, input: { attachmentId: "persisted-file" } },+ expect.anything(),+ );+ });+it("uploads images immediately and sends attachment references", async () => {const image = {...makeImage("image-1"),diff --git a/apps/web/src/lib/attachmentUploadQueue.ts b/apps/web/src/lib/attachmentUploadQueue.tsindex 6681579088d..72cb542c371 100644--- a/apps/web/src/lib/attachmentUploadQueue.ts+++ b/apps/web/src/lib/attachmentUploadQueue.ts@@ -1,4 +1,5 @@import {+ AuthOrchestrationOperateScope,PROVIDER_SEND_TURN_SUPPORTED_IMAGE_MIME_TYPES,type ChatAttachment,type EnvironmentId,@@ -26,7 +27,7 @@ import { appAtomRegistry } from "../rpc/atomRegistry";import { environmentCatalog } from "../connection/catalog";import { assetEnvironment } from "../state/assets";import { attachmentEnvironment } from "../state/attachments";-import { readPreparedConnection } from "../state/session";+import { readEnvironmentScope, readPreparedConnection } from "../state/session";import type { AttachmentUploadState, ReadyAttachmentUpload } from "./attachmentUploadState";const MAX_UPLOADS_PER_ENVIRONMENT = 3;@@ -138,6 +139,7 @@ function stampDraftFileUpload(job: UploadJob, attachmentId: string): void {}function deletePendingUpload(environmentId: EnvironmentId, attachmentId: string): void {+ if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) return;deletePendingAttachmentUpload({registry: appAtomRegistry,remove: attachmentEnvironment.remove,@@ -179,6 +181,15 @@ function uploadBytes(input: {}async function runUpload(job: UploadJob): Promise<void> {+ if (!readEnvironmentScope(job.environmentId, AuthOrchestrationOperateScope)) {+ setUploadState(job.image.id, {+ status: "failed",+ environmentId: job.environmentId,+ reason: "This connection cannot upload attachments.",+ ...(job.previous ? { previous: job.previous } : {}),+ });+ return;+ }if (job.persistedAttachmentId) {const verification = await verifyPersistedAttachmentUpload({registry: appAtomRegistry,@@ -260,6 +271,15 @@ async function runUpload(job: UploadJob): Promise<void> {}let lastStep = -1;+ if (!readEnvironmentScope(job.environmentId, AuthOrchestrationOperateScope)) {+ setUploadState(job.image.id, {+ status: "failed",+ environmentId: job.environmentId,+ reason: "This connection cannot upload attachments.",+ ...(job.previous ? { previous: job.previous } : {}),+ });+ return;+ }const result = await runAttachmentUploadCycle({registry: appAtomRegistry,createUploadUrl: attachmentEnvironment.createUploadUrl,@@ -272,6 +292,12 @@ async function runUpload(job: UploadJob): Promise<void> {sizeBytes: file.size,},resolveUploadUrl: (relativeUrl) => {+ if (+ job.cancelled ||+ !readEnvironmentScope(job.environmentId, AuthOrchestrationOperateScope)+ ) {+ return null;+ }const connection = readPreparedConnection(job.environmentId);return connection ? resolveAssetUrl(connection.httpBaseUrl, relativeUrl) : null;},@@ -295,7 +321,7 @@ async function runUpload(job: UploadJob): Promise<void> {},}),onMinted: (attachmentId) => {- if (job.cancelled) {+ if (job.cancelled && readEnvironmentScope(job.environmentId, AuthOrchestrationOperateScope)) {return "cancel";}job.attachmentId = attachmentId;@@ -328,7 +354,9 @@ async function runUpload(job: UploadJob): Promise<void> {result.step === "mint"? "Upload could not start": result.step === "resolve-url"- ? "Not connected"+ ? readEnvironmentScope(job.environmentId, AuthOrchestrationOperateScope)+ ? "Not connected"+ : "This connection cannot upload attachments.": result.error instanceof Error? result.error.message: "Upload failed",@@ -388,6 +416,7 @@ export function startAttachmentUpload(input: {/** Draft that owns the file; lets a background completion persist its ids. */readonly draftTarget?: ComposerThreadTarget;}): void {+ if (!readEnvironmentScope(input.environmentId, AuthOrchestrationOperateScope)) return;const existingJob = jobsByImageId.get(input.image.id);if (existingJob?.environmentId === input.environmentId) {return;@@ -545,6 +574,7 @@ export function retryAttachmentUpload(input: {readonly image: ComposerImageAttachment | ComposerFileAttachment;readonly draftTarget?: ComposerThreadTarget;}): void {+ if (!readEnvironmentScope(input.environmentId, AuthOrchestrationOperateScope)) return;const previous = readAttachmentUpload(input.image.id);cancelAttachmentUpload(input.image.id);// A failed state's `attachmentId` is always one this queue minted, so thisdiff --git a/apps/web/src/lib/resourceTelemetryState.ts b/apps/web/src/lib/resourceTelemetryState.tsindex 4b97b3b4671..f6561ecffcb 100644--- a/apps/web/src/lib/resourceTelemetryState.ts+++ b/apps/web/src/lib/resourceTelemetryState.ts@@ -1,3 +1,4 @@+import { AuthEnvironmentMaintainScope } from "@t3tools/contracts";import type {EnvironmentId,ResourceTelemetryHistoryInput,@@ -9,6 +10,7 @@ import { useCallback } from "react";import { usePrimaryEnvironment } from "../state/environments";import { useEnvironmentQuery } from "../state/query";import { serverEnvironment } from "../state/server";+import { readEnvironmentScope } from "../state/session";import { useAtomCommand } from "../state/use-atom-command";export interface ResourceTelemetryState {@@ -39,6 +41,9 @@ export function useResourceTelemetry(if (environmentId === null) {throw new Error("No environment is selected.");}+ if (!readEnvironmentScope(environmentId, AuthEnvironmentMaintainScope)) {+ throw new Error("This connection cannot restart the resource monitor.");+ }const result = await retryCommand({ environmentId, input: {} });if (result._tag === "Failure") {throw Cause.squash(result.cause);diff --git a/apps/web/src/routes/__root.tsx b/apps/web/src/routes/__root.tsxindex fff3e430091..2418fb1132f 100644--- a/apps/web/src/routes/__root.tsx+++ b/apps/web/src/routes/__root.tsx@@ -1,6 +1,5 @@import { type ServerLifecycleWelcomePayload } from "@t3tools/contracts";import { scopedProjectKey, scopeProjectRef } from "@t3tools/client-runtime/environment";-import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";import {Outlet,Link,@@ -20,6 +19,7 @@ import { AppSidebarLayout } from "../components/AppSidebarLayout";import { CommandPalette } from "../components/CommandPalette";import { CustomSnoozeDialogHost } from "../components/CustomSnoozeDialog";import { ConfirmDialogHost } from "../components/ConfirmDialogHost";+import { KeybindingsConfigWarning } from "../components/KeybindingsConfigWarning";import { FirstRunGate } from "../components/onboarding/FirstRunGate";import { ConnectOnboardingDialog } from "../components/cloud/ConnectOnboardingDialog";import { RelayClientInstallDialog } from "../components/cloud/RelayClientInstallDialog";@@ -49,7 +49,6 @@ import {ToastProvider,toastManager,} from "../components/ui/toast";-import { resolveAndPersistPreferredEditor } from "../editorPreferences";import { isElectron } from "../env";import { cn } from "../lib/utils";import { applyAppearanceFontVariables } from "~/appearanceFonts";@@ -66,9 +65,7 @@ import { configureClientTracing } from "../observability/clientTracing";import { resolveInitialServerAuthGateState } from "../environments/primary";import { hasHostedPairingRequest, isHostedStaticApp } from "../hostedPairing";import { isLocalEnvironmentDisabled } from "../localEnvironment";-import { shellEnvironment } from "../state/shell";import { useAtomValue } from "@effect/atom-react";-import { useAtomCommand } from "../state/use-atom-command";import { useEnvironments, usePrimaryEnvironment } from "../state/environments";import {primaryServerConfigAtom,@@ -496,9 +493,6 @@ function EventRouter({const pathname = useLocation({ select: (loc) => loc.pathname });const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);const primaryEnvironment = usePrimaryEnvironment();- const openInEditor = useAtomCommand(shellEnvironment.openInEditor, {- reportFailure: false,- });const serverConfig = useAtomValue(primaryServerConfigAtom);const serverConfigEvent = useAtomValue(primaryServerConfigEventAtom);const serverWelcome = useAtomValue(primaryServerWelcomeAtom);@@ -575,42 +569,14 @@ function EventRouter({stackedThreadToast({type: "warning",title: "Invalid keybindings configuration",- description: decision.message,- actionVariant: "outline",- actionProps: {- children: "Open keybindings.json",- onClick: () => {- if (!serverConfig || !primaryEnvironment) {- return;- }-- const editor = resolveAndPersistPreferredEditor(serverConfig.availableEditors);- if (!editor) {- return;- }- void (async () => {- const result = await openInEditor({- environmentId: primaryEnvironment.environmentId,- input: {- cwd: serverConfig.keybindingsConfigPath,- editor,- },- });- 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.",- }),- );- })();- },- },+ description: (+ <KeybindingsConfigWarning+ message={decision.message}+ environmentId={primaryEnvironment?.environmentId ?? null}+ configPath={serverConfig?.keybindingsConfigPath ?? null}+ availableEditors={serverConfig?.availableEditors ?? []}+ />+ ),}),);});diff --git a/apps/web/src/state/session.ts b/apps/web/src/state/session.tsindex c861245b999..a2c00df4f26 100644--- a/apps/web/src/state/session.ts+++ b/apps/web/src/state/session.ts@@ -1,6 +1,7 @@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 { useMemo } from "react";import * as Option from "effect/Option";import { AsyncResult, Atom } from "effect/reactivity";@@ -9,6 +10,66 @@ import { appAtomRegistry } from "../rpc/atomRegistry";export const environmentSession = createEnvironmentSessionAtoms(connectionAtomRuntime);+const EMPTY_SESSION_STATE_ATOM = Atom.make(AsyncResult.initial<AuthSessionState>());++/** 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),+ );+ const session = Option.getOrNull(AsyncResult.value(result));+ return (+ result._tag !== "Failure" &&+ session?.authenticated === true &&+ session.scopes?.includes(scope) === true+ );+}++/** Subscribe to the grants of every selected environment. */+export function useEnvironmentsWithScope(+ environments: ReadonlyArray<{ readonly environmentId: EnvironmentId }>,+ scope: AuthEnvironmentScope,+): ReadonlySet<EnvironmentId> {+ const permitted = useMemo(+ () =>+ Atom.make((get) => {+ const ids = new Set<EnvironmentId>();+ for (const { environmentId } of environments) {+ const result = get(environmentSession.sessionStateAtom(environmentId));+ const session = Option.getOrNull(AsyncResult.value(result));+ if (+ result._tag !== "Failure" &&+ session?.authenticated === true &&+ session.scopes?.includes(scope)+ ) {+ ids.add(environmentId);+ }+ }+ return ids;+ }),+ [environments, scope],+ );+ return useAtomValue(permitted);+}++export function readEnvironmentScope(+ environmentId: EnvironmentId,+ scope: AuthEnvironmentScope,+): boolean {+ const result = appAtomRegistry.get(environmentSession.sessionStateAtom(environmentId));+ const session = Option.getOrNull(AsyncResult.value(result));+ return (+ result._tag !== "Failure" &&+ session?.authenticated === true &&+ session.scopes?.includes(scope) === true+ );+}+const EMPTY_PREPARED_CONNECTION_ATOM = Atom.make(Option.none()).pipe(Atom.withLabel("web-prepared-connection:empty"),);diff --git a/apps/web/src/state/use-orchestration-command.test.ts b/apps/web/src/state/use-orchestration-command.test.tsnew file mode 100644index 00000000000..44941063a8d--- /dev/null+++ b/apps/web/src/state/use-orchestration-command.test.ts@@ -0,0 +1,85 @@+import type { AtomCommand } from "@t3tools/client-runtime/state/runtime";+import {+ AuthOrchestrationOperateScope,+ EnvironmentAuthorizationError,+ EnvironmentId,+} from "@t3tools/contracts";+import * as Cause from "effect/Cause";+import { AsyncResult } from "effect/reactivity";+import { assert, beforeEach, expect, it, vi } from "vite-plus/test";++const state = vi.hoisted(() => ({+ allowed: new Set<string>(),+ readScope: vi.fn(),+ run: vi.fn(),+}));++vi.mock("react", () => ({ useCallback: (callback: unknown) => callback }));+vi.mock("./session", () => ({ readEnvironmentScope: state.readScope }));+vi.mock("./use-atom-command", () => ({ useAtomCommand: () => state.run }));++import { useOrchestrationCommand } from "./use-orchestration-command";++const first = EnvironmentId.make("primary");+const second = EnvironmentId.make("secondary");+type Target = { environmentId: EnvironmentId; input: { threadId: string } };+const command: AtomCommand<Target, string, Error> = { label: "thread mutation", run: state.run };+const target = (environmentId: EnvironmentId): Target => ({+ environmentId,+ input: { threadId: "thread-1" },+});++beforeEach(() => {+ state.allowed.clear();+ state.run.mockReset().mockResolvedValue(AsyncResult.success("receipt"));+ state.readScope+ .mockReset()+ .mockImplementation(+ (environmentId, scope) =>+ scope === AuthOrchestrationOperateScope && state.allowed.has(environmentId),+ );+});++it("checks the command's environment instead of borrowing the primary grant", async () => {+ state.allowed.add(first);+ const mutate = useOrchestrationCommand(command, { reportFailure: false });+ const result = await mutate(target(second));+ assert(result._tag === "Failure");+ const error = Cause.squash(result.cause);+ expect(error).toBeInstanceOf(EnvironmentAuthorizationError);+ expect(error).toMatchObject({ requiredScope: AuthOrchestrationOperateScope });+ expect(state.run).not.toHaveBeenCalled();++ expect(await mutate(target(first))).toMatchObject({ _tag: "Success", value: "receipt" });+ expect(state.run).toHaveBeenCalledWith(target(first));+});++it("a retained callback follows both revocation and a new grant without remounting", async () => {+ state.allowed.add(second);+ const mutate = useOrchestrationCommand(command);+ state.allowed.delete(second);+ expect((await mutate(target(second)))._tag).toBe("Failure");+ expect(state.run).not.toHaveBeenCalled();++ state.allowed.add(second);+ expect((await mutate(target(second)))._tag).toBe("Success");+ expect(state.run).toHaveBeenCalledTimes(1);+});++it("does not dispatch a later mutation after access changes while awaiting a receipt", async () => {+ state.allowed.add(second);+ let finish: (() => void) | undefined;+ state.run.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ finish = () => resolve(AsyncResult.success("first receipt"));+ }),+ );+ const mutate = useOrchestrationCommand(command);+ const pending = mutate(target(second));+ state.allowed.delete(second);+ finish!();+ expect((await pending)._tag).toBe("Success");+ expect((await mutate(target(second)))._tag).toBe("Failure");+ expect(state.run).toHaveBeenCalledTimes(1);+});diff --git a/apps/web/src/state/use-orchestration-command.ts b/apps/web/src/state/use-orchestration-command.tsnew file mode 100644index 00000000000..71bee0a35b5--- /dev/null+++ b/apps/web/src/state/use-orchestration-command.ts@@ -0,0 +1,43 @@+import type {+ AtomCommand,+ AtomCommandOptions,+ AtomCommandResult,+} 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 { useCallback } from "react";++import { readEnvironmentScope } from "./session";+import { useAtomCommand } from "./use-atom-command";++export const ORCHESTRATION_OPERATE_DENIED_MESSAGE =+ "This connection cannot change threads or projects.";++/** Recheck the target grant for every step of a thread or project mutation. */+export function useOrchestrationCommand<W extends { readonly environmentId: EnvironmentId }, A, E>(+ command: AtomCommand<W, A, E>,+ options?: string | AtomCommandOptions,+): (value: W) => Promise<AtomCommandResult<A, E | EnvironmentAuthorizationError>> {+ const run = useAtomCommand(command, options);+ return useCallback(+ async (value: W): Promise<AtomCommandResult<A, E | EnvironmentAuthorizationError>> => {+ if (!readEnvironmentScope(value.environmentId, AuthOrchestrationOperateScope)) {+ return AsyncResult.failure(+ Cause.fail(+ new EnvironmentAuthorizationError({+ requiredScope: AuthOrchestrationOperateScope,+ message: ORCHESTRATION_OPERATE_DENIED_MESSAGE,+ }),+ ),+ );+ }+ return run(value);+ },+ [run],+ );+}diff --git a/docs/internals/environment-auth.md b/docs/internals/environment-auth.mdindex 3acea00472e..58c5ab4ef5c 100644--- a/docs/internals/environment-auth.md+++ b/docs/internals/environment-auth.md@@ -58,6 +58,11 @@ extra authority: [every RPC declares a requiredscope](../../apps/server/src/auth/RpcAuthorization.ts), and the WebSocket RPCgroup's `RpcScopeAuthorization` middleware checks it before any handler runs.+Self-update must work across authorization protocol changes. New servers advertise+`auth.serverUpdateScope`; only an older server that omits it uses+`orchestration:operate` for updates. An unchanged grant on an upgraded server must+still include `environment:maintain`.+Desktop restarts forget the previous local bearer token, so its reusablebootstrap grant replaces earlier sessions for the same subject and method.Revocation and insertion share a [databasediff --git a/docs/user/remote-access.md b/docs/user/remote-access.mdindex 4f6eb711526..04a4a4c0f01 100644--- a/docs/user/remote-access.md+++ b/docs/user/remote-access.md@@ -277,6 +277,16 @@ in web or desktop, use **Add Environment** with the fresh link or code; pairingthe same environment replaces its saved grant. Reconnecting alone does not changepermissions.+Grouping checkouts does not combine their permissions. Shared project settings+require `orchestration:operate` on every member environment; actions on one+checkout use that checkout's permissions.++Settings changes, provider management, and environment maintenance can be granted+separately from access administration. New standard pairings include these+permissions. Existing clients keep their original grants after an update; to+receive newly separated permissions, pair the client again with the scopes it+needs. Reconnecting or refreshing a session does not expand its grant.+To remove an environment from T3 Connect, open your account menu's **T3 Connect**page, or **Settings → T3 Connect** on mobile, and choose **Deregister**. Thisrevokes its cloud access and frees its host space even when the environment isdiff --git a/oxlint-plugin-t3code/index.ts b/oxlint-plugin-t3code/index.tsindex f8c47dfccdf..50fe249d9ba 100644--- a/oxlint-plugin-t3code/index.ts+++ b/oxlint-plugin-t3code/index.ts@@ -9,6 +9,7 @@ import noMobileUniwindThemeEscapeHatches from "./rules/no-mobile-uniwind-theme-eimport noNativeTitleTooltip from "./rules/no-native-title-tooltip.ts";import noRawMcpRegistration from "./rules/no-raw-mcp-registration.ts";import noTestInLoop from "./rules/no-test-in-loop.ts";+import noRpcPermissionBypass from "./rules/no-rpc-permission-bypass.ts";import noUnscopedHas from "./rules/no-unscoped-has.ts";import preferCatchTags from "./rules/prefer-catch-tags.ts";import requireSuppressionReason from "./rules/require-suppression-reason.ts";@@ -27,6 +28,7 @@ export default definePlugin({"no-native-title-tooltip": noNativeTitleTooltip,"no-raw-mcp-registration": noRawMcpRegistration,"no-test-in-loop": noTestInLoop,+ "no-rpc-permission-bypass": noRpcPermissionBypass,"no-unscoped-has": noUnscopedHas,"prefer-catch-tags": preferCatchTags,"require-suppression-reason": requireSuppressionReason,diff --git a/oxlint-plugin-t3code/rules/no-rpc-permission-bypass.test.ts b/oxlint-plugin-t3code/rules/no-rpc-permission-bypass.test.tsnew file mode 100644index 00000000000..5dbf8778a7a--- /dev/null+++ b/oxlint-plugin-t3code/rules/no-rpc-permission-bypass.test.ts@@ -0,0 +1,69 @@+import { createOxlintRuleHarness } from "../test/utils.ts";+const state = createOxlintRuleHarness("t3code/no-rpc-permission-bypass", {+ filename: "fixture.ts",+});+state.invalid("blocks direct session calls", "session.client[tag](input);");+state.invalid("blocks extracting the raw client", 'const raw = session["client"];');+state.invalid(+ "blocks replacing the permission guard",+ 'import { RpcPermissionGuard as Guard } from "../rpc/client.ts";',+);+state.invalid(+ "blocks namespace guard access",+ 'import * as Rpc from "../rpc/client.ts"; const guard = Rpc.RpcPermissionGuard;',+);+state.invalid("blocks raw protocol imports", 'import { makeClient } from "../rpc/protocol.ts";');+state.valid(+ "allows typed requests",+ 'import { request } from "../rpc/client.ts"; request(method, input);',+);+const rpc = createOxlintRuleHarness("t3code/no-rpc-permission-bypass", {+ filename: "fixture.ts",+ ruleOptions: [{ allowRawClientAccess: true }],+});+rpc.valid("allows the transport boundary", "session.client[tag](input);");++const app = createOxlintRuleHarness("t3code/no-rpc-permission-bypass", {+ filename: "fixture.ts",+});+app.invalid(+ "blocks guard imports through the barrel",+ 'import { RpcPermissionGuard as Guard } from "@t3tools/client-runtime/rpc";',+);+app.invalid(+ "blocks explicit index imports",+ 'import { RpcPermissionGuard } from "@t3tools/client-runtime/rpc/index.ts";',+);+app.invalid(+ "blocks raw session access in subscription callbacks",+ "subscribeDynamic(tag, session => session.client[method](input));",+);+app.invalid(+ "blocks raw client destructuring",+ "const { client: raw } = session; raw[method](input);",+);+app.valid(+ "allows public typed RPC helpers",+ 'import { request, runStream } from "@t3tools/client-runtime/rpc";',+);++rpc.invalid(+ "raw client allowance does not permit installing the guard",+ 'import { RpcPermissionGuard } from "@t3tools/client-runtime/rpc";',+);+const boundary = createOxlintRuleHarness("t3code/no-rpc-permission-bypass", {+ filename: "fixture.ts",+ ruleOptions: [{ allowGuardInstallation: true }],+});+boundary.valid(+ "permits guard installation when configured",+ 'import { RpcPermissionGuard } from "@t3tools/client-runtime/rpc"; RpcPermissionGuard.of({ authorize });',+);+boundary.invalid(+ "guard installation allowance does not permit raw clients",+ "session.client[tag](input);",+);+boundary.invalid(+ "guard installation allowance does not permit raw protocol imports",+ 'import { makeWsRpcProtocolClient } from "../rpc/protocol.ts";',+);diff --git a/oxlint-plugin-t3code/rules/no-rpc-permission-bypass.ts b/oxlint-plugin-t3code/rules/no-rpc-permission-bypass.tsnew file mode 100644index 00000000000..e968507c25c--- /dev/null+++ b/oxlint-plugin-t3code/rules/no-rpc-permission-bypass.ts@@ -0,0 +1,91 @@+import { defineRule } from "@oxlint/plugins";+import * as Option from "effect/Option";+import { getPropertyName } from "../utils.ts";++const readOptions = (options: ReadonlyArray<unknown>) => {+ const [first] = options;+ return {+ allowRawClientAccess:+ typeof first === "object" &&+ first !== null &&+ "allowRawClientAccess" in first &&+ first.allowRawClientAccess === true,+ allowGuardInstallation:+ typeof first === "object" &&+ first !== null &&+ "allowGuardInstallation" in first &&+ first.allowGuardInstallation === true,+ };+};++/** A guardrail for ordinary edits, not a security boundary against deliberate casts or aliases. */+export default defineRule({+ meta: {+ type: "problem",+ docs: {+ description:+ "Keep raw RPC access and permission guard installation inside their shared boundaries.",+ },+ schema: [+ {+ type: "object",+ properties: {+ allowRawClientAccess: {+ type: "boolean",+ description: "Permit .client access for non-RPC clients in the configured files.",+ },+ allowGuardInstallation: {+ type: "boolean",+ description: "Permit installing RpcPermissionGuard in a reviewed command boundary.",+ },+ },+ additionalProperties: false,+ },+ ],+ defaultOptions: [{ allowRawClientAccess: false, allowGuardInstallation: false }],+ },+ create(context) {+ const { allowRawClientAccess, allowGuardInstallation } = readOptions(context.options);+ const report = (node: NonNullable<Parameters<typeof context.report>[0]["node"]>) =>+ context.report({+ node,+ message:+ "Use permission-aware environment commands. Raw RPC access and RpcPermissionGuard belong in the shared RPC/command boundary.",+ });+ return {+ ImportDeclaration(node) {+ if (typeof node.source.value !== "string") return;+ const source = node.source.value;+ if (/(?:^|\/)rpc\/protocol(?:\.ts)?$/.test(source) && node.importKind !== "type")+ report(node);+ if (+ !allowGuardInstallation &&+ /(?:^|\/)rpc(?:\/(?:client|index)(?:\.ts)?)?$/.test(source)+ ) {+ for (const specifier of node.specifiers) {+ if (+ specifier.type === "ImportSpecifier" &&+ Option.getOrNull(getPropertyName(specifier.imported)) === "RpcPermissionGuard"+ )+ report(specifier);+ }+ }+ },+ VariableDeclarator(node) {+ if (allowRawClientAccess || node.id.type !== "ObjectPattern") return;+ for (const property of node.id.properties) {+ if (+ property.type === "Property" &&+ Option.getOrNull(getPropertyName(property.key)) === "client"+ )+ report(property);+ }+ },+ MemberExpression(node) {+ const property = Option.getOrNull(getPropertyName(node.property));+ if (!allowGuardInstallation && property === "RpcPermissionGuard") report(node);+ if (!allowRawClientAccess && property === "client") report(node);+ },+ };+ },+});diff --git a/packages/client-runtime/src/rpc/client.ts b/packages/client-runtime/src/rpc/client.tsindex 89ecebe535b..d8ffc24c458 100644--- a/packages/client-runtime/src/rpc/client.ts+++ b/packages/client-runtime/src/rpc/client.ts@@ -1,5 +1,8 @@import {EnvironmentAuthorizationError,+ clientRpcRequiredScopes,+ type EnvironmentId,+ type ClientGuardedRpcTag,ORCHESTRATION_V2_WS_METHODS,WS_METHODS,} from "@t3tools/contracts";@@ -146,7 +149,40 @@ export const getInitialServerConfig = Effect.fn("EnvironmentRpc.getInitialServer},);-export const request = Effect.fn("EnvironmentRpc.request")(function* <+/** Installed by the shared command boundary. A missing boundary denies protected writes. */+export class RpcPermissionGuard extends Context.Reference<{+ readonly authorize: (+ environmentId: EnvironmentId,+ method: string,+ input: unknown,+ ) => Effect.Effect<void, EnvironmentAuthorizationError>;+}>("@t3tools/client-runtime/rpc/RpcPermissionGuard", {+ defaultValue: () => ({+ authorize: (_environmentId, method, input) => {+ const scope = clientRpcRequiredScopes(method, input)[0];+ return scope === undefined+ ? Effect.void+ : Effect.fail(+ new EnvironmentAuthorizationError({+ requiredScope: scope,+ message: `This connection requires ${scope}.`,+ }),+ );+ },+ }),+}) {}++const authorizeRequest = Effect.fn("EnvironmentRpc.authorize")(function* (+ method: string,+ input: unknown,+) {+ if (clientRpcRequiredScopes(method, input).length === 0) return;+ const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;+ const guard = yield* RpcPermissionGuard;+ yield* guard.authorize(supervisor.target.environmentId, method, input);+});++export const requestGuarded = Effect.fn("EnvironmentRpc.request")(function* <TTag extends EnvironmentUnaryRpcTag,>(tag: TTag, input: EnvironmentRpcInput<TTag>) {const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;@@ -155,6 +191,7 @@ export const request = Effect.fn("EnvironmentRpc.request")(function* <"rpc.method": tag,});const session = yield* currentSession();+ yield* authorizeRequest(tag, input);const observer = yield* EnvironmentRpcRequestObserver;const method = session.client[tag] as (input: EnvironmentRpcInput<TTag>,@@ -166,16 +203,19 @@ export const request = Effect.fn("EnvironmentRpc.request")(function* <return yield* method(input).pipe(Effect.ensuring(completeObservation));});-export function runStream<TTag extends EnvironmentStreamCommandRpcTag>(+function runStreamGuarded<TTag extends EnvironmentStreamCommandRpcTag>(tag: TTag,input: EnvironmentRpcInput<TTag>,): Stream.Stream<EnvironmentRpcStreamValue<TTag>,- EnvironmentRpcStreamFailure<TTag> | EnvironmentRpcUnavailableError,+ | EnvironmentRpcStreamFailure<TTag>+ | EnvironmentRpcUnavailableError+ | EnvironmentAuthorizationError,EnvironmentSupervisor.EnvironmentSupervisor> {return Stream.unwrap(- currentSession().pipe(+ authorizeRequest(tag, input).pipe(+ Effect.andThen(currentSession()),Effect.map((session) => {const method = session.client[tag] as (input: EnvironmentRpcInput<TTag>,@@ -393,3 +433,16 @@ export function subscribe<TTag extends EnvironmentSubscriptionRpcTag>(> {return subscribeDynamic(tag, () => Effect.succeed(input), options);}++/** Protected writes must go through the permission-aware command layer. */+export const request = <TTag extends Exclude<EnvironmentUnaryRpcTag, ClientGuardedRpcTag>>(+ tag: TTag,+ input: EnvironmentRpcInput<TTag>,+) => requestGuarded(tag, input);++export const runStream = <+ TTag extends Exclude<EnvironmentStreamCommandRpcTag, ClientGuardedRpcTag>,+>(+ tag: TTag,+ input: EnvironmentRpcInput<TTag>,+) => runStreamGuarded(tag, input);diff --git a/packages/client-runtime/src/rpc/index.ts b/packages/client-runtime/src/rpc/index.tsindex d5b1a6858f4..e0e269bdfa8 100644--- a/packages/client-runtime/src/rpc/index.ts+++ b/packages/client-runtime/src/rpc/index.ts@@ -1,4 +1,4 @@export * from "./client.ts";export * from "./http.ts";-export * from "./protocol.ts";+export type { WsRpcProtocolClient } from "./protocol.ts";export { type RpcSession } from "./session.ts";diff --git a/packages/client-runtime/src/state/commandPermissions.test.ts b/packages/client-runtime/src/state/commandPermissions.test.tsnew file mode 100644index 00000000000..d3142d047f4--- /dev/null+++ b/packages/client-runtime/src/state/commandPermissions.test.ts@@ -0,0 +1,152 @@+import { describe, expect, it } from "@effect/vitest";+import { vi } from "vite-plus/test";+import {+ AuthOrchestrationOperateScope,+ EnvironmentId,+ ScheduledTaskId,+ WS_METHODS,+ type AuthSessionState,+} from "@t3tools/contracts";+import * as Cause from "effect/Cause";+import * as Effect from "effect/Effect";+import * as Fiber from "effect/Fiber";+import * as Layer from "effect/Layer";+import * as TestClock from "effect/testing/TestClock";+import { Atom, AtomRegistry, AsyncResult } from "effect/reactivity";+import { EnvironmentRegistry } from "../connection/registry.ts";+import { createCommandPermissions } from "./commandPermissions.ts";+import { createEnvironmentRpcCommand } from "./runtime.ts";++vi.mock("./session.ts", () => ({+ createEnvironmentSessionAtoms: () => ({ sessionStateAtom: sessions }),+}));+const sessions = Atom.family((_id: EnvironmentId) =>+ Atom.make<AsyncResult.AsyncResult<AuthSessionState, string>>(AsyncResult.initial()),+);+const env = EnvironmentId.make("target");+const other = EnvironmentId.make("other");+const grant = (allowed: boolean): AuthSessionState => ({+ authenticated: true,+ auth: {+ policy: "remote-reachable",+ bootstrapMethods: [],+ sessionMethods: [],+ sessionCookieName: "test",+ },+ scopes: allowed ? [AuthOrchestrationOperateScope] : [],+});+const runtime = Atom.runtime(+ Layer.succeed(EnvironmentRegistry, {+ run: (_id: EnvironmentId, effect: Effect.Effect<unknown>) => effect,+ } as unknown as EnvironmentRegistry["Service"]),+);+const permissions = createCommandPermissions(runtime, WS_METHODS.scheduledTasksDelete);+const setup = Effect.gen(function* () {+ const registry = AtomRegistry.make();+ registry.mount(sessions(env));+ yield* Effect.addFinalizer(() => Effect.sync(() => registry.dispose()));+ return registry;+});++describe("command permissions", () => {+ it.effect("uses the target grant for both availability and execution", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const registry = yield* setup;+ registry.set(sessions(env), AsyncResult.success(grant(true)));+ expect(registry.get(permissions.permissionAtom(env))).toBe(true);+ expect(permissions.permissionAtom(env)).toBe(permissions.permissionAtom(env));+ yield* permissions.authorize(registry, env);+ registry.set(sessions(other), AsyncResult.success(grant(false)));+ expect(registry.get(permissions.permissionAtom(other))).toBe(false);+ const denied = yield* permissions.authorize(registry, other).pipe(Effect.flip);+ expect(denied._tag).toBe("EnvironmentAuthorizationError");+ }),+ ),+ );+ it.effect("waits for an initial grant", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const registry = yield* setup;+ const fiber = yield* permissions.authorize(registry, env).pipe(Effect.forkChild);+ yield* Effect.yieldNow;+ registry.set(sessions(env), AsyncResult.success(grant(true)));+ yield* Fiber.join(fiber);+ }),+ ),+ );+ it.effect("bounds a session that never loads", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const registry = yield* setup;+ const fiber = yield* permissions+ .authorize(registry, env)+ .pipe(Effect.flip, Effect.forkChild);+ yield* TestClock.adjust("6 seconds");+ expect((yield* Fiber.join(fiber))._tag).toBe("EnvironmentAuthorizationError");+ }),+ ),+ );+ it.effect(+ "denies failed and unauthenticated sessions, but accepts a cached refreshing grant",+ () =>+ Effect.scoped(+ Effect.gen(function* () {+ const registry = yield* setup;+ registry.set(sessions(env), AsyncResult.failure(Cause.fail("offline")));+ expect((yield* permissions.authorize(registry, env).pipe(Effect.flip))._tag).toBe(+ "EnvironmentAuthorizationError",+ );+ registry.set(+ sessions(env),+ AsyncResult.success({ ...grant(true), authenticated: false }),+ );+ expect((yield* permissions.authorize(registry, env).pipe(Effect.flip))._tag).toBe(+ "EnvironmentAuthorizationError",+ );+ registry.set(sessions(env), AsyncResult.waiting(AsyncResult.success(grant(true))));+ yield* permissions.authorize(registry, env);+ }),+ ),+ );+ it("rechecks permission after waiting in a serial command lane", async () => {+ const registry = AtomRegistry.make();+ const unmount = registry.mount(sessions(env));+ registry.set(sessions(env), AsyncResult.success(grant(true)));+ let release!: () => void;+ let started!: () => void;+ const entered = new Promise<void>((resolve) => {+ started = resolve;+ });+ const gate = new Promise<void>((resolve) => {+ release = resolve;+ });+ let calls = 0;+ const command = createEnvironmentRpcCommand(runtime, {+ label: "test.delete",+ tag: WS_METHODS.scheduledTasksDelete,+ concurrency: { mode: "serial", key: () => "target" },+ execute: () =>+ Effect.promise(async () => {+ calls++;+ started();+ await gate;+ return { id: ScheduledTaskId.make("task") };+ }),+ });+ const target = { environmentId: env, input: { id: ScheduledTaskId.make("task") } };+ try {+ const first = command.run(registry, target);+ await entered;+ const second = command.run(registry, target);+ registry.set(sessions(env), AsyncResult.success(grant(false)));+ release();+ expect((await first)._tag).toBe("Success");+ expect((await second)._tag).toBe("Failure");+ expect(calls).toBe(1);+ } finally {+ unmount();+ registry.dispose();+ }+ });+});diff --git a/packages/client-runtime/src/state/commandPermissions.ts b/packages/client-runtime/src/state/commandPermissions.tsnew file mode 100644index 00000000000..c6dccd29081--- /dev/null+++ b/packages/client-runtime/src/state/commandPermissions.ts@@ -0,0 +1,97 @@+import {+ clientRpcRequiredScopes,+ EnvironmentAuthorizationError,+ type EnvironmentId,+ type AuthSessionState,+ type AuthEnvironmentScope,+} from "@t3tools/contracts";+import * as Effect from "effect/Effect";+import * as Option from "effect/Option";+import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";+import type { EnvironmentRegistry } from "../connection/registry.ts";+import { createEnvironmentSessionAtoms } from "./session.ts";++function grants(session: AuthSessionState, scope: AuthEnvironmentScope) {+ return session.authenticated && session.scopes?.includes(scope) === true;+}++/** UI availability and dispatch use the same target session and method policy. */+function makeCommandPermissions<R, E>(+ runtime: Atom.AtomRuntime<EnvironmentRegistry | R, E>,+ method: string,+) {+ const sessions = createEnvironmentSessionAtoms(runtime);+ const requiredScopes = (input?: unknown) => clientRpcRequiredScopes(method, input);+ const atomsByEnvironment = Atom.family((environmentId: EnvironmentId | null) =>+ Atom.family((scopeKey: string) =>+ Atom.make((get) => {+ if (environmentId === null) return false;+ const scopes = scopeKey.split(",").filter(Boolean) as AuthEnvironmentScope[];+ if (scopes.length === 0) return true;+ const result = get(sessions.sessionStateAtom(environmentId));+ const session = Option.getOrNull(AsyncResult.value(result));+ return (+ result._tag !== "Failure" &&+ session !== null &&+ scopes.every((scope) => grants(session, scope))+ );+ }),+ ),+ );+ const permissionAtom = (environmentId: EnvironmentId | null, input?: unknown) =>+ atomsByEnvironment(environmentId)(requiredScopes(input).join(","));+ const authorize = (+ registry: AtomRegistry.AtomRegistry,+ environmentId: EnvironmentId,+ input?: unknown,+ ) =>+ Effect.suspend(() => {+ const scopes = requiredScopes(input);+ if (scopes.length === 0) return Effect.void;+ const atom = sessions.sessionStateAtom(environmentId);+ return Effect.scoped(+ Effect.gen(function* () {+ yield* AtomRegistry.mount(registry, atom);+ const session = yield* AtomRegistry.getResult(registry, atom, {+ suspendOnWaiting: false,+ }).pipe(+ Effect.timeoutOption(6_000),+ Effect.catch(() => Effect.succeed(Option.none<AuthSessionState>())),+ );+ const missing = scopes.find(+ (scope) => Option.isNone(session) || !grants(session.value, scope),+ );+ if (missing !== undefined)+ return yield* Effect.fail(+ new EnvironmentAuthorizationError({+ requiredScope: missing,+ message: `This connection requires ${missing}.`,+ }),+ );+ }),+ );+ });+ return { requiredScopes, permissionAtom, authorize };+}++const permissionsByRuntime = new WeakMap<+ object,+ Map<string, ReturnType<typeof makeCommandPermissions>>+>();++/** Reuse availability atoms and dispatch guards across commands on the same runtime. */+export function createCommandPermissions<R, E>(+ runtime: Atom.AtomRuntime<EnvironmentRegistry | R, E>,+ method: string,+) {+ let permissions = permissionsByRuntime.get(runtime);+ if (permissions === undefined) {+ permissions = new Map();+ permissionsByRuntime.set(runtime, permissions);+ }+ const existing = permissions.get(method);+ if (existing !== undefined) return existing;+ const created = makeCommandPermissions(runtime, method);+ permissions.set(method, created);+ return created;+}diff --git a/packages/client-runtime/src/state/environmentStreams.ts b/packages/client-runtime/src/state/environmentStreams.tsnew file mode 100644index 00000000000..6234973238e--- /dev/null+++ b/packages/client-runtime/src/state/environmentStreams.ts@@ -0,0 +1,35 @@+import type { EnvironmentId as EnvironmentIdType } from "@t3tools/contracts";+import * as Effect from "effect/Effect";+import * as Stream from "effect/Stream";+import * as EnvironmentRegistry from "../connection/registry.ts";+import type * as EnvironmentSupervisor from "../connection/supervisor.ts";++export function runStreamInEnvironment<A, E, R>(+ environmentId: EnvironmentIdType,+ stream: Stream.Stream<A, E, R>,+): Stream.Stream<+ A,+ E | EnvironmentRegistry.EnvironmentNotRegisteredError,+ EnvironmentRegistry.EnvironmentRegistry | Exclude<R, EnvironmentSupervisor.EnvironmentSupervisor>+> {+ return Stream.unwrap(+ EnvironmentRegistry.EnvironmentRegistry.pipe(+ Effect.map((registry) => registry.runStream(environmentId, stream)),+ ),+ );+}++export function followStreamInEnvironment<A, E, R>(+ environmentId: EnvironmentIdType,+ stream: Stream.Stream<A, E, R>,+): Stream.Stream<+ A,+ E,+ EnvironmentRegistry.EnvironmentRegistry | Exclude<R, EnvironmentSupervisor.EnvironmentSupervisor>+> {+ return Stream.unwrap(+ EnvironmentRegistry.EnvironmentRegistry.pipe(+ Effect.map((registry) => registry.followStream(environmentId, stream)),+ ),+ );+}diff --git a/packages/client-runtime/src/state/pullRequestRouting.ts b/packages/client-runtime/src/state/pullRequestRouting.tsindex ce46fb31494..f8781837c36 100644--- a/packages/client-runtime/src/state/pullRequestRouting.ts+++ b/packages/client-runtime/src/state/pullRequestRouting.ts@@ -24,7 +24,7 @@ import type { ConnectionCatalogEntry } from "../connection/catalog.ts";import * as ConnectionProfileStore from "../connection/profileStore.ts";import type { RpcSession } from "../rpc/session.ts";import {- request,+ requestGuarded as request,EnvironmentRpcUnavailableError,type EnvironmentRpcInput,type EnvironmentUnaryRpcTag,diff --git a/packages/client-runtime/src/state/runtime.ts b/packages/client-runtime/src/state/runtime.tsindex 64f91d5681a..0d416362d46 100644--- a/packages/client-runtime/src/state/runtime.ts+++ b/packages/client-runtime/src/state/runtime.ts@@ -1,4 +1,11 @@-import { EnvironmentId, type EnvironmentId as EnvironmentIdType } from "@t3tools/contracts";+import { createCommandPermissions } from "./commandPermissions.ts";+import { runStreamInEnvironment, followStreamInEnvironment } from "./environmentStreams.ts";+export { runStreamInEnvironment, followStreamInEnvironment } from "./environmentStreams.ts";+import {+ type ClientGuardedRpcTag,+ EnvironmentId,+ type EnvironmentId as EnvironmentIdType,+} from "@t3tools/contracts";import * as Cause from "effect/Cause";import * as Effect from "effect/Effect";import * as Exit from "effect/Exit";@@ -19,6 +26,8 @@ import {type EnvironmentUnaryRpcTag,EnvironmentRpcUnavailableError,request,+ requestGuarded,+ RpcPermissionGuard,subscribe,} from "../rpc/client.ts";import * as EnvironmentSupervisor from "../connection/supervisor.ts";@@ -459,36 +468,6 @@ function runInEnvironment<A, E, R>();}-export function runStreamInEnvironment<A, E, R>(- environmentId: EnvironmentIdType,- stream: Stream.Stream<A, E, R>,-): Stream.Stream<- A,- E | EnvironmentRegistry.EnvironmentNotRegisteredError,- EnvironmentRegistry.EnvironmentRegistry | Exclude<R, EnvironmentSupervisor.EnvironmentSupervisor>-> {- return Stream.unwrap(- EnvironmentRegistry.EnvironmentRegistry.pipe(- Effect.map((registry) => registry.runStream(environmentId, stream)),- ),- );-}--export function followStreamInEnvironment<A, E, R>(- environmentId: EnvironmentIdType,- stream: Stream.Stream<A, E, R>,-): Stream.Stream<- A,- E,- EnvironmentRegistry.EnvironmentRegistry | Exclude<R, EnvironmentSupervisor.EnvironmentSupervisor>-> {- return Stream.unwrap(- EnvironmentRegistry.EnvironmentRegistry.pipe(- Effect.map((registry) => registry.followStream(environmentId, stream)),- ),- );-}-/*** Refreshes a query when `signal` changes, but only while something reads it.* `Atom.makeRefreshOnSignal` subscribes to the signal, so a query that outlives its view on an@@ -660,7 +639,11 @@ export function createEnvironmentCommand<R, ER, Input, A, E>(});}-export function createEnvironmentRpcQueryAtomFamily<R, ER, TTag extends EnvironmentUnaryRpcTag>(+export function createEnvironmentRpcQueryAtomFamily<+ R,+ ER,+ TTag extends Exclude<EnvironmentUnaryRpcTag, ClientGuardedRpcTag>,+>(runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, ER>,options: {readonly label: string;@@ -767,7 +750,8 @@ export function createEnvironmentRpcCommand<R, ER, TTag extends EnvironmentUnary) => Effect.Effect<void, never, R>;},) {- return createEnvironmentCommand(runtime, {+ const permissions = createCommandPermissions(runtime, options.tag);+ const command = createEnvironmentCommand(runtime, {label: options.label,...(options.scheduler === undefined ? {} : { scheduler: options.scheduler }),...(options.concurrency === undefined ? {} : { concurrency: options.concurrency }),@@ -776,10 +760,22 @@ export function createEnvironmentRpcCommand<R, ER, TTag extends EnvironmentUnaryenvironmentId,input,};- return (options.execute?.(input) ?? request(options.tag, input)).pipe(+ // Routing requires consent on the origin as well as the actual destination.+ // The transport check below deliberately checks the destination again.+ return permissions.authorize(registry, environmentId, input).pipe(+ Effect.andThen(() => options.execute?.(input) ?? requestGuarded(options.tag, input)),+ Effect.provideService(RpcPermissionGuard, {+ authorize: (id, method, payload) =>+ createCommandPermissions(runtime, method).authorize(registry, id, payload),+ }),Effect.tap(() => options.onSuccess?.(target, registry) ?? Effect.void),Effect.ensuring(options.onSettled?.(target, registry) ?? Effect.void),);},});+ return {+ ...command,+ requiredScopes: permissions.requiredScopes,+ permissionAtom: permissions.permissionAtom,+ };}diff --git a/packages/client-runtime/src/state/session.ts b/packages/client-runtime/src/state/session.tsindex 822efa9a1d2..63c23d735fa 100644--- a/packages/client-runtime/src/state/session.ts+++ b/packages/client-runtime/src/state/session.ts@@ -1,9 +1,10 @@import type { AuthSessionState, EnvironmentId, ServerConfig } from "@t3tools/contracts";+import * as Data from "effect/Data";import * as Effect from "effect/Effect";import * as Option from "effect/Option";import * as Stream from "effect/Stream";import * as SubscriptionRef from "effect/SubscriptionRef";-import type { HttpClient } from "effect/http";+import { HttpClient } from "effect/http";import { AsyncResult, Atom } from "effect/reactivity";import * as RemoteEnvironmentAuthorization from "../authorization/service.ts";@@ -14,7 +15,12 @@ import { environmentEndpointUrl } from "../environment/endpoint.ts";import * as ManagedRelay from "../relay/managedRelay.ts";import { safeErrorLogAttributes } from "../errors/safeLog.ts";import { executeAuthenticatedEnvironmentHttpRequest } from "./environmentHttpAuth.ts";-import { followStreamInEnvironment } from "./runtime.ts";+import { followStreamInEnvironment } from "./environmentStreams.ts";++/** @public Required to name the error in consumers' inferred session results. */+export class SessionHttpClientUnavailable extends Data.TaggedError(+ "SessionHttpClientUnavailable",+) {}function initialConfigOption<E>(initialConfig: Effect.Effect<ServerConfig, E>,@@ -61,8 +67,8 @@ export const fetchEnvironmentSessionState = Effect.fn(});});-export function createEnvironmentSessionAtoms<R, E>(- runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | HttpClient.HttpClient | R, E>,+function makeEnvironmentSessionAtoms<R, E>(+ runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, E>,) {const initialConfigAtom = Atom.family((environmentId: EnvironmentId) =>runtime.atom(@@ -137,7 +143,13 @@ export function createEnvironmentSessionAtoms<R, E>(const remoteAuthorization = yield* Effect.serviceOption(RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization,);- return yield* fetchEnvironmentSessionState({ prepared, signer, remoteAuthorization });+ const client = yield* Effect.serviceOption(HttpClient.HttpClient);+ if (Option.isNone(client)) return yield* new SessionHttpClientUnavailable();+ return yield* fetchEnvironmentSessionState({+ prepared,+ signer,+ remoteAuthorization,+ }).pipe(Effect.provideService(HttpClient.HttpClient, client.value));});}).pipe(@@ -163,3 +175,16 @@ export function createEnvironmentSessionAtoms<R, E>(sessionStateValueAtom,};}++const sessionAtomsByRuntime = new WeakMap<object, ReturnType<typeof makeEnvironmentSessionAtoms>>();++/** Commands and UI share one session fetch and the same reconnect invalidation. */+export function createEnvironmentSessionAtoms<R, E>(+ runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, E>,+): ReturnType<typeof makeEnvironmentSessionAtoms<R, E>> {+ const existing = sessionAtomsByRuntime.get(runtime);+ if (existing) return existing as ReturnType<typeof makeEnvironmentSessionAtoms<R, E>>;+ const atoms = makeEnvironmentSessionAtoms(runtime);+ sessionAtomsByRuntime.set(runtime, atoms);+ return atoms;+}diff --git a/packages/client-runtime/src/state/usage.test.ts b/packages/client-runtime/src/state/usage.test.tsindex 9907c99cfc2..6c1fbcd4a72 100644--- a/packages/client-runtime/src/state/usage.test.ts+++ b/packages/client-runtime/src/state/usage.test.ts@@ -75,6 +75,8 @@ function harness(ids = ["a"]) {get(environmentId).query,refreshUsageRates: {label: "test:rates",+ requiredScopes: () => [],+ permissionAtom: () => Atom.make(true),run: (_registry: AtomRegistry.AtomRegistry,{ environmentId }: { environmentId: EnvironmentId },diff --git a/packages/contracts/src/auth.ts b/packages/contracts/src/auth.tsindex 886cd9add68..f811a520c23 100644--- a/packages/contracts/src/auth.ts+++ b/packages/contracts/src/auth.ts@@ -80,6 +80,9 @@ export type ServerAuthSessionMethod = typeof ServerAuthSessionMethod.Type;export const AuthOrchestrationReadScope = "orchestration:read" as const;export const AuthOrchestrationOperateScope = "orchestration:operate" as const;+export const AuthSettingsWriteScope = "settings:write" as const;+export const AuthProvidersManageScope = "providers:manage" as const;+export const AuthEnvironmentMaintainScope = "environment:maintain" as const;export const AuthTerminalOperateScope = "terminal:operate" as const;export const AuthReviewWriteScope = "review:write" as const;export const AuthAccessReadScope = "access:read" as const;@@ -89,6 +92,9 @@ export const AuthRelayWriteScope = "relay:write" as const;export const AuthEnvironmentScope = Schema.Literals([AuthOrchestrationReadScope,AuthOrchestrationOperateScope,+ AuthSettingsWriteScope,+ AuthProvidersManageScope,+ AuthEnvironmentMaintainScope,AuthTerminalOperateScope,AuthReviewWriteScope,AuthAccessReadScope,@@ -103,6 +109,9 @@ export type AuthEnvironmentScopes = typeof AuthEnvironmentScopes.Type;export const AuthStandardClientScopes = [AuthOrchestrationReadScope,AuthOrchestrationOperateScope,+ AuthSettingsWriteScope,+ AuthProvidersManageScope,+ AuthEnvironmentMaintainScope,AuthTerminalOperateScope,AuthReviewWriteScope,AuthRelayReadScope,@@ -145,6 +154,8 @@ export const ServerAuthDescriptor = Schema.Struct({bootstrapMethods: Schema.Array(ServerAuthBootstrapMethod),sessionMethods: Schema.Array(ServerAuthSessionMethod),sessionCookieName: TrimmedNonEmptyString,+ /** Older servers omit this and authorize self-updates with orchestration:operate. */+ serverUpdateScope: Schema.optionalKey(Schema.Literal(AuthEnvironmentMaintainScope)),});export type ServerAuthDescriptor = typeof ServerAuthDescriptor.Type;diff --git a/packages/contracts/src/clientRpcPermissions.ts b/packages/contracts/src/clientRpcPermissions.tsnew file mode 100644index 00000000000..e4f535d792d--- /dev/null+++ b/packages/contracts/src/clientRpcPermissions.ts@@ -0,0 +1,21 @@+import { AuthOrchestrationOperateScope, type AuthEnvironmentScope } from "./auth.ts";+import { WS_METHODS } from "./rpc.ts";++/** Incremental client enforcement; the server still authorizes every request. */+export const CLIENT_GUARDED_RPC_SCOPES = {+ [WS_METHODS.scheduledTasksUpsert]: AuthOrchestrationOperateScope,+ [WS_METHODS.scheduledTasksSetEnabled]: AuthOrchestrationOperateScope,+ [WS_METHODS.scheduledTasksDelete]: AuthOrchestrationOperateScope,+ [WS_METHODS.scheduledTasksRunNow]: AuthOrchestrationOperateScope,+ [WS_METHODS.scheduledTasksRotateWebhookToken]: AuthOrchestrationOperateScope,+} as const;+export type ClientGuardedRpcTag = keyof typeof CLIENT_GUARDED_RPC_SCOPES;++export function clientRpcRequiredScopes(+ method: string,+ _input: unknown,+): readonly AuthEnvironmentScope[] {+ return Object.hasOwn(CLIENT_GUARDED_RPC_SCOPES, method)+ ? [CLIENT_GUARDED_RPC_SCOPES[method as ClientGuardedRpcTag]]+ : [];+}diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.tsindex 277a341f3a5..3a67ab2ccee 100644--- a/packages/contracts/src/index.ts+++ b/packages/contracts/src/index.ts@@ -62,3 +62,4 @@ export * from "./resourceTelemetry.ts";export * from "./rpc.ts";export * from "./worktreeSetup.ts";export * from "./secretRequest.ts";+export * from "./clientRpcPermissions.ts";diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.tsindex 7984ca20b57..942fbb915ff 100644--- a/packages/contracts/src/settings.ts+++ b/packages/contracts/src/settings.ts@@ -1,4 +1,9 @@import { SshDeviceHostConfigs } from "./device.ts";+import {+ AuthSettingsWriteScope,+ AuthProvidersManageScope,+ type AuthEnvironmentScope,+} from "./auth.ts";import * as Effect from "effect/Effect";import * as Duration from "effect/Duration";import * as Schema from "effect/Schema";@@ -1790,6 +1795,26 @@ export const ServerSettingsPatch = Schema.Struct({});export type ServerSettingsPatch = typeof ServerSettingsPatch.Type;+/** A mixed settings patch must be authorized for every configuration domain it changes. */+export function requiredScopesForServerSettingsPatch(+ patch: ServerSettingsPatch,+): ReadonlyArray<AuthEnvironmentScope> {+ let changesProviders = false;+ let changesSettings = false;+ for (const [key, value] of Object.entries(patch)) {+ if (value === undefined) continue;+ if (key === "providers" || key === "providerInstances" || key === "usageLimitSources") {+ changesProviders = true;+ } else {+ changesSettings = true;+ }+ }+ return [+ ...(changesSettings || !changesProviders ? [AuthSettingsWriteScope] : []),+ ...(changesProviders ? [AuthProvidersManageScope] : []),+ ];+}+export const ClientSettingsPatch = Schema.Struct({notificationMode: Schema.optionalKey(NotificationMode),inAppNotificationsEnabled: Schema.optionalKey(Schema.Boolean),diff --git a/vite.config.ts b/vite.config.tsindex ca3ed94432c..b3cd99cafba 100644--- a/vite.config.ts+++ b/vite.config.ts@@ -169,12 +169,53 @@ export default defineConfig({"t3code/no-native-title-tooltip": "error","t3code/no-raw-mcp-registration": "error","t3code/no-test-in-loop": "error",+ "t3code/no-rpc-permission-bypass": ["error", { allowRawClientAccess: true }],"t3code/no-unscoped-has": "error","t3code/namespace-node-imports": "error","t3code/prefer-catch-tags": "error","t3code/require-suppression-reason": "error",},overrides: [+ {+ files: ["packages/client-runtime/src/state/**", "apps/{web,mobile,desktop}/src/**"],+ rules: { "t3code/no-rpc-permission-bypass": ["error", { allowRawClientAccess: false }] },+ },+ {+ // Only shared command boundaries install the session-backed permission guard.+ files: [+ "packages/client-runtime/src/state/runtime.ts",+ "packages/client-runtime/src/state/vcsAction.ts",+ ],+ rules: {+ "t3code/no-rpc-permission-bypass": [+ "error",+ { allowGuardInstallation: true, allowRawClientAccess: false },+ ],+ },+ },+ {+ // These clients are session metadata, device streams, and an Expo update adapter.+ files: [+ "apps/web/src/components/settings/ConnectionsSettings.tsx",+ "apps/mobile/src/features/updates/app-updates.ts",+ "apps/web/src/components/device/DevicePhoneViewport.tsx",+ "apps/web/src/components/device/DeviceDuoViewport.tsx",+ ],+ rules: { "t3code/no-rpc-permission-bypass": ["error", { allowRawClientAccess: true }] },+ },+ {+ // Incompatible hosts cannot open a normal session; their updater uses a dedicated socket.+ files: ["packages/client-runtime/src/connection/outdatedHostUpdate.ts"],+ rules: { "t3code/no-rpc-permission-bypass": "off" },+ },+ {+ // RPC implementation and transport test fixtures need the raw client.+ files: [+ "packages/client-runtime/src/rpc/**",+ "**/*.{test,spec}.{ts,tsx,js,jsx,mts,cts,mjs,cjs}",+ ],+ rules: { "t3code/no-rpc-permission-bypass": "off" },+ },{// The one place that reads the host platform to seed the injected references.files: ["packages/shared/src/hostProcess.ts"],