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 { managedCapabilityDenial } from "@t3tools/client-runtime/contract-labels"; |
| 3 | import { useAtomValue } from "@effect/atom-react"; |
| 4 | import { connectionStatusTitle } from "@t3tools/client-runtime/connection"; |
| 5 | import { AsyncResult } from "effect/reactivity"; |
| 6 | import { |
| 7 | ChevronDownIcon, |
| 8 | Clock3Icon, |
| 9 | CopyIcon, |
| 10 | InboxIcon, |
| 11 | MessageSquareIcon, |
| 12 | MoreHorizontalIcon, |
| 13 | PencilIcon, |
| 14 | PlayIcon, |
| 15 | PlusIcon, |
| 16 | Trash2Icon, |
| 17 | } from "lucide-react"; |
| 18 | import { type ReactNode, useRef, useState } from "react"; |
| 19 | import type { |
| 20 | EnvironmentId, |
| 21 | ModelSelection, |
| 22 | OrchestrationV2ThreadLaunchWorkspaceStrategy, |
| 23 | ProjectId, |
| 24 | ScheduledTask, |
| 25 | ScheduledTaskId, |
| 26 | ScheduledTaskThreadMode, |
| 27 | ScheduledTaskUpsertInput, |
| 28 | ScheduledTaskWebhookDeliverySummary, |
| 29 | ThreadId, |
| 30 | } from "@t3tools/contracts"; |
| 31 | import { |
| 32 | DEFAULT_WEBHOOK_PROMPT, |
| 33 | emptyWebhookFilterDraft, |
| 34 | parseWebhookFilterDrafts, |
| 35 | removeWebhookFilterDraft, |
| 36 | WEBHOOK_FILTER_OPS, |
| 37 | type WebhookFilterDraft, |
| 38 | } from "@t3tools/client-runtime/scheduled-task-webhook"; |
| 39 | import { scheduleTimeZoneLabel } from "@t3tools/client-runtime/scheduled-task-time-zone"; |
| 40 | import { scheduledTaskWorktreeBaseRef } from "@t3tools/client-runtime/scheduled-task-worktree"; |
| 41 | import { |
| 42 | MAX_WEBHOOK_DELIVERY_AGE_MINUTES, |
| 43 | MAX_WEBHOOK_FILTERS, |
| 44 | MIN_SCHEDULED_TASK_INTERVAL_MS, |
| 45 | ProviderInstanceId, |
| 46 | resolveEnvironmentMachineKind, |
| 47 | scheduledTaskThreadMode, |
| 48 | } from "@t3tools/contracts"; |
| 49 | import { |
| 50 | isAtomCommandInterrupted, |
| 51 | squashAtomCommandFailure, |
| 52 | } from "@t3tools/client-runtime/state/runtime"; |
| 53 | import { msg, T, useGT, useLocale, useMessages, Var } from "gt-react"; |
| 54 | import { m, type MessageResolver } from "../../i18n/messages"; |
| 55 | |
| 56 | import { formatRelativeTime } from "../../timestampFormat"; |
| 57 | import { useEnvironmentSettings } from "../../hooks/useSettings"; |
| 58 | import { getCustomModelOptionsByInstance } from "../../modelSelection"; |
| 59 | import { providerInstanceEntriesFor } from "../../providerInstances"; |
| 60 | import { usePrimaryCloudLinkState } from "../../cloud/cloudLinkState"; |
| 61 | import { requestConfirmDialog } from "../../confirmDialog"; |
| 62 | import { webhookAddress } from "@t3tools/client-runtime/webhook-address"; |
| 63 | import { Link, useNavigate } from "@tanstack/react-router"; |
| 64 | import { useCopyToClipboard } from "../../hooks/useCopyToClipboard"; |
| 65 | import { useNowMinute } from "../../hooks/useNowMinute"; |
| 66 | import { |
| 67 | useEnvironment, |
| 68 | useEnvironmentHttpBaseUrl, |
| 69 | type EnvironmentPresentation, |
| 70 | } from "../../state/environments"; |
| 71 | import { |
| 72 | useProjects, |
| 73 | useQuietThreadShell, |
| 74 | useThreadShell, |
| 75 | useVisibleThreadShells, |
| 76 | } from "../../state/entities"; |
| 77 | import { buildThreadRouteParams } from "../../threadRoutes"; |
| 78 | import { scopeThreadRef } from "@t3tools/client-runtime/environment"; |
| 79 | import { environmentAtomList, environmentIdsKey } from "../../state/environmentAtomList"; |
| 80 | import { usePaginatedBranches, useThreadSearch } from "../../state/queries"; |
| 81 | import { formatEnvironmentQueryError, useEnvironmentQuery } from "../../state/query"; |
| 82 | import { EMPTY_SERVER_PROVIDERS, serverEnvironment } from "../../state/server"; |
| 83 | import { threadFamilies } from "../../state/threads"; |
| 84 | import { useAtomCommand } from "../../state/use-atom-command"; |
| 85 | import { WorktreeBaseBranchPicker } from "../WorktreeBaseBranchPicker"; |
| 86 | import { EnvironmentMachineIcon } from "../EnvironmentMachineIcon"; |
| 87 | import { ConnectionStatusDot, connectionPhaseDotClassName } from "../ConnectionStatusDot"; |
| 88 | import { AuthOrchestrationOperateScope, clampManagedRuntimeMode } from "@t3tools/contracts"; |
| 89 | import { resolvePastedPath } from "@t3tools/shared/path"; |
| 90 | import { useManagedPolicy } from "~/state/managedPolicy"; |
| 91 | import { ManagedNotice } from "../ManagedPolicy"; |
| 92 | import { readEnvironmentScope } from "~/state/session"; |
| 93 | import { useSettingsScope } from "./SettingsScopeContext"; |
| 94 | import { EnvironmentRow, useEnvironmentTransportLabel } from "./EnvironmentRow"; |
| 95 | import { SettingsGroup } from "./SettingsGroup"; |
| 96 | import { settingsScopeEnvironmentLabel, settingsScopeEnvironmentLabels } from "./settingsScopeAxis"; |
| 97 | import { |
| 98 | WEBHOOK_SIGNATURE_DEFAULTS, |
| 99 | changeDraftProject, |
| 100 | moveDraftToThread, |
| 101 | scheduleDraftErrors, |
| 102 | scheduledTaskDestinationThreads, |
| 103 | toDateTimeLocalValue, |
| 104 | webhookDeliveryLabel, |
| 105 | defaultScheduledTaskProjectId, |
| 106 | matchesScheduledTaskScope, |
| 107 | scheduleFromDraft, |
| 108 | scheduleLabel, |
| 109 | scheduledTaskDefaultModel, |
| 110 | weekdayShortLabel, |
| 111 | taskToDraft, |
| 112 | unbindDraftFromThread, |
| 113 | type DraftState, |
| 114 | type ScheduleMode, |
| 115 | type WorkspaceMode, |
| 116 | } from "./scheduledTasksSettings.logic"; |
| 117 | import { Label } from "../ui/label"; |
| 118 | import { Menu, MenuTrigger, MenuPopup, MenuItem, MenuSeparator } from "../ui/menu"; |
| 119 | import { ToggleGroup, Toggle } from "../ui/toggle-group"; |
| 120 | import { Empty, EmptyHeader, EmptyTitle, EmptyDescription, EmptyMedia } from "../ui/empty"; |
| 121 | import { ProviderModelPicker } from "../chat/ProviderModelPicker"; |
| 122 | import { Badge } from "../ui/badge"; |
| 123 | import { Button } from "../ui/button"; |
| 124 | import { |
| 125 | Combobox, |
| 126 | ComboboxEmpty, |
| 127 | ComboboxItem, |
| 128 | ComboboxList, |
| 129 | ComboboxPopup, |
| 130 | ComboboxSearchInput, |
| 131 | ComboboxTrigger, |
| 132 | } from "../ui/combobox"; |
| 133 | import { |
| 134 | Dialog, |
| 135 | DialogClose, |
| 136 | DialogDescription, |
| 137 | DialogFooter, |
| 138 | DialogHeader, |
| 139 | DialogPanel, |
| 140 | DialogPopup, |
| 141 | DialogTitle, |
| 142 | } from "../ui/dialog"; |
| 143 | import { Input } from "../ui/input"; |
| 144 | import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select"; |
| 145 | import { Switch } from "../ui/switch"; |
| 146 | import { Textarea } from "../ui/textarea"; |
| 147 | import { stackedThreadToast, toastManager } from "../ui/toast"; |
| 148 | import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; |
| 149 | import { useSearchableSetting } from "./settingsSearch"; |
| 150 | import { |
| 151 | SettingsPageContainer, |
| 152 | SettingsRow, |
| 153 | SettingsSection, |
| 154 | SETTINGS_PICKER_TRIGGER_CLASSNAME, |
| 155 | } from "./settingsLayout"; |
| 156 | |
| 157 | const WEEKDAY_ORDER = [1, 2, 3, 4, 5, 6, 0] as const; |
| 158 | const WEEKDAY_SHORT = [ |
| 159 | msg("Su", { $context: "two-letter Sunday" }), |
| 160 | msg("Mo", { $context: "two-letter Monday" }), |
| 161 | msg("Tu", { $context: "two-letter Tuesday" }), |
| 162 | msg("We", { $context: "two-letter Wednesday" }), |
| 163 | msg("Th", { $context: "two-letter Thursday" }), |
| 164 | msg("Fr", { $context: "two-letter Friday" }), |
| 165 | msg("Sa", { $context: "two-letter Saturday" }), |
| 166 | ] as const; |
| 167 | |
| 168 | // Thread ids are trimmed, so the leading space keeps this from matching one. |
| 169 | const NEW_THREAD_DESTINATION = " new-thread"; |
| 170 | |
| 171 | const WORKSPACE_MODE_LABELS: Record<WorkspaceMode, string> = { |
| 172 | worktree: msg("Create a new worktree"), |
| 173 | root: msg("Use the project checkout"), |
| 174 | existing_worktree: msg("Use a specific checkout"), |
| 175 | }; |
| 176 | |
| 177 | const SCOPE_SUMMARY_TEMPLATES: Record<string, string> = { |
| 178 | "Not connected:": msg("Not connected: {environments}"), |
| 179 | "Loading scheduled tasks on": msg("Loading scheduled tasks on {environments}"), |
| 180 | "Could not load scheduled tasks:": msg("Could not load scheduled tasks: {environments}"), |
| 181 | "No tasks on": msg("No tasks on {environments}"), |
| 182 | }; |
| 183 | |
| 184 | const EMPTY_DRAFT: DraftState = { |
| 185 | editingId: null, |
| 186 | title: "", |
| 187 | prompt: "", |
| 188 | enabled: true, |
| 189 | scheduleMode: "fixed", |
| 190 | intervalMinutes: "15", |
| 191 | timeOfDay: "09:00", |
| 192 | runAt: "", |
| 193 | savedRunAt: "", |
| 194 | weekdays: new Set([1, 2, 3, 4, 5]), |
| 195 | projectId: "", |
| 196 | threadId: "", |
| 197 | savedThreadId: "", |
| 198 | threadMode: "new_thread", |
| 199 | workspaceMode: "worktree", |
| 200 | baseRef: "", |
| 201 | startFromOrigin: true, |
| 202 | existingWorktreePath: "", |
| 203 | modelKey: "", |
| 204 | runtimeMode: "full-access", |
| 205 | interactionMode: "default", |
| 206 | baseModelSelection: null, |
| 207 | signatureEnabled: false, |
| 208 | ...WEBHOOK_SIGNATURE_DEFAULTS, |
| 209 | signatureSecret: "", |
| 210 | maxDeliveryAgeMinutes: "", |
| 211 | replayKey: "", |
| 212 | coalesceKey: "", |
| 213 | coalesceWindowSeconds: "", |
| 214 | filters: [], |
| 215 | savedFilters: [], |
| 216 | }; |
| 217 | |
| 218 | function WebhookFiltersField({ |
| 219 | filters, |
| 220 | onChange, |
| 221 | }: { |
| 222 | filters: ReadonlyArray<WebhookFilterDraft>; |
| 223 | onChange: (filters: ReadonlyArray<WebhookFilterDraft>) => void; |
| 224 | }) { |
| 225 | const gt = useGT(); |
| 226 | const messages = useMessages(); |
| 227 | const update = (index: number, patch: Partial<WebhookFilterDraft>) => |
| 228 | onChange(filters.map((filter, at) => (at === index ? { ...filter, ...patch } : filter))); |
| 229 | return ( |
| 230 | <div className="space-y-2"> |
| 231 | <div className="flex items-center justify-between gap-2"> |
| 232 | <div className="min-w-0 space-y-1"> |
| 233 | <Label> |
| 234 | <T>Filters</T> |
| 235 | </Label> |
| 236 | <p className="text-sm text-muted-foreground"> |
| 237 | <T> |
| 238 | Run only when every filter matches. Other requests are logged as filtered. Separate |
| 239 | “is one of” values with commas; a value can't contain a comma. |
| 240 | </T> |
| 241 | </p> |
| 242 | </div> |
| 243 | <Button |
| 244 | className="shrink-0" |
| 245 | variant="outline" |
| 246 | size="sm" |
| 247 | disabled={filters.length >= MAX_WEBHOOK_FILTERS} |
| 248 | onClick={() => onChange([...filters, emptyWebhookFilterDraft()])} |
| 249 | > |
| 250 | <PlusIcon /> |
| 251 | <T>Add filter</T> |
| 252 | </Button> |
| 253 | </div> |
| 254 | {filters.map((filter, index) => ( |
| 255 | // Always stacked: the dialog stays narrow on wide windows, so a single line |
| 256 | // would cut off typical paths and values. The grid wrappers size each control |
| 257 | // without restyling it; a grid item stretches to its minmax(0, 1fr) track. |
| 258 | <div key={filter.id} className="space-y-2 pt-1"> |
| 259 | <div className="flex items-center gap-2"> |
| 260 | <div className="grid min-w-0 flex-1 grid-cols-1"> |
| 261 | <Input |
| 262 | aria-label={gt("Filter {number} path", { number: index + 1 })} |
| 263 | placeholder="body.action" |
| 264 | value={filter.path} |
| 265 | onChange={(event) => update(index, { path: event.target.value })} |
| 266 | /> |
| 267 | </div> |
| 268 | <Button |
| 269 | variant="ghost" |
| 270 | size="icon-sm" |
| 271 | aria-label={gt("Remove filter {number}", { number: index + 1 })} |
| 272 | onClick={() => onChange(removeWebhookFilterDraft(filters, filter.id))} |
| 273 | > |
| 274 | <Trash2Icon /> |
| 275 | </Button> |
| 276 | </div> |
| 277 | <div className="flex items-center gap-2"> |
| 278 | <Select |
| 279 | value={filter.op} |
| 280 | onValueChange={(op) => { |
| 281 | const known = WEBHOOK_FILTER_OPS.find((option) => option.op === op); |
| 282 | if (known) update(index, { op: known.op }); |
| 283 | }} |
| 284 | > |
| 285 | <div className="grid w-44 shrink-0 grid-cols-1"> |
| 286 | <SelectTrigger |
| 287 | size="sm" |
| 288 | aria-label={gt("Filter {number} test", { number: index + 1 })} |
| 289 | > |
| 290 | <SelectValue> |
| 291 | {messages(WEBHOOK_FILTER_OPS.find((option) => option.op === filter.op)?.label)} |
| 292 | </SelectValue> |
| 293 | </SelectTrigger> |
| 294 | </div> |
| 295 | <SelectPopup> |
| 296 | {WEBHOOK_FILTER_OPS.map((option) => ( |
| 297 | <SelectItem key={option.op} value={option.op}> |
| 298 | {messages(option.label)} |
| 299 | </SelectItem> |
| 300 | ))} |
| 301 | </SelectPopup> |
| 302 | </Select> |
| 303 | {filter.op === "exists" ? null : ( |
| 304 | <div className="grid min-w-0 flex-1 grid-cols-1"> |
| 305 | <Input |
| 306 | aria-label={gt("Filter {number} value", { number: index + 1 })} |
| 307 | // oxlint-disable-next-line t3code/no-untranslated-copy -- webhook action values, matched literally |
| 308 | placeholder={filter.op === "in" ? "opened, reopened" : "opened"} |
| 309 | value={filter.value} |
| 310 | onChange={(event) => update(index, { value: event.target.value })} |
| 311 | /> |
| 312 | </div> |
| 313 | )} |
| 314 | </div> |
| 315 | </div> |
| 316 | ))} |
| 317 | </div> |
| 318 | ); |
| 319 | } |
| 320 | |
| 321 | function Field({ |
| 322 | label, |
| 323 | hint, |
| 324 | htmlFor, |
| 325 | children, |
| 326 | }: { |
| 327 | label: string; |
| 328 | hint?: string; |
| 329 | htmlFor?: string; |
| 330 | children: ReactNode; |
| 331 | }) { |
| 332 | return ( |
| 333 | <div className="space-y-1.5"> |
| 334 | <Label className="flex items-baseline justify-between" htmlFor={htmlFor}> |
| 335 | <span>{label}</span> |
| 336 | {hint ? ( |
| 337 | <span className="font-normal text-2xs text-muted-foreground/80">{hint}</span> |
| 338 | ) : null} |
| 339 | </Label> |
| 340 | {children} |
| 341 | </div> |
| 342 | ); |
| 343 | } |
| 344 | |
| 345 | function splitModelKey(value: string): ModelSelection | null { |
| 346 | const index = value.indexOf(":"); |
| 347 | if (index <= 0 || index === value.length - 1) return null; |
| 348 | return { |
| 349 | instanceId: ProviderInstanceId.make(value.slice(0, index)), |
| 350 | model: value.slice(index + 1), |
| 351 | }; |
| 352 | } |
| 353 | |
| 354 | /** formatRelativeTime handles only the past; upcoming runs need future labels. */ |
| 355 | function relativeLabel(value: string | null, nowMs: number, resolve: MessageResolver = m): string { |
| 356 | if (!value) return resolve(msg("Not scheduled")); |
| 357 | const diffMs = new Date(value).getTime() - nowMs; |
| 358 | if (diffMs <= 0) { |
| 359 | const relative = formatRelativeTime(value, nowMs, resolve); |
| 360 | if (!relative) return resolve(msg("Not scheduled")); |
| 361 | return relative.label; |
| 362 | } |
| 363 | const minutes = Math.ceil(diffMs / 60_000); |
| 364 | if (minutes < 2) return resolve(msg("in under a minute")); |
| 365 | if (minutes < 60) return resolve(msg("in {minutes}m", { minutes })); |
| 366 | const hours = Math.round(minutes / 60); |
| 367 | if (hours < 24) return resolve(msg("in {hours}h", { hours })); |
| 368 | return resolve(msg("in {days}d", { days: Math.round(hours / 24) })); |
| 369 | } |
| 370 | |
| 371 | // Use the label's minute tick because the compiler caches render-time Date.now() on the timestamp. |
| 372 | export function ScheduledRelativeLabel(props: { value: string | null }) { |
| 373 | const messages = useMessages(); |
| 374 | const nowMinute = useNowMinute(); |
| 375 | return relativeLabel(props.value, Date.parse(`${nowMinute}:00.000Z`), messages); |
| 376 | } |
| 377 | |
| 378 | function deliveryOutcomeVariant(outcome: string) { |
| 379 | if (outcome === "accepted") return "success"; |
| 380 | if ( |
| 381 | outcome === "duplicate" || |
| 382 | outcome === "coalesced" || |
| 383 | outcome === "disabled" || |
| 384 | outcome === "rate_limited" || |
| 385 | outcome === "expired" |
| 386 | ) { |
| 387 | return "warning"; |
| 388 | } |
| 389 | if (outcome === "dispatch_failed" || outcome === "rejected_signature") return "error"; |
| 390 | return "outline"; |
| 391 | } |
| 392 | |
| 393 | const RUN_STATUS_LABELS: Record<ScheduledTask["lastRunStatus"], string> = { |
| 394 | never: msg("Never run"), |
| 395 | running: msg("Running", { $context: "scheduled task run status" }), |
| 396 | succeeded: msg("Succeeded"), |
| 397 | failed: msg("Failed", { $context: "scheduled task run status" }), |
| 398 | }; |
| 399 | |
| 400 | function statusVariant(status: ScheduledTask["lastRunStatus"]) { |
| 401 | if (status === "failed") return "error"; |
| 402 | if (status === "succeeded") return "success"; |
| 403 | if (status === "running") return "info"; |
| 404 | return "outline"; |
| 405 | } |
| 406 | |
| 407 | export function ScheduledTasksSettings(target: { |
| 408 | readonly environmentId?: EnvironmentId; |
| 409 | readonly taskId?: ScheduledTaskId | undefined; |
| 410 | }) { |
| 411 | const setting = useSearchableSetting(); |
| 412 | const gt = useGT(); |
| 413 | const { scope, environments, connectedEnvironments, environment } = useSettingsScope(); |
| 414 | const [editor, setEditor] = useState<{ |
| 415 | environmentId: EnvironmentId; |
| 416 | task: ScheduledTask | null; |
| 417 | } | null>(null); |
| 418 | const openForEdit = (environmentId: EnvironmentId, task: ScheduledTask) => { |
| 419 | setEditor({ environmentId, task }); |
| 420 | }; |
| 421 | const defaultEnvironment = environment ?? connectedEnvironments[0]; |
| 422 | const linkedEnvironmentId = target.environmentId ?? defaultEnvironment?.environmentId; |
| 423 | const linkedEnvironmentConnected = environments.some( |
| 424 | (entry) => |
| 425 | entry.environmentId === linkedEnvironmentId && |
| 426 | entry.connection.phase === "connected" && |
| 427 | entry.serverConfig !== null, |
| 428 | ); |
| 429 | const linkedTasksQuery = useEnvironmentQuery( |
| 430 | target.taskId !== undefined && linkedEnvironmentId !== undefined && linkedEnvironmentConnected |
| 431 | ? serverEnvironment.scheduledTasksLive({ environmentId: linkedEnvironmentId, input: {} }) |
| 432 | : null, |
| 433 | ); |
| 434 | const linkedTask = linkedTasksQuery.data?.tasks.find( |
| 435 | (task) => |
| 436 | task.id === target.taskId && |
| 437 | linkedEnvironmentId !== undefined && |
| 438 | matchesScheduledTaskScope(scope, linkedEnvironmentId, task.projectId), |
| 439 | ); |
| 440 | // A `taskId` link opens its editor once, the first time the task loads. The editor then owns |
| 441 | // the session until close, so a disconnect that disables the query cannot drop unsaved edits. |
| 442 | // An editor the user already opened wins: a late-loading link must not replace its draft. |
| 443 | const [openedLinkTaskId, setOpenedLinkTaskId] = useState<ScheduledTaskId | undefined>(); |
| 444 | if (target.taskId === undefined && openedLinkTaskId !== undefined) { |
| 445 | setOpenedLinkTaskId(undefined); |
| 446 | } |
| 447 | if (linkedTask && linkedEnvironmentId !== undefined && openedLinkTaskId !== target.taskId) { |
| 448 | setOpenedLinkTaskId(target.taskId); |
| 449 | if (editor === null) setEditor({ environmentId: linkedEnvironmentId, task: linkedTask }); |
| 450 | } |
| 451 | const navigate = useNavigate({ from: "/settings/scheduled-tasks" }); |
| 452 | const closeEditor = () => { |
| 453 | setEditor(null); |
| 454 | if (target.taskId === undefined) return; |
| 455 | void navigate({ |
| 456 | to: "/settings/scheduled-tasks", |
| 457 | search: ({ taskId: _closed, ...rest }) => rest, |
| 458 | replace: true, |
| 459 | }); |
| 460 | }; |
| 461 | const createPermissions = useAtomValue( |
| 462 | scheduledTaskCreatePermissionsAtom( |
| 463 | environmentIdsKey(connectedEnvironments.map((entry) => entry.environmentId)), |
| 464 | ), |
| 465 | ); |
| 466 | const permittedEnvironments = connectedEnvironments.filter( |
| 467 | (_entry, index) => createPermissions[index], |
| 468 | ); |
| 469 | const creationEnvironment = |
| 470 | permittedEnvironments.find( |
| 471 | (entry) => entry.environmentId === defaultEnvironment?.environmentId, |
| 472 | ) ?? permittedEnvironments[0]; |
| 473 | return ( |
| 474 | <SettingsPageContainer> |
| 475 | <SettingsSection |
| 476 | {...setting("scheduled-tasks")} |
| 477 | variant="plain" |
| 478 | headerAction={ |
| 479 | <Button |
| 480 | size="xs" |
| 481 | variant="ghost-muted" |
| 482 | disabled={!creationEnvironment} |
| 483 | onClick={() => |
| 484 | creationEnvironment && |
| 485 | setEditor({ environmentId: creationEnvironment.environmentId, task: null }) |
| 486 | } |
| 487 | > |
| 488 | <PlusIcon className="size-3" /> |
| 489 | <T>New task</T> |
| 490 | </Button> |
| 491 | } |
| 492 | > |
| 493 | {scope.kind === "unavailable" ? ( |
| 494 | <SettingsSection title={gt("Unavailable selection")}> |
| 495 | <SettingsRow title={scope.message} /> |
| 496 | </SettingsSection> |
| 497 | ) : environments.length === 0 ? ( |
| 498 | <Empty> |
| 499 | <EmptyHeader> |
| 500 | <EmptyMedia variant="icon"> |
| 501 | <Clock3Icon /> |
| 502 | </EmptyMedia> |
| 503 | <EmptyTitle> |
| 504 | <T>No environments available</T> |
| 505 | </EmptyTitle> |
| 506 | <EmptyDescription> |
| 507 | <T>Connect an environment to manage scheduled tasks.</T> |
| 508 | </EmptyDescription> |
| 509 | </EmptyHeader> |
| 510 | </Empty> |
| 511 | ) : environments.length > 1 ? ( |
| 512 | <ScheduledTaskEnvironmentList |
| 513 | environmentId={linkedEnvironmentId} |
| 514 | taskId={target.taskId} |
| 515 | onEdit={openForEdit} |
| 516 | /> |
| 517 | ) : ( |
| 518 | <div className="space-y-8"> |
| 519 | {environments.map((entry) => ( |
| 520 | <ScheduledTaskEnvironmentSection |
| 521 | key={entry.environmentId} |
| 522 | environment={entry} |
| 523 | taskId={linkedEnvironmentId === entry.environmentId ? target.taskId : undefined} |
| 524 | onEdit={openForEdit} |
| 525 | /> |
| 526 | ))} |
| 527 | </div> |
| 528 | )} |
| 529 | </SettingsSection> |
| 530 | {editor ? ( |
| 531 | <ScheduledTaskEditorDialog |
| 532 | key={`${editor.environmentId}:${editor.task?.id ?? "new"}`} |
| 533 | initialEnvironmentId={editor.environmentId} |
| 534 | task={editor.task} |
| 535 | onClose={closeEditor} |
| 536 | /> |
| 537 | ) : null} |
| 538 | </SettingsPageContainer> |
| 539 | ); |
| 540 | } |
| 541 | |
| 542 | const scheduledTaskCreatePermissionsAtom = environmentAtomList( |
| 543 | "web-scheduled-task-create-permissions", |
| 544 | serverEnvironment.upsertScheduledTask.permissionAtom, |
| 545 | ); |
| 546 | |
| 547 | const scheduledTasksListAtom = environmentAtomList("web-scheduled-tasks-list", (environmentId) => |
| 548 | serverEnvironment.scheduledTasksLive({ environmentId, input: {} }), |
| 549 | ); |
| 550 | |
| 551 | function ScheduledTaskEnvironmentList({ |
| 552 | environmentId, |
| 553 | taskId, |
| 554 | onEdit, |
| 555 | }: { |
| 556 | readonly environmentId: EnvironmentId | undefined; |
| 557 | readonly taskId: ScheduledTaskId | undefined; |
| 558 | readonly onEdit: (environmentId: EnvironmentId, task: ScheduledTask) => void; |
| 559 | }) { |
| 560 | const messages = useMessages(); |
| 561 | const gt = useGT(); |
| 562 | const { scope, environments } = useSettingsScope(); |
| 563 | const connectedIds = environments.flatMap((environment) => |
| 564 | environment.connection.phase === "connected" && environment.serverConfig !== null |
| 565 | ? [environment.environmentId] |
| 566 | : [], |
| 567 | ); |
| 568 | const queries = useAtomValue(scheduledTasksListAtom(environmentIdsKey(connectedIds))); |
| 569 | const states = environments.map((environment) => { |
| 570 | const index = connectedIds.indexOf(environment.environmentId); |
| 571 | const query = index < 0 ? null : queries[index]!; |
| 572 | const data = query === null ? null : AsyncResult.getOrElse(query, () => null); |
| 573 | return { |
| 574 | environment, |
| 575 | connected: index >= 0, |
| 576 | timeZone: data?.timeZone, |
| 577 | tasks: data?.tasks.filter((task) => |
| 578 | matchesScheduledTaskScope(scope, environment.environmentId, task.projectId), |
| 579 | ), |
| 580 | error: query?._tag === "Failure" ? formatEnvironmentQueryError(query.cause, messages) : null, |
| 581 | }; |
| 582 | }); |
| 583 | const linkedState = states.find((state) => state.environment.environmentId === environmentId); |
| 584 | const linkedTask = linkedState?.tasks?.find((task) => task.id === taskId); |
| 585 | |
| 586 | const loaded = states.filter((state) => state.connected && state.error === null && state.tasks); |
| 587 | const populated = loaded.filter((state) => state.tasks && state.tasks.length > 0); |
| 588 | const summaries: Record<string, string[]> = { |
| 589 | "Not connected:": [], |
| 590 | "Loading scheduled tasks on": [], |
| 591 | "Could not load scheduled tasks:": [], |
| 592 | "No tasks on": [], |
| 593 | }; |
| 594 | for (const { environment, connected, tasks, error } of states) { |
| 595 | const label = settingsScopeEnvironmentLabel(environment, environments); |
| 596 | if (!connected) { |
| 597 | summaries["Not connected:"]!.push( |
| 598 | `${label} (${connectionStatusTitle(environment.connection, messages)})`, |
| 599 | ); |
| 600 | } else if (error !== null) { |
| 601 | summaries["Could not load scheduled tasks:"]!.push(`${label}: ${error}`); |
| 602 | } else if (!tasks) { |
| 603 | summaries["Loading scheduled tasks on"]!.push(label); |
| 604 | } else if (tasks.length === 0 && populated.length > 0) { |
| 605 | summaries["No tasks on"]!.push(label); |
| 606 | } |
| 607 | } |
| 608 | |
| 609 | return ( |
| 610 | <SettingsGroup> |
| 611 | {populated.map(({ environment, tasks, timeZone }) => { |
| 612 | const { primary, secondary } = settingsScopeEnvironmentLabels(environment, environments); |
| 613 | return ( |
| 614 | <div key={environment.environmentId} className="divide-y divide-border/50"> |
| 615 | <EnvironmentRow |
| 616 | kind={resolveEnvironmentMachineKind(environment.serverConfig)} |
| 617 | label={primary} |
| 618 | subtitle={ |
| 619 | <ScheduledTaskEnvironmentSubtitle environment={environment} secondary={secondary} /> |
| 620 | } |
| 621 | > |
| 622 | <ConnectionStatusDot |
| 623 | dotClassName={connectionPhaseDotClassName(environment.connection.phase)} |
| 624 | tooltipText={connectionStatusTitle(environment.connection, messages)} |
| 625 | /> |
| 626 | <span className="text-xs text-muted-foreground"> |
| 627 | {connectionStatusTitle(environment.connection, messages)} |
| 628 | </span> |
| 629 | </EnvironmentRow> |
| 630 | {tasks?.map((task) => ( |
| 631 | <ScheduledTaskRow |
| 632 | key={task.id} |
| 633 | environmentId={environment.environmentId} |
| 634 | task={task} |
| 635 | timeZone={timeZone} |
| 636 | onEdit={() => onEdit(environment.environmentId, task)} |
| 637 | /> |
| 638 | ))} |
| 639 | </div> |
| 640 | ); |
| 641 | })} |
| 642 | {taskId && linkedState?.tasks && linkedState.error === null && !linkedTask ? ( |
| 643 | <SettingsRow |
| 644 | title={gt("Task unavailable")} |
| 645 | description={gt( |
| 646 | "This task was deleted or belongs to a different project. Check your project filter.", |
| 647 | )} |
| 648 | role="status" |
| 649 | /> |
| 650 | ) : null} |
| 651 | {populated.length === 0 && loaded.length > 0 ? ( |
| 652 | <SettingsRow |
| 653 | title={gt("No scheduled tasks")} |
| 654 | description={gt("No tasks match this environment and project selection.")} |
| 655 | /> |
| 656 | ) : null} |
| 657 | {Object.entries(summaries).map(([label, entries]) => { |
| 658 | if (entries.length === 0) return null; |
| 659 | const summary = messages(SCOPE_SUMMARY_TEMPLATES[label] ?? label, { |
| 660 | environments: entries.join(", "), |
| 661 | }); |
| 662 | return ( |
| 663 | <Tooltip key={label}> |
| 664 | <TooltipTrigger |
| 665 | render={ |
| 666 | <p |
| 667 | className="truncate px-3 py-2.5 text-xs text-muted-foreground sm:px-4" |
| 668 | role="status" |
| 669 | /> |
| 670 | } |
| 671 | > |
| 672 | {summary} |
| 673 | </TooltipTrigger> |
| 674 | <TooltipPopup>{summary}</TooltipPopup> |
| 675 | </Tooltip> |
| 676 | ); |
| 677 | })} |
| 678 | </SettingsGroup> |
| 679 | ); |
| 680 | } |
| 681 | |
| 682 | function ScheduledTaskEnvironmentSubtitle({ |
| 683 | environment, |
| 684 | secondary, |
| 685 | }: { |
| 686 | readonly environment: EnvironmentPresentation; |
| 687 | readonly secondary: string; |
| 688 | }) { |
| 689 | const transport = useEnvironmentTransportLabel(environment); |
| 690 | return ( |
| 691 | <> |
| 692 | {secondary && secondary !== transport ? ( |
| 693 | <span className="block truncate">{secondary}</span> |
| 694 | ) : null} |
| 695 | <span className="block truncate">{transport}</span> |
| 696 | </> |
| 697 | ); |
| 698 | } |
| 699 | |
| 700 | function ScheduledTaskEnvironmentSection({ |
| 701 | environment, |
| 702 | taskId, |
| 703 | onEdit, |
| 704 | }: { |
| 705 | readonly environment: EnvironmentPresentation; |
| 706 | readonly taskId?: ScheduledTaskId | undefined; |
| 707 | readonly onEdit: (environmentId: EnvironmentId, task: ScheduledTask) => void; |
| 708 | }) { |
| 709 | const gt = useGT(); |
| 710 | const { scope } = useSettingsScope(); |
| 711 | const connected = |
| 712 | environment.connection.phase === "connected" && environment.serverConfig !== null; |
| 713 | const tasksQuery = useEnvironmentQuery( |
| 714 | connected |
| 715 | ? serverEnvironment.scheduledTasksLive({ |
| 716 | environmentId: environment.environmentId, |
| 717 | input: {}, |
| 718 | }) |
| 719 | : null, |
| 720 | useMessages(), |
| 721 | ); |
| 722 | const tasks = tasksQuery.data?.tasks.filter((task) => |
| 723 | matchesScheduledTaskScope(scope, environment.environmentId, task.projectId), |
| 724 | ); |
| 725 | const linkedTask = tasks?.find((task) => task.id === taskId); |
| 726 | return ( |
| 727 | <SettingsSection |
| 728 | title={environment.label} |
| 729 | hideTitle |
| 730 | icon={ |
| 731 | <EnvironmentMachineIcon |
| 732 | kind={resolveEnvironmentMachineKind(environment.serverConfig)} |
| 733 | className="size-3.5" |
| 734 | /> |
| 735 | } |
| 736 | > |
| 737 | {!connected ? ( |
| 738 | <SettingsRow |
| 739 | title={gt("Environment disconnected")} |
| 740 | description={gt("Reconnect {label} to view its scheduled tasks.", { |
| 741 | label: environment.label, |
| 742 | })} |
| 743 | /> |
| 744 | ) : tasksQuery.error ? ( |
| 745 | <SettingsRow title={gt("Could not load scheduled tasks")} description={tasksQuery.error} /> |
| 746 | ) : !tasks ? ( |
| 747 | <SettingsRow title={gt("Loading scheduled tasks…")} role="status" /> |
| 748 | ) : ( |
| 749 | <> |
| 750 | {taskId && !linkedTask ? ( |
| 751 | <SettingsRow |
| 752 | title={gt("Task unavailable")} |
| 753 | description={gt( |
| 754 | "This task was deleted or belongs to a different project. Check your project filter.", |
| 755 | )} |
| 756 | role="status" |
| 757 | /> |
| 758 | ) : null} |
| 759 | {tasks.length === 0 ? ( |
| 760 | <SettingsRow |
| 761 | title={gt("No scheduled tasks")} |
| 762 | description={gt("No tasks match this environment and project selection.")} |
| 763 | /> |
| 764 | ) : ( |
| 765 | tasks.map((task) => ( |
| 766 | <ScheduledTaskRow |
| 767 | key={task.id} |
| 768 | environmentId={environment.environmentId} |
| 769 | task={task} |
| 770 | timeZone={tasksQuery.data?.timeZone} |
| 771 | onEdit={() => onEdit(environment.environmentId, task)} |
| 772 | /> |
| 773 | )) |
| 774 | )} |
| 775 | </> |
| 776 | )} |
| 777 | </SettingsSection> |
| 778 | ); |
| 779 | } |
| 780 | |
| 781 | function ScheduledTaskRow({ |
| 782 | environmentId, |
| 783 | task, |
| 784 | timeZone, |
| 785 | onEdit, |
| 786 | }: { |
| 787 | readonly environmentId: EnvironmentId; |
| 788 | readonly task: ScheduledTask; |
| 789 | readonly timeZone: string | undefined; |
| 790 | readonly onEdit: () => void; |
| 791 | }) { |
| 792 | const messages = useMessages(); |
| 793 | const locale = useLocale(); |
| 794 | const gt = useGT(); |
| 795 | const canOperate = useAtomValue( |
| 796 | serverEnvironment.upsertScheduledTask.permissionAtom(environmentId), |
| 797 | ); |
| 798 | const [busy, setBusy] = useState(false); |
| 799 | const [deliveriesOpen, setDeliveriesOpen] = useState(false); |
| 800 | const isWebhook = task.schedule.type === "webhook"; |
| 801 | const toggle = useAtomCommand(serverEnvironment.setScheduledTaskEnabled, { |
| 802 | label: "scheduled task enabled", |
| 803 | }); |
| 804 | const run = useAtomCommand(serverEnvironment.runScheduledTaskNow, { |
| 805 | label: "scheduled task run now", |
| 806 | }); |
| 807 | const remove = useAtomCommand(serverEnvironment.deleteScheduledTask, { |
| 808 | label: "scheduled task delete", |
| 809 | }); |
| 810 | const act = async (action: "toggle" | "run" | "delete") => { |
| 811 | if (busy || !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) return; |
| 812 | if (action === "delete") { |
| 813 | const message = `${gt('Delete "{title}"?', { title: task.title })}\n${gt("This cannot be undone.")}`; |
| 814 | const confirmed = |
| 815 | (await requestConfirmDialog(message, { variant: "destructive" })) ?? |
| 816 | window.confirm(message); |
| 817 | if (!confirmed) return; |
| 818 | } |
| 819 | setBusy(true); |
| 820 | const result = |
| 821 | action === "toggle" |
| 822 | ? await toggle({ environmentId, input: { id: task.id, enabled: !task.enabled } }) |
| 823 | : action === "run" |
| 824 | ? await run({ environmentId, input: { id: task.id } }) |
| 825 | : await remove({ environmentId, input: { id: task.id } }); |
| 826 | setBusy(false); |
| 827 | if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { |
| 828 | toastManager.add( |
| 829 | stackedThreadToast({ |
| 830 | type: "error", |
| 831 | title: gt("Could not update scheduled task"), |
| 832 | description: String(squashAtomCommandFailure(result)), |
| 833 | }), |
| 834 | ); |
| 835 | } |
| 836 | }; |
| 837 | return ( |
| 838 | <SettingsRow |
| 839 | title={task.title} |
| 840 | description={<span className="line-clamp-2">{task.prompt}</span>} |
| 841 | status={ |
| 842 | <div className="flex flex-wrap items-center gap-2"> |
| 843 | <span> |
| 844 | {scheduleLabel(task.schedule, timeZone, task.nextRunAt, messages, locale)} ·{" "} |
| 845 | {task.blockedByPolicy !== undefined ? ( |
| 846 | task.blockedByPolicy |
| 847 | ) : !task.enabled ? ( |
| 848 | gt("Paused") |
| 849 | ) : isWebhook ? ( |
| 850 | gt("Listening") |
| 851 | ) : task.nextRunAt ? ( |
| 852 | <T> |
| 853 | Next run <ScheduledRelativeLabel value={task.nextRunAt} /> |
| 854 | </T> |
| 855 | ) : ( |
| 856 | gt("Not scheduled") |
| 857 | )} |
| 858 | </span> |
| 859 | {task.lastRunStatus !== "never" ? ( |
| 860 | <Badge variant={statusVariant(task.lastRunStatus)}> |
| 861 | {messages(RUN_STATUS_LABELS[task.lastRunStatus])} |
| 862 | </Badge> |
| 863 | ) : null} |
| 864 | {task.threadId !== null && scheduledTaskThreadMode(task) !== "new_thread" ? ( |
| 865 | <ScheduledTaskThreadLink environmentId={environmentId} threadId={task.threadId} /> |
| 866 | ) : null} |
| 867 | {task.lastRunError ? <span className="text-destructive">{task.lastRunError}</span> : null} |
| 868 | </div> |
| 869 | } |
| 870 | control={ |
| 871 | <div className="flex items-center gap-2"> |
| 872 | <Switch |
| 873 | checked={task.enabled} |
| 874 | disabled={busy || !canOperate} |
| 875 | aria-label={gt("Enable {title}", { title: task.title })} |
| 876 | onCheckedChange={() => void act("toggle")} |
| 877 | /> |
| 878 | <Menu> |
| 879 | <MenuTrigger |
| 880 | render={ |
| 881 | <Button |
| 882 | size="icon-sm" |
| 883 | variant="ghost" |
| 884 | disabled={busy || !canOperate} |
| 885 | aria-label={gt("Actions for {title}", { title: task.title })} |
| 886 | /> |
| 887 | } |
| 888 | > |
| 889 | <MoreHorizontalIcon className="size-4" /> |
| 890 | </MenuTrigger> |
| 891 | <MenuPopup align="end"> |
| 892 | <MenuItem onClick={onEdit}> |
| 893 | <PencilIcon /> |
| 894 | <T>Edit</T> |
| 895 | </MenuItem> |
| 896 | {isWebhook ? ( |
| 897 | <MenuItem onClick={() => setDeliveriesOpen(true)}> |
| 898 | <InboxIcon /> |
| 899 | <T>Deliveries</T> |
| 900 | </MenuItem> |
| 901 | ) : ( |
| 902 | <MenuItem onClick={() => void act("run")}> |
| 903 | <PlayIcon /> |
| 904 | <T>Run now</T> |
| 905 | </MenuItem> |
| 906 | )} |
| 907 | <MenuSeparator /> |
| 908 | <MenuItem onClick={() => void act("delete")}> |
| 909 | <Trash2Icon /> |
| 910 | Delete |
| 911 | </MenuItem> |
| 912 | </MenuPopup> |
| 913 | </Menu> |
| 914 | {deliveriesOpen ? ( |
| 915 | <WebhookDeliveriesDialog |
| 916 | environmentId={environmentId} |
| 917 | task={task} |
| 918 | onClose={() => setDeliveriesOpen(false)} |
| 919 | /> |
| 920 | ) : null} |
| 921 | </div> |
| 922 | } |
| 923 | /> |
| 924 | ); |
| 925 | } |
| 926 | |
| 927 | function ScheduledTaskThreadLink({ |
| 928 | environmentId, |
| 929 | threadId, |
| 930 | }: { |
| 931 | readonly environmentId: EnvironmentId; |
| 932 | readonly threadId: ThreadId; |
| 933 | }) { |
| 934 | const gt = useGT(); |
| 935 | const ref = scopeThreadRef(environmentId, threadId); |
| 936 | const title = useQuietThreadShell(ref)?.title.trim(); |
| 937 | return ( |
| 938 | <Link |
| 939 | to="/$environmentId/$threadId" |
| 940 | params={buildThreadRouteParams(ref)} |
| 941 | className="max-w-64 truncate underline underline-offset-2 hover:text-foreground" |
| 942 | > |
| 943 | {title || gt("Open thread")} |
| 944 | </Link> |
| 945 | ); |
| 946 | } |
| 947 | |
| 948 | function WebhookDeliveriesDialog({ |
| 949 | environmentId, |
| 950 | task, |
| 951 | onClose, |
| 952 | }: { |
| 953 | readonly environmentId: EnvironmentId; |
| 954 | readonly task: ScheduledTask; |
| 955 | readonly onClose: () => void; |
| 956 | }) { |
| 957 | const messages = useMessages(); |
| 958 | const gt = useGT(); |
| 959 | const deliveriesQuery = useEnvironmentQuery( |
| 960 | serverEnvironment.scheduledTaskWebhookDeliveries({ |
| 961 | environmentId, |
| 962 | input: { id: task.id, acceptAnyOutcome: true }, |
| 963 | }), |
| 964 | messages, |
| 965 | ); |
| 966 | const [selectedId, setSelectedId] = useState<ScheduledTaskWebhookDeliverySummary["id"] | null>( |
| 967 | null, |
| 968 | ); |
| 969 | const selectedQuery = useEnvironmentQuery( |
| 970 | selectedId === null |
| 971 | ? null |
| 972 | : serverEnvironment.scheduledTaskWebhookDelivery({ |
| 973 | environmentId, |
| 974 | input: { id: task.id, deliveryId: selectedId, acceptAnyOutcome: true }, |
| 975 | }), |
| 976 | messages, |
| 977 | ); |
| 978 | const deliveries = deliveriesQuery.data?.deliveries ?? null; |
| 979 | const selected = selectedQuery.data?.delivery ?? null; |
| 980 | const error = selectedId === null ? deliveriesQuery.error : selectedQuery.error; |
| 981 | |
| 982 | return ( |
| 983 | <Dialog |
| 984 | open |
| 985 | onOpenChange={(next) => { |
| 986 | if (!next) onClose(); |
| 987 | }} |
| 988 | > |
| 989 | <DialogPopup className="max-w-2xl"> |
| 990 | <DialogHeader> |
| 991 | <DialogTitle> |
| 992 | <T> |
| 993 | Deliveries · <Var>{task.title}</Var> |
| 994 | </T> |
| 995 | </DialogTitle> |
| 996 | <DialogDescription> |
| 997 | <T>Recent requests to this task's webhook URL.</T> |
| 998 | </DialogDescription> |
| 999 | </DialogHeader> |
| 1000 | <DialogPanel> |
| 1001 | {error ? <p className="text-sm text-destructive">{error}</p> : null} |
| 1002 | {selectedId !== null && selected === null && selectedQuery.error === null ? ( |
| 1003 | <p className="text-sm text-muted-foreground" role="status"> |
| 1004 | <T>Loading delivery…</T> |
| 1005 | </p> |
| 1006 | ) : selected ? ( |
| 1007 | <div className="space-y-4"> |
| 1008 | <div className="flex flex-wrap items-center gap-2 text-sm"> |
| 1009 | <Badge |
| 1010 | variant={deliveryOutcomeVariant( |
| 1011 | selected.pendingWindow ? "coalesced" : selected.outcome, |
| 1012 | )} |
| 1013 | > |
| 1014 | {webhookDeliveryLabel(selected, messages)} |
| 1015 | </Badge> |
| 1016 | <span> |
| 1017 | {selected.method} · <ScheduledRelativeLabel value={selected.receivedAt} /> |
| 1018 | </span> |
| 1019 | {selected.signatureVerified ? ( |
| 1020 | <span className="text-muted-foreground"> |
| 1021 | <T>Signature verified</T> |
| 1022 | </span> |
| 1023 | ) : null} |
| 1024 | </div> |
| 1025 | {selected.error ? ( |
| 1026 | <p |
| 1027 | className={ |
| 1028 | selected.outcome === "filtered" |
| 1029 | ? "text-sm text-muted-foreground" |
| 1030 | : "text-sm text-destructive" |
| 1031 | } |
| 1032 | > |
| 1033 | {selected.error} |
| 1034 | </p> |
| 1035 | ) : null} |
| 1036 | <DeliveryBlock |
| 1037 | title={ |
| 1038 | selected.pendingWindow ? gt("Scheduled run") : gt("Prompt sent to the agent") |
| 1039 | } |
| 1040 | > |
| 1041 | {selected.renderedPrompt ?? |
| 1042 | (selected.pendingWindow |
| 1043 | ? gt("Run scheduled when the window closes; no run started yet.") |
| 1044 | : gt("No run was started for this request."))} |
| 1045 | </DeliveryBlock> |
| 1046 | {selected.missingFields.length > 0 ? ( |
| 1047 | <p className="text-sm text-muted-foreground"> |
| 1048 | {gt("Empty placeholders: {fields}", { |
| 1049 | fields: selected.missingFields.join(", "), |
| 1050 | })} |
| 1051 | </p> |
| 1052 | ) : null} |
| 1053 | <DeliveryBlock title={gt("Headers")}> |
| 1054 | {Object.entries(selected.headers) |
| 1055 | .map(([name, value]) => `${name}: ${value}`) |
| 1056 | .join("\n")} |
| 1057 | </DeliveryBlock> |
| 1058 | {selected.query ? ( |
| 1059 | <DeliveryBlock title={gt("Query")}>{selected.query}</DeliveryBlock> |
| 1060 | ) : null} |
| 1061 | <DeliveryBlock title={selected.bodyTruncated ? gt("Body (truncated)") : gt("Body")}> |
| 1062 | {selected.body || gt("(empty)")} |
| 1063 | </DeliveryBlock> |
| 1064 | </div> |
| 1065 | ) : selectedId !== null ? null : deliveries === null ? ( |
| 1066 | <p className="text-sm text-muted-foreground" role="status"> |
| 1067 | <T>Loading deliveries…</T> |
| 1068 | </p> |
| 1069 | ) : deliveries.length === 0 ? ( |
| 1070 | <p className="text-sm text-muted-foreground"> |
| 1071 | <T>No requests yet.</T> |
| 1072 | </p> |
| 1073 | ) : ( |
| 1074 | <ul className="divide-y divide-border"> |
| 1075 | {deliveries.map((delivery) => ( |
| 1076 | <li key={delivery.id}> |
| 1077 | <button |
| 1078 | type="button" |
| 1079 | className="flex w-full flex-wrap items-center gap-2 py-2 text-left text-sm hover:bg-accent/40" |
| 1080 | onClick={() => setSelectedId(delivery.id)} |
| 1081 | > |
| 1082 | <Badge |
| 1083 | variant={deliveryOutcomeVariant( |
| 1084 | delivery.pendingWindow ? "coalesced" : delivery.outcome, |
| 1085 | )} |
| 1086 | > |
| 1087 | {webhookDeliveryLabel(delivery, messages)} |
| 1088 | </Badge> |
| 1089 | <span>{delivery.method}</span> |
| 1090 | <span className="text-muted-foreground"> |
| 1091 | <ScheduledRelativeLabel value={delivery.receivedAt} /> |
| 1092 | </span> |
| 1093 | {delivery.outcome === "filtered" && delivery.error ? ( |
| 1094 | <span className="text-muted-foreground">{delivery.error}</span> |
| 1095 | ) : null} |
| 1096 | {delivery.missingFields.length > 0 ? ( |
| 1097 | <span className="text-muted-foreground"> |
| 1098 | {gt( |
| 1099 | "{count, plural, one {{count} empty placeholder} other {{count} empty placeholders}}", |
| 1100 | { count: delivery.missingFields.length }, |
| 1101 | )} |
| 1102 | </span> |
| 1103 | ) : null} |
| 1104 | </button> |
| 1105 | </li> |
| 1106 | ))} |
| 1107 | </ul> |
| 1108 | )} |
| 1109 | </DialogPanel> |
| 1110 | <DialogFooter> |
| 1111 | {selectedId !== null ? ( |
| 1112 | <Button variant="outline" size="sm" onClick={() => setSelectedId(null)}> |
| 1113 | <T>Back</T> |
| 1114 | </Button> |
| 1115 | ) : ( |
| 1116 | <Button |
| 1117 | variant="outline" |
| 1118 | size="sm" |
| 1119 | disabled={deliveriesQuery.isPending} |
| 1120 | onClick={deliveriesQuery.refresh} |
| 1121 | > |
| 1122 | <T>Refresh</T> |
| 1123 | </Button> |
| 1124 | )} |
| 1125 | <DialogClose render={<Button size="sm" />}> |
| 1126 | <T>Done</T> |
| 1127 | </DialogClose> |
| 1128 | </DialogFooter> |
| 1129 | </DialogPopup> |
| 1130 | </Dialog> |
| 1131 | ); |
| 1132 | } |
| 1133 | |
| 1134 | function DeliveryBlock({ title, children }: { title: string; children: ReactNode }) { |
| 1135 | return ( |
| 1136 | <div className="space-y-1"> |
| 1137 | <Label>{title}</Label> |
| 1138 | <pre className="max-h-64 overflow-auto rounded-md bg-muted p-2 text-xs whitespace-pre-wrap break-all"> |
| 1139 | {children} |
| 1140 | </pre> |
| 1141 | </div> |
| 1142 | ); |
| 1143 | } |
| 1144 | |
| 1145 | function WebhookEndpointField({ |
| 1146 | environmentId, |
| 1147 | task, |
| 1148 | }: { |
| 1149 | readonly environmentId: EnvironmentId; |
| 1150 | readonly task: ScheduledTask | null; |
| 1151 | }) { |
| 1152 | const gt = useGT(); |
| 1153 | const messages = useMessages(); |
| 1154 | const canRotate = useAtomValue( |
| 1155 | serverEnvironment.rotateScheduledTaskWebhookToken.permissionAtom(environmentId), |
| 1156 | ); |
| 1157 | const httpBaseUrl = useEnvironmentHttpBaseUrl(environmentId); |
| 1158 | const { copyToClipboard, isCopied } = useCopyToClipboard({ |
| 1159 | target: { |
| 1160 | target: "webhook URL", |
| 1161 | unavailableMessage: msg("Clipboard API is unavailable while copying webhook URL."), |
| 1162 | failureMessage: msg("Failed to copy webhook URL to the clipboard."), |
| 1163 | }, |
| 1164 | }); |
| 1165 | const rotate = useAtomCommand(serverEnvironment.rotateScheduledTaskWebhookToken, { |
| 1166 | label: "scheduled task rotate webhook token", |
| 1167 | }); |
| 1168 | const [rotating, setRotating] = useState(false); |
| 1169 | const endpoint = task?.webhook; |
| 1170 | if (!task || !endpoint) { |
| 1171 | return ( |
| 1172 | <p className="text-sm text-muted-foreground"> |
| 1173 | <T>The URL appears after you save.</T> |
| 1174 | </p> |
| 1175 | ); |
| 1176 | } |
| 1177 | const { address: url, copyable, note } = webhookAddress(endpoint, httpBaseUrl, messages); |
| 1178 | const rotateUrl = async () => { |
| 1179 | const confirmed = |
| 1180 | (await requestConfirmDialog( |
| 1181 | `${gt("Rotate this webhook URL?")}\n${gt("The current URL stops working.")}`, |
| 1182 | { |
| 1183 | variant: "destructive", |
| 1184 | }, |
| 1185 | )) ?? window.confirm(gt("Rotate this webhook URL? The current URL stops working.")); |
| 1186 | if (!confirmed) return; |
| 1187 | setRotating(true); |
| 1188 | const result = await rotate({ environmentId, input: { id: task.id } }); |
| 1189 | setRotating(false); |
| 1190 | if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { |
| 1191 | toastManager.add( |
| 1192 | stackedThreadToast({ |
| 1193 | type: "error", |
| 1194 | title: gt("Could not rotate webhook URL"), |
| 1195 | description: String(squashAtomCommandFailure(result)), |
| 1196 | }), |
| 1197 | ); |
| 1198 | } |
| 1199 | }; |
| 1200 | return ( |
| 1201 | <div className="space-y-1.5"> |
| 1202 | <div className="flex items-center gap-2"> |
| 1203 | <Input |
| 1204 | readOnly |
| 1205 | aria-label={gt("Webhook URL")} |
| 1206 | value={url} |
| 1207 | onFocus={(event) => event.currentTarget.select()} |
| 1208 | /> |
| 1209 | <Button |
| 1210 | size="sm" |
| 1211 | variant="outline" |
| 1212 | type="button" |
| 1213 | disabled={!copyable} |
| 1214 | onClick={() => copyToClipboard(url, undefined)} |
| 1215 | > |
| 1216 | <CopyIcon /> |
| 1217 | {isCopied ? gt("Copied") : gt("Copy")} |
| 1218 | </Button> |
| 1219 | <Button |
| 1220 | size="sm" |
| 1221 | variant="outline" |
| 1222 | type="button" |
| 1223 | disabled={rotating || !canRotate} |
| 1224 | onClick={() => void rotateUrl()} |
| 1225 | > |
| 1226 | <T>Rotate</T> |
| 1227 | </Button> |
| 1228 | </div> |
| 1229 | {note !== null ? <p className="text-xs text-muted-foreground">{note}</p> : null} |
| 1230 | {endpoint.url !== null ? <WebhookDeliveryMode environmentId={environmentId} /> : null} |
| 1231 | </div> |
| 1232 | ); |
| 1233 | } |
| 1234 | |
| 1235 | function WebhookDeliveryMode({ environmentId }: { readonly environmentId: EnvironmentId }) { |
| 1236 | const gt = useGT(); |
| 1237 | const cloudLink = usePrimaryCloudLinkState(); |
| 1238 | if (cloudLink.target?.environmentId !== environmentId || cloudLink.data === null) return null; |
| 1239 | return ( |
| 1240 | <p className="text-xs text-muted-foreground"> |
| 1241 | {cloudLink.data.holdWebhooksWhileOffline |
| 1242 | ? gt("Held for up to 24 hours while this environment is offline. ") |
| 1243 | : gt("Forwarded live. Requests fail while this environment is offline. ")} |
| 1244 | <Link to="/settings/access" className="underline underline-offset-2"> |
| 1245 | <T>Change in Sharing & access</T> |
| 1246 | </Link> |
| 1247 | </p> |
| 1248 | ); |
| 1249 | } |
| 1250 | |
| 1251 | function ScheduledTaskEditorDialog({ |
| 1252 | initialEnvironmentId, |
| 1253 | task, |
| 1254 | onClose, |
| 1255 | }: { |
| 1256 | readonly initialEnvironmentId: EnvironmentId; |
| 1257 | readonly task: ScheduledTask | null; |
| 1258 | readonly onClose: () => void; |
| 1259 | }) { |
| 1260 | const [saving, setSaving] = useState(false); |
| 1261 | return ( |
| 1262 | <Dialog |
| 1263 | open |
| 1264 | onOpenChange={(open) => { |
| 1265 | if (!open && !saving) onClose(); |
| 1266 | }} |
| 1267 | > |
| 1268 | {/* The form owns the draft so a keystroke re-renders it, not the dialog chrome. */} |
| 1269 | <DialogPopup className="max-w-xl"> |
| 1270 | <ScheduledTaskEditorForm |
| 1271 | initialEnvironmentId={initialEnvironmentId} |
| 1272 | task={task} |
| 1273 | saving={saving} |
| 1274 | onSavingChange={setSaving} |
| 1275 | onClose={onClose} |
| 1276 | /> |
| 1277 | </DialogPopup> |
| 1278 | </Dialog> |
| 1279 | ); |
| 1280 | } |
| 1281 | |
| 1282 | const THREAD_MODE_LABELS: Record<ScheduledTaskThreadMode, string> = { |
| 1283 | new_thread: msg("New thread each run"), |
| 1284 | continue: msg("One thread, continuing the conversation"), |
| 1285 | fresh_session: msg("One thread, fresh session each run"), |
| 1286 | }; |
| 1287 | |
| 1288 | function useScheduledTaskThread(environmentId: EnvironmentId, threadId: ThreadId | null) { |
| 1289 | const ref = threadId === null ? null : scopeThreadRef(environmentId, threadId); |
| 1290 | const shell = useThreadShell(ref); |
| 1291 | // The shell can omit older settled threads; their family read still carries the row. |
| 1292 | const family = useEnvironmentQuery( |
| 1293 | ref !== null && shell === null ? threadFamilies.familyAtom(environmentId, ref.threadId) : null, |
| 1294 | ); |
| 1295 | return shell ?? family.data?.threads.find((row) => row.id === threadId) ?? null; |
| 1296 | } |
| 1297 | |
| 1298 | function ScheduledTaskDestination({ |
| 1299 | environmentId, |
| 1300 | projectId, |
| 1301 | threadId, |
| 1302 | threadMode, |
| 1303 | disabled, |
| 1304 | onSelect, |
| 1305 | onThreadModeChange, |
| 1306 | }: { |
| 1307 | readonly environmentId: EnvironmentId; |
| 1308 | readonly projectId: string; |
| 1309 | readonly threadId: ThreadId | null; |
| 1310 | readonly threadMode: ScheduledTaskThreadMode; |
| 1311 | readonly disabled: boolean; |
| 1312 | readonly onSelect: (thread: { id: ThreadId; projectId: ProjectId } | null) => void; |
| 1313 | /** Absent on servers that predate thread modes. */ |
| 1314 | readonly onThreadModeChange: ((mode: ScheduledTaskThreadMode) => void) | undefined; |
| 1315 | }) { |
| 1316 | const messages = useMessages(); |
| 1317 | const gt = useGT(); |
| 1318 | const [open, setOpen] = useState(false); |
| 1319 | const [query, setQuery] = useState(""); |
| 1320 | const ref = threadId === null ? null : scopeThreadRef(environmentId, threadId); |
| 1321 | const thread = useScheduledTaskThread(environmentId, threadId); |
| 1322 | const currentLabel = |
| 1323 | ref !== null |
| 1324 | ? thread?.title.trim() || gt("Thread {id}", { id: ref.threadId }) |
| 1325 | : threadMode === "new_thread" |
| 1326 | ? gt("New thread each run") |
| 1327 | : gt("Started by the first run"); |
| 1328 | const shells = useVisibleThreadShells(open); |
| 1329 | // Mounts older settled threads matching the query, which shells may leave out. |
| 1330 | useThreadSearch(open && projectId ? [environmentId] : [], query, { |
| 1331 | titlesOnly: true, |
| 1332 | projectIds: [projectId as ProjectId], |
| 1333 | }); |
| 1334 | const threads = scheduledTaskDestinationThreads(shells, { |
| 1335 | environmentId, |
| 1336 | projectId, |
| 1337 | currentThreadId: threadId, |
| 1338 | query, |
| 1339 | }); |
| 1340 | const search = query.trim().toLocaleLowerCase(); |
| 1341 | const items: ReadonlyArray<string> = [ |
| 1342 | ...(search ? [] : [NEW_THREAD_DESTINATION]), |
| 1343 | ...(threadId !== null && currentLabel.toLocaleLowerCase().includes(search) ? [threadId] : []), |
| 1344 | ...threads.map((row) => row.id), |
| 1345 | ]; |
| 1346 | const handleOpenChange = (next: boolean) => { |
| 1347 | setOpen(next); |
| 1348 | if (!next) setQuery(""); |
| 1349 | }; |
| 1350 | const detail = |
| 1351 | threadMode === "new_thread" |
| 1352 | ? gt("Each run starts a new thread with the workspace and model below.") |
| 1353 | : ref === null |
| 1354 | ? threadMode === "continue" |
| 1355 | ? gt( |
| 1356 | "The first run starts a thread with the workspace and model below. Later runs continue that conversation.", |
| 1357 | ) |
| 1358 | : gt( |
| 1359 | "The first run starts a thread with the workspace and model below. Later runs post there, each in a fresh session without earlier runs' context.", |
| 1360 | ) |
| 1361 | : threadMode === "continue" |
| 1362 | ? gt("Each run continues this conversation, in its workspace and with its current model.") |
| 1363 | : gt("Each run starts a fresh session in this thread, without earlier runs' context."); |
| 1364 | return ( |
| 1365 | <Field label={gt("Destination")} htmlFor="scheduled-task-destination"> |
| 1366 | {onThreadModeChange ? ( |
| 1367 | <Select |
| 1368 | value={threadMode} |
| 1369 | onValueChange={(value) => onThreadModeChange(value as ScheduledTaskThreadMode)} |
| 1370 | > |
| 1371 | <SelectTrigger size="sm" id="scheduled-task-destination"> |
| 1372 | <SelectValue>{messages(THREAD_MODE_LABELS[threadMode])}</SelectValue> |
| 1373 | </SelectTrigger> |
| 1374 | <SelectPopup> |
| 1375 | {(Object.keys(THREAD_MODE_LABELS) as ScheduledTaskThreadMode[]).map((mode) => ( |
| 1376 | <SelectItem key={mode} value={mode}> |
| 1377 | {messages(THREAD_MODE_LABELS[mode])} |
| 1378 | </SelectItem> |
| 1379 | ))} |
| 1380 | </SelectPopup> |
| 1381 | </Select> |
| 1382 | ) : null} |
| 1383 | {!onThreadModeChange || threadMode !== "new_thread" ? ( |
| 1384 | <Combobox |
| 1385 | items={items} |
| 1386 | filteredItems={items} |
| 1387 | filter={null} |
| 1388 | autoHighlight |
| 1389 | open={open && !disabled} |
| 1390 | onOpenChange={handleOpenChange} |
| 1391 | value={threadId ?? (threadMode === "new_thread" ? NEW_THREAD_DESTINATION : null)} |
| 1392 | onValueChange={(value) => { |
| 1393 | if (value === NEW_THREAD_DESTINATION) { |
| 1394 | onSelect(null); |
| 1395 | handleOpenChange(false); |
| 1396 | return; |
| 1397 | } |
| 1398 | const picked = threads.find((row) => row.id === value); |
| 1399 | if (picked) onSelect(picked); |
| 1400 | handleOpenChange(false); |
| 1401 | }} |
| 1402 | > |
| 1403 | <ComboboxTrigger |
| 1404 | id={ |
| 1405 | onThreadModeChange |
| 1406 | ? "scheduled-task-destination-thread" |
| 1407 | : "scheduled-task-destination" |
| 1408 | } |
| 1409 | aria-label={onThreadModeChange ? gt("Destination thread") : undefined} |
| 1410 | disabled={disabled} |
| 1411 | render={<Button variant="outline" size="sm" />} |
| 1412 | className="w-full justify-between" |
| 1413 | > |
| 1414 | <MessageSquareIcon className="size-3.5 shrink-0 text-muted-foreground" /> |
| 1415 | <span className="min-w-0 flex-1 truncate text-left">{currentLabel}</span> |
| 1416 | <ChevronDownIcon className="size-3.5 shrink-0 text-muted-foreground" /> |
| 1417 | </ComboboxTrigger> |
| 1418 | <ComboboxPopup align="start" side="bottom" className="w-80"> |
| 1419 | <ComboboxSearchInput |
| 1420 | aria-label={gt("Search threads")} |
| 1421 | placeholder={gt("Search all threads...")} |
| 1422 | value={query} |
| 1423 | onChange={(event) => setQuery(event.target.value)} |
| 1424 | /> |
| 1425 | <ComboboxEmpty> |
| 1426 | <T>No threads found.</T> |
| 1427 | </ComboboxEmpty> |
| 1428 | <ComboboxList className="max-h-72"> |
| 1429 | {items.map((value, index) => ( |
| 1430 | <ComboboxItem key={value} index={index} value={value}> |
| 1431 | <span className="block truncate"> |
| 1432 | {value === NEW_THREAD_DESTINATION |
| 1433 | ? gt("New thread each run") |
| 1434 | : value === threadId |
| 1435 | ? currentLabel |
| 1436 | : threads.find((row) => row.id === value)?.title || gt("Untitled thread")} |
| 1437 | </span> |
| 1438 | </ComboboxItem> |
| 1439 | ))} |
| 1440 | </ComboboxList> |
| 1441 | </ComboboxPopup> |
| 1442 | </Combobox> |
| 1443 | ) : null} |
| 1444 | <div className="space-y-1 text-sm"> |
| 1445 | <p className="text-muted-foreground">{detail}</p> |
| 1446 | {threadMode !== "new_thread" ? ( |
| 1447 | <p className="text-muted-foreground"> |
| 1448 | <T>Deleting the thread also deletes this task.</T> |
| 1449 | </p> |
| 1450 | ) : null} |
| 1451 | </div> |
| 1452 | </Field> |
| 1453 | ); |
| 1454 | } |
| 1455 | |
| 1456 | function ScheduledTaskEditorForm({ |
| 1457 | initialEnvironmentId, |
| 1458 | task, |
| 1459 | saving, |
| 1460 | onSavingChange: setSaving, |
| 1461 | onClose, |
| 1462 | }: { |
| 1463 | readonly initialEnvironmentId: EnvironmentId; |
| 1464 | readonly task: ScheduledTask | null; |
| 1465 | readonly saving: boolean; |
| 1466 | readonly onSavingChange: (saving: boolean) => void; |
| 1467 | readonly onClose: () => void; |
| 1468 | }) { |
| 1469 | const messages = useMessages(); |
| 1470 | const locale = useLocale(); |
| 1471 | const gt = useGT(); |
| 1472 | const { scope, connectedEnvironments } = useSettingsScope(); |
| 1473 | const [environmentId, setEnvironmentId] = useState(initialEnvironmentId); |
| 1474 | const environment = useEnvironment(environmentId); |
| 1475 | // Older servers reject one-time schedules, so offer Once only where it can save. |
| 1476 | const offersOnce = |
| 1477 | environment?.serverConfig?.environment.capabilities.oneTimeSchedules === true || |
| 1478 | task?.schedule.type === "once"; |
| 1479 | const offersThreadModes = |
| 1480 | environment?.serverConfig?.environment.capabilities.scheduledTaskThreadModes === true; |
| 1481 | const connected = |
| 1482 | environment?.connection.phase === "connected" && environment.serverConfig !== null; |
| 1483 | const tasksQuery = useEnvironmentQuery( |
| 1484 | connected ? serverEnvironment.scheduledTasksLive({ environmentId, input: {} }) : null, |
| 1485 | messages, |
| 1486 | ); |
| 1487 | const allProjects = useProjects(); |
| 1488 | const projectsOn = (id: EnvironmentId) => |
| 1489 | allProjects.filter( |
| 1490 | (project) => project.environmentId === id && matchesScheduledTaskScope(scope, id, project.id), |
| 1491 | ); |
| 1492 | const scopedProjects = projectsOn(environmentId); |
| 1493 | const settings = useEnvironmentSettings(environmentId); |
| 1494 | const providers = |
| 1495 | useAtomValue(serverEnvironment.providersValueAtom(environmentId)) ?? EMPTY_SERVER_PROVIDERS; |
| 1496 | const canOperate = useAtomValue( |
| 1497 | serverEnvironment.upsertScheduledTask.permissionAtom(environmentId), |
| 1498 | ); |
| 1499 | const upsertTask = useAtomCommand(serverEnvironment.upsertScheduledTask, { |
| 1500 | label: "scheduled task upsert", |
| 1501 | }); |
| 1502 | const webhookDenial = managedCapabilityDenial( |
| 1503 | useManagedPolicy(environmentId), |
| 1504 | "webhookTasks", |
| 1505 | messages, |
| 1506 | ); |
| 1507 | const [draft, setDraft] = useState<DraftState>(() => |
| 1508 | task |
| 1509 | ? taskToDraft(task) |
| 1510 | : { |
| 1511 | ...EMPTY_DRAFT, |
| 1512 | projectId: defaultScheduledTaskProjectId(scopedProjects, scope), |
| 1513 | }, |
| 1514 | ); |
| 1515 | // Pinned first. The chosen project stays listed after it is archived. |
| 1516 | const projects = scopedProjects |
| 1517 | .filter( |
| 1518 | (project) => |
| 1519 | project.archivedAt == null || |
| 1520 | project.id === draft.projectId || |
| 1521 | project.id === task?.projectId, |
| 1522 | ) |
| 1523 | .sort((left, right) => Number(right.pinnedAt != null) - Number(left.pinnedAt != null)); |
| 1524 | const submissionPending = useRef(false); |
| 1525 | const editingTaskMissing = |
| 1526 | draft.editingId !== null && |
| 1527 | tasksQuery.data !== null && |
| 1528 | !tasksQuery.data.tasks.some((entry) => entry.id === draft.editingId); |
| 1529 | const runAtZone = scheduleTimeZoneLabel(tasksQuery.data?.timeZone); |
| 1530 | const liveTask = tasksQuery.data |
| 1531 | ? (tasksQuery.data.tasks.find((entry) => entry.id === draft.editingId) ?? null) |
| 1532 | : task; |
| 1533 | const selectedProjectId = draft.projectId || projects[0]?.id || ""; |
| 1534 | const selectedProject = projects.find((project) => project.id === selectedProjectId); |
| 1535 | const automaticBaseRef = draft.workspaceMode === "worktree" && !draft.baseRef.trim(); |
| 1536 | const automaticBaseRefs = usePaginatedBranches({ |
| 1537 | environmentId, |
| 1538 | cwd: automaticBaseRef ? (selectedProject?.workspaceRoot ?? null) : null, |
| 1539 | query: "", |
| 1540 | }); |
| 1541 | const worktreeBaseRef = scheduledTaskWorktreeBaseRef(draft.baseRef, automaticBaseRefs.refs); |
| 1542 | // Until the project's refs load, the automatic base would save as `main`. A failed lookup falls back to it. |
| 1543 | const automaticBaseRefLoading = |
| 1544 | automaticBaseRef && |
| 1545 | selectedProject !== undefined && |
| 1546 | automaticBaseRefs.data === null && |
| 1547 | automaticBaseRefs.error === null; |
| 1548 | const instanceEntries = providerInstanceEntriesFor( |
| 1549 | providers, |
| 1550 | settings, |
| 1551 | selectedProject?.id ?? null, |
| 1552 | ); |
| 1553 | |
| 1554 | const firstInstance = instanceEntries[0]; |
| 1555 | const draftSelection = draft.modelKey ? splitModelKey(draft.modelKey) : null; |
| 1556 | const activeSelection = |
| 1557 | draftSelection && |
| 1558 | instanceEntries.some((entry) => entry.instanceId === draftSelection.instanceId && entry.enabled) |
| 1559 | ? draftSelection |
| 1560 | : scheduledTaskDefaultModel(settings, selectedProject ?? null, instanceEntries); |
| 1561 | const activeInstanceId = |
| 1562 | activeSelection?.instanceId ?? firstInstance?.instanceId ?? ("" as ProviderInstanceId); |
| 1563 | const activeModel = activeSelection?.model ?? ""; |
| 1564 | const boundThread = useScheduledTaskThread( |
| 1565 | environmentId, |
| 1566 | draft.threadId ? (draft.threadId as ThreadId) : null, |
| 1567 | ); |
| 1568 | // Bound runs use the thread's current model, so the locked picker shows that one. |
| 1569 | const shownSelection = draft.threadId |
| 1570 | ? (boundThread?.modelSelection ?? null) |
| 1571 | : { instanceId: activeInstanceId, model: activeModel }; |
| 1572 | const shownInstanceId = shownSelection?.instanceId ?? activeInstanceId; |
| 1573 | const shownModel = shownSelection?.model ?? ""; |
| 1574 | const modelOptionsByInstance = getCustomModelOptionsByInstance( |
| 1575 | settings, |
| 1576 | providers, |
| 1577 | shownInstanceId, |
| 1578 | shownModel, |
| 1579 | ); |
| 1580 | |
| 1581 | const reportFailure = (title: string, error: unknown) => { |
| 1582 | toastManager.add( |
| 1583 | stackedThreadToast({ |
| 1584 | type: "error", |
| 1585 | title, |
| 1586 | description: |
| 1587 | error instanceof Error ? (thrownErrorMessage(error, m) ?? error.message) : String(error), |
| 1588 | }), |
| 1589 | ); |
| 1590 | }; |
| 1591 | |
| 1592 | const submit = async () => { |
| 1593 | if ( |
| 1594 | !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope) || |
| 1595 | submissionPending.current || |
| 1596 | saving || |
| 1597 | editingTaskMissing || |
| 1598 | !connected || |
| 1599 | tasksQuery.data === null || |
| 1600 | automaticBaseRefLoading |
| 1601 | ) |
| 1602 | return; |
| 1603 | const selection = activeSelection; |
| 1604 | if ( |
| 1605 | !draft.title.trim() || |
| 1606 | !draft.prompt.trim() || |
| 1607 | !projects.some((project) => project.id === selectedProjectId) || |
| 1608 | selection === null |
| 1609 | ) { |
| 1610 | reportFailure( |
| 1611 | gt("Scheduled task is incomplete"), |
| 1612 | gt("Add a title, prompt, project, and model."), |
| 1613 | ); |
| 1614 | return; |
| 1615 | } |
| 1616 | const parsedFilters = parseWebhookFilterDrafts(draft.filters, m); |
| 1617 | if (draft.scheduleMode === "webhook" && "error" in parsedFilters) { |
| 1618 | reportFailure(gt("Invalid filter"), parsedFilters.error); |
| 1619 | return; |
| 1620 | } |
| 1621 | const schedule = scheduleFromDraft(draft); |
| 1622 | if (schedule === null) { |
| 1623 | for (const error of scheduleDraftErrors(draft)) reportFailure(error.title, error.description); |
| 1624 | return; |
| 1625 | } |
| 1626 | if ( |
| 1627 | schedule.type === "webhook" && |
| 1628 | schedule.signature && |
| 1629 | (!schedule.signature.header || |
| 1630 | (!schedule.signature.secret && |
| 1631 | !(liveTask?.schedule.type === "webhook" && liveTask.webhook?.hasSecret))) |
| 1632 | ) { |
| 1633 | reportFailure(gt("Signing secret is required"), gt("Enter the signature header and secret.")); |
| 1634 | return; |
| 1635 | } |
| 1636 | if ( |
| 1637 | schedule.type === "interval" && |
| 1638 | (!Number.isSafeInteger(schedule.everyMs) || schedule.everyMs < MIN_SCHEDULED_TASK_INTERVAL_MS) |
| 1639 | ) { |
| 1640 | reportFailure(gt("Invalid interval"), gt("Enter an interval of at least one minute.")); |
| 1641 | return; |
| 1642 | } |
| 1643 | if (schedule.type === "once" && !offersOnce) { |
| 1644 | reportFailure( |
| 1645 | gt("Once is not available here"), |
| 1646 | gt( |
| 1647 | "This environment runs an older T3 Code. Update it to schedule a one-time task, or pick another schedule.", |
| 1648 | ), |
| 1649 | ); |
| 1650 | return; |
| 1651 | } |
| 1652 | if (draft.workspaceMode === "existing_worktree" && !draft.existingWorktreePath.trim()) { |
| 1653 | reportFailure( |
| 1654 | gt("Checkout path is required"), |
| 1655 | gt("Enter the path of the checkout to run in."), |
| 1656 | ); |
| 1657 | return; |
| 1658 | } |
| 1659 | const modelSelection = |
| 1660 | draft.baseModelSelection !== null && |
| 1661 | draft.baseModelSelection.instanceId === selection.instanceId && |
| 1662 | draft.baseModelSelection.model === selection.model |
| 1663 | ? draft.baseModelSelection |
| 1664 | : selection; |
| 1665 | const workspaceStrategy: OrchestrationV2ThreadLaunchWorkspaceStrategy = |
| 1666 | draft.workspaceMode === "root" |
| 1667 | ? { type: "root" } |
| 1668 | : draft.workspaceMode === "existing_worktree" |
| 1669 | ? { type: "existing_worktree", worktreePath: draft.existingWorktreePath.trim() } |
| 1670 | : { |
| 1671 | type: "worktree", |
| 1672 | baseRef: worktreeBaseRef, |
| 1673 | startFromOrigin: draft.startFromOrigin, |
| 1674 | }; |
| 1675 | const input: ScheduledTaskUpsertInput = { |
| 1676 | ...(draft.editingId ? { id: draft.editingId as ScheduledTaskId, requireExisting: true } : {}), |
| 1677 | title: draft.title.trim(), |
| 1678 | prompt: draft.prompt.trim(), |
| 1679 | enabled: draft.enabled, |
| 1680 | schedule, |
| 1681 | projectId: selectedProjectId as ProjectId, |
| 1682 | threadId: draft.threadId ? (draft.threadId as ThreadId) : null, |
| 1683 | ...(draft.threadId === "" && draft.savedThreadId !== "" ? { unbindThread: true } : {}), |
| 1684 | ...(offersThreadModes ? { threadMode: draft.threadMode } : {}), |
| 1685 | workspaceStrategy, |
| 1686 | modelSelection, |
| 1687 | // Tasks have no mode picker; a mode above the administrator's ceiling would fail every run. |
| 1688 | runtimeMode: |
| 1689 | clampManagedRuntimeMode(environment?.serverConfig?.managedPolicy, draft.runtimeMode) ?? |
| 1690 | draft.runtimeMode, |
| 1691 | interactionMode: draft.interactionMode, |
| 1692 | creationSource: "web", |
| 1693 | }; |
| 1694 | // Lock before React renders, and keep successful creates locked until the form closes. |
| 1695 | submissionPending.current = true; |
| 1696 | setSaving(true); |
| 1697 | const result = await upsertTask({ environmentId, input }); |
| 1698 | setSaving(false); |
| 1699 | if (result._tag === "Failure") { |
| 1700 | submissionPending.current = false; |
| 1701 | if (!isAtomCommandInterrupted(result)) { |
| 1702 | reportFailure(gt("Could not save scheduled task"), squashAtomCommandFailure(result)); |
| 1703 | } |
| 1704 | return; |
| 1705 | } |
| 1706 | onClose(); |
| 1707 | }; |
| 1708 | |
| 1709 | return ( |
| 1710 | <> |
| 1711 | <DialogHeader> |
| 1712 | <DialogTitle>{draft.editingId ? gt("Edit task") : gt("New task")}</DialogTitle> |
| 1713 | <DialogDescription> |
| 1714 | <T> |
| 1715 | Run a prompt automatically on an interval, at a fixed time, once at a set date, or when |
| 1716 | a webhook is called. |
| 1717 | </T> |
| 1718 | </DialogDescription> |
| 1719 | </DialogHeader> |
| 1720 | |
| 1721 | <DialogPanel> |
| 1722 | {/* Fieldsets default to min-width: min-content, which lets one wide control widen the form past the dialog. */} |
| 1723 | <fieldset disabled={saving} className="min-w-0 space-y-5"> |
| 1724 | {!connected ? ( |
| 1725 | <p className="text-sm text-destructive"> |
| 1726 | <T>Reconnect this environment before saving.</T> |
| 1727 | </p> |
| 1728 | ) : null} |
| 1729 | <Field label={gt("Runs on")} htmlFor="scheduled-task-environment"> |
| 1730 | <Select |
| 1731 | value={environmentId} |
| 1732 | disabled={task !== null || saving} |
| 1733 | onValueChange={(id) => { |
| 1734 | const next = connectedEnvironments.find((entry) => entry.environmentId === id); |
| 1735 | if (!next) return; |
| 1736 | setEnvironmentId(next.environmentId); |
| 1737 | setDraft((current) => ({ |
| 1738 | ...unbindDraftFromThread(current), |
| 1739 | projectId: defaultScheduledTaskProjectId(projectsOn(next.environmentId), scope), |
| 1740 | modelKey: "", |
| 1741 | baseModelSelection: null, |
| 1742 | baseRef: "", |
| 1743 | startFromOrigin: true, |
| 1744 | existingWorktreePath: "", |
| 1745 | })); |
| 1746 | }} |
| 1747 | > |
| 1748 | <SelectTrigger id="scheduled-task-environment" size="sm"> |
| 1749 | <SelectValue> |
| 1750 | <span className="flex items-center gap-2"> |
| 1751 | <EnvironmentMachineIcon |
| 1752 | kind={resolveEnvironmentMachineKind(environment?.serverConfig ?? null)} |
| 1753 | className="size-4" |
| 1754 | /> |
| 1755 | {environment?.label ?? gt("Unavailable environment")} |
| 1756 | </span> |
| 1757 | </SelectValue> |
| 1758 | </SelectTrigger> |
| 1759 | <SelectPopup> |
| 1760 | {connectedEnvironments.map((entry) => { |
| 1761 | const { secondary } = settingsScopeEnvironmentLabels( |
| 1762 | entry, |
| 1763 | connectedEnvironments, |
| 1764 | ); |
| 1765 | return ( |
| 1766 | <SelectItem |
| 1767 | key={entry.environmentId} |
| 1768 | value={entry.environmentId} |
| 1769 | label={entry.label} |
| 1770 | > |
| 1771 | <span className="flex min-w-0 items-center gap-2"> |
| 1772 | <EnvironmentMachineIcon |
| 1773 | kind={resolveEnvironmentMachineKind(entry.serverConfig)} |
| 1774 | className="size-4" |
| 1775 | /> |
| 1776 | <span className="min-w-0"> |
| 1777 | <span className="block truncate">{entry.label}</span> |
| 1778 | {secondary ? ( |
| 1779 | <span className="block max-w-72 truncate text-xs text-muted-foreground"> |
| 1780 | {secondary} |
| 1781 | </span> |
| 1782 | ) : null} |
| 1783 | </span> |
| 1784 | </span> |
| 1785 | </SelectItem> |
| 1786 | ); |
| 1787 | })} |
| 1788 | </SelectPopup> |
| 1789 | </Select> |
| 1790 | </Field> |
| 1791 | {tasksQuery.error ? ( |
| 1792 | <p className="text-sm text-destructive" role="status"> |
| 1793 | {tasksQuery.error} |
| 1794 | </p> |
| 1795 | ) : null} |
| 1796 | {editingTaskMissing ? ( |
| 1797 | <p className="text-xs text-destructive" role="status"> |
| 1798 | <T>This scheduled task no longer exists.</T> |
| 1799 | </p> |
| 1800 | ) : null} |
| 1801 | <Field label={gt("Name")} htmlFor="scheduled-task-title"> |
| 1802 | <Input |
| 1803 | id="scheduled-task-title" |
| 1804 | placeholder={gt("e.g. Check for Sentry issues")} |
| 1805 | value={draft.title} |
| 1806 | onChange={(event) => |
| 1807 | setDraft((current) => ({ ...current, title: event.target.value })) |
| 1808 | } |
| 1809 | /> |
| 1810 | </Field> |
| 1811 | |
| 1812 | <ScheduledTaskDestination |
| 1813 | environmentId={environmentId} |
| 1814 | projectId={selectedProjectId} |
| 1815 | threadId={draft.threadId ? (draft.threadId as ThreadId) : null} |
| 1816 | threadMode={draft.threadMode} |
| 1817 | disabled={saving || !connected} |
| 1818 | onSelect={(thread) => |
| 1819 | setDraft((current) => |
| 1820 | thread === null |
| 1821 | ? { ...unbindDraftFromThread(current), threadMode: "new_thread" } |
| 1822 | : moveDraftToThread(current, thread), |
| 1823 | ) |
| 1824 | } |
| 1825 | onThreadModeChange={ |
| 1826 | offersThreadModes |
| 1827 | ? (threadMode) => |
| 1828 | setDraft((current) => ({ |
| 1829 | ...(threadMode === "new_thread" ? unbindDraftFromThread(current) : current), |
| 1830 | threadMode, |
| 1831 | })) |
| 1832 | : undefined |
| 1833 | } |
| 1834 | /> |
| 1835 | |
| 1836 | <div className="grid gap-3 sm:grid-cols-2"> |
| 1837 | <Field label={gt("Project")} htmlFor="scheduled-task-project"> |
| 1838 | <Select |
| 1839 | value={selectedProjectId} |
| 1840 | onValueChange={(projectId) => |
| 1841 | setDraft((current) => changeDraftProject(current, projectId ?? "")) |
| 1842 | } |
| 1843 | > |
| 1844 | <SelectTrigger size="sm" id="scheduled-task-project"> |
| 1845 | <SelectValue placeholder={gt("Select a project")}> |
| 1846 | {selectedProject?.title} |
| 1847 | </SelectValue> |
| 1848 | </SelectTrigger> |
| 1849 | <SelectPopup> |
| 1850 | {projects.map((project) => ( |
| 1851 | <SelectItem key={project.id} value={project.id} label={project.title}> |
| 1852 | <span className="block truncate">{project.title}</span> |
| 1853 | {allProjects.some( |
| 1854 | (other) => |
| 1855 | other.title === project.title && |
| 1856 | (other.environmentId !== project.environmentId || |
| 1857 | other.id !== project.id), |
| 1858 | ) ? ( |
| 1859 | <span className="block max-w-72 truncate text-xs text-muted-foreground"> |
| 1860 | {project.workspaceRoot} |
| 1861 | </span> |
| 1862 | ) : null} |
| 1863 | </SelectItem> |
| 1864 | ))} |
| 1865 | </SelectPopup> |
| 1866 | </Select> |
| 1867 | </Field> |
| 1868 | |
| 1869 | <Field label={gt("Workspace")} htmlFor="scheduled-task-workspace"> |
| 1870 | <Select |
| 1871 | value={draft.workspaceMode} |
| 1872 | onValueChange={(value) => |
| 1873 | setDraft((current) => ({ ...current, workspaceMode: value as WorkspaceMode })) |
| 1874 | } |
| 1875 | > |
| 1876 | <SelectTrigger size="sm" id="scheduled-task-workspace"> |
| 1877 | <SelectValue>{messages(WORKSPACE_MODE_LABELS[draft.workspaceMode])}</SelectValue> |
| 1878 | </SelectTrigger> |
| 1879 | <SelectPopup> |
| 1880 | <SelectItem value="worktree"> |
| 1881 | <T>Create a new worktree</T> |
| 1882 | </SelectItem> |
| 1883 | <SelectItem value="root"> |
| 1884 | <T>Use the project checkout</T> |
| 1885 | </SelectItem> |
| 1886 | <SelectItem value="existing_worktree"> |
| 1887 | <T>Use a specific checkout</T> |
| 1888 | </SelectItem> |
| 1889 | </SelectPopup> |
| 1890 | </Select> |
| 1891 | </Field> |
| 1892 | </div> |
| 1893 | |
| 1894 | {draft.workspaceMode === "worktree" ? ( |
| 1895 | <Field label={gt("Base branch")} htmlFor="scheduled-task-base-ref"> |
| 1896 | <WorktreeBaseBranchPicker |
| 1897 | key={`${environmentId}:${selectedProjectId}`} |
| 1898 | id="scheduled-task-base-ref" |
| 1899 | environmentId={environmentId} |
| 1900 | cwd={selectedProject?.workspaceRoot ?? null} |
| 1901 | value={automaticBaseRefLoading ? "" : worktreeBaseRef} |
| 1902 | onValueChange={(baseRef) => setDraft((current) => ({ ...current, baseRef }))} |
| 1903 | startFromOrigin={draft.startFromOrigin} |
| 1904 | onStartFromOriginChange={(startFromOrigin) => |
| 1905 | setDraft((current) => ({ ...current, startFromOrigin })) |
| 1906 | } |
| 1907 | disabled={saving || !connected} |
| 1908 | /> |
| 1909 | </Field> |
| 1910 | ) : null} |
| 1911 | {draft.workspaceMode === "existing_worktree" ? ( |
| 1912 | <Field label={gt("Checkout path")} htmlFor="scheduled-task-checkout"> |
| 1913 | <Input |
| 1914 | id="scheduled-task-checkout" |
| 1915 | value={draft.existingWorktreePath} |
| 1916 | placeholder="/path/to/checkout" |
| 1917 | onChange={(event) => |
| 1918 | setDraft((current) => ({ |
| 1919 | ...current, |
| 1920 | existingWorktreePath: resolvePastedPath( |
| 1921 | current.existingWorktreePath, |
| 1922 | event.target.value, |
| 1923 | ), |
| 1924 | })) |
| 1925 | } |
| 1926 | /> |
| 1927 | </Field> |
| 1928 | ) : null} |
| 1929 | |
| 1930 | <Field label={gt("Prompt")} htmlFor="scheduled-task-prompt"> |
| 1931 | <Textarea |
| 1932 | id="scheduled-task-prompt" |
| 1933 | className="max-h-64 overflow-y-auto" |
| 1934 | placeholder={gt("What should the agent do each time this runs?")} |
| 1935 | value={draft.prompt} |
| 1936 | onChange={(event) => |
| 1937 | setDraft((current) => ({ ...current, prompt: event.target.value })) |
| 1938 | } |
| 1939 | /> |
| 1940 | </Field> |
| 1941 | |
| 1942 | <Field label={gt("Model")}> |
| 1943 | <div> |
| 1944 | <ProviderModelPicker |
| 1945 | environmentId={environmentId} |
| 1946 | // The saved selection only seeds new threads; bound runs ignore it. |
| 1947 | disabled={saving || !connected || draft.threadId !== ""} |
| 1948 | activeInstanceId={shownInstanceId} |
| 1949 | model={shownModel} |
| 1950 | lockedProvider={null} |
| 1951 | instanceEntries={instanceEntries} |
| 1952 | modelOptionsByInstance={modelOptionsByInstance} |
| 1953 | isComposerOwned={false} |
| 1954 | triggerClassName={SETTINGS_PICKER_TRIGGER_CLASSNAME} |
| 1955 | onInstanceModelChange={(instanceId, model) => |
| 1956 | setDraft((current) => ({ ...current, modelKey: `${instanceId}:${model}` })) |
| 1957 | } |
| 1958 | /> |
| 1959 | </div> |
| 1960 | </Field> |
| 1961 | |
| 1962 | <div className="space-y-3"> |
| 1963 | {task?.schedule.type === "interval" && |
| 1964 | task.schedule.everyMs < MIN_SCHEDULED_TASK_INTERVAL_MS ? ( |
| 1965 | <p className="text-sm text-muted-foreground" role="status"> |
| 1966 | <T> |
| 1967 | This task uses a legacy interval below one minute. Saving updates it to at least |
| 1968 | one minute. |
| 1969 | </T> |
| 1970 | </p> |
| 1971 | ) : null} |
| 1972 | {/* Wraps the toggle below the label when both don't fit, as on phones. */} |
| 1973 | <div className="flex flex-wrap items-center justify-between gap-2"> |
| 1974 | <Label> |
| 1975 | <T>Schedule</T> |
| 1976 | </Label> |
| 1977 | <ToggleGroup |
| 1978 | aria-label={gt("Schedule type")} |
| 1979 | value={[draft.scheduleMode]} |
| 1980 | onValueChange={(values) => { |
| 1981 | const mode = values[0] as ScheduleMode | undefined; |
| 1982 | if ( |
| 1983 | mode === "fixed" || |
| 1984 | mode === "once" || |
| 1985 | mode === "interval" || |
| 1986 | mode === "webhook" |
| 1987 | ) |
| 1988 | setDraft((current) => { |
| 1989 | const suggested = |
| 1990 | mode === "once" && !current.runAt |
| 1991 | ? new Date(Math.ceil(Date.now() / 3_600_000) * 3_600_000) |
| 1992 | : null; |
| 1993 | return { |
| 1994 | ...current, |
| 1995 | scheduleMode: mode, |
| 1996 | // Keep the instant too, so an hour that repeats when clocks go back stays exact. |
| 1997 | ...(suggested === null |
| 1998 | ? {} |
| 1999 | : { |
| 2000 | runAt: toDateTimeLocalValue(suggested), |
| 2001 | savedRunAt: suggested.toISOString(), |
| 2002 | }), |
| 2003 | prompt: |
| 2004 | mode === "webhook" && !current.prompt.trim() |
| 2005 | ? DEFAULT_WEBHOOK_PROMPT |
| 2006 | : current.prompt, |
| 2007 | }; |
| 2008 | }); |
| 2009 | }} |
| 2010 | > |
| 2011 | <Toggle value="fixed"> |
| 2012 | <T>At a time</T> |
| 2013 | </Toggle> |
| 2014 | {offersOnce || draft.scheduleMode === "once" ? ( |
| 2015 | <Toggle value="once"> |
| 2016 | <T>Once</T> |
| 2017 | </Toggle> |
| 2018 | ) : null} |
| 2019 | <Toggle value="interval"> |
| 2020 | <T>Every interval</T> |
| 2021 | </Toggle> |
| 2022 | <Toggle |
| 2023 | value="webhook" |
| 2024 | disabled={webhookDenial !== undefined && draft.scheduleMode !== "webhook"} |
| 2025 | > |
| 2026 | <T>On webhook</T> |
| 2027 | </Toggle> |
| 2028 | </ToggleGroup> |
| 2029 | </div> |
| 2030 | |
| 2031 | {webhookDenial !== undefined ? ( |
| 2032 | <ManagedNotice> |
| 2033 | {draft.scheduleMode === "webhook" |
| 2034 | ? gt( |
| 2035 | "{webhookDenial} Switch this task to a time or an interval, or turn it off, to save it.", |
| 2036 | { webhookDenial }, |
| 2037 | ) |
| 2038 | : webhookDenial} |
| 2039 | </ManagedNotice> |
| 2040 | ) : null} |
| 2041 | {/* A disabled task still saves, so keep its fields reachable for fixing. */} |
| 2042 | {draft.scheduleMode === "webhook" && |
| 2043 | webhookDenial !== undefined && |
| 2044 | draft.enabled ? null : draft.scheduleMode === "webhook" ? ( |
| 2045 | <div className="space-y-4"> |
| 2046 | <WebhookEndpointField environmentId={environmentId} task={liveTask} /> |
| 2047 | <p className="text-xs text-muted-foreground"> |
| 2048 | {gt( |
| 2049 | "Each request runs the prompt. Use {bodyPath}, {headerName}, {queryName}, {body} or {request} in the prompt; only what it names reaches the agent.", |
| 2050 | { |
| 2051 | bodyPath: "{{body.path}}", |
| 2052 | headerName: "{{headers.name}}", |
| 2053 | queryName: "{{query.name}}", |
| 2054 | body: "{{body}}", |
| 2055 | request: "{{request}}", |
| 2056 | }, |
| 2057 | )} |
| 2058 | </p> |
| 2059 | <Field |
| 2060 | label={gt("Skip requests older than")} |
| 2061 | hint={gt("minutes, optional")} |
| 2062 | htmlFor="scheduled-task-max-age" |
| 2063 | > |
| 2064 | <Input |
| 2065 | id="scheduled-task-max-age" |
| 2066 | type="number" |
| 2067 | nativeInput |
| 2068 | min={1} |
| 2069 | max={MAX_WEBHOOK_DELIVERY_AGE_MINUTES} |
| 2070 | placeholder={gt("Run every request")} |
| 2071 | value={draft.maxDeliveryAgeMinutes} |
| 2072 | onChange={(event) => |
| 2073 | setDraft((current) => ({ |
| 2074 | ...current, |
| 2075 | maxDeliveryAgeMinutes: event.target.value, |
| 2076 | })) |
| 2077 | } |
| 2078 | /> |
| 2079 | </Field> |
| 2080 | <WebhookFiltersField |
| 2081 | filters={draft.filters} |
| 2082 | onChange={(filters) => setDraft((current) => ({ ...current, filters }))} |
| 2083 | /> |
| 2084 | <Field |
| 2085 | label={gt("Duplicate request key")} |
| 2086 | hint={gt("template, optional")} |
| 2087 | htmlFor="scheduled-task-replay-key" |
| 2088 | > |
| 2089 | <Input |
| 2090 | id="scheduled-task-replay-key" |
| 2091 | placeholder="{{headers.delivery-id}}" |
| 2092 | value={draft.replayKey} |
| 2093 | onChange={(event) => |
| 2094 | setDraft((current) => ({ ...current, replayKey: event.target.value })) |
| 2095 | } |
| 2096 | /> |
| 2097 | </Field> |
| 2098 | <p className="text-xs text-muted-foreground"> |
| 2099 | <T>Requests with the same key run only once within 7 days.</T> |
| 2100 | </p> |
| 2101 | <Field |
| 2102 | label={gt("Coalesce key")} |
| 2103 | hint={gt("template, optional")} |
| 2104 | htmlFor="scheduled-task-coalesce-key" |
| 2105 | > |
| 2106 | <Input |
| 2107 | id="scheduled-task-coalesce-key" |
| 2108 | placeholder="{{body.id}}" |
| 2109 | value={draft.coalesceKey} |
| 2110 | onChange={(event) => |
| 2111 | setDraft((current) => ({ ...current, coalesceKey: event.target.value })) |
| 2112 | } |
| 2113 | /> |
| 2114 | </Field> |
| 2115 | <Field |
| 2116 | label={gt("Coalesce window")} |
| 2117 | hint={gt("seconds, 10–3600")} |
| 2118 | htmlFor="scheduled-task-coalesce-window" |
| 2119 | > |
| 2120 | <Input |
| 2121 | id="scheduled-task-coalesce-window" |
| 2122 | type="number" |
| 2123 | nativeInput |
| 2124 | min={10} |
| 2125 | max={3600} |
| 2126 | placeholder="120" |
| 2127 | value={draft.coalesceWindowSeconds} |
| 2128 | onChange={(event) => |
| 2129 | setDraft((current) => ({ |
| 2130 | ...current, |
| 2131 | coalesceWindowSeconds: event.target.value, |
| 2132 | })) |
| 2133 | } |
| 2134 | /> |
| 2135 | </Field> |
| 2136 | <p className="text-xs text-muted-foreground"> |
| 2137 | <T> |
| 2138 | Coalescing runs the latest payload once when the window from the first delivery |
| 2139 | closes. Empty keys run normally. |
| 2140 | </T> |
| 2141 | </p> |
| 2142 | <div className="flex items-center justify-between gap-4"> |
| 2143 | <div className="min-w-0 space-y-1"> |
| 2144 | <Label htmlFor="scheduled-task-signature"> |
| 2145 | <T>Require signature</T> |
| 2146 | </Label> |
| 2147 | <p className="text-sm text-muted-foreground"> |
| 2148 | <T>Reject requests without a valid HMAC-SHA256 signature of the body.</T> |
| 2149 | </p> |
| 2150 | </div> |
| 2151 | <Switch |
| 2152 | id="scheduled-task-signature" |
| 2153 | checked={draft.signatureEnabled} |
| 2154 | onCheckedChange={(signatureEnabled) => |
| 2155 | setDraft((current) => ({ ...current, signatureEnabled })) |
| 2156 | } |
| 2157 | /> |
| 2158 | </div> |
| 2159 | {draft.signatureEnabled ? ( |
| 2160 | <div className="grid gap-3 sm:grid-cols-2"> |
| 2161 | <Field label={gt("Header")} htmlFor="scheduled-task-signature-header"> |
| 2162 | <Input |
| 2163 | id="scheduled-task-signature-header" |
| 2164 | value={draft.signatureHeader} |
| 2165 | onChange={(event) => |
| 2166 | setDraft((current) => ({ |
| 2167 | ...current, |
| 2168 | signatureHeader: event.target.value, |
| 2169 | })) |
| 2170 | } |
| 2171 | /> |
| 2172 | </Field> |
| 2173 | <Field label={gt("Prefix")} htmlFor="scheduled-task-signature-prefix"> |
| 2174 | <Input |
| 2175 | id="scheduled-task-signature-prefix" |
| 2176 | value={draft.signaturePrefix} |
| 2177 | placeholder={gt("None")} |
| 2178 | onChange={(event) => |
| 2179 | setDraft((current) => ({ |
| 2180 | ...current, |
| 2181 | signaturePrefix: event.target.value, |
| 2182 | })) |
| 2183 | } |
| 2184 | /> |
| 2185 | </Field> |
| 2186 | <Field label={gt("Encoding")} htmlFor="scheduled-task-signature-encoding"> |
| 2187 | <Select |
| 2188 | value={draft.signatureEncoding} |
| 2189 | onValueChange={(value) => |
| 2190 | setDraft((current) => ({ |
| 2191 | ...current, |
| 2192 | signatureEncoding: value === "base64" ? "base64" : "hex", |
| 2193 | })) |
| 2194 | } |
| 2195 | > |
| 2196 | <SelectTrigger size="sm" id="scheduled-task-signature-encoding"> |
| 2197 | <SelectValue>{draft.signatureEncoding}</SelectValue> |
| 2198 | </SelectTrigger> |
| 2199 | <SelectPopup> |
| 2200 | <SelectItem value="hex">hex</SelectItem> |
| 2201 | <SelectItem value="base64">base64</SelectItem> |
| 2202 | </SelectPopup> |
| 2203 | </Select> |
| 2204 | </Field> |
| 2205 | <Field label={gt("Secret")} htmlFor="scheduled-task-signature-secret"> |
| 2206 | <Input |
| 2207 | id="scheduled-task-signature-secret" |
| 2208 | type="password" |
| 2209 | autoComplete="off" |
| 2210 | value={draft.signatureSecret} |
| 2211 | placeholder={ |
| 2212 | liveTask?.schedule.type === "webhook" && liveTask.webhook?.hasSecret |
| 2213 | ? gt("Unchanged") |
| 2214 | : gt("Shared secret") |
| 2215 | } |
| 2216 | onChange={(event) => |
| 2217 | setDraft((current) => ({ |
| 2218 | ...current, |
| 2219 | signatureSecret: event.target.value, |
| 2220 | })) |
| 2221 | } |
| 2222 | /> |
| 2223 | </Field> |
| 2224 | </div> |
| 2225 | ) : null} |
| 2226 | </div> |
| 2227 | ) : draft.scheduleMode === "once" ? ( |
| 2228 | <div className="flex items-center gap-2"> |
| 2229 | <Label htmlFor="scheduled-task-run-at"> |
| 2230 | <T>Run on</T> |
| 2231 | </Label> |
| 2232 | <Input |
| 2233 | type="datetime-local" |
| 2234 | id="scheduled-task-run-at" |
| 2235 | nativeInput |
| 2236 | className="w-56" |
| 2237 | value={draft.runAt} |
| 2238 | onChange={(event) => |
| 2239 | setDraft((current) => ({ ...current, runAt: event.target.value })) |
| 2240 | } |
| 2241 | /> |
| 2242 | </div> |
| 2243 | ) : draft.scheduleMode === "fixed" ? ( |
| 2244 | <div className="flex flex-wrap items-center gap-3"> |
| 2245 | <div className="flex items-center gap-2"> |
| 2246 | <Label htmlFor="scheduled-task-time"> |
| 2247 | <T>Run at</T> |
| 2248 | </Label> |
| 2249 | <Input |
| 2250 | type="time" |
| 2251 | id="scheduled-task-time" |
| 2252 | aria-describedby={ |
| 2253 | runAtZone === undefined ? undefined : "scheduled-task-time-zone" |
| 2254 | } |
| 2255 | nativeInput |
| 2256 | className="w-32" |
| 2257 | value={draft.timeOfDay} |
| 2258 | onChange={(event) => |
| 2259 | setDraft((current) => ({ ...current, timeOfDay: event.target.value })) |
| 2260 | } |
| 2261 | /> |
| 2262 | {runAtZone === undefined ? null : ( |
| 2263 | <span id="scheduled-task-time-zone" className="text-xs text-muted-foreground"> |
| 2264 | {runAtZone} |
| 2265 | </span> |
| 2266 | )} |
| 2267 | <span className="text-xs text-muted-foreground"> |
| 2268 | <T context="between the run time and the weekday buttons, as in Run at 9:00 on Mon Wed"> |
| 2269 | on |
| 2270 | </T> |
| 2271 | </span> |
| 2272 | </div> |
| 2273 | <ToggleGroup |
| 2274 | multiple |
| 2275 | variant="outline" |
| 2276 | size="sm" |
| 2277 | aria-label={gt("Days to run")} |
| 2278 | value={[...draft.weekdays].map(String)} |
| 2279 | onValueChange={(values) => { |
| 2280 | if (values.length === 0) return; |
| 2281 | setDraft((current) => ({ |
| 2282 | ...current, |
| 2283 | weekdays: new Set(values.map(Number)), |
| 2284 | })); |
| 2285 | }} |
| 2286 | > |
| 2287 | {WEEKDAY_ORDER.map((day) => ( |
| 2288 | <Toggle |
| 2289 | key={day} |
| 2290 | value={String(day)} |
| 2291 | aria-label={weekdayShortLabel(day, locale)} |
| 2292 | > |
| 2293 | {messages(WEEKDAY_SHORT[day])} |
| 2294 | </Toggle> |
| 2295 | ))} |
| 2296 | </ToggleGroup> |
| 2297 | </div> |
| 2298 | ) : ( |
| 2299 | <div className="flex items-center gap-2"> |
| 2300 | <Label htmlFor="scheduled-task-interval"> |
| 2301 | <T>Run every</T> |
| 2302 | </Label> |
| 2303 | <Input |
| 2304 | type="number" |
| 2305 | id="scheduled-task-interval" |
| 2306 | nativeInput |
| 2307 | min={1} |
| 2308 | step="any" |
| 2309 | className="w-24" |
| 2310 | value={draft.intervalMinutes} |
| 2311 | onChange={(event) => |
| 2312 | setDraft((current) => ({ ...current, intervalMinutes: event.target.value })) |
| 2313 | } |
| 2314 | /> |
| 2315 | <span className="text-xs text-muted-foreground">minutes</span> |
| 2316 | </div> |
| 2317 | )} |
| 2318 | </div> |
| 2319 | |
| 2320 | <div className="flex items-center justify-between gap-4"> |
| 2321 | <div className="min-w-0 space-y-1"> |
| 2322 | <Label htmlFor="scheduled-task-enabled"> |
| 2323 | <T>Enabled</T> |
| 2324 | </Label> |
| 2325 | <p id="scheduled-task-enabled-description" className="text-sm text-muted-foreground"> |
| 2326 | <T>Disabled tasks stay saved but do not run.</T> |
| 2327 | </p> |
| 2328 | </div> |
| 2329 | <Switch |
| 2330 | id="scheduled-task-enabled" |
| 2331 | aria-describedby="scheduled-task-enabled-description" |
| 2332 | checked={draft.enabled} |
| 2333 | onCheckedChange={(enabled) => setDraft((current) => ({ ...current, enabled }))} |
| 2334 | /> |
| 2335 | </div> |
| 2336 | </fieldset> |
| 2337 | </DialogPanel> |
| 2338 | |
| 2339 | <DialogFooter> |
| 2340 | <DialogClose render={<Button variant="outline" size="sm" disabled={saving} />}> |
| 2341 | <T>Cancel</T> |
| 2342 | </DialogClose> |
| 2343 | <Button |
| 2344 | size="sm" |
| 2345 | disabled={ |
| 2346 | !canOperate || |
| 2347 | saving || |
| 2348 | editingTaskMissing || |
| 2349 | !connected || |
| 2350 | !tasksQuery.data || |
| 2351 | automaticBaseRefLoading || |
| 2352 | (draft.enabled && draft.scheduleMode === "webhook" && webhookDenial !== undefined) |
| 2353 | } |
| 2354 | onClick={() => void submit()} |
| 2355 | > |
| 2356 | {draft.editingId ? gt("Save task") : gt("Create task")} |
| 2357 | </Button> |
| 2358 | </DialogFooter> |
| 2359 | </> |
| 2360 | ); |
| 2361 | } |