Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion apps/mobile/src/features/keyboard/CommandPalette.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -338,7 +338,7 @@ export function CommandPalette(props: {
key: "scheduledTasks",
kind: "action",
title: gt("Scheduled tasks"),
searchTerms: ["schedule", "automations", "recurring"],
searchTerms: ["schedule", "automations", "recurring", "cron"],
run: () => openSettings(navigation, "SettingsScheduledTasks"),
},
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -205,21 +205,38 @@ function button(label: string) {
return element;
}
describe("scheduled task batched edits", () => {
it("submits the selected interval when saved before React commits", async () => {
await act(async () => {
button("Interval").click();
button("Save changes").click();
});
expect(mocks.alert).not.toHaveBeenCalled();
expect(mocks.upsert).toHaveBeenCalledExactlyOnceWith({
environmentId: "environment",
input: expect.objectContaining({
id: "task",
requireExisting: true,
schedule: { type: "interval", everyMs: 3_600_000 },
}),
});
});
it.each([
{ from: "a fixed time", schedule: {} },
{
from: "an invalid cron expression",
schedule: { mode: "cron", cronExpression: "60 * * * *" },
},
] as const)(
"submits the selected interval when saved before React commits, from $from",
async ({ schedule }) => {
const editor = appAtomRegistry.get(scheduledTaskEditorSessionAtom)?.current;
if (!editor) throw new Error("Missing editor");
act(() =>
startScheduledTaskEditor({
...editor,
draft: { ...editor.draft, schedule: { ...editor.draft.schedule, ...schedule } },
}),
);
await act(async () => {
button("Interval").click();
button("Save changes").click();
});
expect(mocks.alert).not.toHaveBeenCalled();
expect(mocks.upsert).toHaveBeenCalledExactlyOnceWith({
environmentId: "environment",
input: expect.objectContaining({
id: "task",
requireExisting: true,
schedule: { type: "interval", everyMs: 3_600_000 },
}),
});
},
);
it("retains the interval when enabled changes before React commits", async () => {
act(() => {
button("Interval").click();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import { msg, T, useGT, useLocale, useMessages, Var } from "gt-react-native";
import { managedCapabilityDenial } from "@t3tools/client-runtime/contract-labels";
import {
managedCapabilityDenial,
scheduledTaskCronExpressionError,
} from "@t3tools/client-runtime/contract-labels";
import * as Dialog from "../../components/ui/Dialog";
import { useAtomValue } from "@effect/atom-react";
import {
Expand Down Expand Up @@ -139,6 +142,8 @@ function describeSchedule(
}
if (task.schedule.type === "interval")
return formatScheduledTaskInterval(task.schedule.everyMs, resolve);
if (task.schedule.type === "cron")
return resolve(msg("Cron {expression}", { expression: task.schedule.expression }));
const days = task.schedule.weekdays?.length
? repeatLabel(task.schedule.weekdays, resolve, locale)
: resolve(msg("Every day"));
Expand Down Expand Up @@ -202,6 +207,8 @@ function FormField(props: {
readonly value: string;
readonly onChange: (value: string) => void;
readonly keyboardType?: "decimal-pad" | "number-pad";
readonly autoCapitalize?: "none";
readonly autoCorrect?: boolean;
readonly disabled?: boolean;
readonly placeholder?: string;
readonly borderTop?: boolean;
Expand All @@ -220,6 +227,8 @@ function FormField(props: {
onChangeText={props.onChange}
textAlignVertical="center"
keyboardType={props.keyboardType}
autoCapitalize={props.autoCapitalize}
autoCorrect={props.autoCorrect}
placeholder={props.placeholder}
placeholderTextColorClassName="accent-foreground-muted"
className="min-h-8 font-sans text-base text-foreground"
Expand Down Expand Up @@ -789,6 +798,11 @@ function TaskForm({
const environmentUnavailable = !availableTargets.some(
(target) => target.environmentId === environmentId,
);
const cronSupported = config?.environment.capabilities.scheduledTaskCron === true;
const cronError =
draft.schedule.mode === "cron"
? scheduledTaskCronExpressionError(draft.schedule.cronExpression, m)
: null;

const failure = (title: string, result: AtomCommandResult<unknown, unknown>) => {
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
Expand Down Expand Up @@ -857,6 +871,24 @@ function TaskForm({
);
return;
}
if (draft.schedule.mode === "cron" && !cronSupported) {
Dialog.alert(
gt("Custom schedules unavailable"),
gt("Update {product} on this environment to use custom schedules.", {
product: "T3 Code",
}),
);
return;
}
// Checks the draft just read, not the last render, so quick edits before Save count.
const savedCronError =
draft.schedule.mode === "cron"
? scheduledTaskCronExpressionError(draft.schedule.cronExpression, m)
: null;
if (savedCronError !== null) {
Dialog.alert(gt("Invalid cron expression"), savedCronError);
return;
}
if (
!draft.title.trim() ||
!draft.prompt.trim() ||
Expand Down Expand Up @@ -1163,6 +1195,14 @@ function TaskForm({
]
: []),
{ value: "interval", label: gt("Interval") },
...(cronSupported || draft.schedule.mode === "cron"
? [
{
value: "cron" as const,
label: gt("Custom", { $context: "custom cron schedule option" }),
},
]
: []),
...(webhookDenial === undefined || draft.schedule.mode === "webhook"
? [{ value: "webhook" as const, label: gt("On webhook") }]
: []),
Expand Down Expand Up @@ -1424,6 +1464,31 @@ function TaskForm({
</T>
</Text>
</>
) : draft.schedule.mode === "cron" ? (
<>
<FormField
label={gt("Cron expression")}
value={draft.schedule.cronExpression}
placeholder="0 9 * * 1-5"
autoCapitalize="none"
autoCorrect={false}
disabled={saving}
borderTop
onChange={(cronExpression) =>
setDraft((current) => ({
...current,
schedule: { ...current.schedule, cronExpression },
}))
}
/>
{cronError !== null && draft.schedule.cronExpression.trim() ? (
<Text className="px-4 pb-3 text-sm text-danger-foreground">{cronError}</Text>
) : (
<Text className="px-4 pb-3 text-sm text-foreground-muted">
<T>minute hour day month weekday</T>
</Text>
)}
</>
) : (
<>
<FormField
Expand Down Expand Up @@ -1465,7 +1530,7 @@ function TaskForm({
/>
</View>
</SettingsSection>
{draft.schedule.mode === "fixed_time" ? (
{draft.schedule.mode === "fixed_time" || draft.schedule.mode === "cron" ? (
<Text className="px-2 text-sm text-foreground-muted">
<T>Time uses the environment's time zone, which may differ from your phone's.</T>
</Text>
Expand Down
30 changes: 30 additions & 0 deletions apps/mobile/src/features/settings/scheduledTaskDraft.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
editDraft,
scheduledTaskDefaultModel,
DEFAULT_SCHEDULE,
hasScheduledTaskDraftChanges,
scheduleDraftForTask,
scheduleFromDraft,
} from "./scheduledTaskDraft";
Expand All @@ -24,6 +25,17 @@ describe("scheduleDraftForTask", () => {
expect(scheduleFromDraft(draft)).toEqual({ type: "interval", everyMs: 60_000 });
});

it("opens a cron task as cron and saves its expression with whitespace collapsed", () => {
const expression = "17 0,4,8-20 * * *";
const draft = scheduleDraftForTask({ schedule: { type: "cron", expression } });
expect(draft.mode).toBe("cron");
expect(scheduleFromDraft(draft)).toEqual({ type: "cron", expression });
expect(scheduleFromDraft({ ...draft, cronExpression: " 0 9 * *\t1-5\n" })).toEqual({
type: "cron",
expression: "0 9 * * 1-5",
});
});

it("round-trips dedupe settings and rejects invalid windows", () => {
const dedupe = {
replayKey: "{{headers.delivery-id}}",
Expand Down Expand Up @@ -111,6 +123,13 @@ describe("scheduleFromDraft", () => {
).toBeNull();
},
);

it.each(["", "* * * *", "0 0 9 * * 1", "@daily", "60 * * * *", "0 0 30 2 *"])(
"rejects the cron expression %j",
(cronExpression) => {
expect(scheduleFromDraft({ ...DEFAULT_SCHEDULE, mode: "cron", cronExpression })).toBeNull();
},
);
});

describe("scheduled task model defaults", () => {
Expand Down Expand Up @@ -245,3 +264,14 @@ describe("scheduled task worktree base", () => {
).toBe("release");
});
});

it("counts an edit to only the cron expression as an unsaved change", () => {
const draft = createDraft(null, null);
const cron = { ...draft, schedule: { ...draft.schedule, mode: "cron" as const } };
expect(
hasScheduledTaskDraftChanges(cron, {
...cron,
schedule: { ...cron.schedule, cronExpression: "0 10 * * 1-5" },
}),
).toBe(true);
});
19 changes: 17 additions & 2 deletions apps/mobile/src/features/settings/scheduledTaskDraft.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import { isWebhookDedupeTemplate, scheduledTaskThreadMode } from "@t3tools/contracts";
import {
isWebhookDedupeTemplate,
scheduledTaskCronExpressionError,
scheduledTaskThreadMode,
} from "@t3tools/contracts";
import type {
ModelSelection,
ServerConfig,
Expand Down Expand Up @@ -53,12 +57,13 @@ export function scheduledTaskDefaultModel(
}

export type ScheduleDraft = {
readonly mode: "fixed_time" | "once" | "interval" | "webhook";
readonly mode: "fixed_time" | "once" | "interval" | "cron" | "webhook";
readonly timeOfDay: string;
/** ISO time for a one-time run. Empty until the user picks the "Once" mode. */
readonly runAt: string;
readonly weekdays: ReadonlyArray<number>;
readonly intervalMinutes: string;
readonly cronExpression: string;
readonly signature: ScheduledTaskWebhookSignature | null;
readonly maxDeliveryAgeMinutes: string;
readonly replayKey: string;
Expand All @@ -75,6 +80,7 @@ export const DEFAULT_SCHEDULE: ScheduleDraft = {
runAt: "",
weekdays: [1, 2, 3, 4, 5],
intervalMinutes: "15",
cronExpression: "0 9 * * 1-5",
signature: null,
maxDeliveryAgeMinutes: "",
replayKey: "",
Expand Down Expand Up @@ -102,6 +108,8 @@ export function scheduleDraftForTask(task: Pick<ScheduledTask, "schedule">): Sch
mode: "interval",
intervalMinutes: String(Math.max(1, task.schedule.everyMs / 60_000)),
};
case "cron":
return { ...DEFAULT_SCHEDULE, mode: "cron", cronExpression: task.schedule.expression };
case "webhook":
return {
...DEFAULT_SCHEDULE,
Expand Down Expand Up @@ -182,6 +190,12 @@ export function scheduleFromDraft(draft: ScheduleDraft): ScheduledTaskUpsertSche
const everyMs = Math.round(minutes * 60_000);
return minutes >= 1 && Number.isSafeInteger(everyMs) ? { type: "interval", everyMs } : null;
}
if (draft.mode === "cron") {
const expression = draft.cronExpression.trim().split(/\s+/).join(" ");
return scheduledTaskCronExpressionError(expression) === null
? { type: "cron", expression }
: null;
}
const weekdays = [...new Set(draft.weekdays)].sort((a, b) => a - b);
if (
!/^([01]?\d|2[0-3]):[0-5]\d$/.test(draft.timeOfDay) ||
Expand Down Expand Up @@ -232,6 +246,7 @@ function draftSignature(draft: ScheduledTaskDraft): string {
draft.schedule.runAt,
[...draft.schedule.weekdays].sort((a, b) => a - b),
draft.schedule.intervalMinutes,
draft.schedule.cronExpression,
draft.schedule.maxDeliveryAgeMinutes,
draft.schedule.replayKey,
draft.schedule.coalesceKey,
Expand Down
15 changes: 15 additions & 0 deletions apps/mobile/src/i18n/translations/de.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,14 @@
"4735345a111c1581": "Submodule initialisieren",
"fd07736396b009c5": "Setup-Skript ausführen",
"cbbdd0430fbe5fea": "Agent starten",
"91a75ff683dd61f0": "Minute",
"77a4ecca368cb505": "Hour",
"86c33b12375c048d": "Day of month",
"d41aad09317c8868": "Month",
"12e488c816440404": "Weekday",
"154577f6a73dbd21": "Use five fields: minute hour day-of-month month weekday.",
"1c4d6595417793f1": "{field}: {detail}",
"d08c5e483b81b050": "This schedule never runs.",
"2a918ed2e51ab64a": "Verbindung wird hergestellt",
"ed0fecca26116eda": "Objekte werden gezählt",
"521b55ffc0a546df": "Objekte werden empfangen",
Expand Down Expand Up @@ -3611,6 +3619,7 @@
"dc673e51738ee402": "Ein Thread, neue Sitzung",
"d1800696738e0855": "Per Webhook",
"cc68653937406aaa": "Einmal, {date} um {time}",
"cadde1c1929b7f2e": "Cron {expression}",
"e0226f73554fcc85": "Jeden Tag",
"e1222cad4667e338": "{days} um {time}",
"74b25bf2e8d10313": "{days} um {time} {zone}",
Expand Down Expand Up @@ -3639,6 +3648,9 @@
"ef4c41fe7b4ea12c": "Ungültiger Filter",
"1632e755f850f1eb": "Ungültige Webhook-Einstellungen",
"1c2dff0635c02e50": "Jeder Deduplizierungsschlüssel muss einen gültigen Anfrage-Platzhalter enthalten. Das Zusammenfassungsfenster muss in ganzen Sekunden von 10 bis 3600 angegeben werden oder leer sein.",
"b56b036178a623de": "Custom schedules unavailable",
"db785a7bc2aab7f3": "Update {product} on this environment to use custom schedules.",
"eda6a4ccc66dea8a": "Invalid cron expression",
"9dc9be21c13d3824": "Unvollständige Aufgabe",
"d6ff9c3accc17c2e": "Füge einen Namen, einen Prompt, ein Projekt, ein Modell, einen gültigen Zeitplan und bei Bedarf einen Checkout-Pfad hinzu.",
"46ea6572900b7903": "Projekt nicht verfügbar",
Expand Down Expand Up @@ -3669,6 +3681,7 @@
"2a4a08bcab31209e": "Zu einer Uhrzeit",
"6bfb1a0c8f86cd79": "Einmal",
"48997410c44f7d03": "Intervall",
"b66fd8185eefb94a": "Custom",
"c4d24babc0c3056f": "Uhrzeit, {time} {zone}",
"c59bf1e7072eb7d9": "Uhrzeit, {time}",
"a3c37b4a4e597700": "Uhrzeit",
Expand All @@ -3681,6 +3694,7 @@
"7fc5b1876ef80061": "Schlüssel für doppelte Anfragen",
"8ac17a7a408fe36d": "Vorlage für Zusammenfassungsschlüssel",
"5f2e7331b33e224c": "Zusammenfassungsfenster (Sekunden, 10–3600)",
"c9aefc96b00c3d38": "Cron expression",
"e5fc8aff3c397453": "Minuten zwischen Ausführungen",
"7be1adfc7c1d810e": "Aktiviert",
"58d8d00d5d2d6107": "Aufgabe aktiviert",
Expand Down Expand Up @@ -3723,6 +3737,7 @@
"c191069dded46bcc": "Diese Umgebung ist getrennt. Verbinde sie erneut, bevor du speicherst.",
"0d15db4c81851479": "Anfragen mit demselben Schlüssel werden innerhalb von 7 Tagen nur einmal ausgeführt.",
"a5bbe09b0c89d86c": "Beim Zusammenfassen wird die neueste Payload ausgeführt, wenn das Zeitfenster ab der ersten Zustellung endet. Leere Schlüssel werden normal ausgeführt.",
"ba7c18ddb2d17cdc": "minute hour day month weekday",
"0e2233fb297f7c07": "Intervalle müssen mindestens 1 Minute betragen. Passe dieses Intervall vor dem Speichern an.",
"5910fee0e62286fd": "Diese Aufgabe lief bisher mehr als einmal pro Minute. Zum Speichern ist ein Intervall von mindestens 1 Minute nötig.",
"831c6136a8c83755": "Die Uhrzeit verwendet die Zeitzone der Umgebung, die von der deines Smartphones abweichen kann.",
Expand Down
Loading
Loading