TypeScript
fix(web): settings panels derive state instead of syncing it with effects (#25070)
Julius Marmingee14d08c664f9
diff --git a/apps/web/src/components/settings/AuthorizedClientsSettings.tsx b/apps/web/src/components/settings/AuthorizedClientsSettings.tsxindex 41aada6c8bf..608dee07c05 100644--- a/apps/web/src/components/settings/AuthorizedClientsSettings.tsx+++ b/apps/web/src/components/settings/AuthorizedClientsSettings.tsx@@ -26,7 +26,7 @@ import {selectQrEndpointOption,togglePairingScopeSelection,} from "./ConnectionsSettings.logic";-import { useRelativeTimeTick } from "./settingsLayout";+import { useNowSecond } from "../../hooks/useNowSecond";import { Input } from "../ui/input";import { Checkbox } from "../ui/checkbox";import {@@ -152,7 +152,7 @@ const PairingLinkListRow = memo(function PairingLinkListRow({onRevoke,canRevoke,}: PairingLinkListRowProps) {- const nowMs = useRelativeTimeTick(1_000);+ const nowMs = useNowSecond();const expiresAtMs = new Date(pairingLink.expiresAt).getTime();const [isRevealDialogOpen, setIsRevealDialogOpen] = useState(false);const [isQrPanelOpen, setIsQrPanelOpen] = useState(false);@@ -510,7 +510,7 @@ const ConnectedClientListRow = memo(function ConnectedClientListRow({onRevokeSession,canRevoke,}: ConnectedClientListRowProps) {- const nowMs = useRelativeTimeTick(1_000);+ const nowMs = useNowSecond();const isLive = clientSession.current || clientSession.connected;const lastConnectedAt = clientSession.lastConnectedAt;const statusTooltip = isLivediff --git a/apps/web/src/components/settings/DiagnosticsSettings.tsx b/apps/web/src/components/settings/DiagnosticsSettings.tsxindex cc749596f0c..613074b2d91 100644--- a/apps/web/src/components/settings/DiagnosticsSettings.tsx+++ b/apps/web/src/components/settings/DiagnosticsSettings.tsx@@ -11,7 +11,7 @@ import {isAtomCommandInterrupted,squashAtomCommandFailure,} from "@t3tools/client-runtime/state/runtime";-import { useEffect, useRef, useState, type ReactNode } from "react";+import { useRef, useState, type ReactNode } from "react";import type {ServerProcessDiagnosticsEntry,ServerProcessResourceHistorySummary,@@ -714,6 +714,12 @@ function DiagnosticsRefreshButton({}export function DiagnosticsSettingsPanel() {+ const { environment } = useSettingsScope();+ // Signals and pending UI state belong to one environment, so a scope switch starts fresh.+ return <DiagnosticsSettingsBody key={environment?.environmentId ?? ""} />;+}++function DiagnosticsSettingsBody() {const { environment } = useSettingsScope();const environmentId = environment?.environmentId ?? null;const canMaintainEnvironment = useEnvironmentScope(environmentId, AuthEnvironmentMaintainScope);@@ -772,17 +778,6 @@ export function DiagnosticsSettingsPanel() {const [openLogsDirectoryError, setOpenLogsDirectoryError] = useState<string | null>(null);const [signalingPid, setSignalingPid] = useState<number | null>(null);const signalingPidRef = useRef<number | null>(null);- const environmentIdRef = useRef(environmentId);- const processDataRef = useRef(processData);- useEffect(() => {- processDataRef.current = processData;- }, [processData]);- useEffect(() => {- environmentIdRef.current = environmentId;- return () => {- environmentIdRef.current = null;- };- }, [environmentId]);const openLogsDirectory = () => {const logsDirectoryPath = observability?.logsDirectoryPath ?? null;@@ -825,8 +820,8 @@ export function DiagnosticsSettingsPanel() {setExportFormEnvironmentId(environmentId);}const signalProcess = async (pid: number, signal: ServerProcessSignal) => {- const targetEnvironmentId = environmentIdRef.current;- const process = processDataRef.current?.processes.find((entry) => entry.pid === pid);+ const targetEnvironmentId = environmentId;+ const process = processData?.processes.find((entry) => entry.pid === pid);if (targetEnvironmentId === null ||process === undefined ||@@ -861,19 +856,9 @@ export function DiagnosticsSettingsPanel() {return;}}- const currentEnvironmentId = environmentIdRef.current;- if (- currentEnvironmentId === null ||- currentEnvironmentId !== targetEnvironmentId ||- !readEnvironmentScope(currentEnvironmentId, AuthEnvironmentMaintainScope)- ) {- clearSignaling();- return;- }- if (- processDataRef.current?.processes.find((entry) => entry.pid === pid)?.startTimeMs !==- process.startTimeMs- ) {+ // The server rejects a pid whose start time no longer matches, so a process that exited+ // during confirmation is never signaled by mistake.+ if (!readEnvironmentScope(targetEnvironmentId, AuthEnvironmentMaintainScope)) {clearSignaling();return;}diff --git a/apps/web/src/components/settings/OpenSourceLicenses.tsx b/apps/web/src/components/settings/OpenSourceLicenses.tsxindex f8ad15acf6e..df311db516c 100644--- a/apps/web/src/components/settings/OpenSourceLicenses.tsx+++ b/apps/web/src/components/settings/OpenSourceLicenses.tsx@@ -1,5 +1,12 @@import { ChevronRightIcon, ExternalLinkIcon, SearchIcon } from "lucide-react";-import { useEffect, useState } from "react";+import { useAtomRefresh, useAtomValue } from "@effect/atom-react";+import * as Cause from "effect/Cause";+import * as Data from "effect/Data";+import * as Effect from "effect/Effect";+import * as Option from "effect/Option";+import { FetchHttpClient, HttpClient } from "effect/http";+import { Atom } from "effect/reactivity";+import { useState } from "react";import {decodeThirdPartyLicenseManifest,@@ -7,7 +14,6 @@ import {formatLicenseBundles,thirdPartyLicenseEntryKey,type ThirdPartyLicenseEntry,- type ThirdPartyLicenseManifest,} from "@t3tools/shared/thirdPartyLicenses";import { Button } from "../ui/button";@@ -16,41 +22,45 @@ import { InputGroup, InputGroupAddon, InputGroupInput } from "../ui/input-group"import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";import { SettingsPageContainer, SettingsSection } from "./settingsLayout";-type LicenseManifestState =- | { readonly status: "loading" }- | { readonly status: "error"; readonly message: string }- | { readonly status: "ready"; readonly manifest: ThirdPartyLicenseManifest };+class LicenseManifestLoadError extends Data.TaggedError("LicenseManifestLoadError")<{+ readonly message: string;+}> {}-let licenseManifestPromise: Promise<ThirdPartyLicenseManifest> | undefined;--async function fetchLicenseManifest(): Promise<ThirdPartyLicenseManifest> {- const signal = AbortSignal.timeout(30_000);- try {- const response = await fetch(+// Not keepAlive: a failed load must not stick for the session, so each visit to the page loads+// the manifest again (a static asset the HTTP cache serves).+const licenseManifestAtom = Atom.make(+ Effect.gen(function* () {+ const response = yield* HttpClient.get(`${import.meta.env.BASE_URL.replace(/\/$/, "")}/third-party-licenses.json`,- { signal },);- if (!response.ok) {- throw new Error(- `The license manifest request failed with status ${String(response.status)}.`,- );- }- return decodeThirdPartyLicenseManifest((await response.json()) as unknown);- } catch (error) {- if (signal.aborted) {- throw new Error("The license manifest took too long to load.", { cause: error });+ if (response.status < 200 || response.status >= 300) {+ return yield* new LicenseManifestLoadError({+ message: `The license manifest request failed with status ${String(response.status)}.`,+ });}- throw error;- }-}--function loadLicenseManifest(): Promise<ThirdPartyLicenseManifest> {- licenseManifestPromise ??= fetchLicenseManifest().catch((error: unknown) => {- licenseManifestPromise = undefined;- throw error;- });- return licenseManifestPromise;-}+ const body = yield* response.json;+ return yield* Effect.try({+ try: () => decodeThirdPartyLicenseManifest(body),+ catch: (error) =>+ new LicenseManifestLoadError({+ message: error instanceof Error ? error.message : "The license manifest could not load.",+ }),+ });+ }).pipe(+ Effect.catchTags({+ HttpClientError: (error) =>+ Effect.fail(new LicenseManifestLoadError({ message: error.message })),+ }),+ Effect.timeoutOrElse({+ duration: "30 seconds",+ orElse: () =>+ Effect.fail(+ new LicenseManifestLoadError({ message: "The license manifest took too long to load." }),+ ),+ }),+ Effect.provide(FetchHttpClient.layer),+ ),+).pipe(Atom.withLabel("settings:open-source-licenses"));function LicenseNoticeRow({entry,@@ -211,42 +221,28 @@ function LicenseManifestError({ message, onRetry }: { message: string; onRetry:}export function OpenSourceLicensesPanel() {- const [state, setState] = useState<LicenseManifestState>({ status: "loading" });+ const result = useAtomValue(licenseManifestAtom);+ const retry = useAtomRefresh(licenseManifestAtom);const [query, setQuery] = useState("");const [searchOpen, setSearchOpen] = useState(false);const [openEntryKey, setOpenEntryKey] = useState<string | null>(null);- const loading = state.status === "loading";-- useEffect(() => {- if (!loading) return;- let cancelled = false;- void loadLicenseManifest().then(- (manifest) => {- if (!cancelled) setState({ status: "ready", manifest });- },- (error: unknown) => {- if (cancelled) return;- setState({- status: "error",- message: error instanceof Error ? error.message : "The license manifest could not load.",- });- },- );- return () => {- cancelled = true;- };- }, [loading]);-- const entries = state.status === "ready" ? state.manifest.entries : [];+ const manifest = result._tag === "Success" ? result.value : null;+ const entries = manifest?.entries ?? [];const filteredEntries = filterThirdPartyLicenseEntries(entries, query);- const retry = () => setState({ status: "loading" });+ const errorMessage =+ result._tag === "Failure" && !result.waiting+ ? Option.match(Cause.findErrorOption(result.cause), {+ onNone: () => "The license manifest could not load.",+ onSome: (error) => error.message,+ })+ : null;return (<SettingsPageContainer><SettingsSectiontitle="Third-party notices"headerAction={- state.status === "ready" ? (+ manifest ? (<LicenseHeaderActionquery={query}onQueryChange={setQuery}@@ -258,7 +254,7 @@ export function OpenSourceLicensesPanel() {) : null}>- {state.status === "ready" ? (+ {manifest ? (<div className="text-base sm:text-sm">{filteredEntries.length > 0 ? (filteredEntries.map((entry) => {@@ -278,8 +274,8 @@ export function OpenSourceLicensesPanel() {</p>)}</div>- ) : state.status === "error" ? (- <LicenseManifestError message={state.message} onRetry={retry} />+ ) : errorMessage !== null ? (+ <LicenseManifestError message={errorMessage} onRetry={retry} />) : (<p className="px-3 py-5 text-sm/6 text-muted-foreground sm:px-4">Loading open-source notices…diff --git a/apps/web/src/components/settings/ProjectIconPickerDialog.tsx b/apps/web/src/components/settings/ProjectIconPickerDialog.tsxindex a44d2a6ba23..63d76371382 100644--- a/apps/web/src/components/settings/ProjectIconPickerDialog.tsx+++ b/apps/web/src/components/settings/ProjectIconPickerDialog.tsx@@ -6,7 +6,7 @@ import {type ProjectIconColor,type ProjectIconOverride,} from "@t3tools/contracts";-import { createElement, useEffect, useRef, useState } from "react";+import { createElement, useState } from "react";import {filterProjectIconNames,firstEmoji,@@ -57,6 +57,32 @@ export function ProjectIconPickerDialog({readonly open: boolean;readonly onOpenChange: (open: boolean) => void;readonly onSelect: (icon: ProjectIconOverride) => void;+}) {+ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogPopup className="w-full sm:w-[32rem]">+ {/* The popup mounts per open, so the draft below starts from `current` each time. */}+ <ProjectIconPickerBody+ current={current}+ projectName={projectName}+ onClose={() => onOpenChange(false)}+ onSelect={onSelect}+ />+ </DialogPopup>+ </Dialog>+ );+}++function ProjectIconPickerBody({+ current,+ projectName,+ onClose,+ onSelect,+}: {+ readonly current: ProjectIconOverride | null;+ readonly projectName: string;+ readonly onClose: () => void;+ readonly onSelect: (icon: ProjectIconOverride) => void;}) {const automatic = deriveProjectIdentity(projectName);const [mode, setMode] = useState<ProjectIconOverride["kind"]>(current?.kind ?? "lucide");@@ -72,20 +98,6 @@ export function ProjectIconPickerDialog({const [emoji, setEmoji] = useState(current?.kind === "emoji" ? current.emoji : "💻");const [query, setQuery] = useState("");const [customEmoji, setCustomEmoji] = useState("");- const previousOpenRef = useRef(false);-- useEffect(() => {- if (open && !previousOpenRef.current) {- setMode(current?.kind ?? "lucide");- setIconName(current?.kind === "lucide" ? current.name : DEFAULT_ICON);- setColor(current && current.kind !== "emoji" ? current.color : automatic.color);- setLetters(current?.kind === "monogram" ? current.text : automatic.monogram);- setEmoji(current?.kind === "emoji" ? current.emoji : "💻");- setQuery("");- setCustomEmoji("");- }- previousOpenRef.current = open;- }, [current, open, automatic.color, automatic.monogram]);const icons = filterProjectIconNames(query);const selectedColorClassName = projectIconColorClassName(color);@@ -100,160 +112,158 @@ export function ProjectIconPickerDialog({? { kind: "lucide", name: iconName, color }: { kind: "emoji", emoji },);- onOpenChange(false);+ onClose();};return (- <Dialog open={open} onOpenChange={onOpenChange}>- <DialogPopup className="w-full sm:w-[32rem]">- <DialogHeader>- <DialogTitle>Choose project icon</DialogTitle>- <DialogDescription>Choose an icon, emoji, or monogram.</DialogDescription>- </DialogHeader>- <DialogPanel className="flex min-h-0 flex-col">- <ToggleGroup- aria-label="Icon type"- variant="segmented"- value={[mode]}- onValueChange={(next) => {- const value = next[0];- if (value === "lucide" || value === "emoji" || value === "monogram") setMode(value);- }}- >- <Toggle value="lucide">Icons</Toggle>- <Toggle value="emoji">Emoji</Toggle>- <Toggle value="monogram">Monogram</Toggle>- </ToggleGroup>+ <>+ <DialogHeader>+ <DialogTitle>Choose project icon</DialogTitle>+ <DialogDescription>Choose an icon, emoji, or monogram.</DialogDescription>+ </DialogHeader>+ <DialogPanel className="flex min-h-0 flex-col">+ <ToggleGroup+ aria-label="Icon type"+ variant="segmented"+ value={[mode]}+ onValueChange={(next) => {+ const value = next[0];+ if (value === "lucide" || value === "emoji" || value === "monogram") setMode(value);+ }}+ >+ <Toggle value="lucide">Icons</Toggle>+ <Toggle value="emoji">Emoji</Toggle>+ <Toggle value="monogram">Monogram</Toggle>+ </ToggleGroup>- {mode !== "emoji" ? (- <div>- <div className="mb-2 text-xs font-medium text-muted-foreground">Color</div>- <div className="flex flex-wrap gap-1.5" role="group" aria-label="Icon color">- {PROJECT_ICON_COLORS.map((option) => (+ {mode !== "emoji" ? (+ <div>+ <div className="mb-2 text-xs font-medium text-muted-foreground">Color</div>+ <div className="flex flex-wrap gap-1.5" role="group" aria-label="Icon color">+ {PROJECT_ICON_COLORS.map((option) => (+ <button+ key={option.value}+ type="button"+ aria-label={option.label}+ aria-pressed={color === option.value}+ className={cn(+ "flex size-6 items-center justify-center rounded-full border border-transparent outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",+ color === option.value && "border-foreground/64",+ )}+ onClick={() => setColor(option.value)}+ >+ <span className={cn("size-4 rounded-full", option.swatchClassName)} />+ </button>+ ))}+ </div>+ </div>+ ) : null}++ {mode === "lucide" ? (+ <>+ <Input+ type="search"+ value={query}+ aria-label="Search Lucide icons"+ placeholder="Search all Lucide icons"+ onChange={(event) => setQuery(event.currentTarget.value)}+ />+ <ScrollArea scrollFade className="max-h-64">+ <div className="grid grid-cols-8 gap-1 p-0.5 sm:grid-cols-10">+ {icons.map((name) => (<button- key={option.value}+ key={name}type="button"- aria-label={option.label}- aria-pressed={color === option.value}+ aria-label={iconLabel(name)}+ aria-pressed={iconName === name}className={cn(- "flex size-6 items-center justify-center rounded-full border border-transparent outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",- color === option.value && "border-foreground/64",+ "flex aspect-square items-center justify-center rounded-md border border-transparent outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",+ iconName === name && "border-border bg-accent",+ selectedColorClassName,)}- onClick={() => setColor(option.value)}+ onClick={() => setIconName(name)}>- <span className={cn("size-4 rounded-full", option.swatchClassName)} />+ <PickerIcon name={name} /></button>))}</div>- </div>- ) : null}-- {mode === "lucide" ? (- <>+ </ScrollArea>+ {icons.length === 0 ? (+ <p className="py-8 text-center text-sm text-muted-foreground">No icons found.</p>+ ) : null}+ </>+ ) : mode === "monogram" ? (+ <div className="flex items-center gap-4 py-2">+ <ProjectMonogram+ text={validMonogram ? monogram : automatic.monogram}+ color={color}+ className="size-12"+ />+ <div className="flex-1 space-y-2">+ <label htmlFor="project-monogram" className="text-sm font-medium">+ Letters+ </label><Input- type="search"- value={query}- aria-label="Search Lucide icons"- placeholder="Search all Lucide icons"- onChange={(event) => setQuery(event.currentTarget.value)}- />- <ScrollArea scrollFade className="max-h-64">- <div className="grid grid-cols-8 gap-1 p-0.5 sm:grid-cols-10">- {icons.map((name) => (- <button- key={name}- type="button"- aria-label={iconLabel(name)}- aria-pressed={iconName === name}- className={cn(- "flex aspect-square items-center justify-center rounded-md border border-transparent outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",- iconName === name && "border-border bg-accent",- selectedColorClassName,- )}- onClick={() => setIconName(name)}- >- <PickerIcon name={name} />- </button>- ))}- </div>- </ScrollArea>- {icons.length === 0 ? (- <p className="py-8 text-center text-sm text-muted-foreground">No icons found.</p>- ) : null}- </>- ) : mode === "monogram" ? (- <div className="flex items-center gap-4 py-2">- <ProjectMonogram- text={validMonogram ? monogram : automatic.monogram}- color={color}- className="size-12"+ id="project-monogram"+ value={letters}+ onChange={(event) => setLetters(event.currentTarget.value)}+ aria-describedby="project-monogram-hint"+ aria-invalid={!validMonogram}+ autoComplete="off"/>- <div className="flex-1 space-y-2">- <label htmlFor="project-monogram" className="text-sm font-medium">- Letters- </label>- <Input- id="project-monogram"- value={letters}- onChange={(event) => setLetters(event.currentTarget.value)}- aria-describedby="project-monogram-hint"- aria-invalid={!validMonogram}- autoComplete="off"- />- <p id="project-monogram-hint" className="text-xs text-muted-foreground">- One or two letters or numbers.- </p>- </div>+ <p id="project-monogram-hint" className="text-xs text-muted-foreground">+ One or two letters or numbers.+ </p></div>- ) : (- <>- <ScrollArea scrollFade className="max-h-64">- <div className="grid grid-cols-8 gap-1 p-0.5 sm:grid-cols-10">- {PROJECT_EMOJIS.map((option) => (- <button- key={option.emoji}- type="button"- aria-label={option.label}- aria-pressed={emoji === option.emoji}- className={cn(- "flex aspect-square items-center justify-center rounded-md border border-transparent text-xl outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",- emoji === option.emoji && "border-border bg-accent",- )}- onClick={() => setEmoji(option.emoji)}- >- {option.emoji}- </button>- ))}- </div>- </ScrollArea>- <div>- <div className="mb-2 text-xs font-medium text-muted-foreground">- Or paste any emoji- </div>- <Input- value={customEmoji}- aria-label="Custom emoji"- placeholder="Paste an emoji"- onChange={(event) => {- const value = event.currentTarget.value;- setCustomEmoji(value);- const nextEmoji = firstEmoji(value);- if (nextEmoji) setEmoji(nextEmoji);- }}- />+ </div>+ ) : (+ <>+ <ScrollArea scrollFade className="max-h-64">+ <div className="grid grid-cols-8 gap-1 p-0.5 sm:grid-cols-10">+ {PROJECT_EMOJIS.map((option) => (+ <button+ key={option.emoji}+ type="button"+ aria-label={option.label}+ aria-pressed={emoji === option.emoji}+ className={cn(+ "flex aspect-square items-center justify-center rounded-md border border-transparent text-xl outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",+ emoji === option.emoji && "border-border bg-accent",+ )}+ onClick={() => setEmoji(option.emoji)}+ >+ {option.emoji}+ </button>+ ))}</div>- </>- )}- </DialogPanel>- <DialogFooter>- <Button variant="outline" onClick={() => onOpenChange(false)}>- Cancel- </Button>- <Button onClick={save} disabled={mode === "monogram" && !validMonogram}>- Save icon- </Button>- </DialogFooter>- </DialogPopup>- </Dialog>+ </ScrollArea>+ <div>+ <div className="mb-2 text-xs font-medium text-muted-foreground">+ Or paste any emoji+ </div>+ <Input+ value={customEmoji}+ aria-label="Custom emoji"+ placeholder="Paste an emoji"+ onChange={(event) => {+ const value = event.currentTarget.value;+ setCustomEmoji(value);+ const nextEmoji = firstEmoji(value);+ if (nextEmoji) setEmoji(nextEmoji);+ }}+ />+ </div>+ </>+ )}+ </DialogPanel>+ <DialogFooter>+ <Button variant="outline" onClick={onClose}>+ Cancel+ </Button>+ <Button onClick={save} disabled={mode === "monogram" && !validMonogram}>+ Save icon+ </Button>+ </DialogFooter>+ </>);}diff --git a/apps/web/src/components/settings/ProjectSettingsPanel.tsx b/apps/web/src/components/settings/ProjectSettingsPanel.tsxindex 8d2d04f8ed7..d4095c299e6 100644--- a/apps/web/src/components/settings/ProjectSettingsPanel.tsx+++ b/apps/web/src/components/settings/ProjectSettingsPanel.tsx@@ -13,10 +13,10 @@ import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environimport { planProjectRemoval } from "@t3tools/client-runtime/state/projects";import { AsyncResult } from "effect/reactivity";import { type EnvironmentId, type ProjectIconOverride } from "@t3tools/contracts";-import { useLocation, useNavigate } from "@tanstack/react-router";+import { Navigate, useLocation, useNavigate } from "@tanstack/react-router";import * as Cause from "effect/Cause";import { InfoIcon, Trash2Icon } from "lucide-react";-import { lazy, Suspense, useEffect, useRef, useState, type ReactNode } from "react";+import { lazy, Suspense, useRef, useState, type ReactNode } from "react";import { useComposerDraftStore } from "../../composerDraftStore";import { releaseProjectDraftUploads } from "../../lib/composerDraftUploads";@@ -59,6 +59,24 @@ const ProjectIconPickerDialog = lazy(() =>export type ProjectSettingsCategory = "general" | "source-control" | "project";+interface ProjectSelection {+ readonly key: string;+ readonly environmentId: EnvironmentId | null;+ readonly checkoutKey: string | null;+ readonly memberKeys: ReadonlyArray<string>;+}++function sameProjectSelection(a: ProjectSelection | null, b: ProjectSelection): boolean {+ return (+ a !== null &&+ a.key === b.key &&+ a.environmentId === b.environmentId &&+ a.checkoutKey === b.checkoutKey &&+ a.memberKeys.length === b.memberKeys.length &&+ a.memberKeys.every((key, index) => key === b.memberKeys[index])+ );+}+export function ProjectSettingsPanel({projectKey,environmentId = null,@@ -71,7 +89,6 @@ export function ProjectSettingsPanel({unavailable?: ReactNode;}) {const groups = useSettingsProjectGroups();- const navigate = useNavigate({ from: "/settings" });const pathname = useLocation({ select: (location) => location.pathname });const selected = groups.find((group) => group.projectKey === projectKey) ?? null;@@ -83,47 +100,42 @@ export function ProjectSettingsPanel({) ?? [];// Retain group members so grouping-rule changes can follow the project to its new group.- const lastSelectionRef = useRef<{- key: string;- environmentId: EnvironmentId | null;- checkoutKey: string | null;- memberKeys: string[];- } | null>(null);- useEffect(() => {- if (!selected || members.length === 0) return;- lastSelectionRef.current = {+ const [lastSelection, setLastSelection] = useState<ProjectSelection | null>(null);+ if (selected && members.length > 0) {+ const current: ProjectSelection = {key: selected.projectKey,environmentId,checkoutKey,memberKeys: members.map((member) => member.physicalProjectKey),};- }, [selected, members, environmentId, checkoutKey]);+ if (!sameProjectSelection(lastSelection, current)) setLastSelection(current);+ }- useEffect(() => {- if (members.length > 0) return;- const last = lastSelectionRef.current;- if (- last?.key !== projectKey ||- last.environmentId !== environmentId ||- last.checkoutKey !== checkoutKey- )- return;- const successor = groups.find((group) =>- group.memberProjects.some((member) => last.memberKeys.includes(member.physicalProjectKey)),- );- if (successor) {- void navigate({- to: pathname,- search: () => ({+ const successor =+ members.length === 0 &&+ lastSelection?.key === projectKey &&+ lastSelection.environmentId === environmentId &&+ lastSelection.checkoutKey === checkoutKey+ ? groups.find((group) =>+ group.memberProjects.some((member) =>+ lastSelection.memberKeys.includes(member.physicalProjectKey),+ ),+ )+ : undefined;+ if (successor) {+ return (+ <Navigate+ to={pathname}+ search={{project: successor.projectKey,machine: environmentId ?? undefined,checkout: checkoutKey ?? undefined,- }),- replace: true,- hashScrollIntoView: false,- });- }- }, [groups, navigate, pathname, projectKey, members.length, environmentId, checkoutKey]);+ }}+ replace+ hashScrollIntoView={false}+ />+ );+ }if ((!selected || members.length === 0) && unavailable != null) return unavailable;diff --git a/apps/web/src/components/settings/ResourceTelemetryDiagnostics.tsx b/apps/web/src/components/settings/ResourceTelemetryDiagnostics.tsxindex e7d885eab1c..def847d8d6b 100644--- a/apps/web/src/components/settings/ResourceTelemetryDiagnostics.tsx+++ b/apps/web/src/components/settings/ResourceTelemetryDiagnostics.tsx@@ -28,7 +28,8 @@ import type {} from "@t3tools/contracts";import * as DateTime from "effect/DateTime";import * as Option from "effect/Option";-import { useEffect, useRef, useState, type ReactNode } from "react";+import { RegistryContext } from "@effect/atom-react";+import { useContext, useRef, useState, type ReactNode } from "react";import {isAtomCommandInterrupted,squashAtomCommandFailure,@@ -809,6 +810,18 @@ export function ResourceTelemetryDiagnostics({}: {environmentId: EnvironmentId | null;}) {+ // Pending signals and retries belong to one environment, so a switch starts fresh.+ return (+ <ResourceTelemetryDiagnosticsBody key={environmentId ?? ""} environmentId={environmentId} />+ );+}++function ResourceTelemetryDiagnosticsBody({+ environmentId,+}: {+ environmentId: EnvironmentId | null;+}) {+ const registry = useContext(RegistryContext);const [windowMs, setWindowMs] = useState(15 * 60_000);const selectedWindow =HISTORY_WINDOWS.find((option) => option.windowMs === windowMs) ?? HISTORY_WINDOWS[1];@@ -822,29 +835,17 @@ export function ResourceTelemetryDiagnostics({},environmentId,);- const refreshHistory = history.refresh;- const selectedHistoryRef = useRef({ environmentId, windowMs, refreshHistory });- useEffect(() => {- selectedHistoryRef.current = { environmentId, windowMs, refreshHistory };- }, [environmentId, windowMs, refreshHistory]);const signalServerProcess = useAtomCommand(serverEnvironment.signalProcess, {reportFailure: false,});const [signalingKeys, setSignalingKeys] = useState<ReadonlySet<string>>(() => new Set());const signalingKeysRef = useRef<ReadonlySet<string>>(new Set());- const environmentIdRef = useRef(environmentId);- useEffect(() => {- environmentIdRef.current = environmentId;- return () => {- environmentIdRef.current = null;- };- }, [environmentId]);const [isRetrying, setIsRetrying] = useState(false);const snapshot = telemetry.data;const allT3 = snapshot?.groups.allT3;const signalProcess = async (process: ResourceTelemetryProcess, signal: ServerProcessSignal) => {- const targetEnvironmentId = environmentIdRef.current;+ const targetEnvironmentId = environmentId;if (targetEnvironmentId === null ||!readEnvironmentScope(targetEnvironmentId, AuthEnvironmentMaintainScope)@@ -883,10 +884,7 @@ export function ResourceTelemetryDiagnostics({return;}}- if (- environmentIdRef.current !== targetEnvironmentId ||- !readEnvironmentScope(targetEnvironmentId, AuthEnvironmentMaintainScope)- ) {+ if (!readEnvironmentScope(targetEnvironmentId, AuthEnvironmentMaintainScope)) {clearSignaling();return;}@@ -926,7 +924,6 @@ export function ResourceTelemetryDiagnostics({};const retryCollector = () => {- const environmentId = environmentIdRef.current;if (environmentId === null ||!readEnvironmentScope(environmentId, AuthEnvironmentMaintainScope)@@ -935,14 +932,15 @@ export function ResourceTelemetryDiagnostics({setIsRetrying(true);void retryTelemetry().then(() => {- refreshHistory();- const selectedHistory = selectedHistoryRef.current;- if (- environmentIdRef.current === environmentId &&- selectedHistory.environmentId === environmentId &&- selectedHistory.windowMs !== windowMs- ) {- selectedHistory.refreshHistory();+ // The user can pick another window while the retry runs; refreshing every window+ // re-reads the one on screen and only invalidates the rest.+ for (const option of HISTORY_WINDOWS) {+ registry.refresh(+ serverEnvironment.resourceTelemetryHistory({+ environmentId,+ input: { windowMs: option.windowMs, bucketMs: option.bucketMs },+ }),+ );}}).catch((error: unknown) => {diff --git a/apps/web/src/components/settings/ScheduledTasksSettings.browser.test.tsx b/apps/web/src/components/settings/ScheduledTasksSettings.browser.test.tsxnew file mode 100644index 00000000000..e42242f0109--- /dev/null+++ b/apps/web/src/components/settings/ScheduledTasksSettings.browser.test.tsx@@ -0,0 +1,141 @@+import {+ DEFAULT_UNIFIED_SETTINGS,+ EnvironmentId,+ ProjectId,+ ProviderInstanceId,+ ScheduledTaskId,+ type ScheduledTask,+} from "@t3tools/contracts";+import { describe, expect, it, vi } from "vite-plus/test";+import { page, userEvent } from "vite-plus/test/browser";++import "~/index.css";+import { render } from "../../../test/render";+import { ScheduledTasksSettings } from "./ScheduledTasksSettings";++const environmentId = EnvironmentId.make("laptop");+const projectId = ProjectId.make("project");+const task: ScheduledTask = {+ id: ScheduledTaskId.make("nightly"),+ title: "Review issues",+ prompt: "Review open issues",+ enabled: true,+ schedule: { type: "interval", everyMs: 60_000 },+ projectId,+ threadId: null,+ workspaceStrategy: { type: "root" },+ modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },+ runtimeMode: "full-access",+ interactionMode: "default",+ createdBy: "user",+ creationSource: "web",+ createdAt: "2026-09-17T00:00:00.000Z",+ updatedAt: "2026-09-17T00:00:00.000Z",+ nextRunAt: null,+ lastRunAt: null,+ lastRunStatus: "never",+ lastRunError: null,+ runCount: 0,+};++const state = vi.hoisted(() => ({ connected: true, tasksLoaded: true }));++function environment() {+ return {+ environmentId,+ label: "Laptop",+ connection: { phase: state.connected ? "connected" : "disconnected" },+ serverConfig: state.connected ? { environment: { platform: "linux" } } : null,+ };+}++vi.mock(import("./SettingsScopeContext"), async (original) => {+ const scope = () => {+ const entry = environment();+ return {+ scope: { kind: "all", label: "All", members: [], environmentIds: [environmentId] },+ environments: [entry],+ connectedEnvironments: state.connected ? [entry] : [],+ environment: entry,+ target: null,+ targets: [],+ };+ };+ return {+ ...(await original()),+ useSettingsScope: scope as never,+ };+});+vi.mock(import("../../state/server"), async (original) => {+ const actual = await original();+ const { Atom } = await import("effect/reactivity");+ const allowed = Atom.make(true);+ return {+ ...actual,+ serverEnvironment: {+ ...actual.serverEnvironment,+ upsertScheduledTask: {+ ...actual.serverEnvironment.upsertScheduledTask,+ permissionAtom: () => allowed,+ },+ },+ };+});+// Mirrors the real query: a null request (disconnected environment) has no data.+vi.mock(import("../../state/query"), async (original) => ({+ ...(await original()),+ useEnvironmentQuery: ((request: unknown) => ({+ data: request === null ? null : { tasks: state.tasksLoaded ? [task] : [] },+ error: null,+ isPending: false,+ refresh: vi.fn(),+ })) as never,+}));+vi.mock(import("../../state/environments"), async (original) => ({+ ...(await original()),+ useEnvironment: (() => environment()) as never,+}));+vi.mock(import("../../state/entities"), async (original) => ({+ ...(await original()),+ useProjects: (() => [{ id: projectId, environmentId, title: "Project" }]) as never,+}));+vi.mock(import("../../hooks/useSettings"), async (original) => ({+ ...(await original()),+ useEnvironmentSettings: (() => DEFAULT_UNIFIED_SETTINGS) as never,+}));++describe("ScheduledTasksSettings", () => {+ it("keeps a linked task's unsaved edits across a disconnect and reconnect", async () => {+ state.connected = true;+ state.tasksLoaded = true;+ await using screen = await render(<ScheduledTasksSettings taskId={task.id} />);+ const name = page.getByRole("dialog").getByRole("textbox", { name: "Name" });+ await expect.element(name).toHaveValue("Review issues");+ await userEvent.fill(name, "Review stale issues");++ state.connected = false;+ await screen.rerender(<ScheduledTasksSettings taskId={task.id} />);++ await expect.element(name).toHaveValue("Review stale issues");++ state.connected = true;+ await screen.rerender(<ScheduledTasksSettings taskId={task.id} />);+ await expect.element(name).toHaveValue("Review stale issues");+ });++ it("keeps an editor the user opened when the linked task loads later", async () => {+ state.connected = true;+ state.tasksLoaded = false;+ await using screen = await render(<ScheduledTasksSettings taskId={task.id} />);+ await userEvent.click(page.getByRole("button", { name: "New task" }));+ const dialog = page.getByRole("dialog");+ const name = dialog.getByRole("textbox", { name: "Name" });+ await userEvent.fill(name, "My draft");++ state.tasksLoaded = true;+ await screen.rerender(<ScheduledTasksSettings taskId={task.id} />);++ await expect.element(dialog.getByRole("heading", { name: "New task" })).toBeInTheDocument();+ await expect.element(name).toHaveValue("My draft");+ });+});diff --git a/apps/web/src/components/settings/ScheduledTasksSettings.tsx b/apps/web/src/components/settings/ScheduledTasksSettings.tsxindex ee5c8220dbb..3b842367ab4 100644--- a/apps/web/src/components/settings/ScheduledTasksSettings.tsx+++ b/apps/web/src/components/settings/ScheduledTasksSettings.tsx@@ -12,7 +12,7 @@ import {PlusIcon,Trash2Icon,} from "lucide-react";-import { type ReactNode, useEffect, useRef, useState } from "react";+import { type ReactNode, useRef, useState } from "react";import type {EnvironmentId,ModelSelection,@@ -56,7 +56,7 @@ import {import { usePrimaryCloudLinkState } from "../../cloud/primaryCloudLinkState";import { requestConfirmDialog } from "../../confirmDialog";import { webhookAddress } from "@t3tools/client-runtime/webhook-address";-import { Link } from "@tanstack/react-router";+import { Link, useNavigate } from "@tanstack/react-router";import { useCopyToClipboard } from "../../hooks/useCopyToClipboard";import { useNowMinute } from "../../hooks/useNowMinute";import {@@ -362,6 +362,45 @@ export function ScheduledTasksSettings(target: {setEditor({ environmentId, task });};const defaultEnvironment = environment ?? connectedEnvironments[0];+ const linkedEnvironmentId = target.environmentId ?? defaultEnvironment?.environmentId;+ const linkedEnvironmentConnected = environments.some(+ (entry) =>+ entry.environmentId === linkedEnvironmentId &&+ entry.connection.phase === "connected" &&+ entry.serverConfig !== null,+ );+ const linkedTasksQuery = useEnvironmentQuery(+ target.taskId !== undefined && linkedEnvironmentId !== undefined && linkedEnvironmentConnected+ ? serverEnvironment.scheduledTasksLive({ environmentId: linkedEnvironmentId, input: {} })+ : null,+ );+ const linkedTask = linkedTasksQuery.data?.tasks.find(+ (task) =>+ task.id === target.taskId &&+ linkedEnvironmentId !== undefined &&+ matchesScheduledTaskScope(scope, linkedEnvironmentId, task.projectId),+ );+ // A `taskId` link opens its editor once, the first time the task loads. The editor then owns+ // the session until close, so a disconnect that disables the query cannot drop unsaved edits.+ // An editor the user already opened wins: a late-loading link must not replace its draft.+ const [openedLinkTaskId, setOpenedLinkTaskId] = useState<ScheduledTaskId | undefined>();+ if (target.taskId === undefined && openedLinkTaskId !== undefined) {+ setOpenedLinkTaskId(undefined);+ }+ if (linkedTask && linkedEnvironmentId !== undefined && openedLinkTaskId !== target.taskId) {+ setOpenedLinkTaskId(target.taskId);+ if (editor === null) setEditor({ environmentId: linkedEnvironmentId, task: linkedTask });+ }+ const navigate = useNavigate({ from: "/settings/scheduled-tasks" });+ const closeEditor = () => {+ setEditor(null);+ if (target.taskId === undefined) return;+ void navigate({+ to: "/settings/scheduled-tasks",+ search: ({ taskId: _closed, ...rest }) => rest,+ replace: true,+ });+ };const canCreate = useAtomValue(serverEnvironment.upsertScheduledTask.permissionAtom(defaultEnvironment?.environmentId ?? null),);@@ -401,8 +440,7 @@ export function ScheduledTasksSettings(target: {</Empty>) : environments.length > 1 ? (<ScheduledTaskEnvironmentList- key={`${target.environmentId ?? defaultEnvironment?.environmentId}:${target.taskId ?? ""}`}- environmentId={target.environmentId ?? defaultEnvironment?.environmentId}+ environmentId={linkedEnvironmentId}taskId={target.taskId}onEdit={openForEdit}/>@@ -410,15 +448,10 @@ export function ScheduledTasksSettings(target: {<div className="space-y-8">{environments.map((entry) => (<ScheduledTaskEnvironmentSection- key={`${entry.environmentId}:${target.taskId ?? ""}`}+ key={entry.environmentId}environment={entry}showEnvironmentHeading={environments.length > 1}- taskId={- (target.environmentId ?? defaultEnvironment?.environmentId) ===- entry.environmentId- ? target.taskId- : undefined- }+ taskId={linkedEnvironmentId === entry.environmentId ? target.taskId : undefined}onEdit={openForEdit}/>))}@@ -430,7 +463,7 @@ export function ScheduledTasksSettings(target: {key={`${editor.environmentId}:${editor.task?.id ?? "new"}`}initialEnvironmentId={editor.environmentId}task={editor.task}- onClose={() => setEditor(null)}+ onClose={closeEditor}/>) : null}</SettingsPageContainer>@@ -472,13 +505,6 @@ function ScheduledTaskEnvironmentList({});const linkedState = states.find((state) => state.environment.environmentId === environmentId);const linkedTask = linkedState?.tasks?.find((task) => task.id === taskId);- const openedLink = useRef(false);- useEffect(() => {- if (!openedLink.current && environmentId && linkedTask) {- openedLink.current = true;- onEdit(environmentId, linkedTask);- }- }, [environmentId, linkedTask, onEdit]);const loaded = states.filter((state) => state.connected && state.error === null && state.tasks);const populated = loaded.filter((state) => state.tasks && state.tasks.length > 0);@@ -603,13 +629,6 @@ function ScheduledTaskEnvironmentSection({matchesScheduledTaskScope(scope, environment.environmentId, task.projectId),);const linkedTask = tasks?.find((task) => task.id === taskId);- const openedLink = useRef(false);- useEffect(() => {- if (!openedLink.current && linkedTask) {- openedLink.current = true;- onEdit(environment.environmentId, linkedTask);- }- }, [environment.environmentId, linkedTask, onEdit]);return (<SettingsSectiontitle={environment.label}diff --git a/apps/web/src/components/settings/SnapShotSettings.tsx b/apps/web/src/components/settings/SnapShotSettings.tsxindex a911383deb6..1a1dd127abc 100644--- a/apps/web/src/components/settings/SnapShotSettings.tsx+++ b/apps/web/src/components/settings/SnapShotSettings.tsx@@ -1,27 +1,32 @@-import { useAtomValue } from "@effect/atom-react";+import { RegistryContext, useAtomValue } from "@effect/atom-react";import {isModifierPairShortcut,type ClientSettingsPatch,type DesktopSnapShotShortcutAvailability,- type DesktopSnapShotState,type DesktopSnapShotSetupAction,type SnapShotShortcut,} from "@t3tools/contracts";import { PlayIcon } from "lucide-react";import { settlePromise } from "@t3tools/client-runtime/state/runtime";import * as Cause from "effect/Cause";-import { useEffect, useRef, useState } from "react";+import { useContext, useRef, useState } from "react";-import { useStableCallback } from "../../hooks/useStableCallback";import { useClientSettings, updateClientSettings } from "../../hooks/useSettings";import { getDesktopSnapShotBridge } from "../../lib/desktopSnapShot";import {- readSnapShotSetupResume,saveSnapShotSetupResume,clearSnapShotSetupResume,+ readSnapShotSetupResume,} from "../../lib/snapShotSetupResume";import { sameSnapShotShortcut, snapShotKeybindingConflict } from "../../lib/snapShotShortcut";import { playSnapShotSound } from "../../lib/snapShotSound";+import {+ desktopSnapShotAtom,+ refreshDesktopSnapShotState,+ snapShotSetupError,+ type SnapShotSetupError,+} from "../../state/desktopSnapShot";+import { toastManager } from "../ui/toast";import { primaryServerKeybindingsAtom } from "../../state/server";import { commandLabel } from "./KeybindingsSettings.logic";import {@@ -47,7 +52,6 @@ import { Button } from "../ui/button";import { Menu, MenuItem, MenuPopup, MenuRadioGroup, MenuRadioItem, MenuTrigger } from "../ui/menu";import { SelectButton } from "../ui/select";import { Switch } from "../ui/switch";-import { toastManager } from "../ui/toast";import { SnapShotSetupDialog } from "./SnapShotSetupDialog";import { useSnapShotShortcutRecorder } from "./useSnapShotShortcutRecorder";import {@@ -59,20 +63,18 @@ import {const soundOptionRowClassName = "grid grid-cols-[1fr_auto]";-function captureSettingsError(title: string, error: unknown) {- return { title, message: error instanceof Error ? error.message : "Try again." };-}-type ShortcutCheck =| { readonly status: "idle"; readonly availability: null }| {readonly status: "checking";readonly availability: null;readonly shortcut: SnapShotShortcut;+ readonly savedShortcut: SnapShotShortcut;}| {readonly status: "checked";readonly shortcut: SnapShotShortcut;+ readonly savedShortcut: SnapShotShortcut;readonly availability: DesktopSnapShotShortcutAvailability;};@@ -88,31 +90,53 @@ export function SnapShotSettings() {}));const keybindings = useAtomValue(primaryServerKeybindingsAtom);const bridge = getDesktopSnapShotBridge();- const [state, setState] = useState<DesktopSnapShotState | null>(null);+ const registry = useContext(RegistryContext);+ const { state, refreshError } = useAtomValue(desktopSnapShotAtom);const [setupBusy, setSetupBusy] = useState(false);- const [setupError, setSetupError] = useState<ReturnType<typeof captureSettingsError> | null>(- null,- );- const [wizard, setWizard] = useState<{+ const [setupError, setSetupError] = useState<SnapShotSetupError | null>(null);+ // macOS can quit the app from a permission prompt; until the user opens or closes the wizard+ // themselves, a saved resume reopens it where it left off.+ const [resume] = useState(readSnapShotSetupResume);+ const [chosenWizard, setWizard] = useState<{initialStep: CaptureSetupStep;wasEnabled: boolean;- } | null>(null);+ } | null>();+ const wizard =+ chosenWizard !== undefined+ ? chosenWizard+ : state?.macPermissions && resume+ ? { initialStep: "access" as const, wasEnabled: resume.wasEnabled }+ : null;+ // The wizard shows errors inline; outside it there is nowhere to, so they become a toast.+ const reportSetupError = (title: string, error: unknown) => {+ const report = snapShotSetupError(title, error);+ setSetupError(report);+ if (!wizard)+ toastManager.add({ type: "error", title: report.title, description: report.message });+ };+ const refreshState = () =>+ refreshDesktopSnapShotState(registry, (error) =>+ reportSetupError("Couldn't check capture setup", error),+ );const [candidate, setCandidate] = useState<SnapShotShortcut>(settings.snapShotShortcut);const [latestShortcutCheck, setShortcutCheck] = useState<ShortcutCheck>({status: "idle",availability: null,});+ // A check answers for one candidate against one saved shortcut. Once either moves on (an edit,+ // or hydration saving a new shortcut) a late answer no longer shows, so a check for the+ // shortcut that just got saved can't claim it is ready to save.+ const savedShortcut = settings.snapShotShortcut;const shortcutCheck: ShortcutCheck =latestShortcutCheck.status === "idle" ||- sameSnapShotShortcut(latestShortcutCheck.shortcut, candidate)+ (sameSnapShotShortcut(latestShortcutCheck.shortcut, candidate) &&+ sameSnapShotShortcut(latestShortcutCheck.savedShortcut, savedShortcut))? latestShortcutCheck: { status: "idle", availability: null };const shortcutCheckIdRef = useRef(0);- const stateRequestIdRef = useRef(0);const unavailableMessage = snapShotUnavailableMessage(Boolean(bridge));const captureAvailable = Boolean(bridge) && state !== null && state.mode !== "unavailable";const feedbackUnavailable = snapShotFeedbackUnavailableMessage(state);- const savedShortcut = settings.snapShotShortcut;const managedShortcut = state?.linuxBackend === "niri" || state?.linuxBackend === "hyprland";const shortcutChanged = !managedShortcut && !sameSnapShotShortcut(candidate, savedShortcut);const displayShortcut = shortcutChanged ? candidate : (state?.shortcut ?? savedShortcut);@@ -125,20 +149,6 @@ export function SnapShotSettings() {const soundLabel =soundSelection === "off" ? "Off" : soundSelection === "soft-pop" ? "Whoosh (Default)" : "Click";- const refreshState = useStableCallback(async () => {- const requestId = ++stateRequestIdRef.current;- try {- if (bridge) {- const nextState = await bridge.getSnapShotState();- if (requestId === stateRequestIdRef.current) setState(nextState);- return nextState;- }- } catch (error) {- if (requestId === stateRequestIdRef.current)- setSetupError(captureSettingsError("Couldn't check capture setup", error));- }- });-const setup = async (action: DesktopSnapShotSetupAction) => {if (!bridge?.setupSnapShot || setupBusy) return;setSetupBusy(true);@@ -156,52 +166,16 @@ export function SnapShotSettings() {await refreshState();});if (result._tag === "Failure") {- setSetupError(- captureSettingsError(- action === "retry-shortcut"- ? "Couldn't open shortcut permissions"- : "Couldn't complete capture setup",- Cause.squash(result.cause),- ),+ reportSetupError(+ action === "retry-shortcut"+ ? "Couldn't open shortcut permissions"+ : "Couldn't complete capture setup",+ Cause.squash(result.cause),);}setSetupBusy(false);};- const toastedErrorRef = useRef<typeof setupError>(null);- useEffect(() => {- if (!setupError || wizard || toastedErrorRef.current === setupError) return;- toastedErrorRef.current = setupError;- toastManager.add({- type: "error",- title: setupError.title,- description: setupError.message,- });- }, [setupError, wizard]);-- useEffect(() => {- let cancelled = false;- void refreshState().then((current) => {- const resume = readSnapShotSetupResume();- if (!cancelled && current?.macPermissions && resume) {- setWizard({ initialStep: "access", wasEnabled: resume.wasEnabled });- }- });- window.addEventListener("focus", refreshState);- return () => {- cancelled = true;- window.removeEventListener("focus", refreshState);- };- }, [refreshState]);-- useEffect(- () =>- bridge?.onSnapShotEvent((event) => {- if (event.type === "shortcut-changed") void refreshState();- }),- [bridge, refreshState],- );-// Hydration can hand back an equal shortcut object; only a different shortcut resets the edit.const [renderedSavedShortcut, setRenderedSavedShortcut] = useState(savedShortcut);if (!sameSnapShotShortcut(renderedSavedShortcut, savedShortcut)) {@@ -209,12 +183,6 @@ export function SnapShotSettings() {setCandidate(savedShortcut);setShortcutCheck({ status: "idle", availability: null });}- const checkedForSavedShortcutRef = useRef(savedShortcut);- useEffect(() => {- if (sameSnapShotShortcut(checkedForSavedShortcutRef.current, savedShortcut)) return;- checkedForSavedShortcutRef.current = savedShortcut;- shortcutCheckIdRef.current++;- }, [savedShortcut]);const save = async (patch: ClientSettingsPatch) => {setSetupError(null);@@ -222,7 +190,7 @@ export function SnapShotSettings() {await updateClientSettings(patch);return await refreshState();} catch (error) {- setSetupError(captureSettingsError("Couldn't save capture settings", error));+ reportSetupError("Couldn't save capture settings", error);}};@@ -232,7 +200,7 @@ export function SnapShotSettings() {await bridge?.requestSnapShotPermissions(true);await save({ snapShotIncludeAccessibility: includeAccessibility });} catch (error) {- setSetupError(captureSettingsError("Couldn't allow app text capture", error));+ reportSetupError("Couldn't allow app text capture", error);}};@@ -241,17 +209,18 @@ export function SnapShotSettings() {setCandidate(shortcut);const conflict = snapShotKeybindingConflict(shortcut, keybindings);if (conflict || !bridge) return;- setShortcutCheck({ status: "checking", availability: null, shortcut });+ setShortcutCheck({ status: "checking", availability: null, shortcut, savedShortcut });try {const availability = await bridge.checkSnapShotShortcut(shortcut);if (checkId === shortcutCheckIdRef.current) {- setShortcutCheck({ status: "checked", availability, shortcut });+ setShortcutCheck({ status: "checked", availability, shortcut, savedShortcut });}} catch (error) {if (checkId !== shortcutCheckIdRef.current) return;setShortcutCheck({status: "checked",shortcut,+ savedShortcut,availability: {available: false,message: error instanceof Error ? error.message : "Could not check this shortcut.",@@ -278,6 +247,7 @@ export function SnapShotSettings() {setShortcutCheck({status: "checked",shortcut: candidate,+ savedShortcut,availability: { available: false, message },}),});@@ -347,9 +317,7 @@ export function SnapShotSettings() {});setSetupBusy(false);if (verified._tag === "Success") return verified.value;- setSetupError(- captureSettingsError("Couldn't verify capture access", Cause.squash(verified.cause)),- );+ reportSetupError("Couldn't verify capture access", Cause.squash(verified.cause));return false;};@@ -369,9 +337,7 @@ export function SnapShotSettings() {setWizard(null);});if (closed._tag === "Failure") {- setSetupError(- captureSettingsError("Couldn't close capture setup", Cause.squash(closed.cause)),- );+ reportSetupError("Couldn't close capture setup", Cause.squash(closed.cause));}setSetupBusy(false);};@@ -394,7 +360,9 @@ export function SnapShotSettings() {bridge? setupBusy && !wizard? "Updating capture settings…"- : snapShotStatus(state, settings.snapShotEnabled)+ : refreshError+ ? `${refreshError.title}. ${refreshError.message}`+ : snapShotStatus(state, settings.snapShotEnabled): undefined}control={@@ -600,7 +568,7 @@ export function SnapShotSettings() {wasEnabled={wizard.wasEnabled}includeAccessibility={settings.snapShotIncludeAccessibility}busy={setupBusy}- error={setupError?.message ?? null}+ error={(setupError ?? refreshError)?.message ?? null}shortcutInput={shortcutInput}shortcutStatus={shortcutStatus}shortcutChanged={shortcutChanged}diff --git a/apps/web/src/components/settings/StorageSettings.tsx b/apps/web/src/components/settings/StorageSettings.tsxindex f59f5a87202..722285a532a 100644--- a/apps/web/src/components/settings/StorageSettings.tsx+++ b/apps/web/src/components/settings/StorageSettings.tsx@@ -15,6 +15,7 @@ import { environmentAtomList, environmentIdsKey } from "../../state/environmentAimport { serverEnvironment } from "../../state/server";import { useAtomCommand } from "../../state/use-atom-command";import { formatRelativeTimeLabel } from "../../timestampFormat";+import { useNowMinute } from "../../hooks/useNowMinute";import { Button } from "../ui/button";import { toastManager } from "../ui/toast";@@ -33,7 +34,6 @@ import {SettingsPageContainer,SettingsRow,SettingsSection,- useRelativeTimeTick,} from "./settingsLayout";import { DatabaseStorageNotice } from "./DatabaseStorageNotice";import { SettingsScopeNotice } from "./SettingsScopeNotice";@@ -279,7 +279,8 @@ const storageCleanupPermissionsAtom = environmentAtomList();function CleanupSection() {- useRelativeTimeTick(60_000);+ const nowMinute = useNowMinute();+ const nowMs = Date.parse(`${nowMinute}:00.000Z`);const { connectedEnvironments } = useSettingsScope();const [pending, setPending] = useState(false);const run = useAtomCommand(serverEnvironment.runStorageCleanup);@@ -330,7 +331,7 @@ function CleanupSection() {? `${report.counts.removed} removed, ${report.counts.kept} kept${report.counts.failed > 0 ? `, ${report.counts.failed} failed` : ""}`: "",description: report- ? `Last run ${formatRelativeTimeLabel(report.finishedAt)}. ${formatBytes(report.bytesFreed)} recovered.${report.counts.failed > 0 ? ` ${report.counts.failed} ${report.counts.failed === 1 ? "item" : "items"} couldn't be removed.` : ""}`+ ? `Last run ${formatRelativeTimeLabel(report.finishedAt, nowMs)}. ${formatBytes(report.bytesFreed)} recovered.${report.counts.failed > 0 ? ` ${report.counts.failed} ${report.counts.failed === 1 ? "item" : "items"} couldn't be removed.` : ""}`: query?.failed? "Could not load the last run.": query?.loadingdiff --git a/apps/web/src/components/settings/settingsLayout.tsx b/apps/web/src/components/settings/settingsLayout.tsxindex edf723f37e4..816e0e48763 100644--- a/apps/web/src/components/settings/settingsLayout.tsx+++ b/apps/web/src/components/settings/settingsLayout.tsx@@ -6,14 +6,7 @@ import { InfoIcon, Undo2Icon } from "lucide-react";import { DEFAULT_SERVER_SETTINGS, type ServerSettings } from "@t3tools/contracts";import * as Equal from "effect/Equal";import { useLocation, useNavigate } from "@tanstack/react-router";-import {- createContext,- type ComponentPropsWithoutRef,- type ReactNode,- useContext,- useEffect,- useState,-} from "react";+import { createContext, type ComponentPropsWithoutRef, type ReactNode, useContext } from "react";import {PRIMARY_SETTINGS_UNAVAILABLE_MESSAGE,@@ -203,15 +196,6 @@ export function PolicyTooltip({ children }: { readonly children: string }) {);}-export function useRelativeTimeTick(intervalMs = 1_000) {- const [nowMs, setNowMs] = useState(() => Date.now());- useEffect(() => {- const id = setInterval(() => setNowMs(Date.now()), intervalMs);- return () => clearInterval(id);- }, [intervalMs]);- return nowMs;-}-export function SettingsSection({title,hideTitle = false,diff --git a/apps/web/src/state/desktopSnapShot.ts b/apps/web/src/state/desktopSnapShot.tsnew file mode 100644index 00000000000..4c956a496f7--- /dev/null+++ b/apps/web/src/state/desktopSnapShot.ts@@ -0,0 +1,80 @@+import type { DesktopSnapShotState } from "@t3tools/contracts";+import * as Option from "effect/Option";+import { Atom, type AtomRegistry } from "effect/reactivity";++import { getDesktopSnapShotBridge } from "../lib/desktopSnapShot";++export interface SnapShotSetupError {+ readonly title: string;+ readonly message: string;+}++export function snapShotSetupError(title: string, error: unknown): SnapShotSetupError {+ return { title, message: error instanceof Error ? error.message : "Try again." };+}++export interface DesktopSnapShotLoad {+ readonly state: DesktopSnapShotState | null;+ /** Why the last background read (load, focus, shortcut change) failed; a later success clears it. */+ readonly refreshError: SnapShotSetupError | null;+}++const EMPTY_LOAD: DesktopSnapShotLoad = { state: null, refreshError: null };++// Only the newest read lands, so a slow answer cannot regress the state. Dropping the atom bumps+// it too, so a read that was in flight when the page closed does not seed the next visit.+let stateRequestId = 0;++/**+ * The desktop capture state. Reading it starts a load, then re-reads on window focus (the user+ * may have changed OS permissions) and when the desktop reports a shortcut change.+ */+export const desktopSnapShotAtom = Atom.writable(+ (get): DesktopSnapShotLoad => {+ get.addFinalizer(() => {+ stateRequestId++;+ });+ const bridge = getDesktopSnapShotBridge();+ if (!bridge) return EMPTY_LOAD;+ const refresh = () =>+ void refreshDesktopSnapShotState(get.registry, (error) => {+ get.setSelf({+ ...Option.getOrElse(get.self<DesktopSnapShotLoad>(), () => EMPTY_LOAD),+ refreshError: snapShotSetupError("Couldn't check capture setup", error),+ });+ });+ window.addEventListener("focus", refresh);+ get.addFinalizer(() => window.removeEventListener("focus", refresh));+ get.addFinalizer(+ bridge.onSnapShotEvent((event) => {+ if (event.type === "shortcut-changed") refresh();+ }),+ );+ refresh();+ return EMPTY_LOAD;+ },+ (ctx, value: DesktopSnapShotLoad) => ctx.setSelf(value),+).pipe(Atom.withLabel("desktop:snap-shot:state"));++/**+ * Reads the capture state now and stores it. `onError` hears only a failure of the newest read;+ * the result is `undefined` whenever this read did not produce the current state.+ */+export async function refreshDesktopSnapShotState(+ registry: AtomRegistry.AtomRegistry,+ onError: (error: unknown) => void,+): Promise<DesktopSnapShotState | undefined> {+ const bridge = getDesktopSnapShotBridge();+ if (!bridge) return undefined;+ const requestId = ++stateRequestId;+ try {+ const next = await bridge.getSnapShotState();+ if (requestId === stateRequestId) {+ registry.set(desktopSnapShotAtom, { state: next, refreshError: null });+ }+ return next;+ } catch (error) {+ if (requestId === stateRequestId) onError(error);+ return undefined;+ }+}