The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { thrownErrorMessage } from "@t3tools/client-runtime/errors"; |
| 2 | import { m } from "~/i18n/messages"; |
| 3 | import { useAtomValue } from "@effect/atom-react"; |
| 4 | import { useId, useState, type ReactNode } from "react"; |
| 5 | import { |
| 6 | isSecretReference, |
| 7 | type EnvironmentId, |
| 8 | type SettingsSecretValue, |
| 9 | type SimlockDeviceHostConfig, |
| 10 | } from "@t3tools/contracts"; |
| 11 | import * as Cause from "effect/Cause"; |
| 12 | import * as Option from "effect/Option"; |
| 13 | import { AsyncResult, Atom } from "effect/reactivity"; |
| 14 | import { XIcon } from "lucide-react"; |
| 15 | import { T, useGT, useMessages } from "gt-react"; |
| 16 | |
| 17 | import { deviceSimlockIdentityCheck } from "../../state/device"; |
| 18 | import { environmentAtomList, environmentIdsKey } from "../../state/environmentAtomList"; |
| 19 | |
| 20 | import { Button } from "../ui/button"; |
| 21 | import { |
| 22 | Dialog, |
| 23 | DialogDescription, |
| 24 | DialogFooter, |
| 25 | DialogHeader, |
| 26 | DialogPanel, |
| 27 | DialogPopup, |
| 28 | DialogTitle, |
| 29 | } from "../ui/dialog"; |
| 30 | import { Input } from "../ui/input"; |
| 31 | import { Spinner } from "../ui/spinner"; |
| 32 | import { SecretSourceInput, useSecretSources } from "./SecretSourceInput"; |
| 33 | import { |
| 34 | planSimlockDeviceHostSave, |
| 35 | simlockDeviceHostProblem, |
| 36 | type SimlockHostEnvironment, |
| 37 | type SimlockTokenEntry, |
| 38 | } from "./simlockDeviceHostsSettings.logic"; |
| 39 | |
| 40 | const failureMessage = (cause: Cause.Cause<unknown>) => { |
| 41 | const error = Cause.squash(cause); |
| 42 | return error instanceof Error ? (thrownErrorMessage(error, m) ?? error.message) : String(error); |
| 43 | }; |
| 44 | |
| 45 | /** The gateway each environment's own agent-device points at, if any. */ |
| 46 | const machineGatewaysAtom = environmentAtomList("web-simlock-machine-gateways", (environmentId) => |
| 47 | deviceSimlockIdentityCheck({ environmentId, input: {} }), |
| 48 | ); |
| 49 | |
| 50 | const NO_CHECK = Atom.make(AsyncResult.initial()).pipe(Atom.withLabel("simlock-identity:none")); |
| 51 | |
| 52 | /** Shared fields once, then one agent token per environment: Simlock counts leases per token. */ |
| 53 | export function SimlockDeviceHostEditor(props: { |
| 54 | host: SimlockDeviceHostConfig; |
| 55 | isNew: boolean; |
| 56 | environments: ReadonlyArray<SimlockHostEnvironment>; |
| 57 | busy: boolean; |
| 58 | onSave: ( |
| 59 | host: SimlockDeviceHostConfig, |
| 60 | tokens: ReadonlyMap<EnvironmentId, SimlockTokenEntry>, |
| 61 | ) => void; |
| 62 | onClose: () => void; |
| 63 | }) { |
| 64 | const messages = useMessages(); |
| 65 | const gt = useGT(); |
| 66 | const [draft, setDraft] = useState(props.host); |
| 67 | const [urlEdited, setUrlEdited] = useState(false); |
| 68 | const machineGateways = useAtomValue( |
| 69 | machineGatewaysAtom( |
| 70 | environmentIdsKey( |
| 71 | props.isNew ? props.environments.map((environment) => environment.environmentId) : [], |
| 72 | ), |
| 73 | ), |
| 74 | ); |
| 75 | // A new host starts at the gateway an environment's agent-device already uses. |
| 76 | const detectedUrl = machineGateways |
| 77 | .map((result) => Option.getOrUndefined(AsyncResult.value(result))?.gatewayUrl) |
| 78 | .find(Boolean); |
| 79 | const gatewayUrl = urlEdited || draft.gatewayUrl ? draft.gatewayUrl : (detectedUrl ?? ""); |
| 80 | const savedValue = (environment: SimlockHostEnvironment) => |
| 81 | environment.hosts.find((host) => host.id === props.host.id)?.agentToken ?? ""; |
| 82 | const savedToken = (environment: SimlockHostEnvironment) => savedValue(environment) !== ""; |
| 83 | const [tokens, setTokens] = useState<ReadonlyMap<EnvironmentId, SimlockTokenEntry>>( |
| 84 | () => |
| 85 | new Map( |
| 86 | props.environments.map((environment) => [ |
| 87 | environment.environmentId, |
| 88 | savedToken(environment) ? { kind: "saved" } : { kind: "cleared" }, |
| 89 | ]), |
| 90 | ), |
| 91 | ); |
| 92 | const next: SimlockDeviceHostConfig = { |
| 93 | ...draft, |
| 94 | label: draft.label.trim(), |
| 95 | gatewayUrl: gatewayUrl.trim(), |
| 96 | }; |
| 97 | const checkUrl = simlockDeviceHostProblem(next) === null ? next.gatewayUrl : null; |
| 98 | // Environments whose token field holds a secret reference that cannot be saved yet. |
| 99 | const [invalidTokens, setInvalidTokens] = useState<ReadonlySet<EnvironmentId>>(new Set()); |
| 100 | const plan = planSimlockDeviceHostSave(props.environments, next, tokens, messages); |
| 101 | const problem = |
| 102 | "problem" in plan |
| 103 | ? plan.problem |
| 104 | : invalidTokens.size > 0 |
| 105 | ? gt("Enter a valid secret reference.") |
| 106 | : null; |
| 107 | const several = props.environments.length > 1; |
| 108 | |
| 109 | const limit = ( |
| 110 | field: "maxLeases" | "maxLeaseMinutes", |
| 111 | label: string, |
| 112 | min: number, |
| 113 | max: number, |
| 114 | ) => ( |
| 115 | <label className="block space-y-1.5"> |
| 116 | <span>{label}</span> |
| 117 | <Input |
| 118 | type="number" |
| 119 | min={min} |
| 120 | max={max} |
| 121 | value={draft[field]} |
| 122 | disabled={props.busy} |
| 123 | onChange={(event) => { |
| 124 | const value = Number(event.target.value); |
| 125 | setDraft((current) => ({ ...current, [field]: value })); |
| 126 | }} |
| 127 | /> |
| 128 | </label> |
| 129 | ); |
| 130 | |
| 131 | return ( |
| 132 | <Dialog |
| 133 | open |
| 134 | onOpenChange={(open) => { |
| 135 | if (!open && !props.busy) props.onClose(); |
| 136 | }} |
| 137 | > |
| 138 | <DialogPopup showCloseButton={!props.busy}> |
| 139 | <form |
| 140 | className="flex min-h-0 flex-col" |
| 141 | onSubmit={(event) => { |
| 142 | event.preventDefault(); |
| 143 | if (problem === null && !props.busy) props.onSave(next, tokens); |
| 144 | }} |
| 145 | > |
| 146 | <DialogHeader> |
| 147 | <DialogTitle> |
| 148 | {props.isNew ? gt("Add Simlock host") : gt("Edit Simlock host")} |
| 149 | </DialogTitle> |
| 150 | <DialogDescription> |
| 151 | {several |
| 152 | ? gt( |
| 153 | "Each selected environment's server leases devices from your Simlock gateway with its own agent token, and releases them when they close.", |
| 154 | ) |
| 155 | : gt( |
| 156 | "The environment's server leases devices from your Simlock gateway and releases them when they close.", |
| 157 | )} |
| 158 | </DialogDescription> |
| 159 | </DialogHeader> |
| 160 | <DialogPanel> |
| 161 | <label className="block space-y-1.5 text-sm"> |
| 162 | <span> |
| 163 | <T>Name</T> |
| 164 | </span> |
| 165 | <Input |
| 166 | autoFocus |
| 167 | required |
| 168 | value={draft.label} |
| 169 | disabled={props.busy} |
| 170 | onChange={(event) => { |
| 171 | const label = event.target.value; |
| 172 | setDraft((current) => ({ ...current, label })); |
| 173 | }} |
| 174 | /> |
| 175 | </label> |
| 176 | <label className="block space-y-1.5 text-sm"> |
| 177 | <span> |
| 178 | <T>Gateway URL</T> |
| 179 | </span> |
| 180 | <Input |
| 181 | required |
| 182 | type="url" |
| 183 | placeholder="https://gateway.example.ts.net:4700" |
| 184 | value={gatewayUrl} |
| 185 | disabled={props.busy} |
| 186 | onChange={(event) => { |
| 187 | const gatewayUrl = event.target.value; |
| 188 | setUrlEdited(true); |
| 189 | setDraft((current) => ({ ...current, gatewayUrl })); |
| 190 | }} |
| 191 | /> |
| 192 | </label> |
| 193 | <div className="space-y-3"> |
| 194 | {props.environments.map((environment) => ( |
| 195 | <SimlockTokenField |
| 196 | key={environment.environmentId} |
| 197 | environmentId={environment.environmentId} |
| 198 | hostId={props.isNew ? null : props.host.id} |
| 199 | gatewayUrl={checkUrl} |
| 200 | label={ |
| 201 | several |
| 202 | ? gt("Agent token · {label}", { label: environment.label }) |
| 203 | : gt("Agent token") |
| 204 | } |
| 205 | token={tokens.get(environment.environmentId) ?? { kind: "cleared" }} |
| 206 | saved={savedValue(environment)} |
| 207 | busy={props.busy} |
| 208 | onChange={(token) => |
| 209 | setTokens((current) => new Map(current).set(environment.environmentId, token)) |
| 210 | } |
| 211 | onValidityChange={(valid) => |
| 212 | setInvalidTokens((current) => { |
| 213 | const nextInvalid = new Set(current); |
| 214 | if (valid) nextInvalid.delete(environment.environmentId); |
| 215 | else nextInvalid.add(environment.environmentId); |
| 216 | return nextInvalid; |
| 217 | }) |
| 218 | } |
| 219 | /> |
| 220 | ))} |
| 221 | <p className="text-xs text-muted-foreground"> |
| 222 | {several ? ( |
| 223 | <T> |
| 224 | Leases, drives, and streams devices. Create one per environment with{" "} |
| 225 | <code>simlock --gateway token create --role agent</code>, or leave it blank to |
| 226 | add it later. A blank token uses the machine's{" "} |
| 227 | <code>AGENT_DEVICE_DAEMON_AUTH_TOKEN</code> when its{" "} |
| 228 | <code>AGENT_DEVICE_DAEMON_BASE_URL</code> is this gateway. |
| 229 | </T> |
| 230 | ) : ( |
| 231 | <T> |
| 232 | Leases, drives, and streams devices. Create one with{" "} |
| 233 | <code>simlock --gateway token create --role agent</code>, or leave it blank to |
| 234 | add it later. A blank token uses the machine's{" "} |
| 235 | <code>AGENT_DEVICE_DAEMON_AUTH_TOKEN</code> when its{" "} |
| 236 | <code>AGENT_DEVICE_DAEMON_BASE_URL</code> is this gateway. |
| 237 | </T> |
| 238 | )} |
| 239 | </p> |
| 240 | </div> |
| 241 | <div className="grid grid-cols-2 gap-3 text-sm"> |
| 242 | {limit("maxLeases", gt("Devices at once"), 1, 20)} |
| 243 | {limit("maxLeaseMinutes", gt("Lease minutes"), 5, 240)} |
| 244 | </div> |
| 245 | <p className="text-xs text-muted-foreground"> |
| 246 | {props.isNew |
| 247 | ? gt("A lease ends after the lease minutes even while in use.") |
| 248 | : gt( |
| 249 | "A lease ends after the lease minutes even while in use. Saving restarts this host, which releases its devices.", |
| 250 | )} |
| 251 | </p> |
| 252 | {problem === null || !gatewayUrl ? null : ( |
| 253 | <p className="text-xs text-destructive" role="alert"> |
| 254 | {problem} |
| 255 | </p> |
| 256 | )} |
| 257 | </DialogPanel> |
| 258 | <DialogFooter> |
| 259 | <Button type="button" variant="ghost" disabled={props.busy} onClick={props.onClose}> |
| 260 | <T>Cancel</T> |
| 261 | </Button> |
| 262 | <Button type="submit" disabled={props.busy || problem !== null}> |
| 263 | {props.busy ? <Spinner size="xs" /> : null} <T>Save host</T> |
| 264 | </Button> |
| 265 | </DialogFooter> |
| 266 | </form> |
| 267 | </DialogPopup> |
| 268 | </Dialog> |
| 269 | ); |
| 270 | } |
| 271 | |
| 272 | function SimlockTokenField(props: { |
| 273 | environmentId: EnvironmentId; |
| 274 | hostId: string | null; |
| 275 | gatewayUrl: string | null; |
| 276 | label: ReactNode; |
| 277 | token: SimlockTokenEntry; |
| 278 | /** This environment's saved token: redacted when a literal, shown when a secret reference. */ |
| 279 | saved: SettingsSecretValue; |
| 280 | busy: boolean; |
| 281 | onChange: (token: SimlockTokenEntry) => void; |
| 282 | onValidityChange: (valid: boolean) => void; |
| 283 | }) { |
| 284 | const gt = useGT(); |
| 285 | const id = useId(); |
| 286 | const sources = useSecretSources(props.environmentId); |
| 287 | const [inputKey, setInputKey] = useState(0); |
| 288 | // Emptying the field or leaving a reference returns to a saved literal, never to a saved reference. |
| 289 | const savedLiteral = typeof props.saved === "string" && props.saved !== ""; |
| 290 | const entered = |
| 291 | props.token.kind !== "new" |
| 292 | ? "" |
| 293 | : typeof props.token.value === "string" |
| 294 | ? props.token.value.trim() |
| 295 | : props.token.value; |
| 296 | // A cleared field asks about the machine's own token, which a blank one falls back to. |
| 297 | const check = useAtomValue( |
| 298 | props.gatewayUrl === null |
| 299 | ? NO_CHECK |
| 300 | : deviceSimlockIdentityCheck({ |
| 301 | environmentId: props.environmentId, |
| 302 | input: { |
| 303 | gatewayUrl: props.gatewayUrl, |
| 304 | ...(entered |
| 305 | ? { agentToken: entered } |
| 306 | : props.token.kind === "saved" && props.hostId !== null |
| 307 | ? { hostId: props.hostId } |
| 308 | : {}), |
| 309 | }, |
| 310 | }), |
| 311 | ); |
| 312 | const identity = AsyncResult.isSuccess(check) ? check.value : null; |
| 313 | const status = |
| 314 | props.gatewayUrl === null ? null : check._tag === "Initial" || check.waiting ? ( |
| 315 | <span className="text-muted-foreground"> |
| 316 | <T>Checking…</T> |
| 317 | </span> |
| 318 | ) : identity ? ( |
| 319 | <span className="text-muted-foreground"> |
| 320 | {identity.tokenSource === "env" |
| 321 | ? gt("Using this machine's agent-device token ({signedInAs}).", { |
| 322 | signedInAs: identity.signedInAs, |
| 323 | }) |
| 324 | : gt("Accepted as {signedInAs}.", { signedInAs: identity.signedInAs })} |
| 325 | </span> |
| 326 | ) : AsyncResult.isFailure(check) ? ( |
| 327 | <span |
| 328 | className={props.token.kind === "cleared" ? "text-muted-foreground" : "text-destructive"} |
| 329 | > |
| 330 | {failureMessage(check.cause)} |
| 331 | </span> |
| 332 | ) : null; |
| 333 | return ( |
| 334 | <div className="space-y-1.5 text-sm"> |
| 335 | <label htmlFor={id} className="block"> |
| 336 | {props.label} |
| 337 | </label> |
| 338 | <div className="flex items-center gap-2"> |
| 339 | <SecretSourceInput |
| 340 | key={inputKey} |
| 341 | id={id} |
| 342 | aria-label={gt("Agent token")} |
| 343 | environmentId={props.environmentId} |
| 344 | className="min-w-0 flex-1" |
| 345 | configured={props.token.kind === "saved" && typeof props.saved === "string"} |
| 346 | value={ |
| 347 | props.token.kind === "new" |
| 348 | ? props.token.value |
| 349 | : props.token.kind === "saved" && isSecretReference(props.saved) |
| 350 | ? props.saved |
| 351 | : "" |
| 352 | } |
| 353 | sources={sources} |
| 354 | onValidityChange={props.onValidityChange} |
| 355 | onSecretChange={(secret) => |
| 356 | props.onChange( |
| 357 | secret |
| 358 | ? { kind: "new", value: secret } |
| 359 | : savedLiteral |
| 360 | ? { kind: "saved" } |
| 361 | : { kind: "cleared" }, |
| 362 | ) |
| 363 | } |
| 364 | disabled={props.busy} |
| 365 | onChange={(event) => { |
| 366 | const value = event.target.value; |
| 367 | // Emptying the field is not clearing the saved token; the Clear button is. |
| 368 | props.onChange( |
| 369 | value |
| 370 | ? { kind: "new", value } |
| 371 | : savedLiteral |
| 372 | ? { kind: "saved" } |
| 373 | : { kind: "cleared" }, |
| 374 | ); |
| 375 | }} |
| 376 | /> |
| 377 | {props.token.kind !== "cleared" ? ( |
| 378 | <Button |
| 379 | type="button" |
| 380 | size="icon-sm" |
| 381 | variant="ghost-destructive" |
| 382 | aria-label={gt("Clear agent token")} |
| 383 | disabled={props.busy} |
| 384 | onClick={() => { |
| 385 | props.onChange({ kind: "cleared" }); |
| 386 | props.onValidityChange(true); |
| 387 | setInputKey((key) => key + 1); |
| 388 | }} |
| 389 | > |
| 390 | <XIcon className="size-3.5" /> |
| 391 | </Button> |
| 392 | ) : null} |
| 393 | </div> |
| 394 | {status ? <p className="text-xs">{status}</p> : null} |
| 395 | </div> |
| 396 | ); |
| 397 | } |