diff --git a/apps/server/src/guide/topics.ts b/apps/server/src/guide/topics.ts index 372b84a0b..111606878 100644 --- a/apps/server/src/guide/topics.ts +++ b/apps/server/src/guide/topics.ts @@ -216,6 +216,8 @@ A thread link from an assistant or a phone alert, opened in a computer's browser ], body: `{place:scheduled} lists tasks that start an agent at set times (once, hourly, daily, weekdays, weekly or a cron rule) or when an event arrives at the task's address (a webhook, or GitHub events like a new issue or failed checks). Each run starts a new thread with the task's instructions, or sends them to one thread as a follow-up. +New task opens an editor laid out like the new-thread screen: "New task in [project]" on top, then a box with the task's name, a schedule button ("Weekdays at 9:00 AM"), the instructions, the model and access buttons, and Create task (Save when editing). The schedule button opens the repeat pattern, the day and time and the next runs; the time zone, a custom cron rule and When something happens sit at the bottom of that panel. A line under the box says where each run goes, with a menu in each part: a new thread or one to continue (and which agent in a room), the local checkout or a new worktree, and the computer. An event task's settings show below that line. Run now, Pause, Resume and Delete are on the task's own page, and each row in the list has a switch to pause or resume it. + Tasks run while Threadlines is running on that computer. A time missed while it was off or asleep gets one catch-up run when it's back, if the missed time was within the last 7 days. A Mac that wakes only briefly for upkeep (screen off) starts nothing; runs wait until it's fully awake. The desktop app can keep the computer awake for them. Agents can list, create and change scheduled tasks when {place:threads.agentThreads} isn't Off; with Ask me first, a card asks you before a change takes effect. A task an agent sets up on a model already in the room runs at the reasoning you set for that agent, unless the agent or you name another level. diff --git a/apps/web/src/components/ChatView.event-tasks.browser.tsx b/apps/web/src/components/ChatView.event-tasks.browser.tsx index 033e46290..e2080f42e 100644 --- a/apps/web/src/components/ChatView.event-tasks.browser.tsx +++ b/apps/web/src/components/ChatView.event-tasks.browser.tsx @@ -20,6 +20,7 @@ import { type NormalizedWsRpcRequestBody } from "../../test/wsRpcHarness"; import { PROJECT_ID, THREAD_ID, + THREAD_TITLE, NOW_ISO, rpcHarness, wsRequests, @@ -185,6 +186,22 @@ async function openSelect(label: string) { trigger.click(); } +/** Picks an access level from the editor's access button, as on the composer. */ +async function pickAccess(mode: string) { + const trigger = await vi.waitFor(() => { + const element = document.querySelector('[aria-label^="Access level"]'); + expect(element).not.toBeNull(); + return element!; + }); + trigger.click(); + const option = await vi.waitFor(() => { + const element = document.querySelector(`[data-access-option="${mode}"]`); + expect(element).not.toBeNull(); + return element!; + }); + option.click(); +} + const detailPath = `/scheduled?environment=environment-local&task=${TASK_ID}`; describe("ChatView (full app): event tasks", () => { @@ -225,14 +242,14 @@ describe("ChatView (full app): event tasks", () => { page.getByTestId("scheduled-form-prompt"), "Read the issue and propose a fix.", ); - await openSelect("Runs"); - await clickSelectItemContainingText("When something happens"); + await page.getByTestId("scheduled-schedule-button").click(); + await page.getByTestId("scheduled-schedule-events").click(); // The repository and the only sender come from the project and gh. await expect.element(page.getByTestId("scheduled-event-repository")).toHaveValue("acme/app"); await expect.element(page.getByTestId("scheduled-event-person-badcuban")).toBeVisible(); // A new event task asks before changes. - await expect.element(page.getByLabelText("Access")).toHaveTextContent("Supervised"); + await expect.element(page.getByLabelText("Access level: Supervised")).toBeVisible(); expect(byTestId("scheduled-form-time-zone")).toBeNull(); await userEvent.fill(page.getByTestId("scheduled-event-label"), "agent"); @@ -253,15 +270,13 @@ describe("ChatView (full app): event tasks", () => { await vi.waitFor(() => expect(byTestId("scheduled-event-people")).toBeNull()); // Full access with anyone is said before saving. - await openSelect("Access"); - await clickSelectItemContainingText("Full access"); + await pickAccess("full-access"); await expect .element( page.getByText("Anyone who can comment on acme/app can start a run with full access."), ) .toBeVisible(); - await openSelect("Access"); - await clickSelectItemContainingText("Supervised"); + await pickAccess("approval-required"); await page.getByTestId("scheduled-form-save").click(); await vi.waitFor(() => expect(requestsOf(WS_METHODS.scheduledTasksCreate)).toHaveLength(1)); @@ -300,7 +315,10 @@ describe("ChatView (full app): event tasks", () => { }); try { await sendTasks([]); - await openSelect("Runs"); + await page.getByTestId("scheduled-schedule-button").click(); + await expect.element(page.getByTestId("scheduled-schedule-cron")).toBeVisible(); + expect(byTestId("scheduled-schedule-events")).toBeNull(); + await openSelect("Repeat"); await vi.waitFor(() => expect(document.querySelectorAll('[data-slot="select-item"]').length).toBeGreaterThan(0), ); @@ -314,6 +332,151 @@ describe("ChatView (full app): event tasks", () => { } }); + it("creates a clock task from the editor's box, schedule popover and where-it-runs sentence", async () => { + let releaseCreate = () => {}; + const createHeld = new Promise((resolve) => { + releaseCreate = resolve; + }); + const mounted = await mountChatView({ + viewport: WIDE_FOOTER_VIEWPORT, + snapshot: snapshot(), + initialPath: "/scheduled?view=new", + configureFixture: (nextFixture) => { + withScheduledCapabilities(true)(nextFixture); + withCodexModels(nextFixture); + }, + // The create is held open until the test lets it finish. + resolveRpc: (body) => + body._tag === WS_METHODS.scheduledTasksCreate + ? Effect.promise(async () => { + await createHeld; + return { ...eventTask(), ...body, id: TASK_ID }; + }) + : undefined, + }); + try { + await sendTasks([]); + + // Saving empty says what's missing, and puts the cursor in the name. + await page.getByTestId("scheduled-form-save").click(); + await vi.waitFor(() => + expect( + [...document.querySelectorAll('[data-testid="scheduled-form-problems"] li')].map( + (item) => item.textContent, + ), + ).toEqual(["Give the task a name.", "Say what each run should do."]), + ); + expect(document.activeElement).toBe(byTestId("scheduled-form-name")); + expect(requestsOf(WS_METHODS.scheduledTasksCreate)).toHaveLength(0); + + await userEvent.fill(page.getByTestId("scheduled-form-name"), "Friday review"); + await userEvent.fill(page.getByTestId("scheduled-form-prompt"), "Summarize the week."); + + // Weekly on Friday, then a cron rule that starts from it. + await page.getByTestId("scheduled-schedule-button").click(); + await openSelect("Repeat"); + await clickSelectItemContainingText("Weekly"); + await page.getByTestId("scheduled-form-day-5").click(); + await vi.waitFor(() => + expect(byTestId("scheduled-schedule-button")?.textContent).toContain("Fridays at 9:00"), + ); + await page.getByTestId("scheduled-schedule-cron").click(); + await expect.element(page.getByTestId("scheduled-form-cron")).toHaveValue("0 9 * * 5"); + + // The time zone is one step further in, and back. + await page.getByTestId("scheduled-schedule-time-zone").click(); + await expect.element(page.getByTestId("scheduled-form-time-zone")).toBeVisible(); + await page.getByTestId("scheduled-schedule-back").click(); + await expect.element(page.getByTestId("scheduled-form-cron")).toBeVisible(); + await userEvent.keyboard("{Escape}"); + await vi.waitFor(() => expect(byTestId("scheduled-schedule-popover")).toBeNull()); + + // Each run in a new worktree, from the sentence under the box. + await page.getByTestId("scheduled-form-checkout").click(); + await page.getByRole("menuitemradio", { name: /New worktree/ }).click(); + await vi.waitFor(() => + expect(byTestId("scheduled-form-where")?.textContent).toMatch( + /^Each run starts a new thread in a new worktree on /, + ), + ); + + // Cmd/Ctrl+Enter in the prompt saves, and pressing it again while the + // create is still out sends nothing more. + const prompt = byTestId("scheduled-form-prompt")!; + const pressSave = () => + prompt.dispatchEvent( + new KeyboardEvent("keydown", { + key: "Enter", + metaKey: true, + bubbles: true, + cancelable: true, + }), + ); + pressSave(); + await vi.waitFor(() => expect(requestsOf(WS_METHODS.scheduledTasksCreate)).toHaveLength(1)); + pressSave(); + pressSave(); + await new Promise((resolve) => setTimeout(resolve, 150)); + expect(requestsOf(WS_METHODS.scheduledTasksCreate)).toHaveLength(1); + releaseCreate(); + expect(requestsOf(WS_METHODS.scheduledTasksCreate)[0]).toMatchObject({ + name: "Friday review", + prompt: "Summarize the week.", + checkout: "worktree", + cadence: { kind: "custom", cron: "0 9 * * 5" }, + target: { kind: "new_thread" }, + }); + } finally { + await mounted.cleanup(); + } + }); + + it("keeps a continued thread's access when switching to a new thread and back", async () => { + const mounted = await mountChatView({ + viewport: WIDE_FOOTER_VIEWPORT, + snapshot: snapshot(), + initialPath: "/scheduled?view=new", + configureFixture: (nextFixture) => { + withScheduledCapabilities(true)(nextFixture); + withCodexModels(nextFixture); + }, + resolveRpc: (body) => + body._tag === WS_METHODS.scheduledTasksCreate + ? { ...eventTask(), ...body, id: TASK_ID } + : undefined, + }); + const pickThread = async (name: string | RegExp) => { + await page.getByTestId("scheduled-form-target").click(); + await page.getByRole("menuitemradio", { name }).click(); + }; + try { + await sendTasks([]); + await userEvent.fill(page.getByTestId("scheduled-form-name"), "Nightly follow-up"); + await userEvent.fill(page.getByTestId("scheduled-form-prompt"), "Check on the build."); + + // Continuing the thread starts from its access (full access), then the + // task sets its own. + await pickThread(THREAD_TITLE); + await expect.element(page.getByLabelText("Access level: Full access")).toBeVisible(); + await pickAccess("approval-required"); + await expect.element(page.getByLabelText("Access level: Supervised")).toBeVisible(); + + // Off to a new thread and back to the same one: the task's own access stays. + await pickThread(/A new thread/); + await pickThread(THREAD_TITLE); + await expect.element(page.getByLabelText("Access level: Supervised")).toBeVisible(); + + await page.getByTestId("scheduled-form-save").click(); + await vi.waitFor(() => expect(requestsOf(WS_METHODS.scheduledTasksCreate)).toHaveLength(1)); + expect(requestsOf(WS_METHODS.scheduledTasksCreate)[0]).toMatchObject({ + runtimeMode: "approval-required", + target: { kind: "thread", threadId: THREAD_ID }, + }); + } finally { + await mounted.cleanup(); + } + }); + it("offers Add to GitHub, falls back to the steps by hand, and waits for the relay's address", async () => { const mounted = await mountChatView({ viewport: WIDE_FOOTER_VIEWPORT, diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 06ecca6f2..4142f4193 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -29,11 +29,7 @@ import { PROVIDER_SEND_TURN_MAX_FILE_BYTES, PROVIDER_SEND_TURN_MAX_IMAGE_BYTES, } from "@threadlines/contracts"; -import { - createModelSelection, - getProviderOptionCurrentLabel, - normalizeModelSlug, -} from "@threadlines/shared/model"; +import { createModelSelection, normalizeModelSlug } from "@threadlines/shared/model"; import { memo, type ReactNode, @@ -113,7 +109,8 @@ import { ComposerPromptEditor, } from "../ComposerPromptEditor"; import { type ComposerPromptSuggestionDisplay } from "./ComposerPromptSuggestion"; -import { type ModelPickerTriggerSummary, ProviderModelPicker } from "./ProviderModelPicker"; +import { COMPOSER_SURFACE_CLASS_NAME } from "./composerSurface"; +import { ProviderModelPicker } from "./ProviderModelPicker"; import { ModelPickerSettings, type ModelPickerTraitsTarget } from "./ModelPickerSettings"; import { ComposerRunControls, @@ -214,12 +211,7 @@ import { getPickerModelName } from "./providerIconUtils"; import { awaitingInvite } from "@threadlines/shared/roomAgentRequests"; import { shownSettingsChange } from "@threadlines/shared/settingsChangeState"; import { activeParticipants, hasAgentRecords } from "@threadlines/shared/threadParticipants"; -import { - getTraitsSectionVisibility, - getTraitSwitchControls, - isFastModeControl, - shouldRenderTraitsControls, -} from "./traitControls"; +import { modelPickerTriggerSummary, shouldRenderTraitsControls } from "./traitControls"; import { canRequestProviderRateLimitResetCredit, useProviderRateLimitResetCredit, @@ -1787,26 +1779,10 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const runControlsOnRow = !isMobileViewport; // What the settings button says besides the model: the effort and Fast Mode. - const settingsTraits = settingsTraitsTarget - ? getTraitsSectionVisibility({ - provider: settingsTraitsTarget.provider, - models: settingsTraitsTarget.models, - model: settingsTraitsTarget.model, - modelOptions: settingsTraitsTarget.modelOptions, - }) - : null; - const settingsTriggerSummary: ModelPickerTriggerSummary = { - effort: settingsTraits?.reasoningDescriptor - ? (getProviderOptionCurrentLabel(settingsTraits.reasoningDescriptor) ?? null) - : null, - ultracode: settingsTraits?.ultracodeEnabled ?? false, - fastMode: settingsTraits - ? getTraitSwitchControls(settingsTraits.descriptors).some( - (control) => isFastModeControl(control) && control.checked, - ) - : false, - working: settingsTraitsWorking, - }; + const settingsTriggerSummary = modelPickerTriggerSummary( + settingsTraitsTarget, + settingsTraitsWorking, + ); // Build/Plan and access, on the row's own buttons or in the panel. The // panel's rows keep focus there, so several settings can change in one @@ -3876,10 +3852,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) ref={composerSurfaceRef} data-chat-composer-mobile-collapsed={isComposerCollapsedMobile ? "true" : "false"} className={cn( - // The one raised box on the canvas: card fill and a border. In light - // mode a white box on the near-white canvas also needs the soft drop - // to read; in dark the lighter fill does that on its own. - "rounded-4xl border bg-card not-dark:elevate-raised transition-colors duration-200 has-focus-visible:border-focus-ring/45", + COMPOSER_SURFACE_CLASS_NAME, !isComposerCollapsedMobile && hasComposerDockContent({ pullRequests, notices: dockedNotices }) && "rounded-t-none", diff --git a/apps/web/src/components/chat/DraftEmptyState.tsx b/apps/web/src/components/chat/DraftEmptyState.tsx index c1f78ce77..a0f6ab626 100644 --- a/apps/web/src/components/chat/DraftEmptyState.tsx +++ b/apps/web/src/components/chat/DraftEmptyState.tsx @@ -35,8 +35,8 @@ import { MenuItem, MenuPopup, MenuSeparator, - MenuTrigger, } from "../ui/menu"; +import { InlinePickerTrigger } from "../ui/inline-picker"; /** * How the new-thread screen is arranged. `hero` is the roomy layout: only the @@ -227,30 +227,18 @@ export function DraftEmptyState({ > What's next in{" "} - + {isGeneralChat ? ( + + ) : currentProject ? ( + - } - > - {/* Chrome never paints text-decoration under a replaced element, so - the dotted rule is a border on a flex wrapper — that's what keeps - the icon inside the underline instead of beside it. */} - - {isGeneralChat ? ( - - ) : currentProject ? ( - - ) : null} - {targetName} - - + ) : null} + {targetName} + {generalChatsRef ? ( <> diff --git a/apps/web/src/components/chat/EffortMeter.tsx b/apps/web/src/components/chat/EffortMeter.tsx index 46624563f..e37ffef32 100644 --- a/apps/web/src/components/chat/EffortMeter.tsx +++ b/apps/web/src/components/chat/EffortMeter.tsx @@ -4,8 +4,14 @@ import { cn } from "~/lib/utils"; export interface EffortMeterOption { readonly id: string; readonly label: string; + /** The model's own level when none is picked: a dot under its segment says so. */ + readonly isDefault?: boolean | undefined; } +/** Whether a level is marked as the default: one named "Default" already says so. */ +const marksDefault = (option: EffortMeterOption) => + option.isDefault === true && option.label.trim().toLowerCase() !== "default"; + /** Stagger between segments as a level charges up (or drains), per segment. */ const CHARGE_STEP_MS = 55; const DRAIN_STEP_MS = 45; @@ -149,7 +155,8 @@ function RollingLevelName(props: { text: string; preview: boolean; up: boolean } * * Every effect moves or fades the segments only, runs once per change, and * stays still under reduced motion. Keyboard: a radio group, where the arrow - * keys step the level and focus follows it. + * keys step the level and focus follows it. A small dot under a segment + * marks the model's default level. */ export const EffortMeter = memo(function EffortMeter(props: { options: ReadonlyArray; @@ -271,7 +278,8 @@ export const EffortMeter = memo(function EffortMeter(props: { type="button" role="radio" aria-checked={index === selectedIndex} - aria-label={option.label} + aria-label={marksDefault(option) ? `${option.label}, default` : option.label} + title={marksDefault(option) ? `${option.label} (default)` : undefined} tabIndex={leaving ? -1 : index === (selectedIndex < 0 ? 0 : selectedIndex) ? 0 : -1} disabled={disabled || leaving} data-effort-level={option.id} @@ -285,6 +293,9 @@ export const EffortMeter = memo(function EffortMeter(props: { "pointer-events-none animate-[effort-segment-out_300ms_ease_forwards] motion-reduce:animate-none", entering && "animate-[effort-segment-in_300ms_ease] motion-reduce:animate-none", index === hoverIndex && !leaving && "scale-y-[1.35]", + // The default level's dot, under its segment. + marksDefault(option) && + "after:absolute after:top-[calc(100%+3px)] after:left-1/2 after:size-[3px] after:-translate-x-1/2 after:rounded-full after:bg-muted-foreground", )} onPointerEnter={() => { if (!leaving && !disabled) setHoverId(option.id); diff --git a/apps/web/src/components/chat/composerSurface.ts b/apps/web/src/components/chat/composerSurface.ts new file mode 100644 index 000000000..9b3ed4b5e --- /dev/null +++ b/apps/web/src/components/chat/composerSurface.ts @@ -0,0 +1,9 @@ +/** + * The composer's box: the one raised box on the canvas, a card fill and a + * border, its border taking the focus color while a control inside has + * keyboard focus. In light mode a white box on the near-white canvas also + * needs the soft drop to read; in dark the lighter fill does that on its own. + * The scheduled task editor is drawn in the same box. + */ +export const COMPOSER_SURFACE_CLASS_NAME = + "rounded-4xl border bg-card not-dark:elevate-raised transition-colors duration-200 has-focus-visible:border-focus-ring/45"; diff --git a/apps/web/src/components/chat/traitControls.ts b/apps/web/src/components/chat/traitControls.ts index 13b3bd44a..6b62617f3 100644 --- a/apps/web/src/components/chat/traitControls.ts +++ b/apps/web/src/components/chat/traitControls.ts @@ -22,6 +22,7 @@ import { import { useCallback } from "react"; import { useComposerDraftStore, type DraftId } from "../../composerDraftStore"; import { getProviderModelCapabilities } from "../../providerModels"; +import type { ModelPickerTriggerSummary } from "./ProviderModelPicker"; export type ProviderOptions = ReadonlyArray; export type SelectProviderOptionDescriptor = Extract; @@ -347,6 +348,42 @@ export function getTraitsSectionVisibility(input: { }; } +/** + * What the model button says besides the model, for the agent `target` + * describes: its effort and Fast Mode, and Ultracode's look. Null target + * (no options to show): just the model. + */ +export function modelPickerTriggerSummary( + target: { + provider: ProviderDriverKind; + models: ReadonlyArray; + model: string | null | undefined; + modelOptions?: ProviderOptions | null | undefined; + } | null, + working: boolean, +): ModelPickerTriggerSummary { + const traits = target + ? getTraitsSectionVisibility({ + provider: target.provider, + models: target.models, + model: target.model, + modelOptions: target.modelOptions, + }) + : null; + return { + effort: traits?.reasoningDescriptor + ? (getProviderOptionCurrentLabel(traits.reasoningDescriptor) ?? null) + : null, + ultracode: traits?.ultracodeEnabled ?? false, + fastMode: traits + ? getTraitSwitchControls(traits.descriptors).some( + (control) => isFastModeControl(control) && control.checked, + ) + : false, + working, + }; +} + export function shouldRenderTraitsControls(input: { provider: ProviderDriverKind; models: ReadonlyArray; diff --git a/apps/web/src/components/scheduled/ScheduleButton.tsx b/apps/web/src/components/scheduled/ScheduleButton.tsx new file mode 100644 index 000000000..e356a745e --- /dev/null +++ b/apps/web/src/components/scheduled/ScheduleButton.tsx @@ -0,0 +1,411 @@ +import { + BracesIcon, + CalendarClockIcon, + CheckIcon, + ChevronLeftIcon, + ChevronRightIcon, + GlobeIcon, + type LucideIcon, + ZapIcon, +} from "lucide-react"; +import { type ReactNode, useRef, useState } from "react"; + +import { cn } from "../../lib/utils"; +import { Button } from "../ui/button"; +import { DatePicker } from "../ui/date-picker"; +import { Input } from "../ui/input"; +import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover"; +import { SegmentedControl, SegmentedControlItem } from "../ui/segmented-control"; +import { + DropdownChevron, + Select, + SelectItem, + SelectPopup, + SelectTrigger, + SelectValue, +} from "../ui/select"; +import { TimePicker } from "../ui/time-picker"; +import { type TimeZoneSuggestion, TimeZonePicker } from "../ui/time-zone-picker"; +import { + CADENCE_KIND_LABELS, + type CadenceKind, + customCadencePatch, + formatWhen, + previewRuns, + REPEAT_KINDS, + type ScheduledTaskForm, + scheduleSummary, + todayIn, + WEEKDAY_LABELS, +} from "./scheduled.logic"; + +const HOURLY_MINUTES = Array.from({ length: 12 }, (_, index) => index * 5); + +/** Monday first, as calendars here read; values are the cadence's 0 (Sunday) to 6. */ +const WEEK_ORDER = [1, 2, 3, 4, 5, 6, 0] as const; + +/** The words the Repeat field shows for a kind it doesn't list. */ +const REPEAT_LABELS: Record = { + ...CADENCE_KIND_LABELS, + custom: "Custom cron rule", +}; + +/** The catch-up sentence the old page header carried, now beside the times it's about. */ +const CLOCK_NOTE = + "It runs while Threadlines is running on its computer. A time missed while the computer was off or asleep gets one catch-up run."; + +const ZONE_HINT = + "Times use this zone wherever you are. When clocks skip ahead, a skipped time runs right after. When they fall back, a set time runs once and hourly tasks still run every hour."; + +const CRON_HINT = + "Five fields: minute, hour, day of month, month, day of week. Every 15 minutes is */15 * * * *."; + +/** A labelled line of the popover: the label in a narrow column, the control filling the rest. */ +function PopoverRow({ label, children }: { readonly label: string; readonly children: ReactNode }) { + return ( +
+ {label} +
{children}
+
+ ); +} + +/** A row one step further in: a choice that opens more, or switches the task to its kind. */ +function MoreRow({ + icon: Icon, + label, + value, + selected = false, + opens = false, + onClick, + testId, +}: { + readonly icon: LucideIcon; + readonly label: string; + readonly value?: string | undefined; + readonly selected?: boolean; + /** It opens a page of its own (a chevron); else it picks (a check while picked). */ + readonly opens?: boolean; + readonly onClick: () => void; + readonly testId?: string; +}) { + return ( + + ); +} + +/** + * The schedule button at the top of the task editor: the schedule in a few + * words, opening a popover with the repeat pattern, its day and time and the + * next runs. The time zone, a cron rule and event triggers sit one step + * further in. Picking events closes it: their settings sit under the editor. + */ +export function ScheduleButton({ + form, + onChange, + eventsOffered, + problem, + computerTimeZone, + timeZoneSuggestions, + hour12, + nowMs, +}: { + readonly form: ScheduledTaskForm; + readonly onChange: (patch: Partial) => void; + /** The computer runs event tasks, or the task already is one. */ + readonly eventsOffered: boolean; + /** Why the schedule can't be saved, once a save was tried. */ + readonly problem: string | undefined; + readonly computerTimeZone: string | undefined; + readonly timeZoneSuggestions: ReadonlyArray; + readonly hour12: boolean; + readonly nowMs: number; +}) { + const [open, setOpen] = useState(false); + const [page, setPage] = useState<"main" | "timeZone">("main"); + const cronRef = useRef(null); + const pageRef = useRef(null); + // Moving between pages keeps the keyboard's place: the page's first + // control, and back on the main page the row that opened the other. + const showPage = (next: "main" | "timeZone") => { + setPage(next); + const target = + next === "timeZone" ? "scheduled-form-time-zone" : "scheduled-schedule-time-zone"; + requestAnimationFrame(() => + pageRef.current?.querySelector(`[data-testid="${target}"]`)?.focus(), + ); + }; + const kind = form.cadenceKind; + const isEvent = kind === "webhook"; + const clock = !isEvent && kind !== "manual"; + const upcoming = clock ? previewRuns(form, new Date(nowMs), 3) : []; + const timed = kind === "daily" || kind === "weekdays" || kind === "weekly" || kind === "once"; + const zoneLabel = + computerTimeZone !== undefined && form.timeZone === computerTimeZone + ? "This computer" + : form.timeZone; + + return ( + { + setOpen(next); + if (!next) setPage("main"); + }} + > + + } + > + + + {page === "timeZone" ? ( +
+ + onChange({ timeZone, timeZoneChosen: true })} + suggestions={timeZoneSuggestions} + className="w-full" + aria-label="Time zone" + data-testid="scheduled-form-time-zone" + /> +

{ZONE_HINT}

+
+ ) : ( +
+ + + + + {kind === "weekly" ? ( + onChange({ weekday: Number(value) })} + aria-label="Day" + > + {WEEK_ORDER.map((day) => ( + + {WEEKDAY_LABELS[day].slice(0, 3)} + + ))} + + ) : null} + + {kind === "once" ? ( + + onChange({ date })} + data-testid="scheduled-form-date" + /> + + ) : null} + + {kind === "hourly" ? ( + + + + ) : null} + + {timed ? ( + + onChange({ time })} + data-testid="scheduled-form-time" + /> + + ) : null} + + {kind === "custom" ? ( +
+ onChange({ cron: event.target.value, cronChosen: true })} + /> +

{CRON_HINT}

+
+ ) : null} + + {kind === "manual" ? ( +

+ It runs only when you press Run now. +

+ ) : null} + {isEvent ? ( +

+ It runs when an event arrives. Set up which events under the editor. +

+ ) : null} + + {upcoming.length > 0 ? ( +

+ {kind === "once" ? "Your time: " : "Next, your time: "} + {upcoming.map((slot) => formatWhen(slot.toISOString(), nowMs)).join(", ")} +

+ ) : null} + {problem !== undefined && !isEvent ? ( +

{problem}

+ ) : null} + {isEvent ? null : ( +

{CLOCK_NOTE}

+ )} + +
+
+ {clock ? ( + showPage("timeZone")} + /> + ) : null} + { + if (kind !== "custom") onChange(customCadencePatch(form)); + requestAnimationFrame(() => cronRef.current?.focus()); + }} + /> + {eventsOffered ? ( + { + onChange({ cadenceKind: "webhook" }); + setOpen(false); + }} + /> + ) : null} +
+
+ )} + + + ); +} diff --git a/apps/web/src/components/scheduled/ScheduledTaskForm.tsx b/apps/web/src/components/scheduled/ScheduledTaskForm.tsx index 70ce06c50..f676b940e 100644 --- a/apps/web/src/components/scheduled/ScheduledTaskForm.tsx +++ b/apps/web/src/components/scheduled/ScheduledTaskForm.tsx @@ -3,30 +3,30 @@ import { RUNTIME_MODES, type EnvironmentId, type ModelSelection, - type ProjectId, - type RuntimeMode, type ServerProvider, type ThreadId, } from "@threadlines/contracts"; +import { createModelSelection } from "@threadlines/shared/model"; import { PROVIDER_NOT_READY_FIX, providerAgentName, providerNotReady, providerNotReadySentence, } from "@threadlines/shared/providerAuth"; -import { roomAgentKey } from "@threadlines/shared/threadParticipants"; -import { MessagesSquareIcon } from "lucide-react"; -import { useMemo, useState } from "react"; +import { useMemo, useRef, useState } from "react"; import { useShallow } from "zustand/react/shallow"; import { readEnvironmentConnection } from "../../environments/runtime"; import { useEnvironmentProviders } from "../../hooks/useEnvironmentProviders"; +import { useIsPhoneViewport } from "../../hooks/useMediaQuery"; +import { useRelativeTimeTick } from "../../hooks/useRelativeTimeTick"; import { useSettings } from "../../hooks/useSettings"; import { useScheduledTaskEnvironments, useScheduledTasksStore, } from "../../lib/scheduledTasksState"; import { cn } from "../../lib/utils"; +import { getCustomModelOptionsByInstance } from "../../modelSelection"; import { uses12HourClock } from "../../timestampFormat"; import { deriveProviderInstanceEntries, @@ -39,42 +39,36 @@ import { selectSidebarThreadsAcrossEnvironments, useStore, } from "../../store"; -import type { Project } from "../../types"; -import { ProjectFavicon } from "../ProjectFavicon"; -import { SETTINGS_GROUP_ROW_CLASS, SettingsSection } from "../settings/settingsLayout"; -import { ModelSelectionControl } from "../settings/TextGenerationModelControl"; +import { type ComposerAccessControl, ComposerRunControls } from "../chat/ComposerRunControls"; +import { COMPOSER_SURFACE_CLASS_NAME } from "../chat/composerSurface"; +import { ModelPickerSettings, type ModelPickerTraitsTarget } from "../chat/ModelPickerSettings"; +import { ProviderModelPicker } from "../chat/ProviderModelPicker"; +import { modelPickerTriggerSummary, shouldRenderTraitsControls } from "../chat/traitControls"; +import { SettingsSection } from "../settings/settingsLayout"; import { Button } from "../ui/button"; -import { Input } from "../ui/input"; -import { SegmentedControl, SegmentedControlItem } from "../ui/segmented-control"; -import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select"; -import { DatePicker } from "../ui/date-picker"; import { Switch } from "../ui/switch"; -import { Textarea } from "../ui/textarea"; -import { TimePicker } from "../ui/time-picker"; -import { TimeZonePicker } from "../ui/time-zone-picker"; import { failureNotice, toastManager } from "../ui/toast"; +import { TooltipProvider } from "../ui/tooltip"; import { addComputerNotConnectedNotice } from "../computerConnectionNotices"; import { - CADENCE_KIND_LABELS, - type CadenceKind, - cadenceKindsFor, EVENT_TASK_RUNTIME_MODE, emptyTaskForm, eventTaskAccessWarning, + type FormProblems, formatWhen, formDraft, formProblems, previewRuns, type ScheduledTaskForm as FormState, taskForm, - todayIn, viewerTimeZone, - WEEKDAY_LABELS, type WebhookForm, webhookFormWithContext, } from "./scheduled.logic"; +import { ScheduleButton } from "./ScheduleButton"; import { ScheduledEventFields } from "./ScheduledEventFields"; import { FieldRow } from "./ScheduledFormRow"; +import { TaskProjectHeading, TaskRunsSentence } from "./ScheduledTaskWhere"; import { type LocatedTask, taskRef, @@ -83,29 +77,22 @@ import { useScheduledNavigation, } from "./useScheduledPage"; -const HOURLY_MINUTES = Array.from({ length: 12 }, (_, index) => index * 5); +/** Hover labels on the model and access buttons wait a moment, as on the composer's row. */ +const ROW_TOOLTIP_DELAY_MS = 250; -const lowerFirst = (text: string) => text.charAt(0).toLowerCase() + text.slice(1); +/** The order problems are listed in under the editor, top of the editor first. */ +const PROBLEM_ORDER = [ + "name", + "prompt", + "agent", + "schedule", + "project", + "thread", + "goesTo", + "computer", +] as const satisfies ReadonlyArray; -/** A project as the app's other project pickers show it: its logo (General Chats its own glyph) and name. */ -function ProjectLabel({ project }: { readonly project: Project }) { - return ( - - {project.kind === "general-chat" ? ( - - ) : ( - - )} - - {project.kind === "general-chat" ? "General Chats" : project.name} - - - ); -} +const lowerFirst = (text: string) => text.charAt(0).toLowerCase() + text.slice(1); /** The model a new task starts with on a computer: its new-thread default, else its first agent. */ function defaultModelFor( @@ -124,10 +111,12 @@ function defaultModelFor( } /** - * The form for a new task or an edited one (docs/design/fleet.md, Part 6): - * name and instructions; the computer that keeps and runs it, its project - * and where each run works; the agent, model and access; the schedule; and - * whether each run starts a new thread or continues one. + * The editor for a new task or an edited one (docs/design/fleet.md, Part 6), + * laid out like the new-thread screen: "New task in [project]", then the + * composer's box with the task's name and its schedule button on top, the + * prompt, and the model and access buttons beside Create task. A sentence + * under the box says where each run goes (a new thread or one to continue, + * which checkout, which computer); an event task's settings follow it. */ export function ScheduledTaskForm({ editing }: { readonly editing: LocatedTask | null }) { const navigation = useScheduledNavigation(); @@ -136,6 +125,10 @@ export function ScheduledTaskForm({ editing }: { readonly editing: LocatedTask | const settings = useSettings(); const projects = useStore(useShallow(selectProjectsAcrossEnvironments)); const threads = useStore(useShallow(selectSidebarThreadsAcrossEnvironments)); + const isPhone = useIsPhoneViewport(); + const nowMs = useRelativeTimeTick(30_000); + const nameRef = useRef(null); + const promptRef = useRef(null); const [draftForm, setForm] = useState(() => { if (editing) return taskForm(editing.task, editing.environment.environmentId); @@ -161,7 +154,7 @@ export function ScheduledTaskForm({ editing }: { readonly editing: LocatedTask | }); }); const computerZones = useScheduledTasksStore((state) => state.byEnvironment); - // A computer, project or agent the page didn't have yet when the form + // A computer, project or agent the page didn't have yet when the editor // opened (right after a reload) is filled in once it arrives; a choice the // user made is never replaced. Until the user picks a time zone, a new task // is in the chosen computer's own: it runs there, by that computer's clock. @@ -285,8 +278,7 @@ export function ScheduledTaskForm({ editing }: { readonly editing: LocatedTask | : `${providerNotReadySentence( agentNotReady, providerAgentName(chosenProvider, form.modelSelection.instanceId), - environments.find((entry) => entry.environmentId === form.environmentId)?.label ?? - "this computer", + chosenEnvironment?.label ?? "this computer", )} Its runs will fail until you ${lowerFirst(PROVIDER_NOT_READY_FIX[agentNotReady])}.`; // The zones the picker leads with: where the task runs, where you are, UTC. @@ -303,16 +295,30 @@ export function ScheduledTaskForm({ editing }: { readonly editing: LocatedTask | ]; }, [computerTimeZone]); - const now = new Date(); - const problems = { - ...formProblems(form, now, editing?.task, goesTo?.left === true), + const problemsAt = (at: Date): FormProblems => ({ + ...formProblems(form, at, editing?.task, goesTo?.left === true), // The computer stopped offering event tasks (an older Threadlines took its place). ...(isEvent && !eventTasks ? { schedule: "This computer doesn't run event tasks. Update Threadlines on it first." } : {}), - }; - const shownProblems = submitted ? problems : {}; - const upcoming = form.cadenceKind === "manual" || isEvent ? [] : previewRuns(form, now, 3); + }); + // Checked against this render's moment, as the form always was: a change + // re-checks at once, and the half-minute tick (nowMs) re-renders an idle + // form so a one-time run that passes meanwhile is said too. + const now = new Date(); + const problems = problemsAt(now); + const shownProblems: FormProblems = submitted + ? problems + : // An agent that left the continued thread is said at once. + goesTo?.left === true && problems.goesTo !== undefined + ? { goesTo: problems.goesTo } + : {}; + // An event task's schedule problem is said with its settings, below. + const listedProblems = PROBLEM_ORDER.filter( + (key) => shownProblems[key] !== undefined && !(key === "schedule" && isEvent), + ).map((key) => shownProblems[key]!); + const nextRun = + form.cadenceKind === "manual" || isEvent ? undefined : previewRuns(form, now, 1)[0]; const accessWarning = eventTaskAccessWarning(form); const chooseEnvironment = (environmentId: EnvironmentId) => { @@ -336,10 +342,44 @@ export function ScheduledTaskForm({ editing }: { readonly editing: LocatedTask | }); }; + const continueThread = (threadId: ThreadId) => { + if (form.environmentId === null) return; + // Back to the thread it continued: its agent, model and access stay as set. + if (threadId === form.threadId) { + update({ target: "thread" }); + return; + } + // Another thread: its runs are for that thread's own agent, and start + // from its model and access. + const shell = selectEnvironmentState(useStore.getState(), form.environmentId).threadShellById[ + threadId + ]; + update({ + target: "thread", + threadId, + threadParticipantId: null, + ...(shell !== undefined + ? { modelSelection: shell.modelSelection, runtimeMode: shell.runtimeMode } + : {}), + }); + }; + + // One save at a time: the button is off while it runs, but the keyboard + // shortcut can submit again before it re-renders. + const savingRef = useRef(false); const save = async () => { + if (savingRef.current) return; setSubmitted(true); + // Checked against this moment: a one-time run that passed since the last + // render isn't sent. + const current = problemsAt(new Date()); const draft = formDraft(form); - if (Object.keys(problems).length > 0 || draft === null || form.environmentId === null) return; + if (Object.keys(current).length > 0 || draft === null || form.environmentId === null) { + // Back to the first field that needs words. + if (current.name !== undefined) nameRef.current?.focus(); + else if (current.prompt !== undefined) promptRef.current?.focus(); + return; + } const environment = environments.find((entry) => entry.environmentId === form.environmentId); const connection = readEnvironmentConnection(form.environmentId); if (!connection || !environment) { @@ -349,6 +389,7 @@ export function ScheduledTaskForm({ editing }: { readonly editing: LocatedTask | }); return; } + savingRef.current = true; setSaving(true); try { if (editing) { @@ -369,6 +410,7 @@ export function ScheduledTaskForm({ editing }: { readonly editing: LocatedTask | }), ); } finally { + savingRef.current = false; setSaving(false); } }; @@ -378,463 +420,261 @@ export function ScheduledTaskForm({ editing }: { readonly editing: LocatedTask | else navigation.showAll({ replace: true }); }; - const timeField = ( - update({ time })} - data-testid="scheduled-form-time" - /> - ); + // The model button and its panel, as the composer has them: effort and the + // model's other options in the panel, and on phones the access level too. + const selection = form.modelSelection; + const traitsTarget: ModelPickerTraitsTarget | null = + selection !== null && selectedEntry !== undefined + ? { + provider: selectedEntry.driverKind, + instanceId: selection.instanceId, + models: selectedEntry.models, + model: selection.model, + modelOptions: selection.options, + onModelOptionsChange: (options) => + update({ + modelSelection: createModelSelection(selection.instanceId, selection.model, options), + }), + } + : null; + const hasModelPicker = selection !== null && instanceEntries.length > 0; + const shownTraits = + traitsTarget !== null && shouldRenderTraitsControls(traitsTarget) ? traitsTarget : null; + // As on the composer: the level the agent runs at, which can differ from + // the one picked when the agent doesn't offer it. + const accessControl: ComposerAccessControl = { + value: access?.shown ?? form.runtimeMode, + options: + access?.options ?? + RUNTIME_MODES.map((mode) => ({ mode, ...runtimeModeConfig[mode], disabled: false })), + onChange: (mode) => update({ runtimeMode: mode, runtimeModeChosen: true }), + planning: false, + }; return (
{ event.preventDefault(); void save(); }} > -
-

- {editing ? `Edit ${editing.task.name}` : "New task"} -

-

- {isEvent - ? "It runs when an event arrives, while Threadlines is running on its computer. Events wait up to a day while it's off." - : "It runs while Threadlines is running on its computer. A time missed while the computer was off or asleep gets one catch-up run."} -

-
+ + update({ + projectId: project.id, + threadId: null, + threadParticipantId: null, + ...(project.kind === "general-chat" ? { checkout: "local" as const } : {}), + }) + } + /> - - - +
+ update({ name: event.target.value })} /> - - -