The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 22, 17:00 UTC
fix(web): settings panels derive state instead of syncing it with effects (#25070)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 25, 2026 at 18:13 UTC
e14d08c664f9e6fcfdac94c7dc8451f4a5e98da2
12 files changed
+640
-446
apps/web/src/components/settings/AuthorizedClientsSettings.tsx
+3
-3
@@ -26,7 +26,7 @@ import {
26
selectQrEndpointOption,
27
togglePairingScopeSelection,
28
} from "./ConnectionsSettings.logic";
29
-import { useRelativeTimeTick } from "./settingsLayout";
29
+import { useNowSecond } from "../../hooks/useNowSecond";
30
import { Input } from "../ui/input";
31
import { Checkbox } from "../ui/checkbox";
32
import {
@@ -152,7 +152,7 @@ const PairingLinkListRow = memo(function PairingLinkListRow({
152
onRevoke,
153
canRevoke,
154
}: PairingLinkListRowProps) {
155
- const nowMs = useRelativeTimeTick(1_000);
155
+ const nowMs = useNowSecond();
156
const expiresAtMs = new Date(pairingLink.expiresAt).getTime();
157
const [isRevealDialogOpen, setIsRevealDialogOpen] = useState(false);
158
const [isQrPanelOpen, setIsQrPanelOpen] = useState(false);
@@ -510,7 +510,7 @@ const ConnectedClientListRow = memo(function ConnectedClientListRow({
510
onRevokeSession,
511
canRevoke,
512
}: ConnectedClientListRowProps) {
513
- const nowMs = useRelativeTimeTick(1_000);
513
+ const nowMs = useNowSecond();
514
const isLive = clientSession.current || clientSession.connected;
515
const lastConnectedAt = clientSession.lastConnectedAt;
516
const statusTooltip = isLive
apps/web/src/components/settings/DiagnosticsSettings.tsx
+12
-27
@@ -11,7 +11,7 @@ import {
11
isAtomCommandInterrupted,
12
squashAtomCommandFailure,
13
} from "@t3tools/client-runtime/state/runtime";
14
-import { useEffect, useRef, useState, type ReactNode } from "react";
14
+import { useRef, useState, type ReactNode } from "react";
15
import type {
16
ServerProcessDiagnosticsEntry,
17
ServerProcessResourceHistorySummary,
@@ -714,6 +714,12 @@ function DiagnosticsRefreshButton({
714
}
715
716
export function DiagnosticsSettingsPanel() {
717
+ const { environment } = useSettingsScope();
718
+ // Signals and pending UI state belong to one environment, so a scope switch starts fresh.
719
+ return <DiagnosticsSettingsBody key={environment?.environmentId ?? ""} />;
720
+}
721
+
722
+function DiagnosticsSettingsBody() {
723
const { environment } = useSettingsScope();
724
const environmentId = environment?.environmentId ?? null;
725
const canMaintainEnvironment = useEnvironmentScope(environmentId, AuthEnvironmentMaintainScope);
@@ -772,17 +778,6 @@ export function DiagnosticsSettingsPanel() {
778
const [openLogsDirectoryError, setOpenLogsDirectoryError] = useState<string | null>(null);
779
const [signalingPid, setSignalingPid] = useState<number | null>(null);
780
const signalingPidRef = useRef<number | null>(null);
775
- const environmentIdRef = useRef(environmentId);
776
- const processDataRef = useRef(processData);
777
- useEffect(() => {
778
- processDataRef.current = processData;
779
- }, [processData]);
780
- useEffect(() => {
781
- environmentIdRef.current = environmentId;
782
- return () => {
783
- environmentIdRef.current = null;
784
- };
785
- }, [environmentId]);
781
782
const openLogsDirectory = () => {
783
const logsDirectoryPath = observability?.logsDirectoryPath ?? null;
@@ -825,8 +820,8 @@ export function DiagnosticsSettingsPanel() {
820
setExportFormEnvironmentId(environmentId);
821
}
822
const signalProcess = async (pid: number, signal: ServerProcessSignal) => {
828
- const targetEnvironmentId = environmentIdRef.current;
829
- const process = processDataRef.current?.processes.find((entry) => entry.pid === pid);
823
+ const targetEnvironmentId = environmentId;
824
+ const process = processData?.processes.find((entry) => entry.pid === pid);
825
if (
826
targetEnvironmentId === null ||
827
process === undefined ||
@@ -861,19 +856,9 @@ export function DiagnosticsSettingsPanel() {
856
return;
857
}
858
}
864
- const currentEnvironmentId = environmentIdRef.current;
865
- if (
866
- currentEnvironmentId === null ||
867
- currentEnvironmentId !== targetEnvironmentId ||
868
- !readEnvironmentScope(currentEnvironmentId, AuthEnvironmentMaintainScope)
869
- ) {
870
- clearSignaling();
871
- return;
872
- }
873
- if (
874
- processDataRef.current?.processes.find((entry) => entry.pid === pid)?.startTimeMs !==
875
- process.startTimeMs
876
- ) {
859
+ // The server rejects a pid whose start time no longer matches, so a process that exited
860
+ // during confirmation is never signaled by mistake.
861
+ if (!readEnvironmentScope(targetEnvironmentId, AuthEnvironmentMaintainScope)) {
862
clearSignaling();
863
return;
864
}
apps/web/src/components/settings/OpenSourceLicenses.tsx
+58
-62
@@ -1,5 +1,12 @@
1
import { ChevronRightIcon, ExternalLinkIcon, SearchIcon } from "lucide-react";
2
-import { useEffect, useState } from "react";
2
+import { useAtomRefresh, useAtomValue } from "@effect/atom-react";
3
+import * as Cause from "effect/Cause";
4
+import * as Data from "effect/Data";
5
+import * as Effect from "effect/Effect";
6
+import * as Option from "effect/Option";
7
+import { FetchHttpClient, HttpClient } from "effect/http";
8
+import { Atom } from "effect/reactivity";
9
+import { useState } from "react";
10
11
import {
12
decodeThirdPartyLicenseManifest,
@@ -7,7 +14,6 @@ import {
14
formatLicenseBundles,
15
thirdPartyLicenseEntryKey,
16
type ThirdPartyLicenseEntry,
10
- type ThirdPartyLicenseManifest,
17
} from "@t3tools/shared/thirdPartyLicenses";
18
19
import { Button } from "../ui/button";
@@ -16,41 +22,45 @@ import { InputGroup, InputGroupAddon, InputGroupInput } from "../ui/input-group"
22
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
23
import { SettingsPageContainer, SettingsSection } from "./settingsLayout";
24
19
-type LicenseManifestState =
20
- | { readonly status: "loading" }
21
- | { readonly status: "error"; readonly message: string }
22
- | { readonly status: "ready"; readonly manifest: ThirdPartyLicenseManifest };
25
+class LicenseManifestLoadError extends Data.TaggedError("LicenseManifestLoadError")<{
26
+ readonly message: string;
27
+}> {}
28
24
-let licenseManifestPromise: Promise<ThirdPartyLicenseManifest> | undefined;
25
-
26
-async function fetchLicenseManifest(): Promise<ThirdPartyLicenseManifest> {
27
- const signal = AbortSignal.timeout(30_000);
28
- try {
29
- const response = await fetch(
29
+// Not keepAlive: a failed load must not stick for the session, so each visit to the page loads
30
+// the manifest again (a static asset the HTTP cache serves).
31
+const licenseManifestAtom = Atom.make(
32
+ Effect.gen(function* () {
33
+ const response = yield* HttpClient.get(
34
`${import.meta.env.BASE_URL.replace(/\/$/, "")}/third-party-licenses.json`,
31
- { signal },
35
);
33
- if (!response.ok) {
34
- throw new Error(
35
- `The license manifest request failed with status ${String(response.status)}.`,
36
- );
37
- }
38
- return decodeThirdPartyLicenseManifest((await response.json()) as unknown);
39
- } catch (error) {
40
- if (signal.aborted) {
41
- throw new Error("The license manifest took too long to load.", { cause: error });
36
+ if (response.status < 200 || response.status >= 300) {
37
+ return yield* new LicenseManifestLoadError({
38
+ message: `The license manifest request failed with status ${String(response.status)}.`,
39
+ });
40
}
43
- throw error;
44
- }
45
-}
46
-
47
-function loadLicenseManifest(): Promise<ThirdPartyLicenseManifest> {
48
- licenseManifestPromise ??= fetchLicenseManifest().catch((error: unknown) => {
49
- licenseManifestPromise = undefined;
50
- throw error;
51
- });
52
- return licenseManifestPromise;
53
-}
41
+ const body = yield* response.json;
42
+ return yield* Effect.try({
43
+ try: () => decodeThirdPartyLicenseManifest(body),
44
+ catch: (error) =>
45
+ new LicenseManifestLoadError({
46
+ message: error instanceof Error ? error.message : "The license manifest could not load.",
47
+ }),
48
+ });
49
+ }).pipe(
50
+ Effect.catchTags({
51
+ HttpClientError: (error) =>
52
+ Effect.fail(new LicenseManifestLoadError({ message: error.message })),
53
+ }),
54
+ Effect.timeoutOrElse({
55
+ duration: "30 seconds",
56
+ orElse: () =>
57
+ Effect.fail(
58
+ new LicenseManifestLoadError({ message: "The license manifest took too long to load." }),
59
+ ),
60
+ }),
61
+ Effect.provide(FetchHttpClient.layer),
62
+ ),
63
+).pipe(Atom.withLabel("settings:open-source-licenses"));
64
65
function LicenseNoticeRow({
66
entry,
@@ -211,42 +221,28 @@ function LicenseManifestError({ message, onRetry }: { message: string; onRetry:
221
}
222
223
export function OpenSourceLicensesPanel() {
214
- const [state, setState] = useState<LicenseManifestState>({ status: "loading" });
224
+ const result = useAtomValue(licenseManifestAtom);
225
+ const retry = useAtomRefresh(licenseManifestAtom);
226
const [query, setQuery] = useState("");
227
const [searchOpen, setSearchOpen] = useState(false);
228
const [openEntryKey, setOpenEntryKey] = useState<string | null>(null);
218
- const loading = state.status === "loading";
219
-
220
- useEffect(() => {
221
- if (!loading) return;
222
- let cancelled = false;
223
- void loadLicenseManifest().then(
224
- (manifest) => {
225
- if (!cancelled) setState({ status: "ready", manifest });
226
- },
227
- (error: unknown) => {
228
- if (cancelled) return;
229
- setState({
230
- status: "error",
231
- message: error instanceof Error ? error.message : "The license manifest could not load.",
232
- });
233
- },
234
- );
235
- return () => {
236
- cancelled = true;
237
- };
238
- }, [loading]);
239
-
240
- const entries = state.status === "ready" ? state.manifest.entries : [];
229
+ const manifest = result._tag === "Success" ? result.value : null;
230
+ const entries = manifest?.entries ?? [];
231
const filteredEntries = filterThirdPartyLicenseEntries(entries, query);
242
- const retry = () => setState({ status: "loading" });
232
+ const errorMessage =
233
+ result._tag === "Failure" && !result.waiting
234
+ ? Option.match(Cause.findErrorOption(result.cause), {
235
+ onNone: () => "The license manifest could not load.",
236
+ onSome: (error) => error.message,
237
+ })
238
+ : null;
239
240
return (
241
<SettingsPageContainer>
242
<SettingsSection
243
title="Third-party notices"
244
headerAction={
249
- state.status === "ready" ? (
245
+ manifest ? (
246
<LicenseHeaderAction
247
query={query}
248
onQueryChange={setQuery}
@@ -258,7 +254,7 @@ export function OpenSourceLicensesPanel() {
254
) : null
255
}
256
>
261
- {state.status === "ready" ? (
257
+ {manifest ? (
258
<div className="text-base sm:text-sm">
259
{filteredEntries.length > 0 ? (
260
filteredEntries.map((entry) => {
@@ -278,8 +274,8 @@ export function OpenSourceLicensesPanel() {
274
</p>
275
)}
276
</div>
281
- ) : state.status === "error" ? (
282
- <LicenseManifestError message={state.message} onRetry={retry} />
277
+ ) : errorMessage !== null ? (
278
+ <LicenseManifestError message={errorMessage} onRetry={retry} />
279
) : (
280
<p className="px-3 py-5 text-sm/6 text-muted-foreground sm:px-4">
281
Loading open-source notices…
apps/web/src/components/settings/ProjectIconPickerDialog.tsx
+164
-154
@@ -6,7 +6,7 @@ import {
6
type ProjectIconColor,
7
type ProjectIconOverride,
8
} from "@t3tools/contracts";
9
-import { createElement, useEffect, useRef, useState } from "react";
9
+import { createElement, useState } from "react";
10
import {
11
filterProjectIconNames,
12
firstEmoji,
@@ -57,6 +57,32 @@ export function ProjectIconPickerDialog({
57
readonly open: boolean;
58
readonly onOpenChange: (open: boolean) => void;
59
readonly onSelect: (icon: ProjectIconOverride) => void;
60
+}) {
61
+ return (
62
+ <Dialog open={open} onOpenChange={onOpenChange}>
63
+ <DialogPopup className="w-full sm:w-[32rem]">
64
+ {/* The popup mounts per open, so the draft below starts from `current` each time. */}
65
+ <ProjectIconPickerBody
66
+ current={current}
67
+ projectName={projectName}
68
+ onClose={() => onOpenChange(false)}
69
+ onSelect={onSelect}
70
+ />
71
+ </DialogPopup>
72
+ </Dialog>
73
+ );
74
+}
75
+
76
+function ProjectIconPickerBody({
77
+ current,
78
+ projectName,
79
+ onClose,
80
+ onSelect,
81
+}: {
82
+ readonly current: ProjectIconOverride | null;
83
+ readonly projectName: string;
84
+ readonly onClose: () => void;
85
+ readonly onSelect: (icon: ProjectIconOverride) => void;
86
}) {
87
const automatic = deriveProjectIdentity(projectName);
88
const [mode, setMode] = useState<ProjectIconOverride["kind"]>(current?.kind ?? "lucide");
@@ -72,20 +98,6 @@ export function ProjectIconPickerDialog({
98
const [emoji, setEmoji] = useState(current?.kind === "emoji" ? current.emoji : "💻");
99
const [query, setQuery] = useState("");
100
const [customEmoji, setCustomEmoji] = useState("");
75
- const previousOpenRef = useRef(false);
76
-
77
- useEffect(() => {
78
- if (open && !previousOpenRef.current) {
79
- setMode(current?.kind ?? "lucide");
80
- setIconName(current?.kind === "lucide" ? current.name : DEFAULT_ICON);
81
- setColor(current && current.kind !== "emoji" ? current.color : automatic.color);
82
- setLetters(current?.kind === "monogram" ? current.text : automatic.monogram);
83
- setEmoji(current?.kind === "emoji" ? current.emoji : "💻");
84
- setQuery("");
85
- setCustomEmoji("");
86
- }
87
- previousOpenRef.current = open;
88
- }, [current, open, automatic.color, automatic.monogram]);
101
102
const icons = filterProjectIconNames(query);
103
const selectedColorClassName = projectIconColorClassName(color);
@@ -100,160 +112,158 @@ export function ProjectIconPickerDialog({
112
? { kind: "lucide", name: iconName, color }
113
: { kind: "emoji", emoji },
114
);
103
- onOpenChange(false);
115
+ onClose();
116
};
117
118
return (
107
- <Dialog open={open} onOpenChange={onOpenChange}>
108
- <DialogPopup className="w-full sm:w-[32rem]">
109
- <DialogHeader>
110
- <DialogTitle>Choose project icon</DialogTitle>
111
- <DialogDescription>Choose an icon, emoji, or monogram.</DialogDescription>
112
- </DialogHeader>
113
- <DialogPanel className="flex min-h-0 flex-col">
114
- <ToggleGroup
115
- aria-label="Icon type"
116
- variant="segmented"
117
- value={[mode]}
118
- onValueChange={(next) => {
119
- const value = next[0];
120
- if (value === "lucide" || value === "emoji" || value === "monogram") setMode(value);
121
- }}
122
- >
123
- <Toggle value="lucide">Icons</Toggle>
124
- <Toggle value="emoji">Emoji</Toggle>
125
- <Toggle value="monogram">Monogram</Toggle>
126
- </ToggleGroup>
119
+ <>
120
+ <DialogHeader>
121
+ <DialogTitle>Choose project icon</DialogTitle>
122
+ <DialogDescription>Choose an icon, emoji, or monogram.</DialogDescription>
123
+ </DialogHeader>
124
+ <DialogPanel className="flex min-h-0 flex-col">
125
+ <ToggleGroup
126
+ aria-label="Icon type"
127
+ variant="segmented"
128
+ value={[mode]}
129
+ onValueChange={(next) => {
130
+ const value = next[0];
131
+ if (value === "lucide" || value === "emoji" || value === "monogram") setMode(value);
132
+ }}
133
+ >
134
+ <Toggle value="lucide">Icons</Toggle>
135
+ <Toggle value="emoji">Emoji</Toggle>
136
+ <Toggle value="monogram">Monogram</Toggle>
137
+ </ToggleGroup>
138
128
- {mode !== "emoji" ? (
129
- <div>
130
- <div className="mb-2 text-xs font-medium text-muted-foreground">Color</div>
131
- <div className="flex flex-wrap gap-1.5" role="group" aria-label="Icon color">
132
- {PROJECT_ICON_COLORS.map((option) => (
139
+ {mode !== "emoji" ? (
140
+ <div>
141
+ <div className="mb-2 text-xs font-medium text-muted-foreground">Color</div>
142
+ <div className="flex flex-wrap gap-1.5" role="group" aria-label="Icon color">
143
+ {PROJECT_ICON_COLORS.map((option) => (
144
+ <button
145
+ key={option.value}
146
+ type="button"
147
+ aria-label={option.label}
148
+ aria-pressed={color === option.value}
149
+ className={cn(
150
+ "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",
151
+ color === option.value && "border-foreground/64",
152
+ )}
153
+ onClick={() => setColor(option.value)}
154
+ >
155
+ <span className={cn("size-4 rounded-full", option.swatchClassName)} />
156
+ </button>
157
+ ))}
158
+ </div>
159
+ </div>
160
+ ) : null}
161
+
162
+ {mode === "lucide" ? (
163
+ <>
164
+ <Input
165
+ type="search"
166
+ value={query}
167
+ aria-label="Search Lucide icons"
168
+ placeholder="Search all Lucide icons"
169
+ onChange={(event) => setQuery(event.currentTarget.value)}
170
+ />
171
+ <ScrollArea scrollFade className="max-h-64">
172
+ <div className="grid grid-cols-8 gap-1 p-0.5 sm:grid-cols-10">
173
+ {icons.map((name) => (
174
<button
134
- key={option.value}
175
+ key={name}
176
type="button"
136
- aria-label={option.label}
137
- aria-pressed={color === option.value}
177
+ aria-label={iconLabel(name)}
178
+ aria-pressed={iconName === name}
179
className={cn(
139
- "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",
140
- color === option.value && "border-foreground/64",
180
+ "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",
181
+ iconName === name && "border-border bg-accent",
182
+ selectedColorClassName,
183
)}
142
- onClick={() => setColor(option.value)}
184
+ onClick={() => setIconName(name)}
185
>
144
- <span className={cn("size-4 rounded-full", option.swatchClassName)} />
186
+ <PickerIcon name={name} />
187
</button>
188
))}
189
</div>
148
- </div>
149
- ) : null}
150
-
151
- {mode === "lucide" ? (
152
- <>
190
+ </ScrollArea>
191
+ {icons.length === 0 ? (
192
+ <p className="py-8 text-center text-sm text-muted-foreground">No icons found.</p>
193
+ ) : null}
194
+ </>
195
+ ) : mode === "monogram" ? (
196
+ <div className="flex items-center gap-4 py-2">
197
+ <ProjectMonogram
198
+ text={validMonogram ? monogram : automatic.monogram}
199
+ color={color}
200
+ className="size-12"
201
+ />
202
+ <div className="flex-1 space-y-2">
203
+ <label htmlFor="project-monogram" className="text-sm font-medium">
204
+ Letters
205
+ </label>
206
<Input
154
- type="search"
155
- value={query}
156
- aria-label="Search Lucide icons"
157
- placeholder="Search all Lucide icons"
158
- onChange={(event) => setQuery(event.currentTarget.value)}
159
- />
160
- <ScrollArea scrollFade className="max-h-64">
161
- <div className="grid grid-cols-8 gap-1 p-0.5 sm:grid-cols-10">
162
- {icons.map((name) => (
163
- <button
164
- key={name}
165
- type="button"
166
- aria-label={iconLabel(name)}
167
- aria-pressed={iconName === name}
168
- className={cn(
169
- "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",
170
- iconName === name && "border-border bg-accent",
171
- selectedColorClassName,
172
- )}
173
- onClick={() => setIconName(name)}
174
- >
175
- <PickerIcon name={name} />
176
- </button>
177
- ))}
178
- </div>
179
- </ScrollArea>
180
- {icons.length === 0 ? (
181
- <p className="py-8 text-center text-sm text-muted-foreground">No icons found.</p>
182
- ) : null}
183
- </>
184
- ) : mode === "monogram" ? (
185
- <div className="flex items-center gap-4 py-2">
186
- <ProjectMonogram
187
- text={validMonogram ? monogram : automatic.monogram}
188
- color={color}
189
- className="size-12"
207
+ id="project-monogram"
208
+ value={letters}
209
+ onChange={(event) => setLetters(event.currentTarget.value)}
210
+ aria-describedby="project-monogram-hint"
211
+ aria-invalid={!validMonogram}
212
+ autoComplete="off"
213
/>
191
- <div className="flex-1 space-y-2">
192
- <label htmlFor="project-monogram" className="text-sm font-medium">
193
- Letters
194
- </label>
195
- <Input
196
- id="project-monogram"
197
- value={letters}
198
- onChange={(event) => setLetters(event.currentTarget.value)}
199
- aria-describedby="project-monogram-hint"
200
- aria-invalid={!validMonogram}
201
- autoComplete="off"
202
- />
203
- <p id="project-monogram-hint" className="text-xs text-muted-foreground">
204
- One or two letters or numbers.
205
- </p>
206
- </div>
214
+ <p id="project-monogram-hint" className="text-xs text-muted-foreground">
215
+ One or two letters or numbers.
216
+ </p>
217
</div>
208
- ) : (
209
- <>
210
- <ScrollArea scrollFade className="max-h-64">
211
- <div className="grid grid-cols-8 gap-1 p-0.5 sm:grid-cols-10">
212
- {PROJECT_EMOJIS.map((option) => (
213
- <button
214
- key={option.emoji}
215
- type="button"
216
- aria-label={option.label}
217
- aria-pressed={emoji === option.emoji}
218
- className={cn(
219
- "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",
220
- emoji === option.emoji && "border-border bg-accent",
221
- )}
222
- onClick={() => setEmoji(option.emoji)}
223
- >
224
- {option.emoji}
225
- </button>
226
- ))}
227
- </div>
228
- </ScrollArea>
229
- <div>
230
- <div className="mb-2 text-xs font-medium text-muted-foreground">
231
- Or paste any emoji
232
- </div>
233
- <Input
234
- value={customEmoji}
235
- aria-label="Custom emoji"
236
- placeholder="Paste an emoji"
237
- onChange={(event) => {
238
- const value = event.currentTarget.value;
239
- setCustomEmoji(value);
240
- const nextEmoji = firstEmoji(value);
241
- if (nextEmoji) setEmoji(nextEmoji);
242
- }}
243
- />
218
+ </div>
219
+ ) : (
220
+ <>
221
+ <ScrollArea scrollFade className="max-h-64">
222
+ <div className="grid grid-cols-8 gap-1 p-0.5 sm:grid-cols-10">
223
+ {PROJECT_EMOJIS.map((option) => (
224
+ <button
225
+ key={option.emoji}
226
+ type="button"
227
+ aria-label={option.label}
228
+ aria-pressed={emoji === option.emoji}
229
+ className={cn(
230
+ "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",
231
+ emoji === option.emoji && "border-border bg-accent",
232
+ )}
233
+ onClick={() => setEmoji(option.emoji)}
234
+ >
235
+ {option.emoji}
236
+ </button>
237
+ ))}
238
</div>
245
- </>
246
- )}
247
- </DialogPanel>
248
- <DialogFooter>
249
- <Button variant="outline" onClick={() => onOpenChange(false)}>
250
- Cancel
251
- </Button>
252
- <Button onClick={save} disabled={mode === "monogram" && !validMonogram}>
253
- Save icon
254
- </Button>
255
- </DialogFooter>
256
- </DialogPopup>
257
- </Dialog>
239
+ </ScrollArea>
240
+ <div>
241
+ <div className="mb-2 text-xs font-medium text-muted-foreground">
242
+ Or paste any emoji
243
+ </div>
244
+ <Input
245
+ value={customEmoji}
246
+ aria-label="Custom emoji"
247
+ placeholder="Paste an emoji"
248
+ onChange={(event) => {
249
+ const value = event.currentTarget.value;
250
+ setCustomEmoji(value);
251
+ const nextEmoji = firstEmoji(value);
252
+ if (nextEmoji) setEmoji(nextEmoji);
253
+ }}
254
+ />
255
+ </div>
256
+ </>
257
+ )}
258
+ </DialogPanel>
259
+ <DialogFooter>
260
+ <Button variant="outline" onClick={onClose}>
261
+ Cancel
262
+ </Button>
263
+ <Button onClick={save} disabled={mode === "monogram" && !validMonogram}>
264
+ Save icon
265
+ </Button>
266
+ </DialogFooter>
267
+ </>
268
);
269
}
apps/web/src/components/settings/ProjectSettingsPanel.tsx
+47
-35
@@ -13,10 +13,10 @@ import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environ
13
import { planProjectRemoval } from "@t3tools/client-runtime/state/projects";
14
import { AsyncResult } from "effect/reactivity";
15
import { type EnvironmentId, type ProjectIconOverride } from "@t3tools/contracts";
16
-import { useLocation, useNavigate } from "@tanstack/react-router";
16
+import { Navigate, useLocation, useNavigate } from "@tanstack/react-router";
17
import * as Cause from "effect/Cause";
18
import { InfoIcon, Trash2Icon } from "lucide-react";
19
-import { lazy, Suspense, useEffect, useRef, useState, type ReactNode } from "react";
19
+import { lazy, Suspense, useRef, useState, type ReactNode } from "react";
20
21
import { useComposerDraftStore } from "../../composerDraftStore";
22
import { releaseProjectDraftUploads } from "../../lib/composerDraftUploads";
@@ -59,6 +59,24 @@ const ProjectIconPickerDialog = lazy(() =>
59
60
export type ProjectSettingsCategory = "general" | "source-control" | "project";
61
62
+interface ProjectSelection {
63
+ readonly key: string;
64
+ readonly environmentId: EnvironmentId | null;
65
+ readonly checkoutKey: string | null;
66
+ readonly memberKeys: ReadonlyArray<string>;
67
+}
68
+
69
+function sameProjectSelection(a: ProjectSelection | null, b: ProjectSelection): boolean {
70
+ return (
71
+ a !== null &&
72
+ a.key === b.key &&
73
+ a.environmentId === b.environmentId &&
74
+ a.checkoutKey === b.checkoutKey &&
75
+ a.memberKeys.length === b.memberKeys.length &&
76
+ a.memberKeys.every((key, index) => key === b.memberKeys[index])
77
+ );
78
+}
79
+
80
export function ProjectSettingsPanel({
81
projectKey,
82
environmentId = null,
@@ -71,7 +89,6 @@ export function ProjectSettingsPanel({
89
unavailable?: ReactNode;
90
}) {
91
const groups = useSettingsProjectGroups();
74
- const navigate = useNavigate({ from: "/settings" });
92
const pathname = useLocation({ select: (location) => location.pathname });
93
94
const selected = groups.find((group) => group.projectKey === projectKey) ?? null;
@@ -83,47 +100,42 @@ export function ProjectSettingsPanel({
100
) ?? [];
101
102
// Retain group members so grouping-rule changes can follow the project to its new group.
86
- const lastSelectionRef = useRef<{
87
- key: string;
88
- environmentId: EnvironmentId | null;
89
- checkoutKey: string | null;
90
- memberKeys: string[];
91
- } | null>(null);
92
- useEffect(() => {
93
- if (!selected || members.length === 0) return;
94
- lastSelectionRef.current = {
103
+ const [lastSelection, setLastSelection] = useState<ProjectSelection | null>(null);
104
+ if (selected && members.length > 0) {
105
+ const current: ProjectSelection = {
106
key: selected.projectKey,
107
environmentId,
108
checkoutKey,
109
memberKeys: members.map((member) => member.physicalProjectKey),
110
};
100
- }, [selected, members, environmentId, checkoutKey]);
111
+ if (!sameProjectSelection(lastSelection, current)) setLastSelection(current);
112
+ }
113
102
- useEffect(() => {
103
- if (members.length > 0) return;
104
- const last = lastSelectionRef.current;
105
- if (
106
- last?.key !== projectKey ||
107
- last.environmentId !== environmentId ||
108
- last.checkoutKey !== checkoutKey
109
- )
110
- return;
111
- const successor = groups.find((group) =>
112
- group.memberProjects.some((member) => last.memberKeys.includes(member.physicalProjectKey)),
113
- );
114
- if (successor) {
115
- void navigate({
116
- to: pathname,
117
- search: () => ({
114
+ const successor =
115
+ members.length === 0 &&
116
+ lastSelection?.key === projectKey &&
117
+ lastSelection.environmentId === environmentId &&
118
+ lastSelection.checkoutKey === checkoutKey
119
+ ? groups.find((group) =>
120
+ group.memberProjects.some((member) =>
121
+ lastSelection.memberKeys.includes(member.physicalProjectKey),
122
+ ),
123
+ )
124
+ : undefined;
125
+ if (successor) {
126
+ return (
127
+ <Navigate
128
+ to={pathname}
129
+ search={{
130
project: successor.projectKey,
131
machine: environmentId ?? undefined,
132
checkout: checkoutKey ?? undefined,
121
- }),
122
- replace: true,
123
- hashScrollIntoView: false,
124
- });
125
- }
126
- }, [groups, navigate, pathname, projectKey, members.length, environmentId, checkoutKey]);
133
+ }}
134
+ replace
135
+ hashScrollIntoView={false}
136
+ />
137
+ );
138
+ }
139
140
if ((!selected || members.length === 0) && unavailable != null) return unavailable;
141
apps/web/src/components/settings/ResourceTelemetryDiagnostics.tsx
+25
-27
@@ -28,7 +28,8 @@ import type {
28
} from "@t3tools/contracts";
29
import * as DateTime from "effect/DateTime";
30
import * as Option from "effect/Option";
31
-import { useEffect, useRef, useState, type ReactNode } from "react";
31
+import { RegistryContext } from "@effect/atom-react";
32
+import { useContext, useRef, useState, type ReactNode } from "react";
33
import {
34
isAtomCommandInterrupted,
35
squashAtomCommandFailure,
@@ -809,6 +810,18 @@ export function ResourceTelemetryDiagnostics({
810
}: {
811
environmentId: EnvironmentId | null;
812
}) {
813
+ // Pending signals and retries belong to one environment, so a switch starts fresh.
814
+ return (
815
+ <ResourceTelemetryDiagnosticsBody key={environmentId ?? ""} environmentId={environmentId} />
816
+ );
817
+}
818
+
819
+function ResourceTelemetryDiagnosticsBody({
820
+ environmentId,
821
+}: {
822
+ environmentId: EnvironmentId | null;
823
+}) {
824
+ const registry = useContext(RegistryContext);
825
const [windowMs, setWindowMs] = useState(15 * 60_000);
826
const selectedWindow =
827
HISTORY_WINDOWS.find((option) => option.windowMs === windowMs) ?? HISTORY_WINDOWS[1];
@@ -822,29 +835,17 @@ export function ResourceTelemetryDiagnostics({
835
},
836
environmentId,
837
);
825
- const refreshHistory = history.refresh;
826
- const selectedHistoryRef = useRef({ environmentId, windowMs, refreshHistory });
827
- useEffect(() => {
828
- selectedHistoryRef.current = { environmentId, windowMs, refreshHistory };
829
- }, [environmentId, windowMs, refreshHistory]);
838
const signalServerProcess = useAtomCommand(serverEnvironment.signalProcess, {
839
reportFailure: false,
840
});
841
const [signalingKeys, setSignalingKeys] = useState<ReadonlySet<string>>(() => new Set());
842
const signalingKeysRef = useRef<ReadonlySet<string>>(new Set());
835
- const environmentIdRef = useRef(environmentId);
836
- useEffect(() => {
837
- environmentIdRef.current = environmentId;
838
- return () => {
839
- environmentIdRef.current = null;
840
- };
841
- }, [environmentId]);
843
const [isRetrying, setIsRetrying] = useState(false);
844
const snapshot = telemetry.data;
845
const allT3 = snapshot?.groups.allT3;
846
847
const signalProcess = async (process: ResourceTelemetryProcess, signal: ServerProcessSignal) => {
847
- const targetEnvironmentId = environmentIdRef.current;
848
+ const targetEnvironmentId = environmentId;
849
if (
850
targetEnvironmentId === null ||
851
!readEnvironmentScope(targetEnvironmentId, AuthEnvironmentMaintainScope)
@@ -883,10 +884,7 @@ export function ResourceTelemetryDiagnostics({
884
return;
885
}
886
}
886
- if (
887
- environmentIdRef.current !== targetEnvironmentId ||
888
- !readEnvironmentScope(targetEnvironmentId, AuthEnvironmentMaintainScope)
889
- ) {
887
+ if (!readEnvironmentScope(targetEnvironmentId, AuthEnvironmentMaintainScope)) {
888
clearSignaling();
889
return;
890
}
@@ -926,7 +924,6 @@ export function ResourceTelemetryDiagnostics({
924
};
925
926
const retryCollector = () => {
929
- const environmentId = environmentIdRef.current;
927
if (
928
environmentId === null ||
929
!readEnvironmentScope(environmentId, AuthEnvironmentMaintainScope)
@@ -935,14 +932,15 @@ export function ResourceTelemetryDiagnostics({
932
setIsRetrying(true);
933
void retryTelemetry()
934
.then(() => {
938
- refreshHistory();
939
- const selectedHistory = selectedHistoryRef.current;
940
- if (
941
- environmentIdRef.current === environmentId &&
942
- selectedHistory.environmentId === environmentId &&
943
- selectedHistory.windowMs !== windowMs
944
- ) {
945
- selectedHistory.refreshHistory();
935
+ // The user can pick another window while the retry runs; refreshing every window
936
+ // re-reads the one on screen and only invalidates the rest.
937
+ for (const option of HISTORY_WINDOWS) {
938
+ registry.refresh(
939
+ serverEnvironment.resourceTelemetryHistory({
940
+ environmentId,
941
+ input: { windowMs: option.windowMs, bucketMs: option.bucketMs },
942
+ }),
943
+ );
944
}
945
})
946
.catch((error: unknown) => {
apps/web/src/components/settings/ScheduledTasksSettings.browser.test.tsx
new
+141
@@ -0,0 +1,141 @@
1
+import {
2
+ DEFAULT_UNIFIED_SETTINGS,
3
+ EnvironmentId,
4
+ ProjectId,
5
+ ProviderInstanceId,
6
+ ScheduledTaskId,
7
+ type ScheduledTask,
8
+} from "@t3tools/contracts";
9
+import { describe, expect, it, vi } from "vite-plus/test";
10
+import { page, userEvent } from "vite-plus/test/browser";
11
+
12
+import "~/index.css";
13
+import { render } from "../../../test/render";
14
+import { ScheduledTasksSettings } from "./ScheduledTasksSettings";
15
+
16
+const environmentId = EnvironmentId.make("laptop");
17
+const projectId = ProjectId.make("project");
18
+const task: ScheduledTask = {
19
+ id: ScheduledTaskId.make("nightly"),
20
+ title: "Review issues",
21
+ prompt: "Review open issues",
22
+ enabled: true,
23
+ schedule: { type: "interval", everyMs: 60_000 },
24
+ projectId,
25
+ threadId: null,
26
+ workspaceStrategy: { type: "root" },
27
+ modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
28
+ runtimeMode: "full-access",
29
+ interactionMode: "default",
30
+ createdBy: "user",
31
+ creationSource: "web",
32
+ createdAt: "2026-09-17T00:00:00.000Z",
33
+ updatedAt: "2026-09-17T00:00:00.000Z",
34
+ nextRunAt: null,
35
+ lastRunAt: null,
36
+ lastRunStatus: "never",
37
+ lastRunError: null,
38
+ runCount: 0,
39
+};
40
+
41
+const state = vi.hoisted(() => ({ connected: true, tasksLoaded: true }));
42
+
43
+function environment() {
44
+ return {
45
+ environmentId,
46
+ label: "Laptop",
47
+ connection: { phase: state.connected ? "connected" : "disconnected" },
48
+ serverConfig: state.connected ? { environment: { platform: "linux" } } : null,
49
+ };
50
+}
51
+
52
+vi.mock(import("./SettingsScopeContext"), async (original) => {
53
+ const scope = () => {
54
+ const entry = environment();
55
+ return {
56
+ scope: { kind: "all", label: "All", members: [], environmentIds: [environmentId] },
57
+ environments: [entry],
58
+ connectedEnvironments: state.connected ? [entry] : [],
59
+ environment: entry,
60
+ target: null,
61
+ targets: [],
62
+ };
63
+ };
64
+ return {
65
+ ...(await original()),
66
+ useSettingsScope: scope as never,
67
+ };
68
+});
69
+vi.mock(import("../../state/server"), async (original) => {
70
+ const actual = await original();
71
+ const { Atom } = await import("effect/reactivity");
72
+ const allowed = Atom.make(true);
73
+ return {
74
+ ...actual,
75
+ serverEnvironment: {
76
+ ...actual.serverEnvironment,
77
+ upsertScheduledTask: {
78
+ ...actual.serverEnvironment.upsertScheduledTask,
79
+ permissionAtom: () => allowed,
80
+ },
81
+ },
82
+ };
83
+});
84
+// Mirrors the real query: a null request (disconnected environment) has no data.
85
+vi.mock(import("../../state/query"), async (original) => ({
86
+ ...(await original()),
87
+ useEnvironmentQuery: ((request: unknown) => ({
88
+ data: request === null ? null : { tasks: state.tasksLoaded ? [task] : [] },
89
+ error: null,
90
+ isPending: false,
91
+ refresh: vi.fn(),
92
+ })) as never,
93
+}));
94
+vi.mock(import("../../state/environments"), async (original) => ({
95
+ ...(await original()),
96
+ useEnvironment: (() => environment()) as never,
97
+}));
98
+vi.mock(import("../../state/entities"), async (original) => ({
99
+ ...(await original()),
100
+ useProjects: (() => [{ id: projectId, environmentId, title: "Project" }]) as never,
101
+}));
102
+vi.mock(import("../../hooks/useSettings"), async (original) => ({
103
+ ...(await original()),
104
+ useEnvironmentSettings: (() => DEFAULT_UNIFIED_SETTINGS) as never,
105
+}));
106
+
107
+describe("ScheduledTasksSettings", () => {
108
+ it("keeps a linked task's unsaved edits across a disconnect and reconnect", async () => {
109
+ state.connected = true;
110
+ state.tasksLoaded = true;
111
+ await using screen = await render(<ScheduledTasksSettings taskId={task.id} />);
112
+ const name = page.getByRole("dialog").getByRole("textbox", { name: "Name" });
113
+ await expect.element(name).toHaveValue("Review issues");
114
+ await userEvent.fill(name, "Review stale issues");
115
+
116
+ state.connected = false;
117
+ await screen.rerender(<ScheduledTasksSettings taskId={task.id} />);
118
+
119
+ await expect.element(name).toHaveValue("Review stale issues");
120
+
121
+ state.connected = true;
122
+ await screen.rerender(<ScheduledTasksSettings taskId={task.id} />);
123
+ await expect.element(name).toHaveValue("Review stale issues");
124
+ });
125
+
126
+ it("keeps an editor the user opened when the linked task loads later", async () => {
127
+ state.connected = true;
128
+ state.tasksLoaded = false;
129
+ await using screen = await render(<ScheduledTasksSettings taskId={task.id} />);
130
+ await userEvent.click(page.getByRole("button", { name: "New task" }));
131
+ const dialog = page.getByRole("dialog");
132
+ const name = dialog.getByRole("textbox", { name: "Name" });
133
+ await userEvent.fill(name, "My draft");
134
+
135
+ state.tasksLoaded = true;
136
+ await screen.rerender(<ScheduledTasksSettings taskId={task.id} />);
137
+
138
+ await expect.element(dialog.getByRole("heading", { name: "New task" })).toBeInTheDocument();
139
+ await expect.element(name).toHaveValue("My draft");
140
+ });
141
+});
apps/web/src/components/settings/ScheduledTasksSettings.tsx
+45
-26
@@ -12,7 +12,7 @@ import {
12
PlusIcon,
13
Trash2Icon,
14
} from "lucide-react";
15
-import { type ReactNode, useEffect, useRef, useState } from "react";
15
+import { type ReactNode, useRef, useState } from "react";
16
import type {
17
EnvironmentId,
18
ModelSelection,
@@ -56,7 +56,7 @@ import {
56
import { usePrimaryCloudLinkState } from "../../cloud/primaryCloudLinkState";
57
import { requestConfirmDialog } from "../../confirmDialog";
58
import { webhookAddress } from "@t3tools/client-runtime/webhook-address";
59
-import { Link } from "@tanstack/react-router";
59
+import { Link, useNavigate } from "@tanstack/react-router";
60
import { useCopyToClipboard } from "../../hooks/useCopyToClipboard";
61
import { useNowMinute } from "../../hooks/useNowMinute";
62
import {
@@ -362,6 +362,45 @@ export function ScheduledTasksSettings(target: {
362
setEditor({ environmentId, task });
363
};
364
const defaultEnvironment = environment ?? connectedEnvironments[0];
365
+ const linkedEnvironmentId = target.environmentId ?? defaultEnvironment?.environmentId;
366
+ const linkedEnvironmentConnected = environments.some(
367
+ (entry) =>
368
+ entry.environmentId === linkedEnvironmentId &&
369
+ entry.connection.phase === "connected" &&
370
+ entry.serverConfig !== null,
371
+ );
372
+ const linkedTasksQuery = useEnvironmentQuery(
373
+ target.taskId !== undefined && linkedEnvironmentId !== undefined && linkedEnvironmentConnected
374
+ ? serverEnvironment.scheduledTasksLive({ environmentId: linkedEnvironmentId, input: {} })
375
+ : null,
376
+ );
377
+ const linkedTask = linkedTasksQuery.data?.tasks.find(
378
+ (task) =>
379
+ task.id === target.taskId &&
380
+ linkedEnvironmentId !== undefined &&
381
+ matchesScheduledTaskScope(scope, linkedEnvironmentId, task.projectId),
382
+ );
383
+ // A `taskId` link opens its editor once, the first time the task loads. The editor then owns
384
+ // the session until close, so a disconnect that disables the query cannot drop unsaved edits.
385
+ // An editor the user already opened wins: a late-loading link must not replace its draft.
386
+ const [openedLinkTaskId, setOpenedLinkTaskId] = useState<ScheduledTaskId | undefined>();
387
+ if (target.taskId === undefined && openedLinkTaskId !== undefined) {
388
+ setOpenedLinkTaskId(undefined);
389
+ }
390
+ if (linkedTask && linkedEnvironmentId !== undefined && openedLinkTaskId !== target.taskId) {
391
+ setOpenedLinkTaskId(target.taskId);
392
+ if (editor === null) setEditor({ environmentId: linkedEnvironmentId, task: linkedTask });
393
+ }
394
+ const navigate = useNavigate({ from: "/settings/scheduled-tasks" });
395
+ const closeEditor = () => {
396
+ setEditor(null);
397
+ if (target.taskId === undefined) return;
398
+ void navigate({
399
+ to: "/settings/scheduled-tasks",
400
+ search: ({ taskId: _closed, ...rest }) => rest,
401
+ replace: true,
402
+ });
403
+ };
404
const canCreate = useAtomValue(
405
serverEnvironment.upsertScheduledTask.permissionAtom(defaultEnvironment?.environmentId ?? null),
406
);
@@ -401,8 +440,7 @@ export function ScheduledTasksSettings(target: {
440
</Empty>
441
) : environments.length > 1 ? (
442
<ScheduledTaskEnvironmentList
404
- key={`${target.environmentId ?? defaultEnvironment?.environmentId}:${target.taskId ?? ""}`}
405
- environmentId={target.environmentId ?? defaultEnvironment?.environmentId}
443
+ environmentId={linkedEnvironmentId}
444
taskId={target.taskId}
445
onEdit={openForEdit}
446
/>
@@ -410,15 +448,10 @@ export function ScheduledTasksSettings(target: {
448
<div className="space-y-8">
449
{environments.map((entry) => (
450
<ScheduledTaskEnvironmentSection
413
- key={`${entry.environmentId}:${target.taskId ?? ""}`}
451
+ key={entry.environmentId}
452
environment={entry}
453
showEnvironmentHeading={environments.length > 1}
416
- taskId={
417
- (target.environmentId ?? defaultEnvironment?.environmentId) ===
418
- entry.environmentId
419
- ? target.taskId
420
- : undefined
421
- }
454
+ taskId={linkedEnvironmentId === entry.environmentId ? target.taskId : undefined}
455
onEdit={openForEdit}
456
/>
457
))}
@@ -430,7 +463,7 @@ export function ScheduledTasksSettings(target: {
463
key={`${editor.environmentId}:${editor.task?.id ?? "new"}`}
464
initialEnvironmentId={editor.environmentId}
465
task={editor.task}
433
- onClose={() => setEditor(null)}
466
+ onClose={closeEditor}
467
/>
468
) : null}
469
</SettingsPageContainer>
@@ -472,13 +505,6 @@ function ScheduledTaskEnvironmentList({
505
});
506
const linkedState = states.find((state) => state.environment.environmentId === environmentId);
507
const linkedTask = linkedState?.tasks?.find((task) => task.id === taskId);
475
- const openedLink = useRef(false);
476
- useEffect(() => {
477
- if (!openedLink.current && environmentId && linkedTask) {
478
- openedLink.current = true;
479
- onEdit(environmentId, linkedTask);
480
- }
481
- }, [environmentId, linkedTask, onEdit]);
508
509
const loaded = states.filter((state) => state.connected && state.error === null && state.tasks);
510
const populated = loaded.filter((state) => state.tasks && state.tasks.length > 0);
@@ -603,13 +629,6 @@ function ScheduledTaskEnvironmentSection({
629
matchesScheduledTaskScope(scope, environment.environmentId, task.projectId),
630
);
631
const linkedTask = tasks?.find((task) => task.id === taskId);
606
- const openedLink = useRef(false);
607
- useEffect(() => {
608
- if (!openedLink.current && linkedTask) {
609
- openedLink.current = true;
610
- onEdit(environment.environmentId, linkedTask);
611
- }
612
- }, [environment.environmentId, linkedTask, onEdit]);
632
return (
633
<SettingsSection
634
title={environment.label}
apps/web/src/components/settings/SnapShotSettings.tsx
+60
-92
@@ -1,27 +1,32 @@
1
-import { useAtomValue } from "@effect/atom-react";
1
+import { RegistryContext, useAtomValue } from "@effect/atom-react";
2
import {
3
isModifierPairShortcut,
4
type ClientSettingsPatch,
5
type DesktopSnapShotShortcutAvailability,
6
- type DesktopSnapShotState,
6
type DesktopSnapShotSetupAction,
7
type SnapShotShortcut,
8
} from "@t3tools/contracts";
9
import { PlayIcon } from "lucide-react";
10
import { settlePromise } from "@t3tools/client-runtime/state/runtime";
11
import * as Cause from "effect/Cause";
13
-import { useEffect, useRef, useState } from "react";
12
+import { useContext, useRef, useState } from "react";
13
15
-import { useStableCallback } from "../../hooks/useStableCallback";
14
import { useClientSettings, updateClientSettings } from "../../hooks/useSettings";
15
import { getDesktopSnapShotBridge } from "../../lib/desktopSnapShot";
16
import {
19
- readSnapShotSetupResume,
17
saveSnapShotSetupResume,
18
clearSnapShotSetupResume,
19
+ readSnapShotSetupResume,
20
} from "../../lib/snapShotSetupResume";
21
import { sameSnapShotShortcut, snapShotKeybindingConflict } from "../../lib/snapShotShortcut";
22
import { playSnapShotSound } from "../../lib/snapShotSound";
23
+import {
24
+ desktopSnapShotAtom,
25
+ refreshDesktopSnapShotState,
26
+ snapShotSetupError,
27
+ type SnapShotSetupError,
28
+} from "../../state/desktopSnapShot";
29
+import { toastManager } from "../ui/toast";
30
import { primaryServerKeybindingsAtom } from "../../state/server";
31
import { commandLabel } from "./KeybindingsSettings.logic";
32
import {
@@ -47,7 +52,6 @@ import { Button } from "../ui/button";
52
import { Menu, MenuItem, MenuPopup, MenuRadioGroup, MenuRadioItem, MenuTrigger } from "../ui/menu";
53
import { SelectButton } from "../ui/select";
54
import { Switch } from "../ui/switch";
50
-import { toastManager } from "../ui/toast";
55
import { SnapShotSetupDialog } from "./SnapShotSetupDialog";
56
import { useSnapShotShortcutRecorder } from "./useSnapShotShortcutRecorder";
57
import {
@@ -59,20 +63,18 @@ import {
63
64
const soundOptionRowClassName = "grid grid-cols-[1fr_auto]";
65
62
-function captureSettingsError(title: string, error: unknown) {
63
- return { title, message: error instanceof Error ? error.message : "Try again." };
64
-}
65
-
66
type ShortcutCheck =
67
| { readonly status: "idle"; readonly availability: null }
68
| {
69
readonly status: "checking";
70
readonly availability: null;
71
readonly shortcut: SnapShotShortcut;
72
+ readonly savedShortcut: SnapShotShortcut;
73
}
74
| {
75
readonly status: "checked";
76
readonly shortcut: SnapShotShortcut;
77
+ readonly savedShortcut: SnapShotShortcut;
78
readonly availability: DesktopSnapShotShortcutAvailability;
79
};
80
@@ -88,31 +90,53 @@ export function SnapShotSettings() {
90
}));
91
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
92
const bridge = getDesktopSnapShotBridge();
91
- const [state, setState] = useState<DesktopSnapShotState | null>(null);
93
+ const registry = useContext(RegistryContext);
94
+ const { state, refreshError } = useAtomValue(desktopSnapShotAtom);
95
const [setupBusy, setSetupBusy] = useState(false);
93
- const [setupError, setSetupError] = useState<ReturnType<typeof captureSettingsError> | null>(
94
- null,
95
- );
96
- const [wizard, setWizard] = useState<{
96
+ const [setupError, setSetupError] = useState<SnapShotSetupError | null>(null);
97
+ // macOS can quit the app from a permission prompt; until the user opens or closes the wizard
98
+ // themselves, a saved resume reopens it where it left off.
99
+ const [resume] = useState(readSnapShotSetupResume);
100
+ const [chosenWizard, setWizard] = useState<{
101
initialStep: CaptureSetupStep;
102
wasEnabled: boolean;
99
- } | null>(null);
103
+ } | null>();
104
+ const wizard =
105
+ chosenWizard !== undefined
106
+ ? chosenWizard
107
+ : state?.macPermissions && resume
108
+ ? { initialStep: "access" as const, wasEnabled: resume.wasEnabled }
109
+ : null;
110
+ // The wizard shows errors inline; outside it there is nowhere to, so they become a toast.
111
+ const reportSetupError = (title: string, error: unknown) => {
112
+ const report = snapShotSetupError(title, error);
113
+ setSetupError(report);
114
+ if (!wizard)
115
+ toastManager.add({ type: "error", title: report.title, description: report.message });
116
+ };
117
+ const refreshState = () =>
118
+ refreshDesktopSnapShotState(registry, (error) =>
119
+ reportSetupError("Couldn't check capture setup", error),
120
+ );
121
const [candidate, setCandidate] = useState<SnapShotShortcut>(settings.snapShotShortcut);
122
const [latestShortcutCheck, setShortcutCheck] = useState<ShortcutCheck>({
123
status: "idle",
124
availability: null,
125
});
126
+ // A check answers for one candidate against one saved shortcut. Once either moves on (an edit,
127
+ // or hydration saving a new shortcut) a late answer no longer shows, so a check for the
128
+ // shortcut that just got saved can't claim it is ready to save.
129
+ const savedShortcut = settings.snapShotShortcut;
130
const shortcutCheck: ShortcutCheck =
131
latestShortcutCheck.status === "idle" ||
107
- sameSnapShotShortcut(latestShortcutCheck.shortcut, candidate)
132
+ (sameSnapShotShortcut(latestShortcutCheck.shortcut, candidate) &&
133
+ sameSnapShotShortcut(latestShortcutCheck.savedShortcut, savedShortcut))
134
? latestShortcutCheck
135
: { status: "idle", availability: null };
136
const shortcutCheckIdRef = useRef(0);
111
- const stateRequestIdRef = useRef(0);
137
const unavailableMessage = snapShotUnavailableMessage(Boolean(bridge));
138
const captureAvailable = Boolean(bridge) && state !== null && state.mode !== "unavailable";
139
const feedbackUnavailable = snapShotFeedbackUnavailableMessage(state);
115
- const savedShortcut = settings.snapShotShortcut;
140
const managedShortcut = state?.linuxBackend === "niri" || state?.linuxBackend === "hyprland";
141
const shortcutChanged = !managedShortcut && !sameSnapShotShortcut(candidate, savedShortcut);
142
const displayShortcut = shortcutChanged ? candidate : (state?.shortcut ?? savedShortcut);
@@ -125,20 +149,6 @@ export function SnapShotSettings() {
149
const soundLabel =
150
soundSelection === "off" ? "Off" : soundSelection === "soft-pop" ? "Whoosh (Default)" : "Click";
151
128
- const refreshState = useStableCallback(async () => {
129
- const requestId = ++stateRequestIdRef.current;
130
- try {
131
- if (bridge) {
132
- const nextState = await bridge.getSnapShotState();
133
- if (requestId === stateRequestIdRef.current) setState(nextState);
134
- return nextState;
135
- }
136
- } catch (error) {
137
- if (requestId === stateRequestIdRef.current)
138
- setSetupError(captureSettingsError("Couldn't check capture setup", error));
139
- }
140
- });
141
-
152
const setup = async (action: DesktopSnapShotSetupAction) => {
153
if (!bridge?.setupSnapShot || setupBusy) return;
154
setSetupBusy(true);
@@ -156,52 +166,16 @@ export function SnapShotSettings() {
166
await refreshState();
167
});
168
if (result._tag === "Failure") {
159
- setSetupError(
160
- captureSettingsError(
161
- action === "retry-shortcut"
162
- ? "Couldn't open shortcut permissions"
163
- : "Couldn't complete capture setup",
164
- Cause.squash(result.cause),
165
- ),
169
+ reportSetupError(
170
+ action === "retry-shortcut"
171
+ ? "Couldn't open shortcut permissions"
172
+ : "Couldn't complete capture setup",
173
+ Cause.squash(result.cause),
174
);
175
}
176
setSetupBusy(false);
177
};
178
171
- const toastedErrorRef = useRef<typeof setupError>(null);
172
- useEffect(() => {
173
- if (!setupError || wizard || toastedErrorRef.current === setupError) return;
174
- toastedErrorRef.current = setupError;
175
- toastManager.add({
176
- type: "error",
177
- title: setupError.title,
178
- description: setupError.message,
179
- });
180
- }, [setupError, wizard]);
181
-
182
- useEffect(() => {
183
- let cancelled = false;
184
- void refreshState().then((current) => {
185
- const resume = readSnapShotSetupResume();
186
- if (!cancelled && current?.macPermissions && resume) {
187
- setWizard({ initialStep: "access", wasEnabled: resume.wasEnabled });
188
- }
189
- });
190
- window.addEventListener("focus", refreshState);
191
- return () => {
192
- cancelled = true;
193
- window.removeEventListener("focus", refreshState);
194
- };
195
- }, [refreshState]);
196
-
197
- useEffect(
198
- () =>
199
- bridge?.onSnapShotEvent((event) => {
200
- if (event.type === "shortcut-changed") void refreshState();
201
- }),
202
- [bridge, refreshState],
203
- );
204
-
179
// Hydration can hand back an equal shortcut object; only a different shortcut resets the edit.
180
const [renderedSavedShortcut, setRenderedSavedShortcut] = useState(savedShortcut);
181
if (!sameSnapShotShortcut(renderedSavedShortcut, savedShortcut)) {
@@ -209,12 +183,6 @@ export function SnapShotSettings() {
183
setCandidate(savedShortcut);
184
setShortcutCheck({ status: "idle", availability: null });
185
}
212
- const checkedForSavedShortcutRef = useRef(savedShortcut);
213
- useEffect(() => {
214
- if (sameSnapShotShortcut(checkedForSavedShortcutRef.current, savedShortcut)) return;
215
- checkedForSavedShortcutRef.current = savedShortcut;
216
- shortcutCheckIdRef.current++;
217
- }, [savedShortcut]);
186
187
const save = async (patch: ClientSettingsPatch) => {
188
setSetupError(null);
@@ -222,7 +190,7 @@ export function SnapShotSettings() {
190
await updateClientSettings(patch);
191
return await refreshState();
192
} catch (error) {
225
- setSetupError(captureSettingsError("Couldn't save capture settings", error));
193
+ reportSetupError("Couldn't save capture settings", error);
194
}
195
};
196
@@ -232,7 +200,7 @@ export function SnapShotSettings() {
200
await bridge?.requestSnapShotPermissions(true);
201
await save({ snapShotIncludeAccessibility: includeAccessibility });
202
} catch (error) {
235
- setSetupError(captureSettingsError("Couldn't allow app text capture", error));
203
+ reportSetupError("Couldn't allow app text capture", error);
204
}
205
};
206
@@ -241,17 +209,18 @@ export function SnapShotSettings() {
209
setCandidate(shortcut);
210
const conflict = snapShotKeybindingConflict(shortcut, keybindings);
211
if (conflict || !bridge) return;
244
- setShortcutCheck({ status: "checking", availability: null, shortcut });
212
+ setShortcutCheck({ status: "checking", availability: null, shortcut, savedShortcut });
213
try {
214
const availability = await bridge.checkSnapShotShortcut(shortcut);
215
if (checkId === shortcutCheckIdRef.current) {
248
- setShortcutCheck({ status: "checked", availability, shortcut });
216
+ setShortcutCheck({ status: "checked", availability, shortcut, savedShortcut });
217
}
218
} catch (error) {
219
if (checkId !== shortcutCheckIdRef.current) return;
220
setShortcutCheck({
221
status: "checked",
222
shortcut,
223
+ savedShortcut,
224
availability: {
225
available: false,
226
message: error instanceof Error ? error.message : "Could not check this shortcut.",
@@ -278,6 +247,7 @@ export function SnapShotSettings() {
247
setShortcutCheck({
248
status: "checked",
249
shortcut: candidate,
250
+ savedShortcut,
251
availability: { available: false, message },
252
}),
253
});
@@ -347,9 +317,7 @@ export function SnapShotSettings() {
317
});
318
setSetupBusy(false);
319
if (verified._tag === "Success") return verified.value;
350
- setSetupError(
351
- captureSettingsError("Couldn't verify capture access", Cause.squash(verified.cause)),
352
- );
320
+ reportSetupError("Couldn't verify capture access", Cause.squash(verified.cause));
321
return false;
322
};
323
@@ -369,9 +337,7 @@ export function SnapShotSettings() {
337
setWizard(null);
338
});
339
if (closed._tag === "Failure") {
372
- setSetupError(
373
- captureSettingsError("Couldn't close capture setup", Cause.squash(closed.cause)),
374
- );
340
+ reportSetupError("Couldn't close capture setup", Cause.squash(closed.cause));
341
}
342
setSetupBusy(false);
343
};
@@ -394,7 +360,9 @@ export function SnapShotSettings() {
360
bridge
361
? setupBusy && !wizard
362
? "Updating capture settings…"
397
- : snapShotStatus(state, settings.snapShotEnabled)
363
+ : refreshError
364
+ ? `${refreshError.title}. ${refreshError.message}`
365
+ : snapShotStatus(state, settings.snapShotEnabled)
366
: undefined
367
}
368
control={
@@ -600,7 +568,7 @@ export function SnapShotSettings() {
568
wasEnabled={wizard.wasEnabled}
569
includeAccessibility={settings.snapShotIncludeAccessibility}
570
busy={setupBusy}
603
- error={setupError?.message ?? null}
571
+ error={(setupError ?? refreshError)?.message ?? null}
572
shortcutInput={shortcutInput}
573
shortcutStatus={shortcutStatus}
574
shortcutChanged={shortcutChanged}
apps/web/src/components/settings/StorageSettings.tsx
+4
-3
@@ -15,6 +15,7 @@ import { environmentAtomList, environmentIdsKey } from "../../state/environmentA
15
import { serverEnvironment } from "../../state/server";
16
import { useAtomCommand } from "../../state/use-atom-command";
17
import { formatRelativeTimeLabel } from "../../timestampFormat";
18
+import { useNowMinute } from "../../hooks/useNowMinute";
19
import { Button } from "../ui/button";
20
import { toastManager } from "../ui/toast";
21
@@ -33,7 +34,6 @@ import {
34
SettingsPageContainer,
35
SettingsRow,
36
SettingsSection,
36
- useRelativeTimeTick,
37
} from "./settingsLayout";
38
import { DatabaseStorageNotice } from "./DatabaseStorageNotice";
39
import { SettingsScopeNotice } from "./SettingsScopeNotice";
@@ -279,7 +279,8 @@ const storageCleanupPermissionsAtom = environmentAtomList(
279
);
280
281
function CleanupSection() {
282
- useRelativeTimeTick(60_000);
282
+ const nowMinute = useNowMinute();
283
+ const nowMs = Date.parse(`${nowMinute}:00.000Z`);
284
const { connectedEnvironments } = useSettingsScope();
285
const [pending, setPending] = useState(false);
286
const run = useAtomCommand(serverEnvironment.runStorageCleanup);
@@ -330,7 +331,7 @@ function CleanupSection() {
331
? `${report.counts.removed} removed, ${report.counts.kept} kept${report.counts.failed > 0 ? `, ${report.counts.failed} failed` : ""}`
332
: "",
333
description: report
333
- ? `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.` : ""}`
334
+ ? `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.` : ""}`
335
: query?.failed
336
? "Could not load the last run."
337
: query?.loading
apps/web/src/components/settings/settingsLayout.tsx
+1
-17
@@ -6,14 +6,7 @@ import { InfoIcon, Undo2Icon } from "lucide-react";
6
import { DEFAULT_SERVER_SETTINGS, type ServerSettings } from "@t3tools/contracts";
7
import * as Equal from "effect/Equal";
8
import { useLocation, useNavigate } from "@tanstack/react-router";
9
-import {
10
- createContext,
11
- type ComponentPropsWithoutRef,
12
- type ReactNode,
13
- useContext,
14
- useEffect,
15
- useState,
16
-} from "react";
9
+import { createContext, type ComponentPropsWithoutRef, type ReactNode, useContext } from "react";
10
11
import {
12
PRIMARY_SETTINGS_UNAVAILABLE_MESSAGE,
@@ -203,15 +196,6 @@ export function PolicyTooltip({ children }: { readonly children: string }) {
196
);
197
}
198
206
-export function useRelativeTimeTick(intervalMs = 1_000) {
207
- const [nowMs, setNowMs] = useState(() => Date.now());
208
- useEffect(() => {
209
- const id = setInterval(() => setNowMs(Date.now()), intervalMs);
210
- return () => clearInterval(id);
211
- }, [intervalMs]);
212
- return nowMs;
213
-}
214
-
199
export function SettingsSection({
200
title,
201
hideTitle = false,
apps/web/src/state/desktopSnapShot.ts
new
+80
@@ -0,0 +1,80 @@
1
+import type { DesktopSnapShotState } from "@t3tools/contracts";
2
+import * as Option from "effect/Option";
3
+import { Atom, type AtomRegistry } from "effect/reactivity";
4
+
5
+import { getDesktopSnapShotBridge } from "../lib/desktopSnapShot";
6
+
7
+export interface SnapShotSetupError {
8
+ readonly title: string;
9
+ readonly message: string;
10
+}
11
+
12
+export function snapShotSetupError(title: string, error: unknown): SnapShotSetupError {
13
+ return { title, message: error instanceof Error ? error.message : "Try again." };
14
+}
15
+
16
+export interface DesktopSnapShotLoad {
17
+ readonly state: DesktopSnapShotState | null;
18
+ /** Why the last background read (load, focus, shortcut change) failed; a later success clears it. */
19
+ readonly refreshError: SnapShotSetupError | null;
20
+}
21
+
22
+const EMPTY_LOAD: DesktopSnapShotLoad = { state: null, refreshError: null };
23
+
24
+// Only the newest read lands, so a slow answer cannot regress the state. Dropping the atom bumps
25
+// it too, so a read that was in flight when the page closed does not seed the next visit.
26
+let stateRequestId = 0;
27
+
28
+/**
29
+ * The desktop capture state. Reading it starts a load, then re-reads on window focus (the user
30
+ * may have changed OS permissions) and when the desktop reports a shortcut change.
31
+ */
32
+export const desktopSnapShotAtom = Atom.writable(
33
+ (get): DesktopSnapShotLoad => {
34
+ get.addFinalizer(() => {
35
+ stateRequestId++;
36
+ });
37
+ const bridge = getDesktopSnapShotBridge();
38
+ if (!bridge) return EMPTY_LOAD;
39
+ const refresh = () =>
40
+ void refreshDesktopSnapShotState(get.registry, (error) => {
41
+ get.setSelf({
42
+ ...Option.getOrElse(get.self<DesktopSnapShotLoad>(), () => EMPTY_LOAD),
43
+ refreshError: snapShotSetupError("Couldn't check capture setup", error),
44
+ });
45
+ });
46
+ window.addEventListener("focus", refresh);
47
+ get.addFinalizer(() => window.removeEventListener("focus", refresh));
48
+ get.addFinalizer(
49
+ bridge.onSnapShotEvent((event) => {
50
+ if (event.type === "shortcut-changed") refresh();
51
+ }),
52
+ );
53
+ refresh();
54
+ return EMPTY_LOAD;
55
+ },
56
+ (ctx, value: DesktopSnapShotLoad) => ctx.setSelf(value),
57
+).pipe(Atom.withLabel("desktop:snap-shot:state"));
58
+
59
+/**
60
+ * Reads the capture state now and stores it. `onError` hears only a failure of the newest read;
61
+ * the result is `undefined` whenever this read did not produce the current state.
62
+ */
63
+export async function refreshDesktopSnapShotState(
64
+ registry: AtomRegistry.AtomRegistry,
65
+ onError: (error: unknown) => void,
66
+): Promise<DesktopSnapShotState | undefined> {
67
+ const bridge = getDesktopSnapShotBridge();
68
+ if (!bridge) return undefined;
69
+ const requestId = ++stateRequestId;
70
+ try {
71
+ const next = await bridge.getSnapShotState();
72
+ if (requestId === stateRequestId) {
73
+ registry.set(desktopSnapShotAtom, { state: next, refreshError: null });
74
+ }
75
+ return next;
76
+ } catch (error) {
77
+ if (requestId === stateRequestId) onError(error);
78
+ return undefined;
79
+ }
80
+}