Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

IntegrationsSettings.tsx

532 lines19.3 KB

1/**
2 * Integrations settings - preferences for surfaces T3 Code embeds rather than
3 * owns. Browser is the first section: the defaults a preview tab opens at,
4 * applied to both hand-opened tabs and agent `preview_open` calls that don't
5 * state their own size.
6 *
7 * @module IntegrationsSettings
8 */
9import {
10 BROWSER_RECORDING_FRAME_RATES,
11 DEFAULT_BROWSER_AUTO_SHOW_FLOATING_PREVIEW,
12 DEFAULT_BROWSER_RECORDING_FRAME_RATE,
13 DEFAULT_BROWSER_VIEWPORT,
14 DEFAULT_PREVIEW_APPEARANCE,
15 DEFAULT_UNIFIED_SETTINGS,
16 DEFAULT_PREVIEW_ZOOM_FACTOR,
17 FILL_PREVIEW_VIEWPORT,
18 PREVIEW_VIEWPORT_MAX_AREA,
19 PREVIEW_VIEWPORT_MAX_DIMENSION,
20 PREVIEW_VIEWPORT_MIN_DIMENSION,
21 PREVIEW_ZOOM_LEVELS,
22 type PreviewAppearancePreference,
23 type PreviewViewportSetting,
24} from "@t3tools/contracts";
25import { PREVIEW_VIEWPORT_PRESETS } from "@t3tools/shared/previewViewport";
26import { InfoIcon } from "lucide-react";
27import type { ReactNode } from "react";
28​
29import { ScreenRotationIcon } from "~/browser/ScreenRotationIcon";
30import { isElectron } from "../../env";
31​
32import { Button } from "../ui/button";
33import { NumberField, NumberFieldGroup, NumberFieldInput } from "../ui/number-field";
34import {
35 Select,
36 SelectGroup,
37 SelectGroupLabel,
38 SelectItem,
39 SelectPopup,
40 SelectTrigger,
41 SelectValue,
42} from "../ui/select";
43import { Switch } from "../ui/switch";
44import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
45import {
46 useClientSettings,
47 usePrimarySettings,
48 useUpdatePrimarySettings,
49} from "~/hooks/useSettings";
50​
51import {
52 SettingResetButton,
53 SettingsPageContainer,
54 SettingsRow,
55 SettingsSection,
56} from "./settingsLayout";
57import { searchableSetting } from "./settingsSearch";
58​
59const FILL_VALUE = "fill";
60const RESPONSIVE_VALUE = "responsive";
61​
62/**
63 * The size a "Responsive" default falls back to when the user switches away
64 * from Fill and hasn't typed dimensions yet. Fill has no dimensions to carry
65 * over, so the picker needs something concrete to seed the inputs with.
66 */
67const RESPONSIVE_SEED_SIZE = { width: 1280, height: 800 } as const;
68​
69const NO_GROUPING: Intl.NumberFormatOptions = { useGrouping: false };
70​
71const APPEARANCE_LABELS: Readonly<Record<PreviewAppearancePreference, string>> = {
72 system: "System",
73 light: "Light",
74 dark: "Dark",
75};
76​
77const zoomLabel = (zoomFactor: number) => `${Math.round(zoomFactor * 100)}%`;
78​
79const viewportSelectValue = (viewport: PreviewViewportSetting): string => {
80 if (viewport._tag === "fill") return FILL_VALUE;
81 if (
82 viewport._tag === "preset" &&
83 PREVIEW_VIEWPORT_PRESETS.some((preset) => preset.id === viewport.presetId)
84 ) {
85 return viewport.presetId;
86 }
87 return RESPONSIVE_VALUE;
88};
89​
90/**
91 * The trigger renders this rather than a bare `SelectValue`, which would fall
92 * back to printing the raw stored value ("fill") because the options are built
93 * inline instead of from an `items` map.
94 */
95const viewportSelectLabel = (viewport: PreviewViewportSetting): string => {
96 const value = viewportSelectValue(viewport);
97 if (value === FILL_VALUE) return "Fill panel";
98 if (value === RESPONSIVE_VALUE) return "Responsive";
99 return PREVIEW_VIEWPORT_PRESETS.find((preset) => preset.id === value)?.label ?? "Responsive";
100};
101​
102const isValidDimension = (value: number) =>
103 Number.isInteger(value) &&
104 value >= PREVIEW_VIEWPORT_MIN_DIMENSION &&
105 value <= PREVIEW_VIEWPORT_MAX_DIMENSION;
106​
107/**
108 * A sized viewport with width and height swapped. Presets keep their identity
109 * through a rotation — `resolvePreviewViewport` already stores rotated presets
110 * as the preset id plus swapped dimensions — so a rotated iPad is still an
111 * iPad, not an anonymous custom size.
112 */
113const rotateViewport = (
114 viewport: Exclude<PreviewViewportSetting, { readonly _tag: "fill" }>,
115): PreviewViewportSetting => ({
116 ...viewport,
117 width: viewport.height,
118 height: viewport.width,
119});
120​
121function BrowserViewportSetting({ disabled }: { readonly disabled: boolean }) {
122 const viewport = useClientSettings((settings) => settings.browserDefaultViewport);
123 const updateSettings = useUpdatePrimarySettings();
124​
125 const sized = viewport._tag === "fill" ? null : viewport;
126 const presentedSize = {
127 width: sized?.width ?? RESPONSIVE_SEED_SIZE.width,
128 height: sized?.height ?? RESPONSIVE_SEED_SIZE.height,
129 };
130​
131 const selectViewport = (value: string | null) => {
132 if (value === FILL_VALUE) {
133 updateSettings({ browserDefaultViewport: FILL_PREVIEW_VIEWPORT });
134 return;
135 }
136 if (value === RESPONSIVE_VALUE) {
137 updateSettings({
138 browserDefaultViewport: {
139 _tag: "freeform",
140 width: sized?.width ?? RESPONSIVE_SEED_SIZE.width,
141 height: sized?.height ?? RESPONSIVE_SEED_SIZE.height,
142 },
143 });
144 return;
145 }
146 const preset = PREVIEW_VIEWPORT_PRESETS.find((candidate) => candidate.id === value);
147 if (!preset) return;
148 updateSettings({
149 browserDefaultViewport: {
150 _tag: "preset",
151 width: preset.width,
152 height: preset.height,
153 presetId: preset.id,
154 },
155 });
156 };
157​
158 // Committed on blur rather than per keystroke: typing "2560" passes through
159 // "256", which is a legal dimension, so an onValueChange handler would
160 // persist that intermediate size and churn the settings file on every key.
161 const commitDimension = (axis: "width" | "height", value: number | null) => {
162 if (value === null || !isValidDimension(value)) return;
163 const next = { ...presentedSize, [axis]: value };
164 if (next.width * next.height > PREVIEW_VIEWPORT_MAX_AREA) return;
165 if (sized && next.width === sized.width && next.height === sized.height) return;
166 // Typing a size means the preset no longer describes it.
167 updateSettings({ browserDefaultViewport: { _tag: "freeform", ...next } });
168 };
169​
170 return (
171 <SettingsRow
172 {...searchableSetting("browser-default-viewport")}
173 description="The viewport a browser tab opens at, for both you and agents. Fill sizes the page to the panel; any other choice opens the device toolbar at that size."
174 resetAction={
175 !disabled && viewport._tag !== DEFAULT_BROWSER_VIEWPORT._tag ? (
176 <SettingResetButton
177 label="default browser viewport"
178 onClick={() => updateSettings({ browserDefaultViewport: DEFAULT_BROWSER_VIEWPORT })}
179 />
180 ) : null
181 }
182 control={
183 <div className="flex w-full flex-wrap items-center justify-end gap-2 sm:w-auto">
184 <Select
185 value={viewportSelectValue(viewport)}
186 onValueChange={selectViewport}
187 disabled={disabled}
188 >
189 <SelectTrigger
190 size="sm"
191 className="w-full min-w-0 sm:w-44"
192 aria-label="Default browser viewport"
193 >
194 <SelectValue>{viewportSelectLabel(viewport)}</SelectValue>
195 </SelectTrigger>
196 <SelectPopup align="end" alignItemWithTrigger={false} className="min-w-64">
197 <SelectItem value={FILL_VALUE}>Fill panel</SelectItem>
198 <SelectItem value={RESPONSIVE_VALUE}>Responsive</SelectItem>
199 <SelectGroup>
200 <SelectGroupLabel>Standard</SelectGroupLabel>
201 {PREVIEW_VIEWPORT_PRESETS.map((preset) => (
202 <SelectItem key={preset.id} value={preset.id}>
203 <span className="flex w-full items-center justify-between gap-5">
204 <span>{preset.label}</span>
205 <span className="text-xs tabular-nums text-muted-foreground">
206 {preset.detail}
207 </span>
208 </span>
209 </SelectItem>
210 ))}
211 </SelectGroup>
212 </SelectPopup>
213 </Select>
214​
215 {sized ? (
216 <div className="flex min-w-0 items-center gap-1">
217 <NumberField
218 value={presentedSize.width}
219 min={PREVIEW_VIEWPORT_MIN_DIMENSION}
220 max={PREVIEW_VIEWPORT_MAX_DIMENSION}
221 disabled={disabled}
222 // Pixel counts read as raw numbers; grouping would show "1,024".
223 format={NO_GROUPING}
224 size="sm"
225 className="w-20"
226 onValueCommitted={(value) => commitDimension("width", value)}
227 >
228 <NumberFieldGroup>
229 <NumberFieldInput aria-label="Default viewport width" />
230 </NumberFieldGroup>
231 </NumberField>
232 <span className="text-xs text-muted-foreground">×</span>
233 <NumberField
234 value={presentedSize.height}
235 min={PREVIEW_VIEWPORT_MIN_DIMENSION}
236 max={PREVIEW_VIEWPORT_MAX_DIMENSION}
237 disabled={disabled}
238 format={NO_GROUPING}
239 size="sm"
240 className="w-20"
241 onValueCommitted={(value) => commitDimension("height", value)}
242 >
243 <NumberFieldGroup>
244 <NumberFieldInput aria-label="Default viewport height" />
245 </NumberFieldGroup>
246 </NumberField>
247 <Tooltip>
248 <TooltipTrigger
249 render={
250 <Button
251 size="icon-sm"
252 variant="ghost-muted"
253 disabled={disabled}
254 aria-label={`Rotate to ${
255 presentedSize.height >= presentedSize.width ? "landscape" : "portrait"
256 }`}
257 onClick={() =>
258 updateSettings({ browserDefaultViewport: rotateViewport(sized) })
259 }
260 >
261 <ScreenRotationIcon />
262 </Button>
263 }
264 />
265 <TooltipPopup side="top">Rotate</TooltipPopup>
266 </Tooltip>
267 </div>
268 ) : null}
269 </div>
270 }
271 />
272 );
274​
275function BrowserZoomSetting({ disabled }: { readonly disabled: boolean }) {
276 const zoomFactor = useClientSettings((settings) => settings.browserDefaultZoomFactor);
277 const updateSettings = useUpdatePrimarySettings();
278​
279 return (
280 <SettingsRow
281 {...searchableSetting("browser-default-zoom")}
282 description="Page zoom applied to new browser tabs."
283 resetAction={
284 !disabled && zoomFactor !== DEFAULT_PREVIEW_ZOOM_FACTOR ? (
285 <SettingResetButton
286 label="default browser zoom"
287 onClick={() =>
288 updateSettings({ browserDefaultZoomFactor: DEFAULT_PREVIEW_ZOOM_FACTOR })
289 }
290 />
291 ) : null
292 }
293 control={
294 <Select
295 disabled={disabled}
296 value={String(zoomFactor)}
297 onValueChange={(value) => {
298 const next = PREVIEW_ZOOM_LEVELS.find((level) => String(level) === value);
299 if (next !== undefined) updateSettings({ browserDefaultZoomFactor: next });
300 }}
301 >
302 <SelectTrigger className="w-full sm:w-40" aria-label="Default browser zoom">
303 <SelectValue>{zoomLabel(zoomFactor)}</SelectValue>
304 </SelectTrigger>
305 <SelectPopup align="end" alignItemWithTrigger={false}>
306 {PREVIEW_ZOOM_LEVELS.map((level) => (
307 <SelectItem hideIndicator key={level} value={String(level)}>
308 {zoomLabel(level)}
309 </SelectItem>
310 ))}
311 </SelectPopup>
312 </Select>
313 }
314 />
315 );
317​
318function BrowserAppearanceSetting({ disabled }: { readonly disabled: boolean }) {
319 const appearance = useClientSettings((settings) => settings.browserDefaultAppearance);
320 const updateSettings = useUpdatePrimarySettings();
321​
322 return (
323 <SettingsRow
324 {...searchableSetting("browser-default-appearance")}
325 description="The color scheme pages are told to prefer. System follows your OS setting."
326 resetAction={
327 !disabled && appearance !== DEFAULT_PREVIEW_APPEARANCE ? (
328 <SettingResetButton
329 label="default browser appearance"
330 onClick={() => updateSettings({ browserDefaultAppearance: DEFAULT_PREVIEW_APPEARANCE })}
331 />
332 ) : null
333 }
334 control={
335 <Select
336 disabled={disabled}
337 value={appearance}
338 onValueChange={(value) => {
339 if (value === "system" || value === "light" || value === "dark") {
340 updateSettings({ browserDefaultAppearance: value });
341 }
342 }}
343 >
344 <SelectTrigger className="w-full sm:w-40" aria-label="Default browser appearance">
345 <SelectValue>{APPEARANCE_LABELS[appearance]}</SelectValue>
346 </SelectTrigger>
347 <SelectPopup align="end" alignItemWithTrigger={false}>
348 {Object.entries(APPEARANCE_LABELS).map(([value, label]) => (
349 <SelectItem hideIndicator key={value} value={value}>
350 {label}
351 </SelectItem>
352 ))}
353 </SelectPopup>
354 </Select>
355 }
356 />
357 );
359​
360function BrowserRecordingFrameRateSetting({ disabled }: { readonly disabled: boolean }) {
361 const frameRate = useClientSettings((settings) => settings.browserRecordingFrameRate);
362 const updateSettings = useUpdatePrimarySettings();
363​
364 return (
365 <SettingsRow
366 {...searchableSetting("browser-recording-frame-rate")}
367 description="Maximum frame rate for browser recordings. 30 fps is the default and uses less CPU and storage; 60 fps captures smoother motion."
368 resetAction={
369 !disabled && frameRate !== DEFAULT_BROWSER_RECORDING_FRAME_RATE ? (
370 <SettingResetButton
371 label="browser recording frame rate"
372 onClick={() =>
373 updateSettings({ browserRecordingFrameRate: DEFAULT_BROWSER_RECORDING_FRAME_RATE })
374 }
375 />
376 ) : null
377 }
378 control={
379 <Select
380 disabled={disabled}
381 value={String(frameRate)}
382 onValueChange={(value) => {
383 const next = BROWSER_RECORDING_FRAME_RATES.find((rate) => String(rate) === value);
384 if (next !== undefined) {
385 updateSettings({ browserRecordingFrameRate: next });
386 }
387 }}
388 >
389 <SelectTrigger className="w-full sm:w-40" aria-label="Browser recording frame rate">
390 <SelectValue>{frameRate} fps</SelectValue>
391 </SelectTrigger>
392 <SelectPopup align="end" alignItemWithTrigger={false}>
393 {BROWSER_RECORDING_FRAME_RATES.map((rate) => (
394 <SelectItem hideIndicator key={rate} value={String(rate)}>
395 {rate} fps
396 </SelectItem>
397 ))}
398 </SelectPopup>
399 </Select>
400 }
401 />
402 );
404​
405function AgentBrowserAccessSetting() {
406 const settings = usePrimarySettings();
407 const updateSettings = useUpdatePrimarySettings();
408​
409 return (
410 <SettingsRow
411 serverScoped
412 {...searchableSetting("agent-browser-access")}
413 description="Let agents open and drive the preview browser. When off, the browser tools and the instructions describing them are withheld from agent sessions. Your own browser panel is unaffected."
414 status={
415 settings.enableAgentBrowserAccess
416 ? undefined
417 : "Applies to sessions started from now on; a running agent keeps the tools it was given."
418 }
419 resetAction={
420 settings.enableAgentBrowserAccess !== DEFAULT_UNIFIED_SETTINGS.enableAgentBrowserAccess ? (
421 <SettingResetButton
422 label="agent browser access"
423 onClick={() =>
424 updateSettings({
425 enableAgentBrowserAccess: DEFAULT_UNIFIED_SETTINGS.enableAgentBrowserAccess,
426 })
427 }
428 />
429 ) : null
430 }
431 control={
432 <Switch
433 checked={settings.enableAgentBrowserAccess}
434 onCheckedChange={(checked) =>
435 updateSettings({ enableAgentBrowserAccess: Boolean(checked) })
436 }
437 aria-label="Allow agent browser access"
438 />
439 }
440 />
441 );
443​
444function BrowserAutoShowFloatingPreviewSetting({ disabled }: { readonly disabled: boolean }) {
445 const autoShow = useClientSettings((settings) => settings.browserAutoShowFloatingPreview);
446 const updateSettings = useUpdatePrimarySettings();
447​
448 return (
449 <SettingsRow
450 {...searchableSetting("browser-auto-show-floating-preview")}
451 description="Pop the floating preview into view when an agent opens a browser. An agent that explicitly asks to show or hide its preview still gets what it asked for."
452 resetAction={
453 !disabled && autoShow !== DEFAULT_BROWSER_AUTO_SHOW_FLOATING_PREVIEW ? (
454 <SettingResetButton
455 label="auto-show floating preview"
456 onClick={() =>
457 updateSettings({
458 browserAutoShowFloatingPreview: DEFAULT_BROWSER_AUTO_SHOW_FLOATING_PREVIEW,
459 })
460 }
461 />
462 ) : null
463 }
464 control={
465 <Switch
466 disabled={disabled}
467 checked={autoShow}
468 onCheckedChange={(checked) =>
469 updateSettings({ browserAutoShowFloatingPreview: Boolean(checked) })
470 }
471 aria-label="Auto-show floating preview"
472 />
473 }
474 />
475 );
477​
478/**
479 * Frames the client-local preview defaults as one unavailable block.
480 *
481 * Disabling each control on its own left the labels and descriptions at full
482 * strength, so the group still read as editable. Boxing it puts the reason at
483 * the top and dims everything it covers, which is also why the explanation
484 * sits outside the dimmed area — the one part that must stay readable is the
485 * part saying why the rest isn't.
486 *
487 * Disabled rather than hidden because these are *client* settings: editing
488 * them from a browser tab would write preferences belonging to a different
489 * client, reading as though the desktop app had been configured when it
490 * hadn't.
491 */
492function DesktopOnlyBrowserDefaults({ children }: { readonly children: ReactNode }) {
493 return (
494 <div className="rounded-xl border border-border/60 bg-muted/20 py-1.5">
495 <div className="flex items-start gap-2 px-3 py-2 text-[12px] leading-relaxed text-muted-foreground sm:px-4">
496 <InfoIcon className="mt-0.5 size-3.5 shrink-0 text-warning" />
497 <p>Only available in the desktop app.</p>
498 </div>
499 <div className="[&_h3]:opacity-64 [&_p]:opacity-64">{children}</div>
500 </div>
501 );
503​
504export function IntegrationsSettingsPanel() {
505 // Client-local preview defaults are editable only where the preview exists.
506 const previewDefaultsDisabled = !isElectron;
507 const previewDefaults = (
508 <>
509 <BrowserViewportSetting disabled={previewDefaultsDisabled} />
510 <BrowserZoomSetting disabled={previewDefaultsDisabled} />
511 <BrowserAppearanceSetting disabled={previewDefaultsDisabled} />
512 <BrowserRecordingFrameRateSetting disabled={previewDefaultsDisabled} />
513 <BrowserAutoShowFloatingPreviewSetting disabled={previewDefaultsDisabled} />
514 </>
515 );
516​
517 return (
518 <SettingsPageContainer>
519 <SettingsSection id="browser" title="Browser">
520 {/* Server-authoritative, so it stays editable on any client anchored to
521 a server; `serverScoped` covers the hosted app, which has none. It
522 sits outside the block covering the desktop-only defaults. */}
523 <AgentBrowserAccessSetting />
524 {previewDefaultsDisabled ? (
525 <DesktopOnlyBrowserDefaults>{previewDefaults}</DesktopOnlyBrowserDefaults>
526 ) : (
527 previewDefaults
528 )}
529 </SettingsSection>
530 </SettingsPageContainer>
531 );