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 21, 04:45 UTC
| 1 | import { useAtomValue } from "@effect/atom-react"; |
| 2 | import type { OtlpEndpointCheckResult, OtlpSignal, ServerObservability } from "@t3tools/contracts"; |
| 3 | import { useEffect, useEffectEvent, useState } from "react"; |
| 4 | import { msg, T, useGT, useMessages, Var } from "gt-react"; |
| 5 | import { m, type MessageResolver } from "../../i18n/messages"; |
| 6 | |
| 7 | import { serverEnvironment } from "../../state/server"; |
| 8 | import { useAtomCommand } from "../../state/use-atom-command"; |
| 9 | import { Button } from "../ui/button"; |
| 10 | import { Input } from "../ui/input"; |
| 11 | import { Label } from "../ui/label"; |
| 12 | import { ConnectionStatusDot } from "../ConnectionStatusDot"; |
| 13 | import { useSettingsScope } from "./SettingsScopeContext"; |
| 14 | import { useScopedSettings } from "./useScopedSettings"; |
| 15 | import { SettingsSection } from "./settingsLayout"; |
| 16 | import { SettingsScopeNotice } from "./SettingsScopeNotice"; |
| 17 | |
| 18 | const SIGNALS = [ |
| 19 | { |
| 20 | key: "otlpTracesUrl", |
| 21 | sourceKey: "otlpTracesSource", |
| 22 | variableKey: "otlpTracesVariable", |
| 23 | label: msg("Traces endpoint"), |
| 24 | signal: "traces", |
| 25 | }, |
| 26 | { |
| 27 | key: "otlpMetricsUrl", |
| 28 | sourceKey: "otlpMetricsSource", |
| 29 | variableKey: "otlpMetricsVariable", |
| 30 | label: msg("Metrics endpoint"), |
| 31 | signal: "metrics", |
| 32 | }, |
| 33 | { |
| 34 | key: "otlpLogsUrl", |
| 35 | sourceKey: "otlpLogsSource", |
| 36 | variableKey: "otlpLogsVariable", |
| 37 | label: msg("Logs endpoint"), |
| 38 | signal: "logs", |
| 39 | }, |
| 40 | ] as const; |
| 41 | |
| 42 | type SignalDescriptor = (typeof SIGNALS)[number]; |
| 43 | type SignalKey = SignalDescriptor["key"]; |
| 44 | |
| 45 | const OVERRIDE_LABELS = { |
| 46 | environment: msg("Set by environment"), |
| 47 | bootstrap: msg("Set by desktop"), |
| 48 | } as const; |
| 49 | |
| 50 | function runningOverride( |
| 51 | running: ServerObservability | undefined, |
| 52 | { key, sourceKey, variableKey }: SignalDescriptor, |
| 53 | resolve: MessageResolver = m, |
| 54 | ) { |
| 55 | const url = running?.[key]; |
| 56 | const source = running?.[sourceKey]; |
| 57 | if (url === undefined || (source !== "environment" && source !== "bootstrap")) return undefined; |
| 58 | return { url, label: resolve(OVERRIDE_LABELS[source]), variable: running?.[variableKey] }; |
| 59 | } |
| 60 | |
| 61 | type EndpointCheck = { readonly url: string; readonly result: OtlpEndpointCheckResult | null }; |
| 62 | |
| 63 | const isHttpUrl = (url: string) => /^https?:\/\/./i.test(url); |
| 64 | |
| 65 | function endpointStatus( |
| 66 | url: string, |
| 67 | check: EndpointCheck | undefined, |
| 68 | resolve: MessageResolver = m, |
| 69 | ) { |
| 70 | if (url === "") { |
| 71 | return { |
| 72 | label: resolve(msg("Off", { $context: "export disabled" })), |
| 73 | dot: "bg-muted-foreground/40", |
| 74 | }; |
| 75 | } |
| 76 | if (check?.url !== url) { |
| 77 | return { label: resolve(msg("Not checked")), dot: "bg-muted-foreground/40" }; |
| 78 | } |
| 79 | const { result } = check; |
| 80 | if (result === null) return { label: resolve(msg("Checking…")), dot: "bg-warning" }; |
| 81 | switch (result._tag) { |
| 82 | case "Accepted": |
| 83 | return { |
| 84 | label: resolve(msg("Connected · {ms} ms", { ms: Math.round(result.latencyMs) })), |
| 85 | dot: "bg-success", |
| 86 | }; |
| 87 | case "Rejected": |
| 88 | return { |
| 89 | label: resolve(msg("Rejected · HTTP {status}", { status: result.status })), |
| 90 | dot: "bg-destructive", |
| 91 | }; |
| 92 | case "Unreachable": |
| 93 | return { |
| 94 | label: result.timedOut ? resolve(msg("Timed out")) : resolve(msg("Unreachable")), |
| 95 | dot: "bg-destructive", |
| 96 | }; |
| 97 | } |
| 98 | } |
| 99 | |
| 100 | export function TelemetryExportSettings() { |
| 101 | const gt = useGT(); |
| 102 | const { environment, scope } = useSettingsScope(); |
| 103 | if (scope.kind !== "environment" || !environment) { |
| 104 | return ( |
| 105 | <SettingsSection title={gt("OpenTelemetry export")} id="telemetry-export"> |
| 106 | <SettingsScopeNotice target="environment"> |
| 107 | {gt("Choose one environment to configure its telemetry exports.")} |
| 108 | </SettingsScopeNotice> |
| 109 | </SettingsSection> |
| 110 | ); |
| 111 | } |
| 112 | return <TelemetryExportForm key={environment.environmentId} />; |
| 113 | } |
| 114 | |
| 115 | function TelemetryExportForm() { |
| 116 | const messages = useMessages(); |
| 117 | const gt = useGT(); |
| 118 | const { environment } = useSettingsScope(); |
| 119 | const saved = useScopedSettings((settings) => settings.observability); |
| 120 | const [draft, setDraft] = useState<Partial<typeof saved>>({}); |
| 121 | const [saving, setSaving] = useState(false); |
| 122 | const [message, setMessage] = useState<string | null>(null); |
| 123 | const environmentId = environment?.environmentId; |
| 124 | const canEdit = useAtomValue( |
| 125 | serverEnvironment.checkOtlpEndpoint.permissionAtom(environmentId ?? null), |
| 126 | ); |
| 127 | const canCheck = |
| 128 | canEdit && environment?.serverConfig?.environment.capabilities.otlpEndpointCheck === true; |
| 129 | const running = environment?.serverConfig?.observability; |
| 130 | const [checks, setChecks] = useState<Partial<Record<SignalKey, EndpointCheck>>>(() => |
| 131 | Object.fromEntries( |
| 132 | SIGNALS.flatMap((descriptor) => { |
| 133 | const url = runningOverride(running, descriptor)?.url ?? saved[descriptor.key]; |
| 134 | return isHttpUrl(url) ? [[descriptor.key, { url, result: null }]] : []; |
| 135 | }), |
| 136 | ), |
| 137 | ); |
| 138 | const updateSettings = useAtomCommand(serverEnvironment.updateSettings, { reportFailure: true }); |
| 139 | const checkOtlpEndpoint = useAtomCommand(serverEnvironment.checkOtlpEndpoint); |
| 140 | const values = { ...saved, ...draft }; |
| 141 | const changedSignals = SIGNALS.filter(({ key }) => values[key].trim() !== saved[key]); |
| 142 | const changed = changedSignals.length > 0; |
| 143 | |
| 144 | const sendCheck = async (key: SignalKey, signal: OtlpSignal, attempt: EndpointCheck) => { |
| 145 | if (!environmentId) return; |
| 146 | const { url } = attempt; |
| 147 | const response = await checkOtlpEndpoint({ environmentId, input: { signal, url } }); |
| 148 | setChecks((previous) => { |
| 149 | if (previous[key] !== attempt) return previous; |
| 150 | const next = { ...previous }; |
| 151 | if (response._tag === "Success") next[key] = { url, result: response.value }; |
| 152 | else delete next[key]; |
| 153 | return next; |
| 154 | }); |
| 155 | }; |
| 156 | |
| 157 | const checkEndpoint = (key: SignalKey, signal: OtlpSignal, url: string) => { |
| 158 | if (!isHttpUrl(url)) return; |
| 159 | const attempt = { url, result: null }; |
| 160 | setChecks((previous) => ({ ...previous, [key]: attempt })); |
| 161 | void sendCheck(key, signal, attempt); |
| 162 | }; |
| 163 | |
| 164 | const sendPendingChecks = useEffectEvent(() => { |
| 165 | for (const { key, signal } of SIGNALS) { |
| 166 | const check = checks[key]; |
| 167 | if (check?.result === null) void sendCheck(key, signal, check); |
| 168 | } |
| 169 | }); |
| 170 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- sends pending endpoint check requests once the environment can run them |
| 171 | useEffect(() => { |
| 172 | // oxlint-disable-next-line react/set-state-in-effect -- State changes only after the response arrives. |
| 173 | if (canCheck) sendPendingChecks(); |
| 174 | }, [canCheck]); |
| 175 | |
| 176 | return ( |
| 177 | <SettingsSection title={gt("OpenTelemetry export")} id="telemetry-export"> |
| 178 | <form |
| 179 | className="grid gap-4 px-4 py-4 sm:px-5" |
| 180 | onSubmit={async (event) => { |
| 181 | event.preventDefault(); |
| 182 | if (!environment || saving) return; |
| 183 | setSaving(true); |
| 184 | setMessage(null); |
| 185 | const result = await updateSettings({ |
| 186 | environmentId: environment.environmentId, |
| 187 | input: { |
| 188 | patch: { |
| 189 | observability: Object.fromEntries( |
| 190 | changedSignals.map(({ key }) => [key, values[key]]), |
| 191 | ), |
| 192 | }, |
| 193 | }, |
| 194 | }); |
| 195 | setSaving(false); |
| 196 | if (result._tag === "Success") { |
| 197 | setDraft({}); |
| 198 | setMessage(gt("Saved. Restart the server to apply.")); |
| 199 | } |
| 200 | }} |
| 201 | > |
| 202 | <p className="text-xs text-muted-foreground"> |
| 203 | <T> |
| 204 | Send traces, metrics, and logs to an OTLP HTTP receiver. Restart the server to apply. |
| 205 | Environment variables override these settings. |
| 206 | </T> |
| 207 | </p> |
| 208 | {!canEdit && ( |
| 209 | <p className="text-xs text-muted-foreground"> |
| 210 | {environment |
| 211 | ? gt("This connection lacks permission to change settings on {environment}.", { |
| 212 | environment: environment.label, |
| 213 | }) |
| 214 | : gt( |
| 215 | "This connection lacks permission to change settings on the selected environment.", |
| 216 | )} |
| 217 | </p> |
| 218 | )} |
| 219 | {SIGNALS.map((descriptor) => { |
| 220 | const { key, label, signal } = descriptor; |
| 221 | const override = runningOverride(running, descriptor, messages); |
| 222 | const url = override?.url ?? values[key].trim(); |
| 223 | const check = canCheck ? endpointStatus(url, checks[key], messages) : null; |
| 224 | const status = override |
| 225 | ? { |
| 226 | label: check ? `${override.label} · ${check.label}` : override.label, |
| 227 | dot: check?.dot ?? "bg-muted-foreground/40", |
| 228 | } |
| 229 | : check; |
| 230 | return ( |
| 231 | <div key={key} className="grid gap-1.5"> |
| 232 | <div className="flex items-center justify-between gap-3"> |
| 233 | <div className="flex items-center gap-1.5"> |
| 234 | {status && <ConnectionStatusDot dotClassName={status.dot} />} |
| 235 | <Label htmlFor={key}>{messages(label)}</Label> |
| 236 | </div> |
| 237 | {status && <span className="text-xs text-muted-foreground">{status.label}</span>} |
| 238 | </div> |
| 239 | <div className="flex gap-2"> |
| 240 | <Input |
| 241 | id={key} |
| 242 | size="sm" |
| 243 | type="url" |
| 244 | pattern="[Hh][Tt][Tt][Pp][Ss]?://.*" |
| 245 | title={gt("Enter an HTTP or HTTPS endpoint, or leave empty to disable export.")} |
| 246 | placeholder={`http://localhost:4318/v1/${signal}`} |
| 247 | value={values[key]} |
| 248 | disabled={saving || !canEdit} |
| 249 | onChange={(event) => { |
| 250 | const value = event.target.value; |
| 251 | // Clear restored drafts so later saves cannot overwrite another client's changes. |
| 252 | setDraft((previous) => { |
| 253 | const next = { ...previous, [key]: value }; |
| 254 | if (value.trim() === saved[key]) delete next[key]; |
| 255 | return next; |
| 256 | }); |
| 257 | setMessage(null); |
| 258 | }} |
| 259 | /> |
| 260 | {canCheck && ( |
| 261 | <Button |
| 262 | type="button" |
| 263 | size="sm" |
| 264 | variant="outline" |
| 265 | disabled={ |
| 266 | !isHttpUrl(url) || (checks[key]?.url === url && checks[key].result === null) |
| 267 | } |
| 268 | onClick={() => void checkEndpoint(key, signal, url)} |
| 269 | > |
| 270 | <T>Test</T> |
| 271 | </Button> |
| 272 | )} |
| 273 | </div> |
| 274 | {(saved[key] !== (running?.[key] ?? "") || override?.variable) && ( |
| 275 | <p className="break-all text-xs text-muted-foreground"> |
| 276 | {override?.variable ? ( |
| 277 | running?.[key] ? ( |
| 278 | <T> |
| 279 | Running: <Var>{running[key]}</Var> from{" "} |
| 280 | <code className="font-mono"> |
| 281 | <Var>{override.variable}</Var> |
| 282 | </code> |
| 283 | </T> |
| 284 | ) : ( |
| 285 | <T> |
| 286 | Running: Disabled from{" "} |
| 287 | <code className="font-mono"> |
| 288 | <Var>{override.variable}</Var> |
| 289 | </code> |
| 290 | </T> |
| 291 | ) |
| 292 | ) : running?.[key] ? ( |
| 293 | gt("Running: {url}", { url: running[key] }) |
| 294 | ) : ( |
| 295 | gt("Running: Disabled") |
| 296 | )} |
| 297 | </p> |
| 298 | )} |
| 299 | </div> |
| 300 | ); |
| 301 | })} |
| 302 | <div className="flex items-center justify-between gap-3"> |
| 303 | <p role="status" className="text-xs text-muted-foreground"> |
| 304 | {message} |
| 305 | </p> |
| 306 | <div className="flex shrink-0 gap-2"> |
| 307 | <Button |
| 308 | type="button" |
| 309 | size="xs" |
| 310 | variant="outline" |
| 311 | disabled={!changed || saving || !canEdit} |
| 312 | onClick={() => { |
| 313 | setDraft({}); |
| 314 | setMessage(null); |
| 315 | if (!canCheck) return; |
| 316 | for (const descriptor of SIGNALS) { |
| 317 | const { key, signal } = descriptor; |
| 318 | if (runningOverride(running, descriptor)) continue; |
| 319 | if (checks[key]?.url !== saved[key]) checkEndpoint(key, signal, saved[key]); |
| 320 | } |
| 321 | }} |
| 322 | > |
| 323 | <T>Discard</T> |
| 324 | </Button> |
| 325 | <Button type="submit" size="xs" disabled={!changed || saving || !canEdit}> |
| 326 | {saving ? gt("Saving…") : gt("Save")} |
| 327 | </Button> |
| 328 | </div> |
| 329 | </div> |
| 330 | </form> |
| 331 | </SettingsSection> |
| 332 | ); |
| 333 | } |