feat(desktop): add cross-platform window capture #8103
MergedBil0000(GitHub profile, opens in a new tab)merged 250+ commits into
main fromrefs/pull/8103/headmerged by juliusmarminge View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- apps/desktop/src/windowCapture/DesktopWindowCapture.ts lines 64 to 66OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +46,21 @@46+export class DesktopWindowCapture extends Context.Service<47+ DesktopWindowCapture,48+ {49+ readonly initialize: Effect.Effect<void>;50+ readonly configure: (settings: ClientSettings) => Effect.Effect<void>;51+ readonly state: Effect.Effect<DesktopWindowCaptureState>;52+ readonly capture: Effect.Effect<void, DesktopWindowCaptureError>;53+ readonly listPending: Effect.Effect<54+ ReadonlyArray<DesktopPendingWindowCapture>,55+ DesktopWindowCaptureError56+ >;57+ readonly read: (58+ id: string,59+ ) => Effect.Effect<DesktopWindowCaptureValue, DesktopWindowCaptureError>;60+ readonly acknowledge: (id: string) => Effect.Effect<void, DesktopWindowCaptureError>;61+ }62+>()("@t3tools/desktop/windowCapture/DesktopWindowCapture") {}63+64+function captureError(message: string, cause: unknown) {65+ return new DesktopWindowCaptureError({ message, cause });66+}apps/desktop/src/windowCapture/DesktopWindowCapture.ts lines 38 to 44OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +24,21 @@24+import * as DesktopClientSettings from "../settings/DesktopClientSettings.ts";25+import * as DesktopWindow from "../window/DesktopWindow.ts";26+import { findCaptureSource, isWaylandSession, toElectronAccelerator } from "./windowCapture.ts";27+28+const MAX_CAPTURE_WIDTH = 5_120;29+const MAX_CAPTURE_HEIGHT = 2_880;30+const CAPTURE_READY_ACTION = "window-capture-ready";31+const CAPTURE_FAILED_ACTION = "window-capture-failed";32+33+const decodePendingCapture = Schema.decodeUnknownSync(DesktopPendingWindowCapture);34+35+const PendingCaptureJson = Schema.fromJsonString(DesktopPendingWindowCapture);36+const decodePendingCaptureJson = Schema.decodeSync(PendingCaptureJson);37+const encodePendingCaptureJson = Schema.encodeSync(PendingCaptureJson);38+export class DesktopWindowCaptureError extends Schema.TaggedErrorClass<DesktopWindowCaptureError>()(39+ "DesktopWindowCaptureError",40+ {41+ message: Schema.String,42+ cause: Schema.Defect(),43+ },44+) {}
- apps/web/src/components/desktop/WindowCaptureCoordinator.tsx line 113OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +93,21 @@93+ description: "Add a project, then capture the window again.",94+ }),95+ );96+ return;97+ }98+99+ const store = useComposerDraftStore.getState();100+ const existing = store.getComposerDraft(target);101+ if (existing?.persistedAttachments.some((attachment) => attachment.id === item.id)) {102+ await bridge.acknowledgeWindowCapture(item.id);103+ continue;104+ }105+106+ const capture = await bridge.readWindowCapture(item.id);107+ const original = await dataUrlToFile(capture.dataUrl, capture.name, capture.mimeType);108+ const compressed = await compressImageToByteLimit(109+ original,110+ PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,111+ );112+ if (!compressed.ok) {113+ throw new Error("The captured window is too large to attach.");apps/desktop/src/windowCapture/DesktopWindowCapture.ts lines 133 to 136OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +116,21 @@116+ }117+118+ const sources = await Electron.desktopCapturer.getSources({119+ types: mode === "portal" ? ["window", "screen"] : ["window"],120+ thumbnailSize: thumbnailSize(active),121+ fetchWindowIcons: true,122+ });123+ const source =124+ mode === "portal" ? sources[0] : active ? findCaptureSource(sources, active) : undefined;125+ if (!source || source.thumbnail.isEmpty()) {126+ throw new Error(127+ mode === "portal"128+ ? "No window was selected."129+ : "The active window is not available for capture.",130+ );131+ }132+ return { source, active };133+ } catch (cause) {134+ if (hiddenWindow && !hiddenWindow.isDestroyed()) hiddenWindow.show();135+ throw cause;136+ }apps/web/src/components/desktop/WindowCaptureCoordinator.tsx lines 82 to 82OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +62,21 @@62+ if (currentTarget) lastTargetRef.current = currentTarget;63+64+ const resolveTarget = useCallback(async (): Promise<CaptureTarget | null> => {65+ if (lastTargetRef.current) return lastTargetRef.current;66+ const projectRef = resolveThreadActionProjectRef({67+ activeDraftThread,68+ activeThread: activeThread ?? undefined,69+ defaultProjectRef,70+ handleNewThread,71+ });72+ if (!projectRef) return null;73+ const created = await handleNewThread(projectRef);74+ if (!created) return null;75+ lastTargetRef.current = created.draftId;76+ return created.draftId;77+ }, [activeDraftThread, activeThread, defaultProjectRef, handleNewThread]);78+79+ const drain = useCallback(async () => {80+ const bridge = window.desktopBridge;81+ if (!bridge) return;82+ if (drainingRef.current) return drainingRef.current;packages/contracts/src/ipc.ts line 1119OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1081,3 +1114,6 @@10811114 setConnectionCatalog?: (catalog: string) => Promise<boolean>;10821115 clearConnectionCatalog?: () => Promise<void>;10831116 discoverSshHosts: () => Promise<readonly DesktopDiscoveredSshHost[]>;1117+ getWindowCaptureState: () => Promise<DesktopWindowCaptureState>;1118+ captureWindow: () => Promise<void>;1119+ listPendingWindowCaptures: () => Promise<readonly DesktopPendingWindowCapture[]>;apps/desktop/src/windowCapture/DesktopWindowCapture.ts lines 312 to 319OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +299,21 @@299+ ),300+ ),301+ configure,302+ state: Ref.get(stateRef),303+ capture,304+ listPending: Effect.tryPromise({305+ try: async () => {306+ const names = await NodeFSP.readdir(captureDirectory).catch(307+ (error: NodeJS.ErrnoException) => {308+ if (error.code === "ENOENT") return [];309+ throw error;310+ },311+ );312+ const captures = await Promise.all(313+ names314+ .filter((name) => name.endsWith(".json") && !name.endsWith(".json.tmp"))315+ .map(async (name) =>316+ decodePendingCaptureJson(317+ await NodeFSP.readFile(NodePath.join(captureDirectory, name), "utf8"),318+ ),319+ ),apps/desktop/src/windowCapture/DesktopWindowCapture.ts lines 228 to 231OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +211,21 @@211+ name: `window-${capturedAt.replaceAll(":", "-")}.png`,212+ mimeType: "image/png",213+ sizeBytes: png.byteLength,214+ source: {215+ kind: "window-capture",216+ capturedAt,217+ appName: active?.owner.name.trim() || source.name.trim() || "Window",218+ windowTitle: active?.title.trim() || source.name.trim(),219+ ...(active?.platform === "macos" && active.owner.bundleId220+ ? { appIdentifier: active.owner.bundleId }221+ : {}),222+ ...(appIconDataUrl ? { appIconDataUrl } : {}),223+ },224+ });225+ await NodeFSP.mkdir(captureDirectory, { recursive: true });226+ const imagePath = NodePath.join(captureDirectory, `${id}.png`);227+ const metadataPath = NodePath.join(captureDirectory, `${id}.json`);228+ await NodeFSP.writeFile(`${imagePath}.tmp`, png);229+ await NodeFSP.rename(`${imagePath}.tmp`, imagePath);230+ await NodeFSP.writeFile(`${metadataPath}.tmp`, encodePendingCaptureJson(pending), "utf8");231+ await NodeFSP.rename(`${metadataPath}.tmp`, metadataPath);
- apps/web/src/components/chat/ChatComposer.tsx lines 3228 to 3228OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -3216,4 +3218,11 @@32163218 return (32173219 <div32183220 key={image.id}3219- className="relative h-16 w-16 overflow-hidden rounded-lg border border-border/80 bg-background"3221+ className={cn(3222+ "relative overflow-hidden rounded-lg border border-border/80 bg-background",3223+ image.source?.kind === "window-capture"3224+ ? "flex h-20 w-56"3225+ : "h-16 w-16",3226+ image.source?.kind === "window-capture" &&3227+ settings.windowCaptureAnimations &&3228+ "animate-in fade-in zoom-in-95 duration-200 motion-reduce:animate-none",apps/web/src/index.css lines 2412 to 2420OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -2400 +2400,21 @@240024002401+@keyframes window-capture-card-enter {2402+ from {2403+ opacity: 0.35;2404+ transform: scale(0.97);2405+ }2406+ to {2407+ opacity: 1;2408+ transform: scale(1);2409+ }2410+}2411+2412+.animate-in.fade-in.zoom-in-95 {2413+ animation: window-capture-card-enter 180ms cubic-bezier(0.2, 0.8, 0.2, 1) both;2414+}2415+2416+@media (prefers-reduced-motion: reduce) {2417+ .animate-in.fade-in.zoom-in-95 {2418+ animation: none;2419+ }2420+}apps/web/src/components/settings/WindowCaptureSettings.tsx lines 145 to 146OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +126,21 @@126+ {...searchableSetting("window-capture-shortcut")}127+ description="Click the shortcut, then press a key with at least one modifier."128+ resetAction={129+ <SettingResetButton130+ label="window capture shortcut"131+ disabled={132+ shortcutToKeybindingInput(settings.windowCaptureShortcut) ===133+ shortcutToKeybindingInput(DEFAULT_WINDOW_CAPTURE_SHORTCUT)134+ }135+ onClick={() => void save({ windowCaptureShortcut: DEFAULT_WINDOW_CAPTURE_SHORTCUT })}136+ />137+ }138+ control={139+ <Button140+ type="button"141+ size="sm"142+ variant={recording ? "secondary" : "outline"}143+ disabled={!bridge}144+ aria-label="Record window capture shortcut"145+ onClick={() => setRecording(true)}146+ onKeyDown={recordShortcut}
- apps/web/src/components/desktop/WindowCaptureOnboardingDialog.tsx lines 51 to 51OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +31,21 @@31+ };32+33+ return (34+ <Dialog35+ open={open}36+ onOpenChange={(nextOpen) => {37+ if (!nextOpen) close();38+ }}39+ >40+ <DialogPopup className="max-w-md">41+ <DialogHeader>42+ <div className="mb-2 flex size-11 items-center justify-center rounded-xl border border-border bg-muted">43+ <CameraIcon className="size-5" />44+ </div>45+ <DialogTitle>Capture any window</DialogTitle>46+ <DialogDescription>47+ Press the global shortcut from any app. T3 Code captures that window and adds it to your48+ current draft with its app name and icon.49+ </DialogDescription>50+ </DialogHeader>51+ <div className="mx-6 flex items-center justify-between rounded-xl border border-border bg-muted/50 px-4 py-3">
- apps/web/src/components/chat/WindowCaptureAttachmentDetails.tsx lines 22 to 22OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +2,21 @@2+3+import { cn } from "../../lib/utils";4+5+export function WindowCaptureAttachmentDetails({6+ source,7+ className,8+}: {9+ source: WindowCaptureSource;10+ className?: string;11+}) {12+ return (13+ <div className={cn("flex min-w-0 flex-1 items-center gap-2", className)}>14+ {source.appIconDataUrl ? (15+ <img src={source.appIconDataUrl} alt="" className="size-7 shrink-0 rounded-md" />16+ ) : (17+ <div className="flex size-7 shrink-0 items-center justify-center rounded-md bg-secondary text-xs font-medium text-secondary-foreground">18+ {source.appName.slice(0, 1).toUpperCase()}19+ </div>20+ )}21+ <div className="min-w-0">22+ <div className="truncate text-xs font-medium">{source.appName}</div>apps/web/src/components/desktop/WindowCaptureOnboardingDialog.tsx lines 27 to 27OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +7,21 @@7+ useClientSettings,8+ useClientSettingsHydrated,9+ useUpdateClientSettings,10+} from "../../hooks/useSettings";11+import { Button } from "../ui/button";12+import {13+ Dialog,14+ DialogDescription,15+ DialogFooter,16+ DialogHeader,17+ DialogPanel,18+ DialogPopup,19+ DialogTitle,20+} from "../ui/dialog";21+import { Kbd } from "../ui/kbd";22+23+export function WindowCaptureOnboardingDialog() {24+ const settings = useClientSettings();25+ const updateSettings = useUpdateClientSettings();26+ const settingsHydrated = useClientSettingsHydrated();27+ const navigate = useNavigate();apps/web/src/components/desktop/WindowCaptureOnboardingDialog.tsx lines 51 to 51OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +31,21 @@31+ !settings.windowCaptureOnboardingDismissed;32+33+ const close = () => {34+ void updateSettings({ windowCaptureOnboardingDismissed: true });35+ };36+37+ return (38+ <Dialog39+ open={open}40+ onOpenChange={(nextOpen) => {41+ if (!nextOpen) close();42+ }}43+ >44+ <DialogPopup className="max-w-md">45+ <DialogHeader>46+ <div className="mb-2 flex size-11 items-center justify-center rounded-xl border border-border bg-muted">47+ <CameraIcon className="size-5" />48+ </div>49+ <DialogTitle>Capture any window</DialogTitle>50+ <DialogDescription>51+ Press the global shortcut from any app. T3 Code captures that window and adds it to yourapps/web/src/components/settings/WindowCaptureSettings.tsx lines 170 to 174OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +154,21 @@154+ onClick={() => setRecording(true)}155+ onKeyDown={recordShortcut}156+ onBlur={() => setRecording(false)}157+ >158+ {recording ? (159+ "Press shortcut…"160+ ) : (161+ <Kbd>{formatShortcutLabel(settings.windowCaptureShortcut)}</Kbd>162+ )}163+ </Button>164+ }165+ />166+ <SettingsRow167+ {...searchableSetting("window-capture-sound")}168+ description="Play a short sound after the image is attached."169+ control={170+ <Switch171+ checked={settings.windowCapturePlaySound}172+ aria-label="Play window capture sound"173+ onCheckedChange={(checked) => void save({ windowCapturePlaySound: checked })}174+ />
- apps/web/src/components/settings/WindowCaptureSettings.tsx lines 170 to 174OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +154,21 @@154+ onClick={() => setRecording(true)}155+ onKeyDown={recordShortcut}156+ onBlur={() => setRecording(false)}157+ >158+ {recording ? (159+ "Press shortcut…"160+ ) : (161+ <Kbd>{formatShortcutLabel(settings.windowCaptureShortcut)}</Kbd>162+ )}163+ </Button>164+ }165+ />166+ <SettingsRow167+ {...searchableSetting("window-capture-sound")}168+ description="Play a short sound after the image is attached."169+ control={170+ <Switch171+ checked={settings.windowCapturePlaySound}172+ aria-label="Play window capture sound"173+ onCheckedChange={(checked) => void save({ windowCapturePlaySound: checked })}174+ />apps/web/src/components/settings/WindowCaptureSettings.tsx lines 72 to 74OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +54,21 @@54+ const refreshState = useCallback(async () => {55+ if (bridge) setState(await bridge.getWindowCaptureState());56+ }, [bridge]);57+58+ useEffect(() => {59+ void refreshState();60+ }, [refreshState]);61+62+ const save = useCallback(63+ async (patch: ClientSettingsPatch) => {64+ await updateSettings(patch);65+ await refreshState();66+ },67+ [refreshState, updateSettings],68+ );69+70+ const recordShortcut = useCallback(71+ (event: KeyboardEvent<HTMLButtonElement>) => {72+ if (!recording) return;73+ event.preventDefault();74+ event.stopPropagation();
- apps/web/src/components/desktop/WindowCaptureCoordinator.tsx lines 164 to 164OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +144,21 @@144+ };145+ const persistedAttachments =146+ store147+ .getComposerDraft(target)148+ ?.persistedAttachments.filter((attachment) => attachment.id !== capture.id) ?? [];149+ store.syncPersistedAttachments(target, [...persistedAttachments, persisted]);150+ await Promise.resolve();151+ if (152+ !store153+ .getComposerDraft(target)154+ ?.persistedAttachments.some(({ id }) => id === capture.id)155+ ) {156+ throw new Error("The captured window could not be saved to the draft.");157+ }158+ await bridge.acknowledgeWindowCapture(capture.id);159+ if (playSound) {160+ try {161+ playCaptureSound();162+ } catch {}163+ }164+ window.dispatchEvent(new Event("t3:focus-composer"));apps/web/src/components/chat/ChatComposer.tsx lines 3224 to 3224OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -3216,4 +3218,7 @@32163218 return (32173219 <div32183220 key={image.id}3219- className="relative h-16 w-16 overflow-hidden rounded-lg border border-border/80 bg-background"3221+ className={cn(3222+ "relative overflow-hidden rounded-lg border border-border/80 bg-background",3223+ image.source?.kind === "window-capture"3224+ ? "flex h-20 w-56"
- apps/web/src/components/desktop/WindowCaptureCoordinator.tsx lines 164 to 164OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +144,21 @@144+ };145+ const persistedAttachments =146+ store147+ .getComposerDraft(target)148+ ?.persistedAttachments.filter((attachment) => attachment.id !== capture.id) ?? [];149+ store.syncPersistedAttachments(target, [...persistedAttachments, persisted]);150+ await Promise.resolve();151+ if (152+ !store153+ .getComposerDraft(target)154+ ?.persistedAttachments.some(({ id }) => id === capture.id)155+ ) {156+ throw new Error("The captured window could not be saved to the draft.");157+ }158+ await bridge.acknowledgeWindowCapture(capture.id);159+ if (playSound) {160+ try {161+ playCaptureSound();162+ } catch {}163+ }164+ window.dispatchEvent(new Event("t3:focus-composer"));
- apps/web/src/components/desktop/WindowCaptureCoordinator.tsx line 170OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +150,21 @@150+ .getComposerDraft(target)151+ ?.persistedAttachments.filter((attachment) => attachment.id !== capture.id) ?? [];152+ store.syncPersistedAttachments(target, [...persistedAttachments, persisted]);153+ await Promise.resolve();154+ if (155+ !store156+ .getComposerDraft(target)157+ ?.persistedAttachments.some(({ id }) => id === capture.id)158+ ) {159+ throw new Error("The captured window could not be saved to the draft.");160+ }161+ await bridge.acknowledgeWindowCapture(capture.id);162+ if (playSound) {163+ try {164+ playCaptureSound();165+ } catch {}166+ }167+ window.dispatchEvent(new Event(WINDOW_CAPTURE_FOCUS_EVENT));168+ } catch (error) {169+ try {170+ await bridge.acknowledgeWindowCapture(item.id);apps/web/src/components/desktop/WindowCaptureCoordinator.tsx line 70OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +50,21 @@50+}51+52+export function WindowCaptureCoordinator() {53+ const {54+ activeDraftThread,55+ activeThread,56+ defaultProjectRef,57+ handleNewThread,58+ routeDraftId,59+ routeThreadRef,60+ } = useHandleNewThread();61+ const playSound = useClientSettings((settings) => settings.windowCapturePlaySound);62+ const lastTargetRef = useRef<CaptureTarget | null>(null);63+ const drainingRef = useRef<Promise<void> | null>(null);64+ const rerunRequestedRef = useRef(false);65+66+ const currentTarget = routeThreadRef ?? routeDraftId;67+ if (currentTarget) lastTargetRef.current = currentTarget;68+69+ const resolveTarget = useCallback(async (): Promise<CaptureTarget | null> => {70+ if (lastTargetRef.current) return lastTargetRef.current;
- apps/web/src/components/settings/WindowCaptureSettings.tsx lines 113 to 113OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +93,21 @@93+ await bridge.captureWindow();94+ } catch (error) {95+ toastManager.add(96+ stackedThreadToast({97+ type: "error",98+ title: "Window capture failed",99+ description: error instanceof Error ? error.message : "Try the capture again.",100+ }),101+ );102+ } finally {103+ setCapturing(false);104+ await refreshState();105+ }106+ }, [bridge, capturing, refreshState]);107+108+ return (109+ <SettingsPageContainer>110+ <SettingsSection111+ id="window-capture"112+ title="Window Capture"113+ icon={<CameraIcon className="size-4.5" />}apps/web/src/components/settings/WindowCaptureSettings.tsx lines 166 to 201OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +181,21 @@181+ control={182+ <Switch183+ checked={settings.windowCaptureFlash}184+ disabled={!bridge}185+ aria-label="Flash captured window"186+ onCheckedChange={(checked) => void save({ windowCaptureFlash: checked })}187+ />188+ }189+ />190+ <SettingsRow191+ {...searchableSetting("window-capture-animations")}192+ description="Animate new capture cards and the capture flash."193+ control={194+ <Switch195+ checked={settings.windowCaptureAnimations}196+ disabled={!bridge}197+ aria-label="Animate window captures"198+ onCheckedChange={(checked) => void save({ windowCaptureAnimations: checked })}199+ />200+ }201+ />
- apps/web/src/components/settings/settingsLayout.tsx lines 216 to 216Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -147,3 +147,4 @@147147 );148148 }149149150+export function SettingsUnavailableGroup({apps/web/src/components/settings/WindowCaptureSettings.tsx lines 130 to 133OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +113,21 @@113+ description="Capture a window from anywhere and attach it to your current draft."114+ status={bridge ? captureStatus(state, settings.windowCaptureEnabled) : undefined}115+ control={116+ <Switch117+ checked={settings.windowCaptureEnabled}118+ disabled={!bridge}119+ aria-label="Enable window capture"120+ onCheckedChange={(checked) => void save({ windowCaptureEnabled: checked })}121+ />122+ }123+ />124+ <SettingsRow125+ {...searchableSetting("window-capture-shortcut")}126+ description="Click the shortcut, then press a key with at least one modifier."127+ resetAction={128+ <SettingResetButton129+ label="window capture shortcut"130+ disabled={131+ shortcutToKeybindingInput(settings.windowCaptureShortcut) ===132+ shortcutToKeybindingInput(DEFAULT_WINDOW_CAPTURE_SHORTCUT)133+ }
- apps/web/src/components/chat/ChatComposer.tsx lines 3236 to 3236OutdatedResolvedby Bil0000(GitHub profile, opens in a new tab)@@ -3216,9 +3218,19 @@32163218 return (32173219 <div32183220 key={image.id}3219- className="relative h-16 w-16 overflow-hidden rounded-lg border border-border/80 bg-background"3221+ className={cn(3222+ "relative overflow-hidden rounded-lg border border-border/80 bg-background",3223+ image.source?.kind === "window-capture"3224+ ? "flex h-20 max-w-full"3225+ : "h-16 w-16",3226+ image.source?.kind === "window-capture" &&3227+ settings.windowCaptureAnimations &&3228+ "animate-[window-capture-card-enter_180ms_cubic-bezier(0.2,0.8,0.2,1)_both] motion-reduce:animate-none",3229+ )}32203230 >32213231 {image.previewUrl ? (32223232 <button32233233 type="button"3224- className="h-full w-full cursor-zoom-in"3234+ className={3235+ image.source?.kind === "window-capture"3236+ ? "h-full w-24 shrink-0 cursor-zoom-in overflow-hidden border-r border-border/70"
- apps/desktop/src/windowCapture/DesktopWindowCapture.ts line 262OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +242,21 @@242+ : {}),243+ ...(appIconDataUrl ? { appIconDataUrl } : {}),244+ },245+ });246+ await NodeFSP.writeFile(imageTempPath, png);247+ await NodeFSP.rename(imageTempPath, imagePath);248+ await NodeFSP.writeFile(metadataPath + ".tmp", encodePendingCaptureJson(pending), "utf8");249+ await NodeFSP.rename(metadataPath + ".tmp", metadataPath);250+ showFlash(settings, active);251+ } catch (cause) {252+ await Promise.allSettled([253+ NodeFSP.rm(imagePath, { force: true }),254+ NodeFSP.rm(imageTempPath, { force: true }),255+ NodeFSP.rm(metadataPath, { force: true }),256+ NodeFSP.rm(metadataPath + ".tmp", { force: true }),257+ ]);258+ throw cause;259+ }260+ },261+ catch: (cause) =>262+ new DesktopWindowCaptureError({ operation: "capture", captureId: id, cause }),
- apps/desktop/scripts/electron-launcher.mjs lines 165 to 171Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -130,9 +138,12 @@130- NodeFS.writeFileSync(131- targetBinaryPath,132- makeDevelopmentLauncherScript({133- electronBinaryPath,134- mainEntryPath: NodePath.join(desktopDir, "dist-electron", "main.cjs"),135- desktopRoot: desktopDir,136- environment: process.env,137- }),138- );138+ const script = makeDevelopmentLauncherScript({139+ electronBinaryPath,140+ mainEntryPath: NodePath.join(desktopDir, "dist-electron", "main.cjs"),141+ desktopRoot: desktopDir,142+ environment: process.env,143+ });144+ if (145+ NodeFS.existsSync(targetBinaryPath) &&146+ NodeFS.readFileSync(targetBinaryPath, "utf8") === script147+ ) {148+ return false;149+ }
- apps/desktop/src/windowCapture/DesktopWindowCapture.ts lines 66 to 73OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +53,21 @@53+ "acknowledge",54+]);55+const DesktopWindowCaptureFailureReason = Schema.Literals([56+ "unsupported",57+ "no-window-selected",58+ "window-unavailable",59+]);60+61+export class DesktopWindowCaptureError extends Schema.TaggedErrorClass<DesktopWindowCaptureError>()(62+ "DesktopWindowCaptureError",63+ {64+ operation: DesktopWindowCaptureOperation,65+ captureId: Schema.optional(Schema.String),66+ reason: Schema.optional(DesktopWindowCaptureFailureReason),67+ cause: Schema.Defect(),68+ },69+) {70+ override get message(): string {71+ switch (this.operation) {72+ case "capture":73+ return windowCaptureFailureMessage(this.reason);apps/desktop/src/windowCapture/DesktopWindowCapture.ts lines 184 to 188OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +168,21 @@168+ active = await activeWindow({169+ accessibilityPermission: false,170+ screenRecordingPermission: false,171+ });172+ }173+174+ const sources = await Electron.desktopCapturer.getSources({175+ types: mode === "portal" ? ["window", "screen"] : ["window"],176+ thumbnailSize: thumbnailSize(active),177+ fetchWindowIcons: true,178+ });179+ const source =180+ mode === "portal" ? sources[0] : active ? findCaptureSource(sources, active) : undefined;181+ if (!source || source.thumbnail.isEmpty()) {182+ const reason: WindowCaptureFailureReason =183+ mode === "portal" ? "no-window-selected" : "window-unavailable";184+ throw new DesktopWindowCaptureError({185+ operation: "capture",186+ captureId,187+ reason,188+ cause: new Error(windowCaptureFailureMessage(reason)),
- apps/desktop/src/preload.ts lines 54 to 60OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -51,3 +51,10 @@5151 getClientSettings: () => ipcRenderer.invoke(IpcChannels.GET_CLIENT_SETTINGS_CHANNEL),5252 setClientSettings: (settings) =>5353 ipcRenderer.invoke(IpcChannels.SET_CLIENT_SETTINGS_CHANNEL, settings),54+ getWindowCaptureState: () => ipcRenderer.invoke(IpcChannels.GET_WINDOW_CAPTURE_STATE_CHANNEL),55+ captureWindow: () => ipcRenderer.invoke(IpcChannels.CAPTURE_WINDOW_CHANNEL),56+ listPendingWindowCaptures: () =>57+ ipcRenderer.invoke(IpcChannels.LIST_PENDING_WINDOW_CAPTURES_CHANNEL),58+ readWindowCapture: (id) => ipcRenderer.invoke(IpcChannels.READ_WINDOW_CAPTURE_CHANNEL, id),59+ acknowledgeWindowCapture: (id) =>60+ ipcRenderer.invoke(IpcChannels.ACKNOWLEDGE_WINDOW_CAPTURE_CHANNEL, id),apps/desktop/src/windowCapture/DesktopWindowCapture.ts lines 196 to 204OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +184,21 @@184+async function requestMacWindowCapturePermissions(): Promise<string | null> {185+ const accessibilityGranted = Electron.systemPreferences.isTrustedAccessibilityClient(true);186+ const screenMessage = await requestMacScreenCapturePermission();187+ if (!accessibilityGranted && screenMessage) {188+ return "Allow Accessibility and Screen Recording in System Settings, then restart T3 Code.";189+ }190+ if (!accessibilityGranted) {191+ return "Allow Accessibility in System Settings, then restart T3 Code.";192+ }193+ return screenMessage;194+}195+196+async function readAccessibleWindowText(): Promise<string | undefined> {197+ try {198+ const { App } = await import("@crowecawcaw/xa11y");199+ const app = await App.foreground({ timeout: 0 });200+ const text = accessibleWindowText(await app.tree(), WINDOW_CAPTURE_ACCESSIBLE_TEXT_MAX_CHARS);201+ return text || undefined;202+ } catch {203+ return undefined;204+ }apps/desktop/src/windowCapture/DesktopWindowCapture.ts lines 207 to 213OutdatedResolvedby Bil0000(GitHub profile, opens in a new tab)@@ -0,0 +193,21 @@193+ return screenMessage;194+}195+196+async function readAccessibleWindowText(): Promise<string | undefined> {197+ try {198+ const { App } = await import("@crowecawcaw/xa11y");199+ const app = await App.foreground({ timeout: 0 });200+ const text = accessibleWindowText(await app.tree(), WINDOW_CAPTURE_ACCESSIBLE_TEXT_MAX_CHARS);201+ return text || undefined;202+ } catch {203+ return undefined;204+ }205+}206+207+async function revealPreviousWindowIfNeeded(): Promise<Electron.BrowserWindow | undefined> {208+ const focused = Electron.BrowserWindow.getFocusedWindow();209+ if (!focused) return undefined;210+ focused.hide();211+ await new Promise((resolve) => setTimeout(resolve, 120));212+ return focused;213+}apps/desktop/src/windowCapture/windowCapture.ts lines 15 to 27OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +7,21 @@7+}8+9+export function accessibleWindowText(root: AccessibilityTreeNode, maxChars: number): string {10+ const lines: string[] = [];11+ const seen = new Set<string>();12+ const stack = [root];13+ while (stack.length > 0) {14+ const node = stack.pop()!;15+ for (const candidate of [node.name, node.value]) {16+ const text = candidate?.replaceAll("\0", "").trim();17+ if (text && !seen.has(text)) {18+ seen.add(text);19+ lines.push(text);20+ }21+ }22+ stack.push(...node.children.toReversed());23+ }24+ const text = lines.join("\n");25+ if (text.length <= maxChars) return text;26+ const end = /[\uD800-\uDBFF]/.test(text[maxChars - 1] ?? "") ? maxChars - 1 : maxChars;27+ return text.slice(0, end);apps/desktop/src/windowCapture/windowCapture.ts line 43OutdatedResolvedby Bil0000(GitHub profile, opens in a new tab)@@ -0,0 +23,21 @@23+ }24+ const text = lines.join("\n");25+ if (text.length <= maxChars) return text;26+ const end = /[\uD800-\uDBFF]/.test(text[maxChars - 1] ?? "") ? maxChars - 1 : maxChars;27+ return text.slice(0, end);28+}29+30+const ELECTRON_KEY_NAMES: Readonly<Record<string, string>> = {31+ " ": "Space",32+ "+": "Plus",33+ ArrowDown: "Down",34+ ArrowLeft: "Left",35+ ArrowRight: "Right",36+ ArrowUp: "Up",37+ Escape: "Esc",38+};39+40+export function toElectronAccelerator(shortcut: WindowCaptureShortcut): string {41+ const parts: string[] = [];42+ if (shortcut.modKey) parts.push("CommandOrControl");43+ if (shortcut.metaKey) parts.push("Command");apps/server/src/provider/Layers/ProviderService.ts lines 740 to 756OutdatedResolvedby Bil0000(GitHub profile, opens in a new tab)@@ -740,7 +739,18 @@739+ const attachmentContext = attachments.flatMap((attachment) => {740+ const source = attachment.source;741+ const accessibleText = source?.accessibleText;742+ const sourceLabel = source?.windowTitle743+ ? `${source.appName} — ${source.windowTitle}`744+ : source?.appName;745+ const textSection = accessibleText746+ ? [`[Available text from ${sourceLabel}]\n${accessibleText}\n[End available window text]`]747+ : [];740748 const attachmentPath = resolveAttachmentPath({741749 attachmentsDir: serverConfig.attachmentsDir,742750 attachment,743751 });744- return attachmentPath === null745- ? []746- : [`[Attached ${attachment.type} "${attachment.name}" is saved at: ${attachmentPath}]`];752+ const pathSection =753+ attachmentPath === null754+ ? []755+ : [`[Attached ${attachment.type} "${attachment.name}" is saved at: ${attachmentPath}]`];756+ return [...textSection, ...pathSection];apps/web/src/components/settings/WindowCaptureSettings.tsx lines 116 to 123OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +103,21 @@103+ } finally {104+ setCapturing(false);105+ await refreshState();106+ }107+ }, [bridge, capturing, refreshState]);108+109+ return (110+ <SettingsPageContainer>111+ <SettingsSection id="window-capture" title="Window Capture">112+ <SettingsUnavailableGroup message={unavailableMessage}>113+ <SettingsRow114+ {...searchableSetting("window-capture-enabled")}115+ description="Capture a window with available text and attach it to your current draft."116+ status={bridge ? captureStatus(state, settings.windowCaptureEnabled) : undefined}117+ control={118+ <Switch119+ checked={settings.windowCaptureEnabled}120+ disabled={!bridge}121+ aria-label="Enable window capture"122+ onCheckedChange={(checked) => void save({ windowCaptureEnabled: checked })}123+ />
- apps/desktop/src/windowCapture/windowCapture.ts lines 37 to 57OutdatedResolvedby Bil0000(GitHub profile, opens in a new tab)@@ -0,0 +37,21 @@37+export function findAccessibleWindow<38+ T extends { readonly name: string | null; readonly bounds: WindowBounds | null },39+>(40+ windows: readonly T[],41+ captured: { readonly title: string; readonly bounds: WindowBounds },42+): T | undefined {43+ const matches = windows.filter((window) => {44+ const bounds = window.bounds;45+ return (46+ bounds !== null &&47+ (["x", "y", "width", "height"] as const).every(48+ (key) => Math.abs(bounds[key] - captured.bounds[key]) <= 2,49+ )50+ );51+ });52+ if (matches.length === 1) return matches[0];53+54+ const title = captured.title.trim();55+ if (!title) return undefined;56+ const titleMatches = matches.filter((window) => window.name?.trim() === title);57+ return titleMatches.length === 1 ? titleMatches[0] : undefined;apps/server/src/provider/Layers/ProviderService.ts lines 736 to 756OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -739,0 +736,21 @@736+ // Attachment paths are added after schema decode. Their count is capped,737+ // while accessible window text shares the input length limit.738+ let remainingTextChars = PROVIDER_SEND_TURN_MAX_INPUT_CHARS - (parsed.input?.length ?? 0);739+ const attachmentContext = attachments.flatMap((attachment) => {740+ const source = attachment.source;741+ const accessibleText = source?.accessibleText;742+ const sourceLabel = source?.windowTitle743+ ? `${source.appName} — ${source.windowTitle}`744+ : source?.appName;745+ const textPrefix = `[Available text from ${sourceLabel}]\n`;746+ const textSuffix = "\n[End available window text]";747+ const maxTextChars = Math.max(remainingTextChars - textPrefix.length - textSuffix.length, 0);748+ const candidateEnd = Math.min(accessibleText?.length ?? 0, maxTextChars);749+ const textEnd = /[\uD800-\uDBFF]/.test(accessibleText?.[candidateEnd - 1] ?? "")750+ ? candidateEnd - 1751+ : candidateEnd;752+ const textSection =753+ accessibleText && textEnd > 0754+ ? [`${textPrefix}${accessibleText.slice(0, textEnd)}${textSuffix}`]755+ : [];756+ remainingTextChars -= textSection[0]?.length ?? 0;
- apps/web/src/components/settings/WindowCaptureSettings.tsx line 102OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +82,21 @@82+ event.preventDefault();83+ event.stopPropagation();84+ if (event.key === "Escape") {85+ setRecording(false);86+ return;87+ }88+ const input = keybindingFromKeyboardEvent(event, navigator.platform);89+ if (!input) return;90+ const shortcut = parseKeybindingShortcut(input);91+ if (!shortcut) return;92+ setRecording(false);93+ void save({ windowCaptureShortcut: shortcut });94+ },95+ [recording, save],96+ );97+98+ const captureNow = useCallback(async () => {99+ if (!captureAvailable || !bridge || capturing) return;100+ setCapturing(true);101+ try {102+ await bridge.captureWindow();
- apps/server/src/provider/Layers/ProviderService.ts line 1542Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -732,8 +742,16 @@732742 // Adapters inline attachment pixels into the model prompt, but the model's733743 // tools cannot dereference pixels. Appending the on-disk path is what lets734744 // a turn like "include this screenshot in the PR" copy the actual file.735- // This runs after schema decode, so the appended lines are exempt from the736- // PROVIDER_SEND_TURN_MAX_INPUT_CHARS check; attachment count is capped, so737- // the overhead is bounded. Unresolvable ids are skipped here and surface738- // as adapter errors when the file is read for inlining.739- const attachmentPathLines = attachments.flatMap((attachment) => {745+ // Generated attachment context is added only while the complete provider746+ // input stays within the validated input length limit.747+ let inputTextWithAttachmentContext = parsed.input;748+ const appendAttachmentContext = (context: string | undefined) => {749+ if (context === undefined) return;750+ const candidate = inputTextWithAttachmentContext751+ ? `${inputTextWithAttachmentContext}\n\n${context}`752+ : context;753+ if (candidate.length <= PROVIDER_SEND_TURN_MAX_INPUT_CHARS) {754+ inputTextWithAttachmentContext = candidate;755+ }756+ };757+ for (const attachment of attachments) {
- apps/web/src/components/desktop/WindowCaptureOnboardingDialog.tsx lines 46 to 47OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +27,21 @@27+ const navigate = useNavigate();28+ const open =29+ settingsHydrated &&30+ Boolean(getDesktopWindowCaptureBridge()) &&31+ !settings.windowCaptureOnboardingDismissed;32+33+ const close = () => {34+ void updateSettings({ windowCaptureOnboardingDismissed: true });35+ };36+37+ return (38+ <Dialog39+ open={open}40+ onOpenChange={(nextOpen) => {41+ if (!nextOpen) close();42+ }}43+ >44+ <DialogPopup className="max-w-md">45+ <DialogHeader>46+ <div className="mb-2 flex size-11 items-center justify-center rounded-xl border border-border bg-muted">47+ <CameraIcon className="size-5" />apps/web/src/components/settings/WindowCaptureSettings.tsx lines 153 to 153OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +133,21 @@133+ />134+ <SettingsRow135+ {...searchableSetting("window-capture-shortcut")}136+ description="Click the shortcut, then press a key with at least one modifier."137+ resetAction={138+ <SettingResetButton139+ label="window capture shortcut"140+ disabled={141+ !captureAvailable ||142+ shortcutToKeybindingInput(settings.windowCaptureShortcut) ===143+ shortcutToKeybindingInput(DEFAULT_WINDOW_CAPTURE_SHORTCUT)144+ }145+ onClick={() =>146+ void save({ windowCaptureShortcut: DEFAULT_WINDOW_CAPTURE_SHORTCUT })147+ }148+ />149+ }150+ control={151+ <Button152+ type="button"153+ size="sm"
Sign in to join this conversation.
Note
Reviews paused#
It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the
reviews.auto_review.auto_pause_after_reviewed_commitssetting.Use the following commands to manage reviews:
@coderabbitai resumeto resume automatic reviews.@coderabbitai reviewto trigger a single review.Use the checkboxes below for quick actions:
No actionable comments were generated in the recent review. 🎉
ℹ️ Recent review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Team
Run ID:
b89b0292-7355-41c8-9420-68f886f4056f📥 Commits
Reviewing files that changed from the base of the PR and between cbfd64cc0d53e2b83d1fa55aed58c40335157e4c and 994d8c836aaec6cce92e1efb60966354217083b2.
📒 Files selected for processing (18)
apps/desktop/src/electron/ElectronWindow.test.tsapps/desktop/src/electron/ElectronWindow.tsapps/desktop/src/electron/WindowsForegroundFocusWorker.test.tsapps/desktop/src/electron/WindowsForegroundFocusWorker.tsapps/desktop/src/snapShot/CaptureShortcutConfig.test.tsapps/desktop/src/snapShot/LinuxSnapShot.dbus.test.tsapps/desktop/src/snapShot/RegionSnapShot.test.tsapps/desktop/src/snapShot/RegionSnapShot.tsapps/desktop/src/snapShot/SnapShotAccessibilityProcess.test.tsapps/desktop/src/snapShot/SnapShotAccessibilityProcess.tsapps/desktop/src/snapShot/captureConfigEdit.test.tsapps/desktop/src/snapShot/captureConfigKdl.tsapps/server/src/provider/Layers/ProviderService.test.tsapps/web/src/components/settings/SnapShotSetupDialog.logic.test.tsapps/web/src/components/settings/SnapShotSetupDialog.logic.tsdocs/internals/linux-snap-shot.mddocs/user/snap-shot.mdnative/kde-snap-shot/src/main.rs🚧 Files skipped from review as they are similar to previous changes (1)
Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review.
📝 Walkthrough
Walkthrough#
This pull request adds a "SnapShots" window-capture feature for the desktop app. It provides shared contracts, native capture backends for macOS, Windows, GNOME, KDE, Hyprland, and Niri, IPC and preload wiring, a GNOME Shell extension, Rust helper binaries, web composer and settings UI, provider prompt handling, packaging, and documentation.
Changes#
SnapShot window capture feature
packages/contracts/src/ipc.ts,orchestration.ts,settings.ts,*.test.tsDesktopBridgemethods used across the feature.apps/desktop/package.json,pnpm-workspace.yaml,package.json,scripts/build-desktop-artifact.ts,apps/desktop/vite.config.tsapps/desktop/scripts/electron-launcher.mjs,apps/desktop/src/app/*apps/desktop/src/ipc/...,apps/desktop/src/window/DesktopWindow.ts,apps/desktop/src/preload.ts,apps/desktop/src/main.tsapps/desktop/src/electron/*,apps/desktop/src/preview/Manager.tsapps/desktop/src/snapShot/DesktopSnapShot.ts,MacSnapShot.ts,RegionSnapShot.ts,SnapShotAccessibility*.ts,SnapShotTransition.ts,NativeCaptureFeedback.ts, shortcut process filesapps/desktop/src/snapShot/LinuxSnapShot.ts,PortalCaptureShortcut.ts,GnomeCaptureSetup.ts,KdeSnapShot.ts,HyprlandSnapShot.ts,NiriSnapShot.ts,captureConfigEdit.ts,captureConfigKdl.tsapps/desktop/gnome-extension/*native/hyprland-snap-shot/*,native/kde-snap-shot/*apps/web/src/components/chat/*,apps/web/src/components/desktop/SnapShotCoordinator.tsx,composerDraftStore.ts,apps/web/src/lib/snapShotAnimation.ts,desktopSnapShot.tsapps/web/src/components/settings/SnapShot*.tsx,useSnapShotShortcutRecorder.tsx,keybindings.ts,settingsSearch.ts,ui/wizard-steps.tsxapps/server/src/provider/Layers/ProviderService.ts,Normalizer.ts,apps/web/src/hooks/useSettings.tsdocs/internals/linux-snap-shot.md,docs/user/snap-shot.md,docs/README.mdEstimated code review effort: 5 (Critical) | ~180 minutes
Merge Risk: 🟡 Moderate · up to
994d8SnapShots adds cross-platform capture and provider context handling, but unresolved risks remain around untrusted captured text reaching provider input, captures attaching to the wrong draft, stalled native operations, and platform shortcut or build behavior. These issues should be resolved or explicitly accepted before merge.
Sequence Diagram(s)#
🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)#
✅ Passed checks (4 passed)
Full details: Docstring Coverage
Explanation
Docstring coverage is 6.75% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 163 functions across 92 files. (2 skipped: 2 unsupported.)
✨ Finishing Touches 💡 1
🛠️ Fix failing CI checks 💡
🧪 Generate unit tests (beta)
Comment `@coderabbitai help` to get the list of available commands.