diff --git a/packages/app/e2e/automations/automations-panel.spec.ts b/packages/app/e2e/automations/automations-panel.spec.ts index 14954db3d..a5ca24a6b 100644 --- a/packages/app/e2e/automations/automations-panel.spec.ts +++ b/packages/app/e2e/automations/automations-panel.spec.ts @@ -1,6 +1,31 @@ +import type { Page } from "@playwright/test" import { test, expect } from "../fixtures" import { openSidebar } from "../actions" +type ModelKey = { providerID: string; modelID: string } + +// Discover an e2e model that actually exposes thinking variants (most opencode +// mock models don't), via the composer probe, mirroring model-picker-thinking. +async function findVariantModel(page: Page): Promise { + const models = (await page.evaluate(() => { + const win = window as Window & { __opencode_e2e?: { model?: { current?: { models?: Array } } } } + return win.__opencode_e2e?.model?.current?.models ?? [] + })) as Array + for (const model of models) { + const variants = await page.evaluate((value) => { + const win = window as Window & { + __opencode_e2e?: { + model?: { controls?: { setModel?: (v: ModelKey) => void }; current?: { variants?: string[] } } + } + } + win.__opencode_e2e?.model?.controls?.setModel?.(value) + return win.__opencode_e2e?.model?.current?.variants ?? [] + }, model) + if (variants.length > 0) return model + } + return undefined +} + const recurring = (projectID: string, title: string, prompt: string, expression: string) => ({ automationCreateInput: { kind: "recurring" as const, @@ -62,6 +87,274 @@ test("@smoke automations panel: list, detail, pause, delete", async ({ page, pro await expect(rows).toHaveCount(0) }) +async function openAutomations(page: Parameters[0]) { + await openSidebar(page) + await page.locator('[data-action="pawwork-automations-open"]').click() + const surface = page.locator('[data-component="automations-page"]') + await expect(surface).toBeVisible() + return surface +} + +test("automations panel: create manually adds an automation", async ({ page, project }) => { + test.setTimeout(120_000) + + await project.open() + const surface = await openAutomations(page) + await expect(surface.locator('[data-component="automations-empty"]')).toBeVisible() + + // Split entry: open the New automation menu, then Create manually. + await surface.locator('[data-action="automation-create-open"]').click() + await page.locator('[data-action="automation-create-manual"]').click() + + const card = page.locator('[data-component="automation-create"]') + await expect(card).toBeVisible() + await card.locator('[data-action="automation-create-title"]').fill("Release notes draft") + await card.locator('[data-action="automation-create-prompt"]').fill("Draft release notes from the latest merges.") + // Model seeds from the last-used model, so Create is enabled with no extra step. + await card.locator('[data-action="automation-create-submit"]').click() + + // Lands on the new automation's detail; it also shows up in the list. + const detail = surface.locator('[data-component="automation-detail"]') + await expect(detail).toBeVisible() + await expect(detail.getByRole("heading", { name: "Release notes draft" })).toBeVisible() + + await detail.locator('[data-action="automation-detail-back"]').click() + await expect(surface.locator('[data-action="automation-row"]')).toHaveCount(1) +}) + +test("automations panel: schedule picker opens, selects, and layers escape", async ({ page, project }) => { + test.setTimeout(120_000) + + await project.open() + const surface = await openAutomations(page) + + await surface.locator('[data-action="automation-create-open"]').click() + await page.locator('[data-action="automation-create-manual"]').click() + + const card = page.locator('[data-component="automation-create"]') + await expect(card).toBeVisible() + + // The time token opens a UI Popover portalled to . Inside the modal + // dialog it must mount and stay — not flash shut as the focus scope hands off + // from the dialog's trap (issue #950 PR7). + await card.locator('[data-action="automation-time"]').click() + const popover = page.locator('[data-component="popover-content"]') + await expect(popover).toBeVisible() + + // The visible flash is a real-OS focus race that synthetic input can't trigger, + // so assert the fix's mechanism instead. Shove focus back into the dialog (what + // the modal Dialog's focus trap does on open): with a non-modal popover focus + // escapes and stays on the title — the same outside-focus that, in the real + // window, lets the dialog dismiss the picker (the #950 PR7 flash). The modal + // popover traps focus back into itself, so it can never see an outside-focus + // dismiss. The visible flash itself is verified manually in the Electron window. + await card.locator('[data-action="automation-create-title"]').focus() + await expect(popover).toBeVisible() + await expect + .poll(() => page.evaluate(() => !!document.activeElement?.closest('[data-component="popover-content"]'))) + .toBe(true) + + // Picking a value works and never dismisses the parent dialog. + await popover.locator('[data-action="automation-time-minute"][data-value="30"]').click() + await expect(card.locator('[data-action="automation-time"]')).toContainText("09:30") + await expect(popover).toBeVisible() + await expect(card).toBeVisible() + + // Escape is layer-aware: the first press closes only the top-most popover and + // the card stays; the second press closes the card. Guards against the shared + // dialog stealing Escape from the picker layer. + await page.keyboard.press("Escape") + await expect(popover).toHaveCount(0) + await expect(card).toBeVisible() + await page.keyboard.press("Escape") + await expect(card).toHaveCount(0) +}) + +test("automations panel: model picker survives the dialog focus trap and reopens", async ({ page, project }) => { + test.setTimeout(120_000) + + await project.open() + const surface = await openAutomations(page) + await surface.locator('[data-action="automation-create-open"]').click() + await page.locator('[data-action="automation-create-manual"]').click() + const card = page.locator('[data-component="automation-create"]') + await expect(card).toBeVisible() + + const trigger = page.locator('[data-action="automation-model-trigger"]') + const picker = page.locator("[data-picker-content]") + + // The model picker is the shared composer popover. Inside the modal dialog its + // hand-rolled focus-outside dismiss used to fire when the dialog's focus trap + // stole focus on open — flashing the picker shut, then wedging it permanently + // closed because focus stayed trapped on the title (#950 PR7). Shoving focus + // back into the dialog must NOT dismiss it. + await trigger.click() + await expect(picker).toBeVisible() + await card.locator('[data-action="automation-create-title"]').focus() + await expect(picker).toBeVisible() + + // Escape is layer-aware: it closes only the picker, the card stays. + await page.keyboard.press("Escape") + await expect(picker).toHaveCount(0) + await expect(card).toBeVisible() + + // And it reopens — the wedged-shut state is gone. + await trigger.click() + await expect(picker).toBeVisible() +}) + +test("automations panel: thinking submenu stays open inside the modal create card", async ({ page, project }) => { + test.setTimeout(120_000) + + await project.open() + + // The thinking submenu only renders for models that expose variants; discover + // one via the composer probe before navigating to the panel. + await expect + .poll( + () => + page.evaluate(() => { + const win = window as Window & { __opencode_e2e?: { model?: { current?: { models?: unknown[] } } } } + return win.__opencode_e2e?.model?.current?.models?.length ?? 0 + }), + { timeout: 30_000 }, + ) + .toBeGreaterThan(0) + const model = await findVariantModel(page) + test.skip(!model, "no e2e model with thinking variants") + if (!model) return + + const surface = await openAutomations(page) + await surface.locator('[data-action="automation-create-open"]').click() + await page.locator('[data-action="automation-create-manual"]').click() + const card = page.locator('[data-component="automation-create"]') + await expect(card).toBeVisible() + + // Select the variant-capable model so the thinking trigger is enabled. + await page.locator('[data-action="automation-model-trigger"]').click() + const picker = page.locator("[data-picker-content]") + await expect(picker).toBeVisible() + await picker + .locator(`[data-slot="list-item"][data-key="${model.providerID}:${model.modelID}"]`) + .first() + .click({ force: true }) + + // Reopen the picker and open the thinking submenu. + await page.locator('[data-action="automation-model-trigger"]').click() + const thinkingTrigger = page.locator('[data-action="prompt-model-thinking-trigger"]').first() + await expect(thinkingTrigger).toBeVisible() + await expect(thinkingTrigger).toBeEnabled() + await thinkingTrigger.click() + + // The nested thinking popover is non-modal; inside the modal outer picker the + // outer's focus trap used to steal focus the instant the submenu autofocused, + // flashing it shut (#950 PR7). A single auto-retrying toBeVisible can catch the + // brief open frame and pass anyway, so sample the option count over time and + // assert it is still open after the focus hand-off would have fired. + const option = page.locator('[data-action="prompt-model-thinking-option"]').first() + await expect(option).toBeVisible() + await expect + .poll(() => page.locator('[data-action="prompt-model-thinking-option"]').count(), { timeout: 2_000 }) + .toBeGreaterThan(0) + await page.waitForTimeout(300) + await expect(option).toBeVisible() + + // And it is usable: picking a non-default level applies the selection (the + // option marks itself selected) without tearing down the outer picker or card. + const level = page.locator('[data-action="prompt-model-thinking-option"]').nth(1) + await level.click() + await expect(level).toHaveAttribute("data-selected", "") + await expect(card).toBeVisible() +}) + +test("automations panel: template prefills the create card", async ({ page, project }) => { + test.setTimeout(120_000) + + await project.open() + const surface = await openAutomations(page) + const empty = surface.locator('[data-component="automations-empty"]') + await expect(empty).toBeVisible() + + // Empty-state quick-starts open the create card pre-filled with the template. + await empty.locator('[data-action="automation-template"]').first().click() + const card = page.locator('[data-component="automation-create"]') + await expect(card).toBeVisible() + await expect(card.locator('[data-action="automation-create-title"]')).not.toHaveValue("") + await expect(card.locator('[data-action="automation-create-prompt"]')).not.toHaveValue("") +}) + +test("automations panel: create via chat opens a prefilled session", async ({ page, project }) => { + test.setTimeout(120_000) + + await project.open() + const surface = await openAutomations(page) + + await surface.locator('[data-action="automation-create-open"]').click() + await page.locator('[data-action="automation-create-chat"]').click() + + // Leaves the panel for a fresh session whose composer carries the guiding prompt. + await expect(surface).toHaveCount(0) + await expect(page.getByText("set up an automation", { exact: false })).toBeVisible() +}) + +test("automations panel: the automate tool card jumps into the panel", async ({ page, project, assistant }) => { + test.setTimeout(120_000) + + await project.open() + + // The agent creates an automation in chat; the backend executes the tool for + // real and echoes the resolved definition in the tool part metadata. + await assistant.tool("automate", { + title: "Nightly digest", + prompt: "Summarize the day's changes every morning.", + cron: "0 9 * * *", + }) + await project.prompt("Set up a nightly digest automation.") + + const card = page.locator('[data-component="automate-tool-card"]') + await expect(card).toBeVisible() + await expect(card.getByText("Nightly digest")).toBeVisible() + + // The jump opens the Automations panel focused on the new automation. + await card.locator('[data-component="automate-tool-action"]').click() + const surface = page.locator('[data-component="automations-page"]') + await expect(surface).toBeVisible() + const detail = surface.locator('[data-component="automation-detail"]') + await expect(detail).toBeVisible() + await expect(detail.getByRole("heading", { name: "Nightly digest" })).toBeVisible() +}) + +test("automations panel: a second tool card jump opens its own automation", async ({ page, project, assistant }) => { + test.setTimeout(120_000) + + await project.open() + + // First card → panel focused on Alpha. + await assistant.tool("automate", { title: "Alpha digest", prompt: "Summarize A.", cron: "0 9 * * *" }) + await project.prompt("Set up alpha.") + const cardA = page.locator('[data-component="automate-tool-card"]').filter({ hasText: "Alpha digest" }) + await expect(cardA).toBeVisible() + await cardA.locator('[data-component="automate-tool-action"]').click() + const surface = page.locator('[data-component="automations-page"]') + const detail = surface.locator('[data-component="automation-detail"]') + await expect(detail.getByRole("heading", { name: "Alpha digest" })).toBeVisible() + + // Close the panel (the surface takes over main, so the chat — and the next + // tool card — is only reachable once it's closed), then jump from a second + // card. The surface is -gated, so it remounts and must focus Bravo, not + // re-show the stale Alpha selection. + await page.keyboard.press("Escape") + await page.keyboard.press("Escape") + await expect(surface).toHaveCount(0) + + await assistant.tool("automate", { title: "Bravo digest", prompt: "Summarize B.", cron: "0 10 * * *" }) + await project.prompt("Set up bravo.") + const cardB = page.locator('[data-component="automate-tool-card"]').filter({ hasText: "Bravo digest" }) + await expect(cardB).toBeVisible() + await cardB.locator('[data-component="automate-tool-action"]').click() + await expect(detail.getByRole("heading", { name: "Bravo digest" })).toBeVisible() +}) + test("automations panel: escape unwinds detail then closes the surface", async ({ page, project }) => { test.setTimeout(120_000) diff --git a/packages/app/e2e/prompt/prompt-footer-focus.spec.ts b/packages/app/e2e/prompt/prompt-footer-focus.spec.ts index e0437c00d..5e6b6b05c 100644 --- a/packages/app/e2e/prompt/prompt-footer-focus.spec.ts +++ b/packages/app/e2e/prompt/prompt-footer-focus.spec.ts @@ -115,6 +115,44 @@ test("model select returns focus to the prompt", async ({ page, gotoSession }) = await expect.poll(() => body(prompt)).toContain("focus model") }) +test("model picker escape returns focus to the prompt", async ({ page, gotoSession }) => { + await gotoSession() + + const prompt = await ready(page) + + await page.locator(`${promptModelSelector} [data-action="prompt-model"]`).first().click() + await expect(page.locator('[data-slot="list-item"]').first()).toBeVisible() + + // Escape closes the picker and hands focus back to the prompt (the dismiss + // refactor delegates the close to Kobalte but still reports the cause so the + // composer can restore focus — see ModelSelectorPopover.onClose). + await page.keyboard.press("Escape") + await expect(page.locator('[data-slot="list-item"]').first()).toBeHidden() + await expect(prompt).toBeFocused() + await prompt.pressSequentially(" esc") + await expect.poll(() => body(prompt)).toContain("focus esc") +}) + +test("model picker outside dismiss leaves focus where the pointer went", async ({ page, gotoSession }) => { + await gotoSession() + + const prompt = await ready(page) + + await page.locator(`${promptModelSelector} [data-action="prompt-model"]`).first().click() + await expect(page.locator('[data-slot="list-item"]').first()).toBeVisible() + + // Click into the prompt to dismiss the picker. An outside dismiss must leave + // focus on the prompt the user clicked, not snap it back to the model trigger. + // The dismiss refactor delegates outside handling to Kobalte, which already + // keeps focus off the trigger on outside interaction; this guards that the + // refactor didn't regress it. + await prompt.click() + await expect(page.locator('[data-slot="list-item"]').first()).toBeHidden() + await expect(prompt).toBeFocused() + await prompt.pressSequentially(" outside") + await expect.poll(() => body(prompt)).toContain("focus outside") +}) + test("home selected model is used for the first prompt", async ({ page, project }) => { await project.open() diff --git a/packages/app/e2e/snap/automations-surface.snap.ts b/packages/app/e2e/snap/automations-surface.snap.ts index 60cc55d67..db4d31916 100644 --- a/packages/app/e2e/snap/automations-surface.snap.ts +++ b/packages/app/e2e/snap/automations-surface.snap.ts @@ -49,11 +49,33 @@ test("automations-surface", async ({ page, project }) => { await surface.locator('[data-component="automation-detail"]').waitFor({ state: "visible", timeout: 30_000 }) const detail = await page.screenshot() + // Split entry: back to the list, open the New automation menu, screenshot it, + // then Create manually, fill the card, and expand the schedule popover. + await surface.locator('[data-action="automation-detail-back"]').click() + await surface.locator('[data-action="automation-create-open"]').click() + const manualItem = page.locator('[data-action="automation-create-manual"]') + await manualItem.waitFor({ state: "visible", timeout: 10_000 }) + const createMenu = await page.screenshot() + + await manualItem.click() + const card = page.locator('[data-component="automation-create"]') + await card.waitFor({ state: "visible", timeout: 10_000 }) + await card.locator('[data-action="automation-create-title"]').fill("Release notes draft") + await card.locator('[data-action="automation-create-prompt"]').fill("Draft release notes from PRs merged since the last tag.") + const createCard = await page.screenshot() + + await card.locator('[data-action="automation-schedule-trigger"]').click() + await page.locator('[data-action="automation-frequency-trigger"]').waitFor({ state: "visible", timeout: 10_000 }) + const schedulePopover = await page.screenshot() + const shots: Shot[] = [ { name: "empty", buf: empty }, { name: "list", buf: list }, { name: "list-hover", buf: listHover }, { name: "detail", buf: detail }, + { name: "create-menu", buf: createMenu }, + { name: "create-card", buf: createCard }, + { name: "schedule", buf: schedulePopover }, ] const out = snapOutputPath("automations-surface") await composeGrid(shots, out) diff --git a/packages/app/src/components/prompt-input/model-picker.tsx b/packages/app/src/components/prompt-input/model-picker.tsx index 04e469533..45eae7e59 100644 --- a/packages/app/src/components/prompt-input/model-picker.tsx +++ b/packages/app/src/components/prompt-input/model-picker.tsx @@ -2,6 +2,7 @@ import { Popover as Kobalte } from "@kobalte/core/popover" import { Component, ComponentProps, createMemo, createSignal, For, JSX, Show, ValidComponent } from "solid-js" import { createStore } from "solid-js/store" import { useLocal } from "@/context/local" +import type { ModelKey } from "@/context/models" import { popularProviders } from "@/hooks/use-providers" import { Icon } from "@opencode-ai/ui/icon" import { ProviderIcon } from "@opencode-ai/ui/provider-icon" @@ -17,7 +18,23 @@ import { translateVariant } from "@/components/prompt-input/variant-label" const isFree = (provider: string, cost: { input: number } | undefined) => provider === "opencode" && (!cost || cost.input === 0) -type ModelState = ReturnType["model"] +// The picker reads only this slice of the local model state. Decoupling it from +// useLocal lets the Automations create card (which renders outside the +// per-directory LocalProvider) drive the same UI from a panel-local controller +// (see pages/automations/automation-model-state). The full useLocal().model is +// a structural superset, so existing composer call sites are unaffected. +export type PickerModel = ReturnType["model"]["list"]>[number] +export interface ModelPickerState { + list: () => PickerModel[] + current: () => PickerModel | undefined + visible: (item: ModelKey) => boolean + set: (item: ModelKey | undefined, options?: { recent?: boolean }) => void + variant: { + list: () => string[] + current: () => string | undefined + set: (value: string | undefined) => void + } +} const [externalOpen, setExternalOpen] = createSignal(false) @@ -29,7 +46,7 @@ const ModelList: Component<{ provider?: string class?: string onSelect: () => void - model?: ModelState + model?: ModelPickerState }> = (props) => { const model = props.model ?? useLocal().model const language = useLanguage() @@ -93,7 +110,7 @@ const ModelList: Component<{ ) } -const ThinkingLevelSection: Component<{ model?: ModelState }> = (props) => { +const ThinkingLevelSection: Component<{ model?: ModelPickerState; modal?: boolean }> = (props) => { const model = props.model ?? useLocal().model const language = useLanguage() const variants = createMemo(() => model.variant.list()) @@ -104,7 +121,12 @@ const ThinkingLevelSection: Component<{ model?: ModelState }> = (props) => { return (
- + {/* Inherit the outer picker's modality. A non-modal nested popover opened + inside a modal outer would lose focus to the outer's trap the instant + it autofocuses and dismiss itself (the #950 PR7 thinking-submenu flash); + a modal inner traps focus into itself and stays open. Composer keeps the + outer (and so this) non-modal. */} + = (props) => { } type ModelSelectorTriggerProps = Omit, "as" | "ref"> -type Dismiss = "escape" | "outside" | "select" - -const isPickerContentTarget = (target: EventTarget | null) => - target instanceof Element && !!target.closest("[data-picker-content]") export function ModelSelectorPopover(props: { provider?: string - model?: ModelState + model?: ModelPickerState children?: JSX.Element triggerAs?: ValidComponent triggerProps?: ModelSelectorTriggerProps onClose?: (cause: "escape" | "select") => void + // Inside a modal dialog (the Automations create card) the picker must be modal + // too: the parent dialog's focus trap steals focus on open, and a non-modal + // popover treats that as a focus-outside and dismisses (the #950 PR7 flash). + // Kobalte only preventDefaults focus-outside for modal content. Default false + // keeps the composer behaviour (close when keyboard focus leaves) intact. + modal?: boolean }) { - const [store, setStore] = createStore<{ - open: boolean - dismiss: Dismiss | null - }>({ - open: false, - dismiss: null, - }) + const [store, setStore] = createStore<{ open: boolean }>({ open: false }) const language = useLanguage() const open = createMemo(() => store.open || externalOpen()) - const close = (dismiss: Dismiss) => { - setStore("dismiss", dismiss) + // Dismiss is delegated to Kobalte's native, layer-aware DismissableLayer: the + // parent dialog is recognised as an ancestor layer and the nested Thinking + // popover registers as a child layer, so neither trips an outside-dismiss. We + // only track *why* the picker closed, so the composer can restore focus to the + // prompt on escape/select — an outside dismiss must leave focus where it went. + let closeCause: "escape" | "select" | null = null + + const selectAndClose = () => { + closeCause = "select" setStore("open", false) setExternalOpen(false) } - let ignoreFocusOutsideForPointerInside = false - - const handlePointerDownInside = () => { - ignoreFocusOutsideForPointerInside = true - window.setTimeout(() => { - ignoreFocusOutsideForPointerInside = false - }, 0) - } - - const handleFocusOutside = ( - event: Parameters["onFocusOutside"]>>[0], - ) => { - if (isPickerContentTarget(event.target)) { - event.preventDefault() - return - } - if (ignoreFocusOutsideForPointerInside) { - ignoreFocusOutsideForPointerInside = false - event.preventDefault() - return - } - close("outside") - } return ( { - if (next) setStore("dismiss", null) setStore("open", next) if (!next) setExternalOpen(false) }} - modal={false} + modal={props.modal ?? false} placement="bottom-start" gutter={4} > @@ -216,42 +217,23 @@ export function ModelSelectorPopover(props: { { - close("escape") - event.preventDefault() - event.stopPropagation() - }} - onPointerDown={handlePointerDownInside} - onPointerDownOutside={(event) => { - // The nested ThinkingLevel popover renders into Kobalte.Portal, so - // its Content sits outside this outer Content's DOM subtree. Without - // this guard, clicks inside the inner picker satisfy "outside" for - // the outer popover and dismiss the model picker before the inner - // button click runs. - if (isPickerContentTarget(event.target)) { - event.preventDefault() - return - } - close("outside") + onEscapeKeyDown={() => { + // Record the cause and let Kobalte's top-most-layer Escape do the + // close; don't preventDefault, so a parent dialog stays open. + closeCause = "escape" }} - onFocusOutside={handleFocusOutside} onCloseAutoFocus={(event) => { - const dismiss = store.dismiss - if (dismiss === "outside") event.preventDefault() - if (dismiss === "escape" || dismiss === "select") { + const cause = closeCause + closeCause = null + if (cause) { event.preventDefault() - props.onClose?.(dismiss) + props.onClose?.(cause) } - setStore("dismiss", null) }} > {language.t("dialog.model.select.title")} - close("select")} - /> - + + diff --git a/packages/app/src/context/global-sync.tsx b/packages/app/src/context/global-sync.tsx index 3405df769..554ee36f2 100644 --- a/packages/app/src/context/global-sync.tsx +++ b/packages/app/src/context/global-sync.tsx @@ -1,4 +1,5 @@ import type { + AutomationCreateInput, Config, OpencodeClient, Path, @@ -389,6 +390,20 @@ function createGlobalSync() { } } + // create echoes the resolved definition (with normalizationWarnings); apply it + // immediately so the panel reflects the new automation before the SSE event. + async function createAutomation(directory: string, input: AutomationCreateInput) { + children.pin(directory) + try { + const [store, setStore] = children.peek(directory, { bootstrap: false }) + const res = await sdkFor(directory).automation.create({ automationCreateInput: input }) + if (res.data) applyAutomationDefinition(store, setStore, res.data) + return res.data + } finally { + children.unpin(directory) + } + } + async function bootstrapInstance(directory: string) { if (!directory) return const pending = booting.get(directory) @@ -642,6 +657,7 @@ function createGlobalSync() { updateConfig, project: projectApi, automation: { + create: createAutomation, loadRuns: loadAutomationRuns, pause: pauseAutomation, resume: resumeAutomation, diff --git a/packages/app/src/context/models.test.ts b/packages/app/src/context/models.test.ts index 96f407c3b..ea87db527 100644 --- a/packages/app/src/context/models.test.ts +++ b/packages/app/src/context/models.test.ts @@ -1,10 +1,13 @@ import { beforeAll, describe, expect, mock, test } from "bun:test" +import { createRoot } from "solid-js" import { VOLCENGINE_PLAN_PROVIDER_ID } from "@opencode-ai/util/volcengine-plan" import { compareModelsForDisplay } from "@/utils/model-order" +import type { useProviders } from "@/hooks/use-providers" let findProviderModel: typeof import("./models").findProviderModel let listAvailableProviderModels: typeof import("./models").listAvailableProviderModels let listProviderModels: typeof import("./models").listProviderModels +let createModelsView: typeof import("./models").createModelsView beforeAll(async () => { mock.module("@solidjs/router", () => ({ @@ -16,8 +19,29 @@ beforeAll(async () => { findProviderModel = mod.findProviderModel listAvailableProviderModels = mod.listAvailableProviderModels listProviderModels = mod.listProviderModels + createModelsView = mod.createModelsView }) +// A providers scope with just the connected models the test cares about — the +// only thing createModelsView reads. Models carry no release_date so they stay +// visible by default (release memo treats them as undated). +function fakeProviders(connected: Array<{ providerID: string; modelID: string }>): ReturnType { + const byProvider = new Map }>() + for (const m of connected) { + const p = byProvider.get(m.providerID) ?? { id: m.providerID, models: {} } + p.models[m.modelID] = { id: m.modelID, name: m.modelID, release_date: "" } + byProvider.set(m.providerID, p) + } + const list = [...byProvider.values()] + return { + all: () => list, + default: () => ({}), + popular: () => [], + connected: () => list, + paid: () => [], + } as unknown as ReturnType +} + const provider = { id: VOLCENGINE_PLAN_PROVIDER_ID, models: { @@ -57,3 +81,46 @@ describe("provider model list helpers", () => { expect(visible.map((model) => model.id)).toEqual(["doubao-seed-2.0-code", "glm-5.1", "kimi-k2.6"]) }) }) + +describe("createModelsView scopes to the providers it is given", () => { + // The #950 PR7 P1 fix: the Automations create card builds its model view from + // the *selected* directory's providers (via useScopedModels), not the route's. + // The load-bearing property is that the view only ever reflects the providers + // handed to it — so swapping the scope swaps the models, defaults and lookups. + test("list and find reflect the scoped providers, not another scope's", () => { + createRoot((dispose) => { + const noHidden = () => new Map() + const viewA = createModelsView(fakeProviders([{ providerID: "alpha", modelID: "a-1" }]), noHidden) + const viewB = createModelsView(fakeProviders([{ providerID: "bravo", modelID: "b-1" }]), noHidden) + + expect(viewA.list().map((m) => m.id)).toEqual(["a-1"]) + expect(viewB.list().map((m) => m.id)).toEqual(["b-1"]) + + expect(viewA.find({ providerID: "alpha", modelID: "a-1" })?.id).toBe("a-1") + // A model that belongs to the other scope must not resolve here. + expect(viewA.find({ providerID: "bravo", modelID: "b-1" })).toBeUndefined() + expect(viewB.find({ providerID: "bravo", modelID: "b-1" })?.id).toBe("b-1") + + dispose() + }) + }) + + test("visible honours the shared visibility map", () => { + createRoot((dispose) => { + const hidden = () => new Map([["alpha:a-1", "hide"]]) + const view = createModelsView( + fakeProviders([ + { providerID: "alpha", modelID: "a-1" }, + { providerID: "alpha", modelID: "a-2" }, + ]), + hidden, + ) + + expect(view.visible({ providerID: "alpha", modelID: "a-1" })).toBe(false) + // Undated, no explicit pref → visible by default. + expect(view.visible({ providerID: "alpha", modelID: "a-2" })).toBe(true) + + dispose() + }) + }) +}) diff --git a/packages/app/src/context/models.tsx b/packages/app/src/context/models.tsx index 08038ca57..af8009f81 100644 --- a/packages/app/src/context/models.tsx +++ b/packages/app/src/context/models.tsx @@ -1,4 +1,4 @@ -import { createMemo } from "solid-js" +import { createMemo, type Accessor } from "solid-js" import { createStore } from "solid-js/store" import { DateTime } from "luxon" import { filter, firstBy, flat, groupBy, mapValues, pipe, uniqueBy, values } from "remeda" @@ -46,6 +46,98 @@ export function findProviderModel( return listProviderModels(provider).find((model) => model.id === key.modelID) } +// The provider-derived model view (available list, latest/release, find, +// visibility filter) computed over one providers scope. Extracted from the +// context so the Automations create card can build a view scoped to its +// selected directory (see useScopedModels) instead of the route's, while still +// sharing the global, directory-independent user prefs (visibility map). +export function createModelsView( + providers: ReturnType, + visibility: Accessor>, +) { + const available = createMemo(() => + providers.connected().flatMap((p) => + listAvailableProviderModels(p).map((m) => ({ + ...m, + provider: p, + })), + ), + ) + + const release = createMemo( + () => + new Map( + available().map((model) => { + const parsed = DateTime.fromISO(model.release_date) + return [modelKey({ providerID: model.provider.id, modelID: model.id }), parsed] as const + }), + ), + ) + + const latest = createMemo(() => + pipe( + available(), + filter( + (x) => + Math.abs( + (release().get(modelKey({ providerID: x.provider.id, modelID: x.id })) ?? DateTime.invalid("invalid")) + .diffNow() + .as("months"), + ) < 6, + ), + groupBy((x) => x.provider.id), + mapValues((models) => + pipe( + models, + groupBy((x) => x.family), + values(), + (groups) => + groups.flatMap((g) => { + const first = firstBy(g, [(x) => x.release_date, "desc"]) + return first ? [{ modelID: first.id, providerID: first.provider.id }] : [] + }), + ), + ), + values(), + flat(), + ), + ) + + const latestSet = createMemo(() => new Set(latest().map((x) => modelKey(x)))) + + const decorateModel = (model: ReturnType[number]) => ({ + ...model, + name: model.name.replace("(latest)", "").trim(), + latest: model.name.includes("(latest)"), + }) + + const list = createMemo(() => available().map(decorateModel)) + + const find = (key: ModelKey) => { + const visibleModel = list().find((m) => m.id === key.modelID && m.provider.id === key.providerID) + if (visibleModel) return visibleModel + + const hit = findProviderModel(providers.connected(), key) + if (!hit) return + const provider = providers.connected().find((item) => item.id === key.providerID) + if (!provider) return + return decorateModel({ ...hit, provider }) + } + + const visible = (model: ModelKey) => { + const key = modelKey(model) + const state = visibility().get(key) + if (state === "hide") return false + if (state === "show") return true + if (latestSet().has(key)) return true + const date = release().get(key) + if (!date?.isValid) return true + return false + } + + return { list, find, visible } +} + export const { use: useModels, provider: ModelsProvider } = createSimpleContext({ name: "Models", init: () => { @@ -60,80 +152,13 @@ export const { use: useModels, provider: ModelsProvider } = createSimpleContext( }), ) - const available = createMemo(() => - providers.connected().flatMap((p) => - listAvailableProviderModels(p).map((m) => ({ - ...m, - provider: p, - })), - ), - ) - - const release = createMemo( - () => - new Map( - available().map((model) => { - const parsed = DateTime.fromISO(model.release_date) - return [modelKey({ providerID: model.provider.id, modelID: model.id }), parsed] as const - }), - ), - ) - - const latest = createMemo(() => - pipe( - available(), - filter( - (x) => - Math.abs( - (release().get(modelKey({ providerID: x.provider.id, modelID: x.id })) ?? DateTime.invalid("invalid")) - .diffNow() - .as("months"), - ) < 6, - ), - groupBy((x) => x.provider.id), - mapValues((models) => - pipe( - models, - groupBy((x) => x.family), - values(), - (groups) => - groups.flatMap((g) => { - const first = firstBy(g, [(x) => x.release_date, "desc"]) - return first ? [{ modelID: first.id, providerID: first.provider.id }] : [] - }), - ), - ), - values(), - flat(), - ), - ) - - const latestSet = createMemo(() => new Set(latest().map((x) => modelKey(x)))) - const visibility = createMemo(() => { const map = new Map() for (const item of store.user) map.set(`${item.providerID}:${item.modelID}`, item.visibility) return map }) - const decorateModel = (model: ReturnType[number]) => ({ - ...model, - name: model.name.replace("(latest)", "").trim(), - latest: model.name.includes("(latest)"), - }) - - const list = createMemo(() => available().map(decorateModel)) - - const find = (key: ModelKey) => { - const visible = list().find((m) => m.id === key.modelID && m.provider.id === key.providerID) - if (visible) return visible - - const hit = findProviderModel(providers.connected(), key) - if (!hit) return - const provider = providers.connected().find((item) => item.id === key.providerID) - if (!provider) return - return decorateModel({ ...hit, provider }) - } + const view = createModelsView(providers, visibility) function update(model: ModelKey, state: Visibility) { const index = store.user.findIndex((x) => x.modelID === model.modelID && x.providerID === model.providerID) @@ -144,17 +169,6 @@ export const { use: useModels, provider: ModelsProvider } = createSimpleContext( setStore("user", store.user.length, { ...model, visibility: state }) } - const visible = (model: ModelKey) => { - const key = modelKey(model) - const state = visibility().get(key) - if (state === "hide") return false - if (state === "show") return true - if (latestSet().has(key)) return true - const date = release().get(key) - if (!date?.isValid) return true - return false - } - const setVisibility = (model: ModelKey, state: boolean) => { update(model, state ? "show" : "hide") } @@ -179,9 +193,10 @@ export const { use: useModels, provider: ModelsProvider } = createSimpleContext( return { ready, - list, - find, - visible, + list: view.list, + find: view.find, + visible: view.visible, + visibility, setVisibility, recent: { list: createMemo(() => store.recent), @@ -194,3 +209,16 @@ export const { use: useModels, provider: ModelsProvider } = createSimpleContext( } }, }) + +// Models scoped to a chosen directory rather than the current route. The +// Automations create card files an automation against any open project, so its +// model list, default and validation must follow the selected folder — not the +// routed one — or it would offer/seed a model the target project can't run +// (#950 PR7). Shares the global user prefs (visibility, recent, variant) since +// those are per-user, not per-project. +export function useScopedModels(dir: Accessor) { + const global = useModels() + const providers = useProviders(dir) + const view = createModelsView(providers, global.visibility) + return { ...global, list: view.list, find: view.find, visible: view.visible } +} diff --git a/packages/app/src/hooks/use-providers.ts b/packages/app/src/hooks/use-providers.ts index b51c8764f..30b397960 100644 --- a/packages/app/src/hooks/use-providers.ts +++ b/packages/app/src/hooks/use-providers.ts @@ -1,7 +1,7 @@ import { useGlobalSync } from "@/context/global-sync" import { decode64 } from "@/utils/base64" import { useParams } from "@solidjs/router" -import { createMemo } from "solid-js" +import { createMemo, type Accessor } from "solid-js" export const popularProviders = [ "opencode", @@ -17,10 +17,14 @@ export const popularProviders = [ ] const popularProviderSet = new Set(popularProviders) -export function useProviders() { +export function useProviders(dirOverride?: Accessor) { const globalSync = useGlobalSync() const params = useParams() - const dir = createMemo(() => decode64(params.dir) ?? "") + // dirOverride is a raw directory (e.g. the Automations create card's selected + // folder, which can differ from the current route). When provided it fully + // replaces the route's encoded dir param, so providers/models can be scoped to + // a directory other than the one in the URL. + const dir = createMemo(() => (dirOverride ? (dirOverride() ?? "") : (decode64(params.dir) ?? ""))) const providers = () => { if (dir()) { const [projectStore] = globalSync.child(dir()) diff --git a/packages/app/src/i18n/en.ts b/packages/app/src/i18n/en.ts index b9d964c19..34e2ff8b3 100644 --- a/packages/app/src/i18n/en.ts +++ b/packages/app/src/i18n/en.ts @@ -832,6 +832,28 @@ export const dict = { "automations.delete.title": "Delete automation", "automations.delete.confirm": "Delete “{{title}}”?", "automations.delete.description": "This stops future runs and removes the automation. Past run sessions are kept.", + "automations.create.cta": "New automation", + "automations.create.viaChat": "Create via chat", + "automations.create.manually": "Create manually", + "automations.create.viaChatPrompt": "Help me set up an automation. Ask me what it should do and when it should run, then create it.", + "automations.create.titlePlaceholder": "Automation title", + "automations.create.promptPlaceholder": "Add a prompt, e.g. summarize today's email into a brief every morning", + "automations.create.useTemplate": "Use template", + "automations.create.submit": "Create", + "automations.create.failed": "Couldn't create automation", + "automations.create.at": "at", + "automations.create.hour": "Hour", + "automations.create.minute": "Min", + "automations.create.frequency.once": "Once", + "automations.create.frequency.daily": "Daily", + "automations.create.frequency.weekdays": "Weekdays", + "automations.create.frequency.weekly": "Weekly", + "automations.template.dailyBrief.title": "Daily brief", + "automations.template.dailyBrief.prompt": "Summarize what needs my attention today: progress, open tasks, risks, and decisions to make. Keep it to a short list of bullet points.", + "automations.template.weeklyReview.title": "Weekly review", + "automations.template.weeklyReview.prompt": "Review the past week: what shipped, what progressed, what's blocked, and the top priorities to focus on next week.", + "automations.template.projectMonitor.title": "Project monitor", + "automations.template.projectMonitor.prompt": "Check this project's latest state: new issues, failing checks, or anything unusual. Call out what needs attention in bullets, or confirm all clear.", "sidebar.pawwork.empty.description": "Open a project to start using the session-first sidebar.", "sidebar.pawwork.pinned": "Pinned", "sidebar.pawwork.all": "All sessions", diff --git a/packages/app/src/i18n/zh.ts b/packages/app/src/i18n/zh.ts index 6b71e60cb..740cb2e5a 100644 --- a/packages/app/src/i18n/zh.ts +++ b/packages/app/src/i18n/zh.ts @@ -691,9 +691,9 @@ export const dict = { "sidebar.empty.title": "还没有打开项目", "sidebar.empty.description": "打开一个项目开始使用", "sidebar.pawwork.search": "搜索", - "sidebar.pawwork.automations": "自动化", - "automations.title": "自动化", - "automations.empty.title": "还没有自动化", + "sidebar.pawwork.automations": "定时任务", + "automations.title": "定时任务", + "automations.empty.title": "还没有定时任务", "automations.empty.description": "在对话里让助手把当前项目的某个任务设为自动运行。", "automations.schedule.once": "单次", "automations.schedule.hourly": "每小时", @@ -716,9 +716,9 @@ export const dict = { "automations.action.resume": "恢复", "automations.action.runNow": "立即运行", "automations.action.delete": "删除", - "automations.toast.actionFailed.title": "更新自动化失败", - "automations.toast.failureStreak.title": "自动化持续失败", - "automations.toast.failureStreak.description": "“{{title}}”已连续失败 {{count}} 次,打开自动化面板查看。", + "automations.toast.actionFailed.title": "更新定时任务失败", + "automations.toast.failureStreak.title": "定时任务持续失败", + "automations.toast.failureStreak.description": "“{{title}}”已连续失败 {{count}} 次,打开定时任务面板查看。", "automations.detail.instructions": "指令", "automations.detail.statusHeading": "状态", "automations.detail.detailsHeading": "详情", @@ -739,9 +739,31 @@ export const dict = { "automations.run.succeeded": "成功", "automations.run.failed": "失败", "automations.run.stopped": "已停止", - "automations.delete.title": "删除自动化", + "automations.delete.title": "删除定时任务", "automations.delete.confirm": "删除“{{title}}”?", - "automations.delete.description": "这会停止后续运行并移除该自动化。过往运行的会话会保留。", + "automations.delete.description": "这会停止后续运行并移除该定时任务。过往运行的会话会保留。", + "automations.create.cta": "新建定时任务", + "automations.create.viaChat": "对话创建", + "automations.create.manually": "手动创建", + "automations.create.viaChatPrompt": "帮我建一个定时任务。先问我它该做什么、什么时候运行,然后创建它。", + "automations.create.titlePlaceholder": "定时任务标题", + "automations.create.promptPlaceholder": "写下要做什么,例如:每天把今天的邮件总结成一份简报", + "automations.create.useTemplate": "使用模板", + "automations.create.submit": "创建", + "automations.create.failed": "创建定时任务失败", + "automations.create.at": "于", + "automations.create.hour": "时", + "automations.create.minute": "分", + "automations.create.frequency.once": "单次", + "automations.create.frequency.daily": "每天", + "automations.create.frequency.weekdays": "工作日", + "automations.create.frequency.weekly": "每周", + "automations.template.dailyBrief.title": "每日简报", + "automations.template.dailyBrief.prompt": "汇总今天需要我关注的重点:进展、待办、风险和需要决策的事项,用简明的条目列出。", + "automations.template.weeklyReview.title": "每周回顾", + "automations.template.weeklyReview.prompt": "回顾过去一周:完成了什么、有哪些进展和阻塞,并给出下周建议优先处理的事项。", + "automations.template.projectMonitor.title": "项目监控", + "automations.template.projectMonitor.prompt": "检查这个项目的最新状态:新出现的问题、失败的检查或异常情况。有需要关注的就用要点列出,没有就说明一切正常。", "sidebar.pawwork.empty.description": "打开一个项目后,即可使用以会话为中心的侧边栏。", "sidebar.pawwork.pinned": "已置顶", "sidebar.pawwork.all": "全部会话", diff --git a/packages/app/src/pages/automations/automation-create-dialog.tsx b/packages/app/src/pages/automations/automation-create-dialog.tsx new file mode 100644 index 000000000..bda28514b --- /dev/null +++ b/packages/app/src/pages/automations/automation-create-dialog.tsx @@ -0,0 +1,278 @@ +import { Popover } from "@kobalte/core/popover" +import { createEffect, createMemo, createSignal, For, on, Show, type JSX } from "solid-js" +import type { AutomationCreateInput, AutomationDefinition } from "@opencode-ai/sdk/v2/client" +import { Button } from "@opencode-ai/ui/button" +import { Dialog } from "@opencode-ai/ui/dialog" +import { Icon } from "@opencode-ai/ui/icon" +import { ProviderIcon } from "@opencode-ai/ui/provider-icon" +import { showToast } from "@opencode-ai/ui/toast" +import { useDialog } from "@opencode-ai/ui/context/dialog" +import { ModelSelectorPopover } from "@/components/prompt-input/model-picker" +import { translateVariant } from "@/components/prompt-input/variant-label" +import { useGlobalSync } from "@/context/global-sync" +import { useLanguage } from "@/context/language" +import { useLayout } from "@/context/layout" +import { useScopedModels, type ModelKey } from "@/context/models" +import { useProviders } from "@/hooks/use-providers" +import { formatServerError } from "@/utils/server-errors" +import { AutomationScheduleControls } from "./automation-schedule-controls" +import { AutomationFolderPicker, type AutomationProject } from "./automation-folder-picker" +import { buildScheduleInput, DEFAULT_SCHEDULE, type ScheduleDraft } from "./automation-schedule-form" +import { createAutomationModelState } from "./automation-model-state" +import { AUTOMATION_TEMPLATES, type AutomationTemplate } from "./automation-templates" + +const KNOB_CLASS = + "flex h-[30px] min-w-0 items-center gap-1.5 rounded-lg border border-border-weak px-2.5 text-body text-fg-base hover:bg-row-hover-overlay focus:outline-none cursor-default" + +// Manual create card (issue #950 PR7). Title + prompt, then an inline schedule +// row (frequency segmented switch + time), then a Folder | Model bottom bar. +// context, stop, and worktree are pinned to fresh / never / none (see handoff); +// the folder picker lets the automation be filed against any open project. The +// Automations surface renders outside the per-directory LocalProvider, so the +// composer's useLocal-backed model state can't be reused; a panel-local +// controller (see automation-model-state) drives the same picker UI from +// useModels(), seeded with the last-used / default model. +export function AutomationCreateDialog(props: { + directory: string + projectID: string + template?: AutomationTemplate + onCreated: (definition: AutomationDefinition) => void +}): JSX.Element { + const globalSync = useGlobalSync() + const language = useLanguage() + const layout = useLayout() + const dialog = useDialog() + const t = language.t + + // The folder picker can file the automation against any open project, so the + // model list, default and validation must follow the *selected* directory, not + // the current route — otherwise we'd offer/seed a model the target project + // can't run (#950 PR7 P1). Declared before the scoped model/provider views so + // they react to folder switches. + const [directory, setDirectory] = createSignal(props.directory) + const [projectID, setProjectID] = createSignal(props.projectID) + const models = useScopedModels(directory) + const providers = useProviders(directory) + + // Open projects the automation can be filed against (excludes the synthetic + // "global" project). Each carries the projectID the create input needs. + const projects = createMemo(() => + layout.projects + .list() + .filter((project) => project.id && project.id !== "global" && project.worktree) + .map((project) => ({ id: project.id!, worktree: project.worktree, name: project.name })), + ) + + // Seed with the same priority the composer uses: last-used model, then the + // configured project default, then the first connected model. Resolved once; + // the picker takes over from here. + const seedModel = (): ModelKey | undefined => { + for (const recent of models.recent.list()) if (models.find(recent)) return recent + const defaults = providers.default() + for (const providerID in defaults) { + const modelID = defaults[providerID] + if (modelID && models.find({ providerID, modelID })) return { providerID, modelID } + } + const first = models.list()[0] + return first ? { providerID: first.provider.id, modelID: first.id } : undefined + } + + const [title, setTitle] = createSignal(props.template ? t(props.template.titleKey) : "") + const [prompt, setPrompt] = createSignal(props.template ? t(props.template.promptKey) : "") + const [schedule, setSchedule] = createSignal(props.template?.schedule ?? DEFAULT_SCHEDULE) + const [model, setModel] = createSignal(seedModel()) + const [variant, setVariant] = createSignal() + const [creating, setCreating] = createSignal(false) + + // When the folder changes, the model list reflects the new project. If the + // current pick isn't available there, re-seed (and drop the variant) so we + // never submit a model the target project can't run. + createEffect( + on(directory, () => { + const selected = model() + if (selected && models.find(selected)) return + setModel(seedModel()) + setVariant(undefined) + }, { defer: true }), + ) + + const modelState = createAutomationModelState({ models, model, setModel, variant, setVariant }) + + const applyTemplate = (template: AutomationTemplate) => { + setTitle(t(template.titleKey)) + setPrompt(t(template.promptKey)) + setSchedule(template.schedule) + } + + // The model must be valid for the *selected* project, not just set. + const validModel = createMemo(() => { + const selected = model() + return selected ? models.find(selected) : undefined + }) + + const canCreate = createMemo( + () => title().trim().length > 0 && prompt().trim().length > 0 && !!validModel() && !!projectID(), + ) + + const create = async () => { + const selected = model() + if (creating() || !canCreate() || !selected) return + setCreating(true) + try { + const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC" + const scheduled = buildScheduleInput(schedule(), timezone, Date.now()) + const common = { + title: title().trim(), + prompt: prompt().trim(), + context: "fresh" as const, + where: { projectID: projectID() }, + timezone, + model: selected, + ...(variant() ? { variant: variant() } : {}), + } + const input: AutomationCreateInput = + scheduled.kind === "oneshot" + ? { kind: "oneshot", ...common, fireAt: scheduled.fireAt } + : { kind: "recurring", ...common, rhythm: scheduled.rhythm, stop: { kind: "never" } } + const definition = await globalSync.automation.create(directory(), input) + dialog.close() + if (definition) props.onCreated(definition) + } catch (error) { + showToast({ + variant: "error", + title: t("automations.create.failed"), + description: formatServerError(error, t), + }) + } finally { + setCreating(false) + } + } + + return ( + +
+
+ setTitle(event.currentTarget.value)} + placeholder={t("automations.create.titlePlaceholder")} + class="min-w-0 flex-1 bg-transparent text-h3 text-fg-strong placeholder:text-fg-weak focus:outline-none" + autofocus + /> + + + {t("automations.create.useTemplate")} + + + + + {(template) => ( + applyTemplate(template)} + class="flex h-[34px] w-full items-center gap-2.5 rounded-md px-2.5 text-body text-fg-base hover:bg-row-hover-overlay focus:outline-none" + > + + {t(template.titleKey)} + + )} + + + + + +
+ +