Skip to content
TypeScript

feat(auth): separate browser preview control permissions (#9789)

Julius Marminge7175edcff4f2
diff --git a/apps/desktop/src/ipc/channels.ts b/apps/desktop/src/ipc/channels.ts
index 00cbe008c4a..9ae71cab1df 100644
--- a/apps/desktop/src/ipc/channels.ts
+++ b/apps/desktop/src/ipc/channels.ts
@@ -90,6 +90,8 @@ export const PREVIEW_GET_CONFIG_CHANNEL = "desktop:preview-get-config";
export const PREVIEW_IMPORT_SOURCES_CHANNEL = "desktop:preview-import-sources";
export const PREVIEW_IMPORT_COOKIES_CHANNEL = "desktop:preview-import-cookies";
export const PREVIEW_SET_ANNOTATION_THEME_CHANNEL = "desktop:preview-set-annotation-theme";
+export const PREVIEW_SET_ANNOTATION_SEND_ENABLED_CHANNEL =
+ "desktop:preview-set-annotation-send-enabled";
export const PREVIEW_PICK_ELEMENT_CHANNEL = "desktop:preview-pick-element";
export const PREVIEW_CANCEL_PICK_ELEMENT_CHANNEL = "desktop:preview-cancel-pick-element";
export const PREVIEW_CAPTURE_SCREENSHOT_CHANNEL = "desktop:preview-capture-screenshot";
diff --git a/apps/desktop/src/ipc/methods/preview.ts b/apps/desktop/src/ipc/methods/preview.ts
index e9b795a2326..4afc61d6f76 100644
--- a/apps/desktop/src/ipc/methods/preview.ts
+++ b/apps/desktop/src/ipc/methods/preview.ts
@@ -1,4 +1,5 @@
import {
+ DesktopPreviewAnnotationSendEnabledInputSchema,
DesktopPreviewAnnotationThemeInputSchema,
DesktopPreviewArtifactInputSchema,
DesktopPreviewConfigInputSchema,
@@ -377,6 +378,19 @@ export const pickElement = DesktopIpc.makeIpcMethod({
}),
});
+export const setAnnotationSendEnabled = DesktopIpc.makeIpcMethod({
+ channel: IpcChannels.PREVIEW_SET_ANNOTATION_SEND_ENABLED_CHANNEL,
+ payload: DesktopPreviewAnnotationSendEnabledInputSchema,
+ result: Schema.Void,
+ handler: Effect.fn("desktop.ipc.preview.setAnnotationSendEnabled")(function* ({
+ tabId,
+ enabled,
+ }) {
+ const manager = yield* PreviewManager.PreviewManager;
+ yield* manager.setAnnotationSendEnabled(tabId, enabled);
+ }),
+});
+
export const captureScreenshot = DesktopIpc.makeIpcMethod({
channel: IpcChannels.PREVIEW_CAPTURE_SCREENSHOT_CHANNEL,
payload: DesktopPreviewTabInputSchema,
@@ -438,6 +452,7 @@ export const methods = [
clearCache,
getPreviewConfig,
setAnnotationTheme,
+ setAnnotationSendEnabled,
pickElement,
cancelPickElement,
captureScreenshot,
diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts
index d6e6470483f..a97f224a1b4 100644
--- a/apps/desktop/src/preload.ts
+++ b/apps/desktop/src/preload.ts
@@ -339,6 +339,11 @@ contextBridge.exposeInMainWorld("desktopBridge", {
ipcRenderer.invoke(IpcChannels.PREVIEW_GET_CONFIG_CHANNEL, { environmentId, profileId }),
setAnnotationTheme: (theme) =>
ipcRenderer.invoke(IpcChannels.PREVIEW_SET_ANNOTATION_THEME_CHANNEL, { theme }),
+ setAnnotationSendEnabled: (tabId, enabled) =>
+ ipcRenderer.invoke(IpcChannels.PREVIEW_SET_ANNOTATION_SEND_ENABLED_CHANNEL, {
+ tabId,
+ enabled,
+ }),
pickElement: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_PICK_ELEMENT_CHANNEL, { tabId }),
cancelPickElement: (tabId) =>
ipcRenderer.invoke(IpcChannels.PREVIEW_CANCEL_PICK_ELEMENT_CHANNEL, { tabId }),
diff --git a/apps/desktop/src/preview/AnnotationKeyboard.test.ts b/apps/desktop/src/preview/AnnotationKeyboard.test.ts
index f49c1cb79f1..4124e548bec 100644
--- a/apps/desktop/src/preview/AnnotationKeyboard.test.ts
+++ b/apps/desktop/src/preview/AnnotationKeyboard.test.ts
@@ -15,14 +15,23 @@ const keyboardEvent = (
describe("resolveAnnotationSubmission", () => {
it("attaches on Enter and sends on Cmd/Ctrl+Enter", () => {
- expect(resolveAnnotationSubmission(keyboardEvent())).toBe("attach");
- expect(resolveAnnotationSubmission(keyboardEvent({ metaKey: true }))).toBe("send");
- expect(resolveAnnotationSubmission(keyboardEvent({ ctrlKey: true }))).toBe("send");
+ expect(resolveAnnotationSubmission(keyboardEvent(), true)).toBe("attach");
+ expect(resolveAnnotationSubmission(keyboardEvent({ metaKey: true }), true)).toBe("send");
+ expect(resolveAnnotationSubmission(keyboardEvent({ ctrlKey: true }), true)).toBe("send");
});
it("leaves Shift+Enter and composition events available for editing", () => {
- expect(resolveAnnotationSubmission(keyboardEvent({ shiftKey: true }))).toBeNull();
- expect(resolveAnnotationSubmission(keyboardEvent({ isComposing: true }))).toBeNull();
- expect(resolveAnnotationSubmission(keyboardEvent({ key: " " }))).toBeNull();
+ expect(resolveAnnotationSubmission(keyboardEvent({ shiftKey: true }), true)).toBeNull();
+ expect(resolveAnnotationSubmission(keyboardEvent({ isComposing: true }), true)).toBeNull();
+ expect(resolveAnnotationSubmission(keyboardEvent({ key: " " }), true)).toBeNull();
+ });
+
+ it("keeps attach available while the send shortcut follows permission changes", () => {
+ const send = keyboardEvent({ ctrlKey: true });
+ expect(resolveAnnotationSubmission(send, false)).toBeNull();
+ expect(resolveAnnotationSubmission(keyboardEvent(), false)).toBe("attach");
+ expect(resolveAnnotationSubmission(send, true)).toBe("send");
+ expect(resolveAnnotationSubmission(send, false)).toBeNull();
+ expect(resolveAnnotationSubmission(keyboardEvent({ metaKey: true }), false)).toBeNull();
});
});
diff --git a/apps/desktop/src/preview/AnnotationKeyboard.ts b/apps/desktop/src/preview/AnnotationKeyboard.ts
index 6c694ccd2ed..8b935bfbec1 100644
--- a/apps/desktop/src/preview/AnnotationKeyboard.ts
+++ b/apps/desktop/src/preview/AnnotationKeyboard.ts
@@ -10,7 +10,8 @@ interface AnnotationKeyboardEvent {
export function resolveAnnotationSubmission(
event: AnnotationKeyboardEvent,
+ canSend: boolean,
): PreviewAnnotationSubmission | null {
if (event.key !== "Enter" || event.shiftKey || event.isComposing) return null;
- return event.metaKey || event.ctrlKey ? "send" : "attach";
+ return event.metaKey || event.ctrlKey ? (canSend ? "send" : null) : "attach";
}
diff --git a/apps/desktop/src/preview/GuestProtocol.ts b/apps/desktop/src/preview/GuestProtocol.ts
index 1a73bb30f29..5019076a100 100644
--- a/apps/desktop/src/preview/GuestProtocol.ts
+++ b/apps/desktop/src/preview/GuestProtocol.ts
@@ -3,6 +3,7 @@ export const CANCEL_PICK_CHANNEL = "preview:cancel-pick";
export const ELEMENT_PICKED_CHANNEL = "preview:element-picked";
export const ANNOTATION_CAPTURED_CHANNEL = "preview:annotation-captured";
export const ANNOTATION_THEME_CHANNEL = "preview:annotation-theme";
+export const ANNOTATION_SEND_ENABLED_CHANNEL = "preview:annotation-send-enabled";
export const HUMAN_INPUT_CHANNEL = "preview:human-input";
export const MOUSE_NAVIGATE_CHANNEL = "preview:mouse-navigate";
export const RECORDING_CURSOR_CHANNEL = "preview:recording-cursor";
diff --git a/apps/desktop/src/preview/Manager.test.ts b/apps/desktop/src/preview/Manager.test.ts
index 9b8bf7c50de..11ee2d83e48 100644
--- a/apps/desktop/src/preview/Manager.test.ts
+++ b/apps/desktop/src/preview/Manager.test.ts
@@ -3937,6 +3937,85 @@ describe("PreviewManager", () => {
),
);
+ effectIt.effect("keeps annotation send grants isolated and updates an active pick", () =>
+ withManager((manager) =>
+ Effect.gen(function* () {
+ const picked = new Map<number, (event: unknown, ...args: unknown[]) => void>();
+ const capturePage = vi.fn(async () => ({
+ toJPEG: () => Buffer.from("annotation"),
+ toDataURL: () => "data:image/png;base64,YW5ub3RhdGlvbg==",
+ getSize: () => ({ width: 10, height: 10 }),
+ }));
+ const guests = new Map(
+ [42, 43, 44].map(
+ (id) =>
+ [
+ id,
+ Object.assign(makeTestPreviewWebContents(capturePage, id), {
+ isFocused: () => true,
+ once: vi.fn(),
+ ipc: {
+ on: vi.fn(
+ (channel: string, listener: (event: unknown, ...args: unknown[]) => void) => {
+ if (channel === "preview:element-picked") picked.set(id, listener);
+ },
+ ),
+ off: vi.fn(),
+ removeListener: vi.fn(),
+ },
+ }),
+ ] as const,
+ ),
+ );
+ fromId.mockImplementation((id) => (id === undefined ? null : (guests.get(id) ?? null)));
+ yield* manager.createTab("tab_a");
+ yield* manager.createTab("tab_b");
+ yield* manager.registerWebview("tab_a", 42);
+ yield* manager.registerWebview("tab_b", 43);
+ yield* manager.setAnnotationSendEnabled("tab_a", true);
+ const annotation = {
+ id: "annotation-scopes",
+ pageUrl: "https://example.com",
+ pageTitle: "Example",
+ comment: "Tighten this spacing",
+ elements: [],
+ regions: [],
+ strokes: [],
+ styleChanges: [],
+ screenshot: null,
+ createdAt: "2026-09-05T00:00:00.000Z",
+ };
+ for (const [tabId, id, nextGrant, expected] of [
+ ["tab_b", 43, undefined, "attach"],
+ ["tab_a", 42, false, "attach"],
+ ["tab_a", 42, true, "send"],
+ ] as const) {
+ const pick = yield* manager.pickElement(tabId).pipe(Effect.forkChild);
+ yield* Effect.yieldNow;
+ if (nextGrant !== undefined) {
+ yield* manager.setAnnotationSendEnabled(tabId, nextGrant);
+ }
+ picked.get(id)?.({}, annotation, null, "send");
+ const result = yield* Fiber.join(pick);
+ expect(result?.annotation.id).toBe(annotation.id);
+ expect(result?.submission).toBe(expected);
+ }
+ yield* manager.registerWebview("tab_a", 44);
+ const replacementPick = yield* manager.pickElement("tab_a").pipe(Effect.forkChild);
+ yield* Effect.yieldNow;
+ picked.get(44)?.({}, annotation, null, "send");
+ expect((yield* Fiber.join(replacementPick))?.submission).toBe("send");
+ yield* manager.closeTab("tab_a");
+ yield* manager.createTab("tab_a");
+ yield* manager.registerWebview("tab_a", 44);
+ const reopenedPick = yield* manager.pickElement("tab_a").pipe(Effect.forkChild);
+ yield* Effect.yieldNow;
+ picked.get(44)?.({}, annotation, null, "send");
+ expect((yield* Fiber.join(reopenedPick))?.submission).toBe("attach");
+ }),
+ ),
+ );
+
effectIt.effect("settles the pick when the annotation screenshot never arrives", () =>
withManager((manager) =>
Effect.gen(function* () {
@@ -3983,6 +4062,7 @@ describe("PreviewManager", () => {
const pick = yield* manager.pickElement("tab_1").pipe(Effect.forkChild);
yield* Effect.yieldNow;
+ yield* manager.setAnnotationSendEnabled("tab_1", true);
onPicked?.(
{},
{
diff --git a/apps/desktop/src/preview/Manager.ts b/apps/desktop/src/preview/Manager.ts
index 74b391a025b..f98694145b6 100644
--- a/apps/desktop/src/preview/Manager.ts
+++ b/apps/desktop/src/preview/Manager.ts
@@ -65,6 +65,7 @@ import * as DesktopBrowserHost from "./DesktopBrowserHost.ts";
import * as BrowserSession from "./BrowserSession.ts";
import {
ANNOTATION_CAPTURED_CHANNEL,
+ ANNOTATION_SEND_ENABLED_CHANNEL,
ANNOTATION_THEME_CHANNEL,
CANCEL_PICK_CHANNEL,
ELEMENT_PICKED_CHANNEL,
@@ -559,6 +560,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
let forwardedShortcuts: ReadonlyArray<PreviewForwardedShortcut> = [];
const annotationThemeRef = yield* Ref.make(DEFAULT_ANNOTATION_THEME);
+ const annotationSendEnabled = new Map<string, boolean>();
const mainWindowRef = yield* Ref.make<Option.Option<BrowserWindow>>(Option.none());
const tabsRef = yield* SynchronizedRef.make<ReadonlyMap<string, PreviewTabState>>(new Map());
const attachedRef = yield* Ref.make<ReadonlyMap<number, ManagedListeners>>(new Map());
@@ -1713,6 +1715,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
const closeTabUnlocked = Effect.fn("PreviewManager.closeTabUnlocked")(function* (tabId: string) {
if (!(yield* SynchronizedRef.get(tabsRef)).has(tabId)) return;
clearPendingRecording(tabId);
+ annotationSendEnabled.delete(tabId);
yield* Effect.all(
[
cancelPickElement(tabId),
@@ -1814,9 +1817,10 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
// changed. Only push its zoom back down — Chromium may have just handed
// this guest the app window's zoom level.
yield* assertTabZoom(tabId);
- yield* attempt({ operation: "registerWebview.sendTheme", tabId, webContentsId }, () =>
- wc.send(ANNOTATION_THEME_CHANNEL, annotationTheme),
- );
+ yield* attempt({ operation: "registerWebview.sendTheme", tabId, webContentsId }, () => {
+ wc.send(ANNOTATION_THEME_CHANNEL, annotationTheme);
+ wc.send(ANNOTATION_SEND_ENABLED_CHANNEL, annotationSendEnabled.get(tabId) === true);
+ });
return;
}
const replacedWebContentsId =
@@ -1923,9 +1927,10 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
// syncTabAudible's ownership check, so re-read and reconcile through the
// same path the event uses.
yield* syncTabAudible(tabId, wc, yield* readAudible);
- yield* attempt({ operation: "registerWebview.sendTheme", tabId, webContentsId }, () =>
- wc.send(ANNOTATION_THEME_CHANNEL, annotationTheme),
- );
+ yield* attempt({ operation: "registerWebview.sendTheme", tabId, webContentsId }, () => {
+ wc.send(ANNOTATION_THEME_CHANNEL, annotationTheme);
+ wc.send(ANNOTATION_SEND_ENABLED_CHANNEL, annotationSendEnabled.get(tabId) === true);
+ });
const latestNavStatus = (yield* SynchronizedRef.get(tabsRef)).get(tabId)?.navStatus;
if (
pendingUrl &&
@@ -2139,6 +2144,17 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
);
});
+ const setAnnotationSendEnabled = Effect.fn("PreviewManager.setAnnotationSendEnabled")(function* (
+ tabId: string,
+ enabled: boolean,
+ ) {
+ const wc = yield* requireWebContents(tabId);
+ yield* attempt({ operation: "setAnnotationSendEnabled", tabId, webContentsId: wc.id }, () => {
+ annotationSendEnabled.set(tabId, enabled);
+ wc.send(ANNOTATION_SEND_ENABLED_CHANNEL, enabled);
+ });
+ });
+
const pickElement = Effect.fn("PreviewManager.pickElement")(function* (tabId: string) {
const wc = yield* requireWebContents(tabId);
yield* cancelPickElement(tabId);
@@ -2216,7 +2232,8 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
return;
}
const cropRect = normalizeCaptureRect(args[1]);
- const submission = args[2] === "send" ? "send" : "attach";
+ const submission =
+ args[2] === "send" && annotationSendEnabled.get(tabId) === true ? "send" : "attach";
runFork(
captureAnnotationScreenshot(tabId, wc, cropRect).pipe(
// The renderer cannot tell a dropped crop from a comment-only
@@ -2275,7 +2292,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
wc.once("destroyed", onDestroyed);
wc.on("did-start-navigation", onNavigated);
if (!wc.isFocused()) wc.focus();
- wc.send(START_PICK_CHANNEL, annotationTheme);
+ wc.send(START_PICK_CHANNEL, annotationTheme, annotationSendEnabled.get(tabId) === true);
});
});
runFork(
@@ -3356,6 +3373,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
revealArtifact,
saveRecording,
setAnnotationTheme,
+ setAnnotationSendEnabled,
setAudioMuted,
setColorScheme,
setMainWindow,
@@ -3580,6 +3598,10 @@ export class PreviewManager extends Context.Service<
readonly setAnnotationTheme: (
theme: DesktopPreviewAnnotationTheme,
) => Effect.Effect<void, PreviewManagerError>;
+ readonly setAnnotationSendEnabled: (
+ tabId: string,
+ enabled: boolean,
+ ) => Effect.Effect<void, PreviewManagerError>;
readonly pickElement: (
tabId: string,
) => Effect.Effect<PreviewAnnotationSubmissionResult | null, PreviewManagerError>;
@@ -3697,6 +3719,7 @@ export const make = Effect.gen(function* PreviewManagerMake() {
},
),
setAnnotationTheme: operations.setAnnotationTheme,
+ setAnnotationSendEnabled: operations.setAnnotationSendEnabled,
pickElement: operations.pickElement,
cancelPickElement: operations.cancelPickElement,
captureScreenshot: operations.captureScreenshot,
diff --git a/apps/desktop/src/preview/PickPreload.ts b/apps/desktop/src/preview/PickPreload.ts
index 78351e9d79c..a9155677ad3 100644
--- a/apps/desktop/src/preview/PickPreload.ts
+++ b/apps/desktop/src/preview/PickPreload.ts
@@ -20,6 +20,7 @@ import { installRecordingCursor } from "./RecordingCursor.ts";
import { DEFAULT_RECORDING_INPUT_OPTIONS } from "./RecordingInput.ts";
import {
ANNOTATION_CAPTURED_CHANNEL,
+ ANNOTATION_SEND_ENABLED_CHANNEL,
ANNOTATION_THEME_CHANNEL,
CANCEL_PICK_CHANNEL,
ELEMENT_PICKED_CHANNEL,
@@ -129,6 +130,7 @@ interface SelectedElement {
interface AnnotationSession {
teardown: (notifyMain: boolean) => void;
applyTheme: (theme: DesktopPreviewAnnotationTheme) => void;
+ setSendEnabled: (enabled: boolean) => void;
}
let activeSession: AnnotationSession | null = null;
@@ -512,7 +514,7 @@ function strokeBounds(
return { x: left, y: top, width: right - left, height: bottom - top };
}
-function startAnnotation(): void {
+function startAnnotation(sendEnabled: boolean): void {
activeSession?.teardown(false);
let finished = false;
const host = document.createElement("div");
@@ -589,6 +591,12 @@ function startAnnotation(): void {
composerRow.appendChild(dragHandle);
const submit = createButton("Attach", "Attach annotation and screenshot (Enter)");
+ const updateSendHint = () => {
+ submit.title = sendEnabled
+ ? "Attach annotation and screenshot (Enter). Send with Cmd/Ctrl+Enter."
+ : "Attach annotation and screenshot (Enter)";
+ };
+ updateSendHint();
submit.className +=
" h-8 shrink-0 border-primary bg-primary px-3 text-primary-foreground shadow-sm hover:bg-primary/90";
composerRow.appendChild(submit);
@@ -1345,6 +1353,7 @@ function startAnnotation(): void {
};
const submitAnnotation = (submission: PreviewAnnotationSubmission): void => {
+ if (submission === "send" && !sendEnabled) return;
if (pendingCapture || (selected.size === 0 && regions.length === 0 && strokes.length === 0))
return;
pendingCapture = true;
@@ -1396,7 +1405,12 @@ function startAnnotation(): void {
...submittedRegions.map((region) => region.rect),
...submittedStrokes.map((stroke) => stroke.bounds),
]);
- ipcRenderer.send(ELEMENT_PICKED_CHANNEL, annotation, screenshotRect, submission);
+ ipcRenderer.send(
+ ELEMENT_PICKED_CHANNEL,
+ annotation,
+ screenshotRect,
+ submission === "send" && !sendEnabled ? "attach" : submission,
+ );
})
.catch(() => {
// Last resort. Main is waiting on this message, so hand it an empty
@@ -1407,7 +1421,8 @@ function startAnnotation(): void {
};
submit.addEventListener("click", () => submitAnnotation("attach"));
root.addEventListener("keydown", (event) => {
- const submission = event.target === comment ? resolveAnnotationSubmission(event) : null;
+ const submission =
+ event.target === comment ? resolveAnnotationSubmission(event, sendEnabled) : null;
// Keep this in the bubble phase so editor inputs receive the event before
// it is isolated from listeners installed by the inspected page.
event.stopImmediatePropagation();
@@ -1433,12 +1448,22 @@ function startAnnotation(): void {
activeSession = {
teardown,
applyTheme: (theme) => applyAnnotationTheme(host, theme),
+ setSendEnabled: (enabled) => {
+ sendEnabled = enabled;
+ updateSendHint();
+ },
};
}
-ipcRenderer.on(START_PICK_CHANNEL, (_event, theme: DesktopPreviewAnnotationTheme | undefined) => {
- if (theme) annotationTheme = theme;
- startAnnotation();
+ipcRenderer.on(
+ START_PICK_CHANNEL,
+ (_event, theme: DesktopPreviewAnnotationTheme | undefined, sendEnabled?: boolean) => {
+ if (theme) annotationTheme = theme;
+ startAnnotation(sendEnabled === true);
+ },
+);
+ipcRenderer.on(ANNOTATION_SEND_ENABLED_CHANNEL, (_event, enabled: boolean) => {
+ activeSession?.setSendEnabled(enabled === true);
});
ipcRenderer.on(ANNOTATION_THEME_CHANNEL, (_event, theme: DesktopPreviewAnnotationTheme) => {
annotationTheme = theme;
diff --git a/apps/server/src/auth/RpcAuthorization.test.ts b/apps/server/src/auth/RpcAuthorization.test.ts
index 581c26d8abb..be5f02ab3f0 100644
--- a/apps/server/src/auth/RpcAuthorization.test.ts
+++ b/apps/server/src/auth/RpcAuthorization.test.ts
@@ -9,6 +9,7 @@ import {
AuthOrchestrationOperateScope,
AuthOrchestrationReadScope,
AuthSourceControlWriteScope,
+ AuthPreviewOperateScope,
AuthRelayReadScope,
AuthRelayWriteScope,
WS_METHODS,
@@ -138,6 +139,28 @@ describe("RPC authorization scopes", () => {
);
});
+ it("separates preview control from observation", () => {
+ for (const method of [
+ WS_METHODS.previewOpen,
+ WS_METHODS.previewNavigate,
+ WS_METHODS.previewResize,
+ WS_METHODS.previewRefresh,
+ WS_METHODS.previewClose,
+ WS_METHODS.previewReportStatus,
+ WS_METHODS.previewAdjust,
+ WS_METHODS.previewClearProfile,
+ ]) {
+ expect(requiredScopeForRpcMethod(method)).toBe(AuthPreviewOperateScope);
+ }
+ for (const method of [
+ WS_METHODS.previewList,
+ WS_METHODS.subscribePreviewEvents,
+ WS_METHODS.subscribeDiscoveredLocalServers,
+ ]) {
+ expect(requiredScopeForRpcMethod(method)).toBe(AuthOrchestrationReadScope);
+ }
+ });
+
it("rejects unknown RPC method names", () => {
for (const method of ["server.notRegistered", "toString", "constructor"]) {
expect(() => requiredScopeForRpcMethod(method)).toThrow(
diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.ts
index 19ca722001b..28815d53cfa 100644
--- a/apps/server/src/auth/RpcAuthorization.ts
+++ b/apps/server/src/auth/RpcAuthorization.ts
@@ -14,6 +14,7 @@ import {
AuthFilesystemWriteScope,
AuthOrchestrationOperateScope,
AuthOrchestrationReadScope,
+ AuthPreviewOperateScope,
AuthRelayReadScope,
AuthRelayWriteScope,
AuthTerminalOperateScope,
@@ -167,15 +168,15 @@ export const RPC_REQUIRED_SCOPES = {
[WS_METHODS.terminalClose]: AuthTerminalOperateScope,
[WS_METHODS.subscribeTerminalEvents]: AuthTerminalOperateScope,
[WS_METHODS.subscribeTerminalMetadata]: AuthTerminalOperateScope,
- [WS_METHODS.previewOpen]: AuthOrchestrationOperateScope,
- [WS_METHODS.previewNavigate]: AuthOrchestrationOperateScope,
- [WS_METHODS.previewResize]: AuthOrchestrationOperateScope,
- [WS_METHODS.previewAdjust]: AuthOrchestrationOperateScope,
- [WS_METHODS.previewRefresh]: AuthOrchestrationOperateScope,
- [WS_METHODS.previewClose]: AuthOrchestrationOperateScope,
+ [WS_METHODS.previewOpen]: AuthPreviewOperateScope,
+ [WS_METHODS.previewNavigate]: AuthPreviewOperateScope,
+ [WS_METHODS.previewResize]: AuthPreviewOperateScope,
+ [WS_METHODS.previewAdjust]: AuthPreviewOperateScope,
+ [WS_METHODS.previewRefresh]: AuthPreviewOperateScope,
+ [WS_METHODS.previewClose]: AuthPreviewOperateScope,
[WS_METHODS.previewList]: AuthOrchestrationReadScope,
- [WS_METHODS.previewClearProfile]: AuthOrchestrationOperateScope,
- [WS_METHODS.previewReportStatus]: AuthOrchestrationOperateScope,
+ [WS_METHODS.previewClearProfile]: AuthPreviewOperateScope,
+ [WS_METHODS.previewReportStatus]: AuthPreviewOperateScope,
[WS_METHODS.subscribePreviewEvents]: AuthOrchestrationReadScope,
[WS_METHODS.subscribeDiscoveredLocalServers]: AuthOrchestrationReadScope,
[WS_METHODS.deviceConfigure]: AuthSettingsWriteScope,
diff --git a/apps/server/src/mcp/PreviewAutomationBroker.test.ts b/apps/server/src/mcp/PreviewAutomationBroker.test.ts
index 211d8b6cc23..c8b02aa549e 100644
--- a/apps/server/src/mcp/PreviewAutomationBroker.test.ts
+++ b/apps/server/src/mcp/PreviewAutomationBroker.test.ts
@@ -1,7 +1,6 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
import {
- AuthOrchestrationOperateScope,
EnvironmentId,
PreviewAutomationClientDisconnectedError,
PreviewAutomationInvalidSelectorError,
@@ -11,15 +10,12 @@ import {
PreviewTabId,
ProviderInstanceId,
ThreadId,
- WS_METHODS,
- WsRpcGroup,
type PreviewAutomationHost,
type PreviewAutomationRequest,
type PreviewAutomationStreamEvent,
SERVER_BROWSER_AUTOMATION_CLIENT_ID,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
-import * as Layer from "effect/Layer";
import * as Exit from "effect/Exit";
import * as Deferred from "effect/Deferred";
import * as Fiber from "effect/Fiber";
@@ -27,10 +23,7 @@ import * as Result from "effect/Result";
import * as Scheduler from "effect/Scheduler";
import * as Stream from "effect/Stream";
import * as TestClock from "effect/testing/TestClock";
-import * as RpcGroup from "effect/rpc/RpcGroup";
-import * as RpcTest from "effect/rpc/RpcTest";
-import * as RpcAuthorization from "../auth/RpcAuthorization.ts";
import * as PreviewAutomationBroker from "./PreviewAutomationBroker.ts";
const makeBroker = PreviewAutomationBroker.make.pipe(Effect.provide(NodeServices.layer));
diff --git a/apps/web/src/browser/ElectronBrowserHost.tsx b/apps/web/src/browser/ElectronBrowserHost.tsx
index 4d6a7caa2e3..5cbefd9dded 100644
--- a/apps/web/src/browser/ElectronBrowserHost.tsx
+++ b/apps/web/src/browser/ElectronBrowserHost.tsx
@@ -1,15 +1,16 @@
"use client";
import { parseScopedThreadKey } from "@t3tools/client-runtime/environment";
-import { FILL_PREVIEW_VIEWPORT } from "@t3tools/contracts";
+import { AuthPreviewOperateScope, FILL_PREVIEW_VIEWPORT } from "@t3tools/contracts";
import { useAtomValue } from "@effect/atom-react";
-import { useEffect, useMemo } from "react";
+import { type ComponentProps, useEffect, useMemo } from "react";
import { primaryEnvironmentIdAtom } from "~/state/primaryEnvironment";
import { isElectron } from "~/env";
import { useTheme } from "~/hooks/useTheme";
import { useActivePreviewSessions } from "~/previewStateStore";
+import { useEnvironmentScope } from "~/state/session";
import { readPreviewAnnotationTheme } from "./annotationTheme";
import { useBrowserPointerStore } from "./browserPointerStore";
@@ -97,7 +98,7 @@ export function ElectronBrowserHost() {
{sessions.map(({ threadRef, snapshot, runtimeTabId, pictureInPicture, zoomFactor }) => {
const url = snapshot.navStatus._tag === "Idle" ? null : snapshot.navStatus.url;
return (
- <HostedBrowserWebview
+ <AuthorizedBrowserWebview
key={runtimeTabId}
threadRef={threadRef}
tabId={snapshot.tabId}
@@ -122,3 +123,11 @@ export function ElectronBrowserHost() {
</div>
);
}
+
+function AuthorizedBrowserWebview(props: ComponentProps<typeof HostedBrowserWebview>) {
+ const canOperatePreview = useEnvironmentScope(
+ props.threadRef.environmentId,
+ AuthPreviewOperateScope,
+ );
+ return canOperatePreview ? <HostedBrowserWebview {...props} /> : null;
+}
diff --git a/apps/web/src/browser/useOpenLink.ts b/apps/web/src/browser/useOpenLink.ts
index d23d40a3f53..d6d33efc699 100644
--- a/apps/web/src/browser/useOpenLink.ts
+++ b/apps/web/src/browser/useOpenLink.ts
@@ -1,4 +1,4 @@
-import type { ScopedThreadRef } from "@t3tools/contracts";
+import { AuthPreviewOperateScope, type ScopedThreadRef } from "@t3tools/contracts";
import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
@@ -8,6 +8,7 @@ import { useCallback } from "react";
import { recordVisitForThread } from "~/browserHistoryStore";
import { readLocalApi } from "~/localApi";
import { previewEnvironment } from "~/state/preview";
+import { readEnvironmentScope } from "~/state/session";
import { useAtomCommand } from "~/state/use-atom-command";
import {
@@ -46,7 +47,10 @@ export function useOpenLink(threadRef: ScopedThreadRef | null | undefined): (
url,
event: options.event ?? NO_MODIFIER,
preference: await resolveBrowserLinkTargetPreference(),
- canOpenInApp: canOpenLinksInApp(targetThreadRef),
+ canOpenInApp:
+ targetThreadRef != null &&
+ readEnvironmentScope(targetThreadRef.environmentId, AuthPreviewOperateScope) &&
+ canOpenLinksInApp(targetThreadRef),
});
if (target === "app" && targetThreadRef) {
const result = await openUrlInPreview({ threadRef: targetThreadRef, url, openPreview });
diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx
index 4894b15ae07..0d0126edb8e 100644
--- a/apps/web/src/components/ChatMarkdown.tsx
+++ b/apps/web/src/components/ChatMarkdown.tsx
@@ -27,12 +27,13 @@ import {
type LucideIcon,
} from "lucide-react";
import { Check, Copy, Maximize2, Minimize2 } from "lucide";
-import type {
- AssetResource,
- EnvironmentId,
- ScopedThreadRef,
- ServerProviderSkill,
- ThreadPullRequestKey,
+import {
+ AuthPreviewOperateScope,
+ type AssetResource,
+ type EnvironmentId,
+ type ScopedThreadRef,
+ type ServerProviderSkill,
+ type ThreadPullRequestKey,
} from "@t3tools/contracts";
import { faviconUrlForOrigin } from "@t3tools/shared/favicon";
import { githubMediaFetchUrl } from "@t3tools/shared/githubMedia";
@@ -2518,6 +2519,7 @@ function useChatMarkdownState({
const pullRequestLinking = usePullRequestLinking(threadRef?.environmentId);
const environmentId = threadRef?.environmentId ?? explicitEnvironmentId ?? null;
const canOperateHost = useEnvironmentScope(environmentId, AuthOrchestrationOperateScope);
+ const canOperatePreview = useEnvironmentScope(environmentId, AuthPreviewOperateScope);
const remoteOpen = useRemoteOpenResolution(environmentId);
const canUseShellActions =
canOperateHost &&
@@ -2701,12 +2703,12 @@ function useChatMarkdownState({
);
const openExternalLinkInPreview = useCallback(
(url: string) => {
- if (!threadRef) {
+ if (!threadRef || !canOperatePreview) {
return Promise.resolve(
AsyncResult.failure<void, BrowserPreviewUnavailableError>(
Cause.fail(
new BrowserPreviewUnavailableError({
- message: "Thread context is unavailable.",
+ message: "Preview access is unavailable for this client.",
}),
),
),
@@ -2729,11 +2731,11 @@ function useChatMarkdownState({
return result;
});
},
- [openPreview, threadRef],
+ [canOperatePreview, openPreview, threadRef],
);
const openMarkdownFileInPreview = useCallback(
(path: string) => {
- if (!threadRef || preparedConnection._tag === "None") {
+ if (!threadRef || !canOperatePreview || preparedConnection._tag === "None") {
return Promise.resolve(
AsyncResult.failure<void, BrowserPreviewUnavailableError>(
Cause.fail(
@@ -2753,7 +2755,7 @@ function useChatMarkdownState({
openPreview,
});
},
- [createAssetUrl, cwd, openPreview, preparedConnection, threadRef],
+ [canOperatePreview, createAssetUrl, cwd, openPreview, preparedConnection, threadRef],
);
const findWorkspaceBasenameMatch = useCallback(
async (workspaceRelativePath: string) => {
@@ -2866,6 +2868,7 @@ function useChatMarkdownState({
revealLabel={revealInFileManagerLabel}
onOpenInBrowser={
threadRef &&
+ canOperatePreview &&
isPreviewAvailableFor(threadRef.environmentId) &&
isBrowserPreviewFile(fileLinkMeta.filePath)
? () => openMarkdownFileInPreview(fileLinkMeta.filePath)
@@ -2876,6 +2879,7 @@ function useChatMarkdownState({
},
[
canUseShellActions,
+ canOperatePreview,
fileLinkParentSuffixByPath,
openFileInPanel,
openInPreferredEditor,
@@ -2892,6 +2896,7 @@ function useChatMarkdownState({
const componentState = useMemo(
() => ({
canOperateHost,
+ canOperatePreview,
cwd,
diffThemeName,
environmentId,
@@ -2924,6 +2929,7 @@ function useChatMarkdownState({
}),
[
canOperateHost,
+ canOperatePreview,
cwd,
diffThemeName,
environmentId,
@@ -3079,6 +3085,7 @@ const CHAT_MARKDOWN_COMPONENTS = {
a: function MarkdownAnchor({ node, href, children, title: _title, ...props }) {
const {
canOperateHost,
+ canOperatePreview,
cwd,
environmentId,
imageBaseDir,
@@ -3139,7 +3146,8 @@ const CHAT_MARKDOWN_COMPONENTS = {
: null;
const isSameDocumentLink = href?.startsWith("#") ?? false;
const onClick = props.onClick;
- const canOpenInPreview = Boolean(threadRef && isPreviewAvailableFor(threadRef.environmentId));
+ const canOpenInPreview =
+ canOperatePreview && Boolean(threadRef && isPreviewAvailableFor(threadRef.environmentId));
const linkChildren = <MarkdownLinkContext value>{children}</MarkdownLinkContext>;
const link = (
<a
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx
index 25cf8b7e776..0e62851bfc8 100644
--- a/apps/web/src/components/ChatView.tsx
+++ b/apps/web/src/components/ChatView.tsx
@@ -51,6 +51,7 @@ import {
AuthOrchestrationOperateScope,
AuthSettingsWriteScope,
AuthSourceControlWriteScope,
+ AuthPreviewOperateScope,
type AssistantCitation,
type ChatFileAttachment,
CommandId,
@@ -5302,9 +5303,13 @@ export default function ChatView(props: ChatViewProps) {
},
[environmentId, navigate],
);
+ const canOperatePreview = useEnvironmentScope(
+ activeThreadRef?.environmentId ?? null,
+ AuthPreviewOperateScope,
+ );
const createBrowserSurface = useCallback(
(profileId?: string) => {
- if (!activeThreadRef) return;
+ if (!activeThreadRef || !canOperatePreview) return;
void addBrowserSurface({
threadRef: activeThreadRef,
openPreview,
@@ -5323,7 +5328,7 @@ export default function ChatView(props: ChatViewProps) {
}
});
},
- [activeThreadRef, openPreview],
+ [activeThreadRef, canOperatePreview, openPreview],
);
const addDiffSurface = useCallback(() => {
if (!activeThreadRef || !isServerThread || !isGitRepo) return;
@@ -5770,6 +5775,7 @@ export default function ChatView(props: ChatViewProps) {
closePreviewPanel();
return;
}
+ if (!canOperatePreview) return;
const activeTabId = activePreviewState.activeTabId;
if (activeTabId) {
useRightPanelStore.getState().openBrowser(activeThreadRef, activeTabId);
@@ -5780,6 +5786,7 @@ export default function ChatView(props: ChatViewProps) {
activePreviewState.activeTabId,
activeThreadRef,
browserAvailable,
+ canOperatePreview,
closePreviewPanel,
createBrowserSurface,
previewPanelOpen,
@@ -5938,7 +5945,10 @@ export default function ChatView(props: ChatViewProps) {
(surfaces: readonly RightPanelSurface[]) => {
if (!activeThreadRef) return;
for (const surface of surfaces) {
- if (surface.kind === "preview" && surface.resourceId) {
+ // Without preview access only the local surface goes away. The
+ // server record is in-memory bookkeeping, not a live view, and stays
+ // listed until a client with the scope closes it or the server restarts.
+ if (canOperatePreview && surface.kind === "preview" && surface.resourceId) {
void closePreviewSession({
closePreview,
snapshot: activePreviewState.sessions[surface.resourceId] ?? null,
@@ -5960,6 +5970,7 @@ export default function ChatView(props: ChatViewProps) {
[
activeThreadRef,
activePreviewState.sessions,
+ canOperatePreview,
closePreview,
closeTerminalMutation,
storeCloseTerminal,
@@ -11635,10 +11646,13 @@ export default function ChatView(props: ChatViewProps) {
</div>
</div>
- {activeThreadRef && activeEnvironmentServerBrowser ? (
+ {canOperatePreview && activeThreadRef && activeEnvironmentServerBrowser ? (
<PreviewSessionSync threadRef={activeThreadRef} />
) : null}
- {activeThreadRef && activePreviewMiniPlayer && previewMiniPlayerVisible ? (
+ {activeThreadRef &&
+ activePreviewMiniPlayer &&
+ previewMiniPlayerVisible &&
+ (activePreviewMiniPlayer.source.kind === "device" || canOperatePreview) ? (
<ThreadPreviewMiniPlayer
key={`${activeThreadKey}:${previewMiniPlayerSourceKey(activePreviewMiniPlayer.source)}`}
threadRef={activeThreadRef}
@@ -11754,7 +11768,7 @@ export default function ChatView(props: ChatViewProps) {
onAddPullRequest={addPullRequestSurface}
onAddPullRequests={addPullRequestsSurface}
onAddDevice={addDeviceSurface}
- browserAvailable={browserAvailable}
+ browserAvailable={canOperatePreview && browserAvailable}
terminalAvailable={activeProject !== null}
diffAvailable={isServerThread && isGitRepo}
filesAvailable={activeProject !== null}
@@ -11812,7 +11826,7 @@ export default function ChatView(props: ChatViewProps) {
onAddPullRequest={addPullRequestSurface}
onAddPullRequests={addPullRequestsSurface}
onAddDevice={addDeviceSurface}
- browserAvailable={browserAvailable}
+ browserAvailable={canOperatePreview && browserAvailable}
terminalAvailable={activeProject !== null}
diffAvailable={isServerThread && isGitRepo}
filesAvailable={activeProject !== null}
diff --git a/apps/web/src/components/LegacySidebar.tsx b/apps/web/src/components/LegacySidebar.tsx
index 55db8a49c9d..b78c6f955e2 100644
--- a/apps/web/src/components/LegacySidebar.tsx
+++ b/apps/web/src/components/LegacySidebar.tsx
@@ -46,6 +46,7 @@ import { restrictToFirstScrollableAncestor, restrictToVerticalAxis } from "@dnd-
import { CSS } from "@dnd-kit/utilities";
import {
AuthOrchestrationOperateScope,
+ AuthPreviewOperateScope,
type ContextMenuItem,
type EnvironmentId,
ProjectId,
@@ -405,6 +406,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
thread,
} = props;
const canOperateThread = useEnvironmentScope(thread.environmentId, AuthOrchestrationOperateScope);
+ const canOperatePreview = useEnvironmentScope(thread.environmentId, AuthPreviewOperateScope);
const threadRef = scopeThreadRef(thread.environmentId, thread.id);
const threadKey = scopedThreadKey(threadRef);
const [isFileDragOver, setIsFileDragOver] = useState(false);
@@ -462,7 +464,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
const handleOpenDiscoveredPort = useCallback(
(event: React.MouseEvent<HTMLButtonElement>) => {
const port = discoveredPorts[0];
- if (!port) return;
+ if (!port || !canOperatePreview) return;
event.preventDefault();
event.stopPropagation();
navigateToThread(threadRef);
@@ -482,7 +484,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
);
})();
},
- [discoveredPorts, navigateToThread, openPreview, threadRef],
+ [canOperatePreview, discoveredPorts, navigateToThread, openPreview, threadRef],
);
const isThreadRunning = !threadRuntimeCanArchive(thread.runtime);
const threadStatus = resolveThreadStatusPill({
@@ -826,7 +828,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
)}
</div>
<div className="ml-auto flex shrink-0 items-center gap-1.5">
- {discoveredPorts.length > 0 && (
+ {canOperatePreview && discoveredPorts.length > 0 && (
<Tooltip>
<TooltipTrigger
render={
diff --git a/apps/web/src/components/ThreadTerminalDrawer.tsx b/apps/web/src/components/ThreadTerminalDrawer.tsx
index b155421572e..58cbceaec17 100644
--- a/apps/web/src/components/ThreadTerminalDrawer.tsx
+++ b/apps/web/src/components/ThreadTerminalDrawer.tsx
@@ -19,6 +19,7 @@ import {
Trash2,
} from "lucide-react";
import {
+ AuthPreviewOperateScope,
type ContextMenuItem,
type ProviderInstanceId,
type ResolvedKeybindingsConfig,
@@ -80,6 +81,7 @@ import { useLocalStorage } from "../hooks/useLocalStorage";
import { useAttachedTerminalSession } from "../state/terminalSessions";
import { serverEnvironment } from "../state/server";
import { previewEnvironment } from "../state/preview";
+import { readEnvironmentScope } from "../state/session";
import { terminalEnvironment } from "../state/terminal";
import { openTerminalLinkInPreview } from "./preview/openTerminalLinkInPreview";
import { useAtomCommand } from "../state/use-atom-command";
@@ -797,6 +799,10 @@ export function TerminalViewport({
);
});
};
+ if (!readEnvironmentScope(environmentId, AuthPreviewOperateScope)) {
+ fallbackToBrowser();
+ return;
+ }
void openTerminalLinkInPreview({
url: text,
threadRef,
diff --git a/apps/web/src/components/files/FilePreviewPanel.tsx b/apps/web/src/components/files/FilePreviewPanel.tsx
index 46a272794aa..6692417adc6 100644
--- a/apps/web/src/components/files/FilePreviewPanel.tsx
+++ b/apps/web/src/components/files/FilePreviewPanel.tsx
@@ -1,9 +1,10 @@
import { Spinner } from "~/components/ui/spinner";
-import type {
- EditorId,
- EnvironmentId,
- ResolvedKeybindingsConfig,
- ScopedThreadRef,
+import {
+ AuthPreviewOperateScope,
+ type EditorId,
+ type EnvironmentId,
+ type ResolvedKeybindingsConfig,
+ type ScopedThreadRef,
} from "@t3tools/contracts";
import { filePreviewDelimiter } from "@t3tools/shared/delimitedPreview";
import { AuthFilesystemWriteScope } from "@t3tools/contracts";
@@ -1021,6 +1022,7 @@ export default function FilePreviewPanel({
attachment === undefined ? resolveFilePreviewPath(requestedPath, cwd) : requestedPath;
const { resolvedTheme } = useTheme();
const wordWrap = useClientSettings((settings) => settings.wordWrap);
+ const canOperatePreview = useEnvironmentScope(environmentId, AuthPreviewOperateScope);
const primaryEnvironmentId = usePrimaryEnvironmentId();
const remoteOpenState = useRemoteOpenState(environmentId);
const environmentHttpBaseUrl = useEnvironmentHttpBaseUrl(environmentId);
@@ -1128,6 +1130,7 @@ export default function FilePreviewPanel({
? setRenderTablePreferred
: setRenderBrowserFilePreferred;
const canOpenInBrowser =
+ canOperatePreview &&
previewPath !== null &&
attachment === undefined &&
!isVideo &&
@@ -1170,7 +1173,7 @@ export default function FilePreviewPanel({
};
const handleOpenInBrowser = useCallback(() => {
- if (!canReadFiles || !absolutePath || !environmentHttpBaseUrl) return;
+ if (!canReadFiles || !canOperatePreview || !absolutePath || !environmentHttpBaseUrl) return;
void (async () => {
const result = await openFileInPreview({
threadRef,
@@ -1195,6 +1198,7 @@ export default function FilePreviewPanel({
}, [
absolutePath,
canReadFiles,
+ canOperatePreview,
createAssetUrl,
cwd,
environmentHttpBaseUrl,
diff --git a/apps/web/src/components/preview/PreviewPanel.tsx b/apps/web/src/components/preview/PreviewPanel.tsx
index 4328cbc5a92..81501ae7d72 100644
--- a/apps/web/src/components/preview/PreviewPanel.tsx
+++ b/apps/web/src/components/preview/PreviewPanel.tsx
@@ -1,9 +1,14 @@
"use client";
-import type { PreviewAnnotationPayload, ScopedThreadRef } from "@t3tools/contracts";
+import {
+ AuthPreviewOperateScope,
+ type PreviewAnnotationPayload,
+ type ScopedThreadRef,
+} from "@t3tools/contracts";
import type { ComposerImageAttachment } from "~/composerDraftStore";
import { usePreviewAvailable } from "~/browser/previewRuntime";
+import { useEnvironmentScope } from "~/state/session";
import { PreviewPanelShell, type PreviewPanelMode } from "./PreviewPanelShell";
import { PreviewView } from "./PreviewView";
@@ -28,12 +33,16 @@ export function PreviewPanel({
visible,
onSendAnnotation,
}: Props) {
- if (!usePreviewAvailable(threadRef.environmentId)) {
+ const available = usePreviewAvailable(threadRef.environmentId);
+ const canOperatePreview = useEnvironmentScope(threadRef.environmentId, AuthPreviewOperateScope);
+ if (!canOperatePreview || !available) {
return (
<PreviewPanelShell mode={mode}>
<div className="flex min-h-0 flex-1 flex-col items-center justify-center gap-3 p-8 text-center">
<p className="max-w-sm text-sm text-muted-foreground">
- Preview is only available in the T3 Code desktop app.
+ {canOperatePreview
+ ? "Preview is only available in the T3 Code desktop app."
+ : "Pair this client again with preview access to control browser previews."}
</p>
</div>
</PreviewPanelShell>
diff --git a/apps/web/src/components/preview/PreviewView.test.tsx b/apps/web/src/components/preview/PreviewView.test.tsx
index 37c3844fa7a..522cda3d42c 100644
--- a/apps/web/src/components/preview/PreviewView.test.tsx
+++ b/apps/web/src/components/preview/PreviewView.test.tsx
@@ -15,6 +15,9 @@ const mocks = vi.hoisted(() => ({
navigate: vi.fn(async (_tabId: string, _url: string): Promise<void> => undefined),
rememberPreviewUrl: vi.fn(),
readPreparedConnection: vi.fn(() => ({ httpBaseUrl: "http://172.25.85.75:3773" })),
+ readEnvironmentScope: vi.fn(() => true),
+ setAnnotationSendEnabled: vi.fn(async (): Promise<void> => undefined),
+ cancelPickElement: vi.fn(async () => undefined),
submittedUrl: null as ((url: string) => void) | null,
emptyStateUrl: null as ((url: string) => void) | null,
togglePictureInPicture: null as (() => void) | null,
@@ -61,6 +64,8 @@ vi.mock("~/browserHistoryStore", () => ({
vi.mock("~/state/session", async (importOriginal) => ({
...(await importOriginal<typeof import("~/state/session")>()),
readPreparedConnection: mocks.readPreparedConnection,
+ readEnvironmentScope: mocks.readEnvironmentScope,
+ useEnvironmentScope: mocks.readEnvironmentScope,
}));
// File-preview errors share a module with asset hooks. Keep the pure URL resolver
@@ -214,6 +219,8 @@ vi.mock("./previewBridge", () => ({
previewBridge: {
navigate: mocks.navigate,
pickElement: mocks.pickElement,
+ setAnnotationSendEnabled: mocks.setAnnotationSendEnabled,
+ cancelPickElement: mocks.cancelPickElement,
pictureInPicture: {
open: mocks.openPictureInPicture,
close: mocks.closePictureInPicture,
@@ -338,6 +345,9 @@ describe("PreviewView navigation", () => {
mocks.navigate.mockClear();
mocks.rememberPreviewUrl.mockClear();
mocks.readPreparedConnection.mockClear();
+ mocks.readEnvironmentScope.mockReset().mockReturnValue(true);
+ mocks.setAnnotationSendEnabled.mockClear();
+ mocks.cancelPickElement.mockClear();
mocks.submittedUrl = null;
mocks.emptyStateUrl = null;
mocks.togglePictureInPicture = null;
@@ -588,6 +598,94 @@ describe("PreviewView navigation", () => {
expect(mocks.addPreviewAnnotation).toHaveBeenCalledWith(TEST_THREAD_REF, annotation);
});
+ it("retains the annotation locally when its own environment loses access during capture", async () => {
+ const annotation = {
+ id: "annotation-revoked",
+ pageUrl: "https://example.com/dashboard",
+ pageTitle: "Dashboard",
+ comment: "Tighten this spacing",
+ elements: [],
+ regions: [],
+ strokes: [],
+ styleChanges: [],
+ screenshot: null,
+ createdAt: "2026-09-05T00:00:00.000Z",
+ };
+ const onSendAnnotation = vi.fn();
+ let submitPick: (() => void) | undefined;
+ mocks.pickElement.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ submitPick = () => resolve({ annotation, submission: "send" });
+ }),
+ );
+ const document = installTestDom();
+ const { createRoot } = await import("react-dom/client");
+ const root = createRoot(document.createElement("div") as unknown as Element);
+ const view = () => (
+ <PreviewView
+ threadRef={TEST_THREAD_REF}
+ tabId="tab-1"
+ visible
+ onSendAnnotation={onSendAnnotation}
+ />
+ );
+ try {
+ await act(async () => root.render(view()));
+ await act(async () => mocks.toggleAnnotation?.());
+ expect(submitPick).toBeDefined();
+ expect(mocks.setAnnotationSendEnabled).toHaveBeenLastCalledWith(TEST_RUNTIME_TAB_ID, true);
+
+ mocks.readEnvironmentScope.mockImplementation(
+ (environmentId?: unknown) => environmentId !== TEST_THREAD_REF.environmentId,
+ );
+ await act(async () => root.render(view()));
+ expect(mocks.setAnnotationSendEnabled).toHaveBeenLastCalledWith(TEST_RUNTIME_TAB_ID, false);
+ await act(async () => submitPick!());
+ expect(mocks.addPreviewAnnotation).toHaveBeenCalledWith(TEST_THREAD_REF, annotation);
+ expect(onSendAnnotation).not.toHaveBeenCalled();
+
+ mocks.readEnvironmentScope.mockReturnValue(true);
+ mocks.pickElement.mockResolvedValue({ annotation, submission: "send" });
+ await act(async () => root.render(view()));
+ await act(async () => mocks.toggleAnnotation?.());
+ expect(mocks.setAnnotationSendEnabled).toHaveBeenLastCalledWith(TEST_RUNTIME_TAB_ID, true);
+ expect(onSendAnnotation).toHaveBeenCalledWith(annotation, null);
+ } finally {
+ await act(async () => root.unmount());
+ vi.unstubAllGlobals();
+ }
+ });
+
+ it("does not reopen a cancelled picker after the permission update finishes", async () => {
+ let finishUpdate: (() => void) | undefined;
+ mocks.setAnnotationSendEnabled.mockImplementationOnce(
+ () =>
+ new Promise<void>((resolve) => {
+ finishUpdate = resolve;
+ }),
+ );
+ const document = installTestDom();
+ const { createRoot } = await import("react-dom/client");
+ const root = createRoot(document.createElement("div") as unknown as Element);
+ try {
+ await act(async () =>
+ root.render(<PreviewView threadRef={TEST_THREAD_REF} tabId="tab-1" visible />),
+ );
+ await act(async () => mocks.toggleAnnotation?.());
+ expect(finishUpdate).toBeDefined();
+ expect(mocks.pickElement).not.toHaveBeenCalled();
+ await act(async () => mocks.toggleAnnotation?.());
+ expect(mocks.cancelPickElement).toHaveBeenCalledWith(TEST_RUNTIME_TAB_ID);
+ await act(async () => finishUpdate!());
+ expect(mocks.pickElement).not.toHaveBeenCalled();
+ expect(mocks.addPreviewAnnotation).not.toHaveBeenCalled();
+ } finally {
+ await act(async () => root.unmount());
+ vi.unstubAllGlobals();
+ }
+ });
+
it("warns when main dropped the crop before handing over the pick", async () => {
const annotation = {
id: "annotation-3",
diff --git a/apps/web/src/components/preview/PreviewView.tsx b/apps/web/src/components/preview/PreviewView.tsx
index ab49b388e20..af525344865 100644
--- a/apps/web/src/components/preview/PreviewView.tsx
+++ b/apps/web/src/components/preview/PreviewView.tsx
@@ -6,6 +6,7 @@ import {
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import {
+ AuthOrchestrationOperateScope,
DEFAULT_BROWSER_PROFILE_ID,
FILL_PREVIEW_VIEWPORT,
type PreviewAnnotationPayload,
@@ -42,6 +43,7 @@ import {
selectThreadPreviewMiniPlayerTabId,
usePreviewMiniPlayerStore,
} from "~/previewMiniPlayerStore";
+import { readEnvironmentScope, useEnvironmentScope } from "~/state/session";
import { useRightPanelStore } from "~/rightPanelStore";
import { previewBridge } from "./previewBridge";
@@ -114,8 +116,11 @@ export function PreviewView({
}: Props) {
const [focusUrlNonce, setFocusUrlNonce] = useState<number | undefined>(undefined);
const [pickActive, setPickActive] = useState(false);
+ const canSendAnnotation =
+ useEnvironmentScope(threadRef.environmentId, AuthOrchestrationOperateScope) &&
+ Boolean(onSendAnnotation);
const activeRecordingTabIds = useActiveBrowserRecordingTabIds();
- const pickActiveRef = useRef(false);
+ const pickActiveRef = useRef<{ cancelled: boolean } | null>(null);
const isMountedRef = useRef(true);
// Kept in sync so the title effect can depend on the stable thread key
// instead of the thread object, which is recreated on every update.
@@ -720,6 +725,7 @@ export function PreviewView({
const handlePickElement = useCallback(() => {
if (!previewBridge || !runtimeTabId) return;
if (pickActiveRef.current) {
+ pickActiveRef.current.cancelled = true;
void previewBridge.cancelPickElement(runtimeTabId).catch(() => undefined);
return;
}
@@ -730,12 +736,28 @@ export function PreviewView({
// every pick they'd have to click back into the textarea.
const previouslyFocused =
typeof document !== "undefined" ? (document.activeElement as HTMLElement | null) : null;
- pickActiveRef.current = true;
+ const pickRequest = { cancelled: false };
+ let submitted = false;
+ pickActiveRef.current = pickRequest;
setPickActive(true);
void (async () => {
try {
+ await previewBridge.setAnnotationSendEnabled?.(
+ runtimeTabId,
+ Boolean(onSendAnnotation) &&
+ readEnvironmentScope(threadRef.environmentId, AuthOrchestrationOperateScope),
+ );
+ if (pickRequest.cancelled) return;
const result = await previewBridge.pickElement(runtimeTabId);
- if (!result) return;
+ if (!result || pickRequest.cancelled) return;
+ // The user has submitted. Nothing that happens after this point (a
+ // second picker click, a tab change, unmount) may discard it, so the
+ // pick stops being cancellable here rather than in `finally`.
+ if (pickActiveRef.current === pickRequest) {
+ pickActiveRef.current = null;
+ if (isMountedRef.current) setPickActive(false);
+ submitted = true;
+ }
const { annotation: picked, submission, screenshotFailed = false } = result;
// The structured annotation is still sendable when its optional crop
// stalls or fails, so tell the user what they lost and keep going
@@ -775,20 +797,28 @@ export function PreviewView({
if (image) {
addImage(threadRef, image);
}
- if (submission === "send") {
+ if (
+ submission === "send" &&
+ readEnvironmentScope(threadRef.environmentId, AuthOrchestrationOperateScope)
+ ) {
onSendAnnotation?.(annotation, image);
}
} catch {
// Picker failed (e.g. webview navigated). Treat as silent cancel.
} finally {
- pickActiveRef.current = false;
- // Avoid `setState on unmounted component` if the panel/thread closed
- // while the pick was in flight.
- if (isMountedRef.current) setPickActive(false);
+ // A submitted pick already released itself above; a cancelled or
+ // failed one releases here. Avoid `setState on unmounted component`
+ // if the panel/thread closed while the pick was in flight.
+ const isCurrentPick = pickActiveRef.current === pickRequest;
+ if (isCurrentPick) {
+ pickActiveRef.current = null;
+ if (isMountedRef.current) setPickActive(false);
+ }
// Best-effort: restore focus to whatever the user had before the
// pick stole it into the guest webContents. Skip if the previously-
// focused element was unmounted or is no longer focusable.
if (
+ (isCurrentPick || submitted) &&
previouslyFocused &&
previouslyFocused.isConnected &&
typeof previouslyFocused.focus === "function"
@@ -803,13 +833,21 @@ export function PreviewView({
})();
}, [addImage, addPreviewAnnotation, onSendAnnotation, runtimeTabId, threadRef]);
+ useEffect(() => {
+ if (!pickActive || !previewBridge || !runtimeTabId) return;
+ void previewBridge
+ .setAnnotationSendEnabled?.(runtimeTabId, canSendAnnotation)
+ .catch(() => undefined);
+ }, [canSendAnnotation, pickActive, runtimeTabId]);
+
// If the active tab changes mid-pick (close, thread switch, hot restart),
// tell main to tear down the in-flight session AND reset our local toggle
// state so the button doesn't get stuck pressed against a stale tab id.
useEffect(() => {
return () => {
if (!pickActiveRef.current) return;
- pickActiveRef.current = false;
+ pickActiveRef.current.cancelled = true;
+ pickActiveRef.current = null;
if (previewBridge && runtimeTabId) {
void previewBridge.cancelPickElement(runtimeTabId).catch(() => undefined);
}
diff --git a/apps/web/src/components/settings/ConnectionsSettings.tsx b/apps/web/src/components/settings/ConnectionsSettings.tsx
index bed04c3f0a8..e6a5d88942e 100644
--- a/apps/web/src/components/settings/ConnectionsSettings.tsx
+++ b/apps/web/src/components/settings/ConnectionsSettings.tsx
@@ -28,6 +28,7 @@ import {
AuthEnvironmentMaintainScope,
AuthOrchestrationOperateScope,
AuthOrchestrationReadScope,
+ AuthPreviewOperateScope,
AuthRelayReadScope,
AuthRelayWriteScope,
AuthSourceControlWriteScope,
@@ -257,6 +258,11 @@ const PAIRING_SCOPE_OPTIONS: ReadonlyArray<{
title: "Maintain environment",
description: "Update the server and control environment processes.",
},
+ {
+ scope: AuthPreviewOperateScope,
+ title: "Control previews",
+ description: "Open browser previews and host browser automation.",
+ },
{
scope: AuthTerminalOperateScope,
title: "Use terminals",
diff --git a/apps/web/src/routes/_chat.tsx b/apps/web/src/routes/_chat.tsx
index 5be294ae006..29d62bea19c 100644
--- a/apps/web/src/routes/_chat.tsx
+++ b/apps/web/src/routes/_chat.tsx
@@ -1,3 +1,4 @@
+import { AuthPreviewOperateScope } from "@t3tools/contracts";
import { Outlet, createFileRoute, redirect, useParams } from "@tanstack/react-router";
import { useAtomValue } from "@effect/atom-react";
import { useEffect, useMemo } from "react";
@@ -10,6 +11,7 @@ import { openCommandPalette } from "../commandPaletteBus";
import { useProjects } from "../state/entities";
import { isPreviewAvailableFor } from "../browser/previewRuntime";
import { usePrimaryEnvironmentId } from "../state/environments";
+import { useEnvironmentScope } from "../state/session";
import { selectProjectGroupingSettings } from "../logicalProject";
import { buildSidebarProjectSnapshots } from "../sidebarProjectGrouping";
import { dispatchPreviewAction } from "../components/preview/previewActionBus";
@@ -33,6 +35,10 @@ function ChatRouteGlobalShortcuts() {
const selectedThreadKeysSize = useThreadSelectionStore((state) => state.selectedThreadKeys.size);
const { activeDraftThread, activeThread, defaultProjectRef, handleNewThread, routeThreadRef } =
useHandleNewThread();
+ const canOperatePreview = useEnvironmentScope(
+ routeThreadRef?.environmentId ?? null,
+ AuthPreviewOperateScope,
+ );
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
const legacySidebarEnabled = useLegacySidebarEnabled();
const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
@@ -140,7 +146,7 @@ function ChatRouteGlobalShortcuts() {
if (command === "preview.toggle") {
event.preventDefault();
event.stopPropagation();
- if (!routeThreadRef) return;
+ if (!routeThreadRef || (!canOperatePreview && !previewOpen)) return;
if (!isPreviewAvailableFor(routeThreadRef.environmentId)) {
toastManager.add(
stackedThreadToast({
@@ -167,6 +173,7 @@ function ChatRouteGlobalShortcuts() {
) {
event.preventDefault();
event.stopPropagation();
+ if (!canOperatePreview) return;
const action =
command === "preview.refresh"
? "refresh"
@@ -189,6 +196,7 @@ function ChatRouteGlobalShortcuts() {
activeDraftThread,
activeThread,
clearSelection,
+ canOperatePreview,
handleNewThread,
keybindings,
defaultProjectRef,
diff --git a/packages/contracts/src/auth.ts b/packages/contracts/src/auth.ts
index 79b9c966324..3f474fc31a2 100644
--- a/packages/contracts/src/auth.ts
+++ b/packages/contracts/src/auth.ts
@@ -83,6 +83,7 @@ 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 AuthPreviewOperateScope = "preview:operate" as const;
export const AuthTerminalOperateScope = "terminal:operate" as const;
export const AuthSourceControlWriteScope = "source-control:write" as const;
export const AuthFilesystemReadScope = "filesystem:read" as const;
@@ -99,6 +100,7 @@ export const AuthEnvironmentScope = Schema.Literals([
AuthSettingsWriteScope,
AuthProvidersManageScope,
AuthEnvironmentMaintainScope,
+ AuthPreviewOperateScope,
AuthTerminalOperateScope,
AuthFilesystemReadScope,
AuthFilesystemWriteScope,
@@ -126,6 +128,7 @@ export const AuthStandardClientScopes = [
AuthSettingsWriteScope,
AuthProvidersManageScope,
AuthEnvironmentMaintainScope,
+ AuthPreviewOperateScope,
AuthTerminalOperateScope,
AuthSourceControlWriteScope,
AuthFilesystemReadScope,
diff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.ts
index 081958acdeb..e661bc2b187 100644
--- a/packages/contracts/src/ipc.ts
+++ b/packages/contracts/src/ipc.ts
@@ -1069,6 +1069,11 @@ export const DesktopPreviewAnnotationThemeInputSchema = Schema.Struct({
theme: DesktopPreviewAnnotationThemeSchema,
});
+export const DesktopPreviewAnnotationSendEnabledInputSchema = Schema.Struct({
+ tabId: DesktopPreviewTabIdSchema,
+ enabled: Schema.Boolean,
+});
+
export const DesktopPreviewArtifactInputSchema = Schema.Struct({
path: Schema.String.check(Schema.isTrimmed()).check(Schema.isNonEmpty()),
});
@@ -1278,6 +1283,8 @@ export interface DesktopPreviewBridge {
readonly targetProfileId: string;
}) => Promise<BrowserImportResult>;
setAnnotationTheme: (theme: DesktopPreviewAnnotationTheme) => Promise<void>;
+ /** Keep an open annotation picker's send shortcut in sync with its thread grant. */
+ setAnnotationSendEnabled: (tabId: string, enabled: boolean) => Promise<void>;
/**
* Activate the in-page element picker for the given tab. Resolves with
* the picked annotation and its attach/send intent, or `null` when the