The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import { isListedThreadLineage, isWebhookDedupeTemplate } from "@t3tools/contracts"; |
| 2 | import { |
| 3 | EnvironmentId, |
| 4 | MAX_WEBHOOK_DELIVERY_AGE_MINUTES, |
| 5 | type ProjectId, |
| 6 | ScheduledTaskId, |
| 7 | type ScheduledTask, |
| 8 | type ScheduledTaskSchedule, |
| 9 | type ScheduledTaskThreadMode, |
| 10 | type ScheduledTaskUpsertSchedule, |
| 11 | scheduledTaskThreadMode, |
| 12 | type ModelSelection, |
| 13 | type RuntimeMode, |
| 14 | type ProviderInteractionMode, |
| 15 | type ServerSettings, |
| 16 | type ThreadId, |
| 17 | } from "@t3tools/contracts"; |
| 18 | import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/models"; |
| 19 | import { |
| 20 | parseMaxDeliveryAge, |
| 21 | parseWebhookFilterDrafts, |
| 22 | webhookFilterDrafts, |
| 23 | webhookFilterDraftsChanged, |
| 24 | type WebhookFilterDraft, |
| 25 | } from "@t3tools/client-runtime/scheduled-task-webhook"; |
| 26 | import { scheduleTimeZoneLabel } from "@t3tools/client-runtime/scheduled-task-time-zone"; |
| 27 | import { msg } from "gt-react"; |
| 28 | |
| 29 | import { |
| 30 | resolveProjectSettings, |
| 31 | type LegacyProjectSettingsFields, |
| 32 | } from "@t3tools/shared/projectSettings"; |
| 33 | import { getActiveLocale, m, type MessageResolver } from "../../i18n/messages"; |
| 34 | import type { ProviderInstanceEntry } from "../../providerInstances"; |
| 35 | |
| 36 | import type { ResolvedSettingsScope } from "./settingsScope"; |
| 37 | |
| 38 | /** Abbreviated weekday name, 0 = Sunday. */ |
| 39 | export function weekdayShortLabel(day: number, locale: string = getActiveLocale()): string { |
| 40 | // 2024-01-07 was a Sunday. |
| 41 | return new Intl.DateTimeFormat(locale, { weekday: "short", timeZone: "UTC" }).format( |
| 42 | new Date(Date.UTC(2024, 0, 7 + day)), |
| 43 | ); |
| 44 | } |
| 45 | |
| 46 | const ONCE_FORMATTER = new Intl.DateTimeFormat(undefined, { |
| 47 | dateStyle: "medium", |
| 48 | timeStyle: "short", |
| 49 | }); |
| 50 | |
| 51 | export function scheduleLabel( |
| 52 | schedule: ScheduledTaskSchedule, |
| 53 | timeZone?: string, |
| 54 | runAt?: string | null, |
| 55 | resolve: MessageResolver = m, |
| 56 | locale: string = getActiveLocale(), |
| 57 | ): string { |
| 58 | if (schedule.type === "webhook") return resolve(msg("On webhook")); |
| 59 | if (schedule.type === "once") { |
| 60 | return resolve(msg("Once, {time}", { time: ONCE_FORMATTER.format(new Date(schedule.runAt)) })); |
| 61 | } |
| 62 | if (schedule.type === "interval") { |
| 63 | const minutes = schedule.everyMs / 60_000; |
| 64 | return Number.isInteger(minutes) |
| 65 | ? resolve(msg("Every {minutes} min", { minutes })) |
| 66 | : resolve(msg("Every {seconds} sec", { seconds: Math.round(schedule.everyMs / 1000) })); |
| 67 | } |
| 68 | const weekdays = schedule.weekdays ?? []; |
| 69 | const time = schedule.timeOfDay; |
| 70 | const zone = scheduleTimeZoneLabel(timeZone, runAt); |
| 71 | if (weekdays.length === 0) { |
| 72 | return zone === undefined |
| 73 | ? resolve(msg("Daily at {time}", { time })) |
| 74 | : resolve(msg("Daily at {time} {zone}", { time, zone })); |
| 75 | } |
| 76 | if (weekdays.length === 5 && weekdays.every((day) => day >= 1 && day <= 5)) { |
| 77 | return zone === undefined |
| 78 | ? resolve(msg("Weekdays at {time}", { time })) |
| 79 | : resolve(msg("Weekdays at {time} {zone}", { time, zone })); |
| 80 | } |
| 81 | const days = weekdays |
| 82 | .map((day) => (day >= 0 && day <= 6 ? weekdayShortLabel(day, locale) : "")) |
| 83 | .join(", "); |
| 84 | return zone === undefined |
| 85 | ? resolve(msg("{days} at {time}", { days, time })) |
| 86 | : resolve(msg("{days} at {time} {zone}", { days, time, zone })); |
| 87 | } |
| 88 | |
| 89 | export function matchesScheduledTaskScope( |
| 90 | scope: ResolvedSettingsScope, |
| 91 | environmentId: EnvironmentId, |
| 92 | projectId: ProjectId, |
| 93 | ): boolean { |
| 94 | if (scope.kind === "unavailable" || !scope.environmentIds.includes(environmentId)) return false; |
| 95 | if (scope.kind === "project" || scope.kind === "checkout") { |
| 96 | return scope.members.some( |
| 97 | (member) => member.environmentId === environmentId && member.id === projectId, |
| 98 | ); |
| 99 | } |
| 100 | return true; |
| 101 | } |
| 102 | |
| 103 | export function validateScheduledTasksSearch(raw: Record<string, unknown>) { |
| 104 | return { |
| 105 | ...(typeof raw.environmentId === "string" && raw.environmentId.trim() |
| 106 | ? { environmentId: EnvironmentId.make(raw.environmentId) } |
| 107 | : {}), |
| 108 | ...(typeof raw.taskId === "string" && raw.taskId.trim() |
| 109 | ? { taskId: ScheduledTaskId.make(raw.taskId) } |
| 110 | : {}), |
| 111 | }; |
| 112 | } |
| 113 | |
| 114 | export type ScheduleMode = "fixed" | "once" | "interval" | "webhook"; |
| 115 | export type WorkspaceMode = "root" | "worktree" | "existing_worktree"; |
| 116 | |
| 117 | export interface DraftState { |
| 118 | readonly editingId: string | null; |
| 119 | readonly title: string; |
| 120 | readonly prompt: string; |
| 121 | readonly enabled: boolean; |
| 122 | readonly scheduleMode: ScheduleMode; |
| 123 | readonly intervalMinutes: string; |
| 124 | readonly timeOfDay: string; |
| 125 | /** Local date and time as a `datetime-local` input value, such as 2026-11-02T15:00. */ |
| 126 | readonly runAt: string; |
| 127 | /** The stored ISO run time, sent back unchanged when the field was not edited. */ |
| 128 | readonly savedRunAt: string; |
| 129 | readonly weekdays: ReadonlySet<number>; |
| 130 | readonly projectId: string; |
| 131 | readonly threadId: string; |
| 132 | /** The thread the form opened with, so a save can tell a cleared destination from an unbound one. */ |
| 133 | readonly savedThreadId: string; |
| 134 | readonly threadMode: ScheduledTaskThreadMode; |
| 135 | readonly workspaceMode: WorkspaceMode; |
| 136 | readonly baseRef: string; |
| 137 | readonly startFromOrigin: boolean; |
| 138 | readonly existingWorktreePath: string; |
| 139 | readonly modelKey: string; |
| 140 | readonly runtimeMode: RuntimeMode; |
| 141 | readonly interactionMode: ProviderInteractionMode; |
| 142 | /** Retain the source selection's provider options when the picker leaves instanceId:model unchanged. */ |
| 143 | readonly baseModelSelection: ModelSelection | null; |
| 144 | readonly signatureEnabled: boolean; |
| 145 | readonly signatureHeader: string; |
| 146 | readonly signatureEncoding: "hex" | "base64"; |
| 147 | readonly signaturePrefix: string; |
| 148 | /** Write-only: empty keeps the secret already stored on the server. */ |
| 149 | readonly signatureSecret: string; |
| 150 | readonly maxDeliveryAgeMinutes: string; |
| 151 | readonly replayKey: string; |
| 152 | readonly coalesceKey: string; |
| 153 | readonly coalesceWindowSeconds: string; |
| 154 | readonly filters: ReadonlyArray<WebhookFilterDraft>; |
| 155 | /** The filter rows the form opened with. */ |
| 156 | readonly savedFilters: ReadonlyArray<WebhookFilterDraft>; |
| 157 | } |
| 158 | |
| 159 | export const WEBHOOK_SIGNATURE_DEFAULTS = { |
| 160 | signatureHeader: "x-hub-signature-256", |
| 161 | signatureEncoding: "hex", |
| 162 | signaturePrefix: "sha256=", |
| 163 | } as const; |
| 164 | |
| 165 | /** Formats a date as a `datetime-local` input value in the browser's time zone. */ |
| 166 | export function toDateTimeLocalValue(date: Date): string { |
| 167 | const pad = (value: number) => String(value).padStart(2, "0"); |
| 168 | return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}`; |
| 169 | } |
| 170 | |
| 171 | export function scheduleDraftErrors(draft: DraftState, resolve: MessageResolver = m) { |
| 172 | const invalidRunTime = (description: string) => [ |
| 173 | { title: resolve(msg("Invalid run time")), description }, |
| 174 | ]; |
| 175 | if (draft.scheduleMode === "once") { |
| 176 | const runAt = new Date(draft.runAt); |
| 177 | if (Number.isNaN(runAt.getTime())) return invalidRunTime(resolve(msg("Pick a date and time."))); |
| 178 | // A time skipped by a daylight saving change parses to a different clock time. |
| 179 | if (toDateTimeLocalValue(runAt) !== draft.runAt) |
| 180 | return invalidRunTime(resolve(msg("That time does not exist in your time zone."))); |
| 181 | return []; |
| 182 | } |
| 183 | if (draft.scheduleMode === "fixed" && !draft.timeOfDay) |
| 184 | return invalidRunTime(resolve(msg("Pick a time."))); |
| 185 | if (draft.scheduleMode !== "webhook") return []; |
| 186 | if (parseMaxDeliveryAge(draft.maxDeliveryAgeMinutes) === undefined) |
| 187 | return [ |
| 188 | { |
| 189 | title: resolve(msg("Invalid age limit")), |
| 190 | description: resolve( |
| 191 | msg("Enter whole minutes from 1 to {max}, or leave it blank.", { |
| 192 | max: MAX_WEBHOOK_DELIVERY_AGE_MINUTES, |
| 193 | }), |
| 194 | ), |
| 195 | }, |
| 196 | ]; |
| 197 | const errors: Array<{ title: string; description: string }> = []; |
| 198 | for (const [description, value] of [ |
| 199 | [msg("Duplicate request key must contain a valid request placeholder."), draft.replayKey], |
| 200 | [msg("Coalesce key must contain a valid request placeholder."), draft.coalesceKey], |
| 201 | ] as const) { |
| 202 | if (value.trim() && !isWebhookDedupeTemplate(value.trim())) |
| 203 | errors.push({ |
| 204 | title: resolve(msg("Invalid webhook settings")), |
| 205 | description: resolve(description), |
| 206 | }); |
| 207 | } |
| 208 | const window = draft.coalesceWindowSeconds.trim(); |
| 209 | if (window && (!Number.isInteger(Number(window)) || Number(window) < 10 || Number(window) > 3600)) |
| 210 | errors.push({ |
| 211 | title: resolve(msg("Invalid webhook settings")), |
| 212 | description: resolve(msg("Coalesce window must be whole seconds from 10 to 3600.")), |
| 213 | }); |
| 214 | return errors; |
| 215 | } |
| 216 | |
| 217 | const WEBHOOK_DELIVERY_LABELS: Record<string, string> = { |
| 218 | dispatch_failed: msg("Run failed"), |
| 219 | duplicate: msg("Duplicate", { $context: "webhook delivery outcome" }), |
| 220 | coalesced: msg("Coalesced"), |
| 221 | filtered: msg("Filtered", { $context: "webhook delivery outcome" }), |
| 222 | rejected_signature: msg("Bad signature"), |
| 223 | disabled: msg("Task paused"), |
| 224 | rate_limited: msg("Rate limited"), |
| 225 | expired: msg("Too old"), |
| 226 | }; |
| 227 | |
| 228 | export function webhookDeliveryLabel( |
| 229 | delivery: { |
| 230 | readonly outcome: string; |
| 231 | readonly pendingWindow?: boolean | undefined; |
| 232 | }, |
| 233 | resolve: MessageResolver = m, |
| 234 | ) { |
| 235 | if (delivery.outcome === "accepted") { |
| 236 | return delivery.pendingWindow |
| 237 | ? resolve(msg("Opened window")) |
| 238 | : resolve(msg("Ran", { $context: "webhook delivery outcome" })); |
| 239 | } |
| 240 | const label = WEBHOOK_DELIVERY_LABELS[delivery.outcome]; |
| 241 | return label ? resolve(label) : delivery.outcome.replaceAll("_", " "); |
| 242 | } |
| 243 | |
| 244 | export function scheduleFromDraft(draft: DraftState): ScheduledTaskUpsertSchedule | null { |
| 245 | if (scheduleDraftErrors(draft).length > 0) return null; |
| 246 | if (draft.scheduleMode === "once") { |
| 247 | const saved = draft.savedRunAt ? new Date(draft.savedRunAt) : null; |
| 248 | if (saved !== null && toDateTimeLocalValue(saved) === draft.runAt) |
| 249 | return { type: "once", runAt: draft.savedRunAt }; |
| 250 | // A `datetime-local` value has no offset. In an hour that repeats when clocks go |
| 251 | // back, keep the saved time's offset; otherwise Date reads it as local time. |
| 252 | const withSavedOffset = |
| 253 | saved === null |
| 254 | ? null |
| 255 | : new Date(Date.parse(`${draft.runAt}Z`) + saved.getTimezoneOffset() * 60_000); |
| 256 | return { |
| 257 | type: "once", |
| 258 | runAt: |
| 259 | withSavedOffset !== null && toDateTimeLocalValue(withSavedOffset) === draft.runAt |
| 260 | ? withSavedOffset.toISOString() |
| 261 | : new Date(draft.runAt).toISOString(), |
| 262 | }; |
| 263 | } |
| 264 | if (draft.scheduleMode === "webhook") { |
| 265 | const maxDeliveryAgeMinutes = parseMaxDeliveryAge(draft.maxDeliveryAgeMinutes); |
| 266 | const replayKey = draft.replayKey.trim(); |
| 267 | const coalesceKey = draft.coalesceKey.trim(); |
| 268 | const coalesceWindowSeconds = draft.coalesceWindowSeconds.trim() |
| 269 | ? Number(draft.coalesceWindowSeconds) |
| 270 | : undefined; |
| 271 | if (maxDeliveryAgeMinutes === undefined) return null; |
| 272 | const parsedFilters = parseWebhookFilterDrafts(draft.filters); |
| 273 | if (!("filters" in parsedFilters)) return null; |
| 274 | const secret = draft.signatureSecret.trim(); |
| 275 | return { |
| 276 | type: "webhook", |
| 277 | signature: draft.signatureEnabled |
| 278 | ? { |
| 279 | header: draft.signatureHeader.trim(), |
| 280 | encoding: draft.signatureEncoding, |
| 281 | prefix: draft.signaturePrefix, |
| 282 | ...(secret ? { secret } : {}), |
| 283 | } |
| 284 | : null, |
| 285 | maxDeliveryAgeMinutes, |
| 286 | ...(replayKey || coalesceKey || coalesceWindowSeconds !== undefined |
| 287 | ? { |
| 288 | dedupe: { |
| 289 | ...(replayKey ? { replayKey } : {}), |
| 290 | ...(coalesceKey ? { coalesceKey } : {}), |
| 291 | ...(coalesceWindowSeconds === undefined ? {} : { coalesceWindowSeconds }), |
| 292 | }, |
| 293 | } |
| 294 | : { dedupe: {} }), |
| 295 | // Only edited filters are sent; the server keeps the stored ones otherwise. |
| 296 | ...(webhookFilterDraftsChanged(draft.savedFilters, draft.filters) |
| 297 | ? { filters: parsedFilters.filters } |
| 298 | : {}), |
| 299 | }; |
| 300 | } |
| 301 | if (draft.scheduleMode === "interval") { |
| 302 | const everyMs = Math.round(Number(draft.intervalMinutes) * 60_000); |
| 303 | return { type: "interval", everyMs }; |
| 304 | } |
| 305 | const selectedEveryDay = draft.weekdays.size === 0 || draft.weekdays.size === 7; |
| 306 | return { |
| 307 | type: "fixed_time", |
| 308 | timeOfDay: draft.timeOfDay, |
| 309 | ...(selectedEveryDay ? {} : { weekdays: [...draft.weekdays].toSorted() }), |
| 310 | }; |
| 311 | } |
| 312 | |
| 313 | export function taskToDraft(task: ScheduledTask): DraftState { |
| 314 | const schedule = task.schedule; |
| 315 | const filters = webhookFilterDrafts(schedule.type === "webhook" ? schedule.filters : undefined); |
| 316 | const weekdays = |
| 317 | schedule.type === "fixed_time" && schedule.weekdays && schedule.weekdays.length > 0 |
| 318 | ? new Set(schedule.weekdays) |
| 319 | : new Set([0, 1, 2, 3, 4, 5, 6]); |
| 320 | return { |
| 321 | editingId: task.id, |
| 322 | title: task.title, |
| 323 | prompt: task.prompt, |
| 324 | enabled: task.enabled, |
| 325 | scheduleMode: schedule.type === "fixed_time" ? "fixed" : schedule.type, |
| 326 | intervalMinutes: |
| 327 | schedule.type === "interval" ? String(Math.max(1, schedule.everyMs / 60_000)) : "15", |
| 328 | // A time input shows nothing for an unpadded hour such as 9:05, which agents may save. |
| 329 | timeOfDay: schedule.type === "fixed_time" ? schedule.timeOfDay.padStart(5, "0") : "09:00", |
| 330 | runAt: schedule.type === "once" ? toDateTimeLocalValue(new Date(schedule.runAt)) : "", |
| 331 | savedRunAt: schedule.type === "once" ? schedule.runAt : "", |
| 332 | weekdays, |
| 333 | projectId: task.projectId, |
| 334 | threadId: task.threadId ?? "", |
| 335 | savedThreadId: task.threadId ?? "", |
| 336 | threadMode: scheduledTaskThreadMode(task), |
| 337 | workspaceMode: task.workspaceStrategy.type, |
| 338 | baseRef: task.workspaceStrategy.type === "worktree" ? task.workspaceStrategy.baseRef : "", |
| 339 | startFromOrigin: |
| 340 | task.workspaceStrategy.type === "worktree" |
| 341 | ? (task.workspaceStrategy.startFromOrigin ?? false) |
| 342 | : true, |
| 343 | existingWorktreePath: |
| 344 | task.workspaceStrategy.type === "existing_worktree" |
| 345 | ? task.workspaceStrategy.worktreePath |
| 346 | : "", |
| 347 | modelKey: `${task.modelSelection.instanceId}:${task.modelSelection.model}`, |
| 348 | runtimeMode: task.runtimeMode, |
| 349 | interactionMode: task.interactionMode, |
| 350 | baseModelSelection: task.modelSelection, |
| 351 | ...(schedule.type === "webhook" && schedule.signature !== null |
| 352 | ? { |
| 353 | signatureEnabled: true, |
| 354 | signatureHeader: schedule.signature.header, |
| 355 | signatureEncoding: schedule.signature.encoding, |
| 356 | signaturePrefix: schedule.signature.prefix, |
| 357 | } |
| 358 | : { signatureEnabled: false, ...WEBHOOK_SIGNATURE_DEFAULTS }), |
| 359 | signatureSecret: "", |
| 360 | replayKey: schedule.type === "webhook" ? (schedule.dedupe?.replayKey ?? "") : "", |
| 361 | coalesceKey: schedule.type === "webhook" ? (schedule.dedupe?.coalesceKey ?? "") : "", |
| 362 | coalesceWindowSeconds: |
| 363 | schedule.type === "webhook" && schedule.dedupe?.coalesceWindowSeconds !== undefined |
| 364 | ? String(schedule.dedupe.coalesceWindowSeconds) |
| 365 | : "", |
| 366 | maxDeliveryAgeMinutes: |
| 367 | schedule.type === "webhook" && schedule.maxDeliveryAgeMinutes != null |
| 368 | ? String(schedule.maxDeliveryAgeMinutes) |
| 369 | : "", |
| 370 | filters, |
| 371 | savedFilters: filters, |
| 372 | }; |
| 373 | } |
| 374 | |
| 375 | export function moveDraftToThread( |
| 376 | draft: DraftState, |
| 377 | thread: { readonly id: ThreadId; readonly projectId: ProjectId }, |
| 378 | ): DraftState { |
| 379 | return { |
| 380 | ...draft, |
| 381 | threadId: thread.id, |
| 382 | projectId: thread.projectId, |
| 383 | threadMode: draft.threadMode === "new_thread" ? "continue" : draft.threadMode, |
| 384 | }; |
| 385 | } |
| 386 | |
| 387 | /** Leaves the thread but keeps the mode. Matches MCP: new threads stay out of the shared checkout. */ |
| 388 | export function unbindDraftFromThread(draft: DraftState): DraftState { |
| 389 | if (!draft.threadId) return draft; |
| 390 | return { |
| 391 | ...draft, |
| 392 | threadId: "", |
| 393 | ...(draft.workspaceMode === "root" |
| 394 | ? { workspaceMode: "worktree" as const, startFromOrigin: true } |
| 395 | : {}), |
| 396 | }; |
| 397 | } |
| 398 | |
| 399 | export function changeDraftProject(draft: DraftState, projectId: string): DraftState { |
| 400 | if (projectId === draft.projectId) return draft; |
| 401 | return { ...unbindDraftFromThread(draft), projectId }; |
| 402 | } |
| 403 | |
| 404 | /** Threads a task can move to. The current one is left out; the picker always shows it. */ |
| 405 | export function scheduledTaskDestinationThreads( |
| 406 | threads: ReadonlyArray<EnvironmentThreadShell>, |
| 407 | target: { |
| 408 | readonly environmentId: EnvironmentId; |
| 409 | readonly projectId: string; |
| 410 | readonly currentThreadId: ThreadId | null; |
| 411 | readonly query: string; |
| 412 | }, |
| 413 | ): ReadonlyArray<EnvironmentThreadShell> { |
| 414 | const search = target.query.trim().toLocaleLowerCase(); |
| 415 | return threads |
| 416 | .filter( |
| 417 | (thread) => |
| 418 | thread.environmentId === target.environmentId && |
| 419 | thread.projectId === target.projectId && |
| 420 | thread.id !== target.currentThreadId && |
| 421 | thread.archivedAt === null && |
| 422 | isListedThreadLineage(thread.lineage) && |
| 423 | thread.title.toLocaleLowerCase().includes(search), |
| 424 | ) |
| 425 | .toSorted((left, right) => right.updatedAt.localeCompare(left.updatedAt)); |
| 426 | } |
| 427 | |
| 428 | export function scheduledTaskDefaultModel( |
| 429 | settings: ServerSettings, |
| 430 | project: (LegacyProjectSettingsFields & { readonly id: ProjectId }) | null, |
| 431 | entries: readonly ProviderInstanceEntry[], |
| 432 | ): ModelSelection | null { |
| 433 | const available = entries.filter( |
| 434 | (entry) => |
| 435 | entry.enabled && |
| 436 | entry.installed && |
| 437 | entry.isAvailable && |
| 438 | entry.snapshot.auth.status !== "unauthenticated", |
| 439 | ); |
| 440 | const configured = resolveProjectSettings(settings, project?.id ?? null, project).settings |
| 441 | .defaultModelSelection; |
| 442 | for (const selection of [configured, settings.defaultModelSelection]) { |
| 443 | if ( |
| 444 | selection && |
| 445 | available.some( |
| 446 | (entry) => |
| 447 | entry.instanceId === selection.instanceId && |
| 448 | entry.models.find((model) => model.slug === selection.model)?.isLegacy !== true, |
| 449 | ) |
| 450 | ) |
| 451 | return selection; |
| 452 | } |
| 453 | const models = available.flatMap((entry) => |
| 454 | entry.models |
| 455 | .filter((model) => !model.isLegacy) |
| 456 | .map((model) => ({ instanceId: entry.instanceId, model })), |
| 457 | ); |
| 458 | const fallback = models.find(({ model }) => model.isDefault) ?? models[0]; |
| 459 | return fallback ? { instanceId: fallback.instanceId, model: fallback.model.slug } : null; |
| 460 | } |
| 461 | |
| 462 | /** |
| 463 | * A new task's project: a pinned open project, then any open one. An archived |
| 464 | * project only when Settings is scoped to it, so that scope can still save. |
| 465 | */ |
| 466 | export function defaultScheduledTaskProjectId< |
| 467 | TProject extends { |
| 468 | readonly id: ProjectId; |
| 469 | readonly pinnedAt?: string | null | undefined; |
| 470 | readonly archivedAt?: string | null | undefined; |
| 471 | }, |
| 472 | >(scopedProjects: ReadonlyArray<TProject>, scope: ResolvedSettingsScope): ProjectId | "" { |
| 473 | const open = scopedProjects.filter((project) => project.archivedAt == null); |
| 474 | const scopedToProject = scope.kind === "project" || scope.kind === "checkout"; |
| 475 | return ( |
| 476 | ( |
| 477 | open.find((project) => project.pinnedAt != null) ?? |
| 478 | open[0] ?? |
| 479 | (scopedToProject ? scopedProjects[0] : undefined) |
| 480 | )?.id ?? "" |
| 481 | ); |
| 482 | } |