From 782125f72a60220a4896490be628d16be56ac1da Mon Sep 17 00:00:00 2001 From: Filip Hejmowski <34747899+neriousy@users.noreply.github.com> Date: Thu, 26 Nov 2026 16:14:19 +0100 Subject: [PATCH] feat(app): show where automations run and which session they wake (#66393) --- .../app/e2e/regression/automations.spec.ts | 273 ++++++++++++++++++ packages/app/e2e/utils/mock-api.ts | 27 ++ packages/app/e2e/utils/mock-server.ts | 57 +++- packages/app/src/automations/format.ts | 110 +++++++ packages/app/src/automations/model.ts | 172 +++++++++++ packages/app/src/automations/route.tsx | 186 ++++++++++++ packages/app/src/automations/source.ts | 139 +++++++++ packages/app/src/automations/view.tsx | 258 +++++++++++++++++ packages/app/src/home/projects/view.tsx | 16 + .../new-session/workspace/controller.test.ts | 5 + .../src/new-session/workspace/controller.ts | 18 +- packages/app/src/runtime/i18n/en.ts | 50 ++++ .../settings/experimental/experimental.tsx | 14 + packages/app/src/settings/model.tsx | 9 + packages/app/src/settings/search-catalog.ts | 7 + packages/app/src/shell/routes/routes.tsx | 12 +- packages/app/src/shell/state/layout.test.ts | 2 +- packages/app/src/shell/state/layout.tsx | 3 + packages/app/src/shell/tabs/tabs.tsx | 21 ++ packages/app/src/shell/titlebar/titlebar.tsx | 57 ++++ packages/plugin/src/gui/icon-name.ts | 1 + packages/ui/src/icons/catalog.ts | 4 + 22 files changed, 1431 insertions(+), 10 deletions(-) create mode 100644 packages/app/e2e/regression/automations.spec.ts create mode 100644 packages/app/src/automations/format.ts create mode 100644 packages/app/src/automations/model.ts create mode 100644 packages/app/src/automations/route.tsx create mode 100644 packages/app/src/automations/source.ts create mode 100644 packages/app/src/automations/view.tsx diff --git a/packages/app/e2e/regression/automations.spec.ts b/packages/app/e2e/regression/automations.spec.ts new file mode 100644 index 00000000000..84cc9af476d --- /dev/null +++ b/packages/app/e2e/regression/automations.spec.ts @@ -0,0 +1,273 @@ +import type { AutomationInfo } from "@opencode/client/promise" +import { expect, test } from "@playwright/test" +import { project, provider, REMOTE_SERVER, seed, SERVER, sessionHref } from "../utils/app" +import { mockServers } from "../utils/mock-server" +import { mockWorkspace } from "../utils/workspace" + +test("inspects event and timer automations and manages the selected row", async ({ page }) => { + await page.setViewportSize({ width: 1440, height: 900 }) + const directory = "C:/OpenCode/Atlas" + const now = Date.UTC(2026, 10, 17, 9, 10) + + const base = { + projectID: "proj_atlas", + directory: `${directory}/release`, + tz: "UTC", + sessionID: "ses_release", + status: "active", + runCount: 3, + time: { created: now, updated: now }, + } as const + + const automations: AutomationInfo[] = [ + { + ...base, + id: "aut_deploy", + name: "Release health watch", + trigger: { type: "event", server: "deployments", event: "deployment.finished", args: { environment: "staging" } }, + action: { + type: "code", + code: 'console.log(`Deployment status: ${event.data.status}`)\nif (event.data.status === "failed")\n return { send: { prompt: "Review the failed deployment." } }', + }, + lastRunAt: now, + lastOutcome: "fired", + lastOutput: "Deployment status: succeeded", + }, + { + ...base, + id: "aut_brief", + name: "Morning release brief", + trigger: { type: "cron", cron: "0 9 * * 1-5" }, + action: { type: "prompt", prompt: "Summarize release activity since yesterday.", to: { session: "ses_brief" } }, + nextDueAt: now + 86_400_000, + }, + { + ...base, + id: "aut_smoke", + name: "Nightly smoke test", + trigger: { type: "cron", cron: "0 2 * * *" }, + action: { type: "shell", command: "bun run test:smoke --reporter=dot" }, + nextDueAt: now + 2 * 86_400_000, + lastRunAt: now, + lastOutcome: "fired", + lastOutput: "Exit code: 0\n42 pass, 0 fail", + }, + { + ...base, + id: "aut_docs", + name: "Documentation review", + status: "paused", + trigger: { type: "every", every: "1 day" }, + action: { type: "prompt", prompt: "Review the documentation changes.", to: { subagent: "reviewer" } }, + }, + ] + + await mockWorkspace(page, { + name: "Atlas", + directory, + project: { name: "Atlas (sample)" }, + hostname: "release-runner-03", + commands: [{ name: "automation" }], + sessions: [ + { id: "ses_release", title: "Release planning" }, + { id: "ses_brief", title: "Release notes" }, + ], + automations, + seed: { + theme: { id: "oc-2", scheme: "dark" }, + settings: { general: { automations: true }, appearance: { tabLayout: "vertical", sidebarOpen: true } }, + }, + }) + await page.goto(sessionHref("ses_release")) + const nav = page.getByRole("button", { name: "Automations", exact: true }) + await nav.click() + await expect(page.getByRole("button", { name: /Morning release brief/ })).toContainText("Weekdays at 9:00 AM") + const detail = page.getByRole("article") + await page.getByRole("button", { name: /Release health watch/ }).click() + await expect(detail.getByRole("heading", { name: "Release health watch" })).toBeVisible() + await expect(detail.getByText("deployment.finished from deployments", { exact: true })).toBeVisible() + await expect( + detail + .getByRole("term") + .filter({ hasText: /^Runs on$/ }) + .locator("+ dd"), + ).toHaveText("release-runner-03") + await expect(detail.getByText('environment = "staging"', { exact: true })).toBeVisible() + await expect(detail.getByText("Next run")).toHaveCount(0) + await expect( + detail.getByText("Wakes the creating session only when the code returns send", { exact: false }), + ).toBeVisible() + await expect(detail.getByText(`${directory}/release`, { exact: true })).toBeVisible() + await expect(detail.getByText("Deployment status: succeeded", { exact: true })).toBeVisible() + await page.screenshot({ path: test.info().outputPath("automation-inspector.png"), animations: "disabled" }) + await detail.getByRole("button", { name: "Pause", exact: true }).click() + await expect(nav).toContainText("2") + await detail.getByRole("button", { name: "Resume", exact: true }).click() + await expect(nav).toContainText("3") + await detail.getByRole("button", { name: "Delete", exact: true }).click() + await page.getByRole("dialog").getByRole("button", { name: "Delete", exact: true }).click() + await expect(page.getByRole("button", { name: /Release health watch/ })).toHaveCount(0) + await expect(detail.getByText("Next run")).toBeVisible() + await expect(detail.getByRole("button", { name: "Release planning" })).toBeVisible() + await expect(detail.getByRole("button", { name: "Release notes" })).toBeVisible() + await page.getByRole("button", { name: /Nightly smoke test/ }).click() + await expect(detail.getByText("bun run test:smoke --reporter=dot", { exact: true })).toBeVisible() + await expect(detail.getByText("Doesn’t wake a session", { exact: false })).toBeVisible() + await page.getByRole("button", { name: /Documentation review/ }).click() + await expect(detail.getByText("Send a prompt to a new reviewer subagent")).toBeVisible() + await page.getByRole("button", { name: "New automation" }).click() + await expect(page.locator('[data-component="composer-editor"]')).toHaveText(/\/automation/) +}) + +test("hides every automation entry point while the experimental setting is off", async ({ page }) => { + await mockWorkspace(page, { name: "Off", commands: [{ name: "automation" }] }) + await page.goto("/automations") + await expect(page.getByText("Turn on Automations in Settings → Experimental.")).toBeVisible() + await expect(page.getByRole("button", { name: "Automations", exact: true })).toHaveCount(0) + await expect(page.getByRole("button", { name: "New automation" })).toHaveCount(0) +}) + +test("keeps the entry for an empty server and withdraws New automation when the server removes its command", async ({ + page, +}) => { + let enabled = true + + const { push, directory } = await mockWorkspace(page, { + name: "Empty", + commands: () => (enabled ? [{ name: "automation" }] : []), + seed: { settings: { general: { automations: true } } }, + }) + + await page.goto("/automations") + await expect(page.getByRole("heading", { name: "No automations yet" })).toBeVisible() + enabled = false + await push([ + { id: "evt_automation_disabled", created: 1, type: "command.updated", location: { directory }, data: {} }, + ]) + await expect(page.getByRole("button", { name: "New automation" })).toHaveCount(0) + await expect(page.getByRole("heading", { name: "No automations yet" })).toBeVisible() + await expect(page.getByRole("button", { name: "Automations", exact: true })).toBeVisible() +}) + +test("manages a watch outside open locations and opens the recipient instead of its last viewed child", async ({ + page, +}) => { + const directory = "/projects/repo" + const docs = `${directory}/docs` + await mockWorkspace(page, { + name: "Repo", + directory, + commands: (dir) => (dir === docs ? [{ name: "automation" }] : []), + automations: [ + { + id: "aut_docs", + projectID: "proj_repo", + directory: docs, + name: "Review docs", + tz: "UTC", + trigger: { type: "every", every: "1 day" }, + action: { type: "prompt", prompt: "Review new documentation.", to: { session: "ses_parent" } }, + status: "active", + runCount: 0, + time: { created: 1, updated: 1 }, + }, + ], + sessions: [ + { id: "ses_parent", title: "Docs planning" }, + { id: "ses_child", title: "Research notes", parentID: "ses_parent" }, + ], + seed: { + settings: { general: { automations: true } }, + storage: { + "opencode.window.browser.dat:tabs": [ + { + type: "session", + sessionId: "ses_parent", + server: SERVER, + routeSessionId: "ses_child", + routeParentId: "ses_parent", + }, + ], + }, + }, + }) + await page.goto(sessionHref("ses_child")) + await expect(page.getByRole("heading", { name: "Research notes", exact: true })).toBeVisible() + await page.getByRole("button", { name: "Automations", exact: true }).click() + const detail = page.getByRole("article") + await expect(detail.getByRole("heading", { name: "Review docs" })).toBeVisible() + await expect(detail.getByText(docs, { exact: true })).toBeVisible() + await expect(page.getByRole("button", { name: "New automation" })).toBeVisible() + await detail.getByRole("button", { name: /Docs planning|ses_parent/ }).click() + await expect(page).toHaveURL(sessionHref("ses_parent")) + await expect(page.locator('[data-component="composer-editor"]')).toBeEditable() +}) + +test("keeps identically keyed automations on separate servers and starts the draft in the row’s saved directory", async ({ + page, +}) => { + const servers = [SERVER, REMOTE_SERVER] as const + const creates: unknown[] = [] + const commands: unknown[] = [] + await mockServers( + page, + Object.fromEntries( + servers.map((server) => { + const name = server === SERVER ? "Local" : "Remote" + const directory = `/projects/${name.toLowerCase()}` + + const row: AutomationInfo = { + id: "aut_brief", + name: `${name} brief`, + projectID: "proj_shared", + directory: `${directory}/worktrees/docs`, + status: "active", + runCount: 0, + trigger: { type: "at", at: "2027-01-04T09:00" }, + tz: "UTC", + action: { type: "prompt", prompt: "Review the release notes.", to: { session: "ses_notes" } }, + time: { created: 1, updated: 1 }, + } + + return [ + server, + { + directory, + project: project({ id: row.projectID, directory, name: `${name} project` }), + provider: provider(), + pageMessages: () => ({ items: [] }), + onSessionCreate: (body: { location?: unknown }) => void creates.push({ server, location: body.location }), + onCommand: (input: { body: unknown }) => void commands.push({ server, body: input.body }), + sessions: [], + commands: [{ name: "automation" }], + automations: [row], + }, + ] + }), + ), + ) + await seed(page, { + settings: { general: { automations: true } }, + servers: [REMOTE_SERVER], + usedProjects: { local: ["proj_shared"], [REMOTE_SERVER]: ["proj_shared"] }, + }) + await page.goto("/automations") + await page.getByRole("button", { name: /Remote brief/ }).click() + const detail = page.getByRole("article") + await expect(detail.getByText("Remote project", { exact: true })).toBeVisible() + await expect(detail.getByText("Created by")).toHaveCount(0) + await expect(detail.getByRole("button", { name: "ses_notes" })).toBeVisible() + const directory = "/projects/remote/worktrees/docs" + await expect(detail.getByText(directory, { exact: true })).toBeVisible() + await page.getByRole("button", { name: "New automation" }).click() + const editor = page.locator('[data-component="composer-editor"]') + await expect(editor).toHaveText(/\/automation/) + await editor.fill("/automation Review the release notes on Friday") + await editor.press("Enter") + await expect.poll(() => creates).toEqual([{ server: REMOTE_SERVER, location: { directory } }]) + await expect + .poll(() => commands) + .toMatchObject([ + { server: REMOTE_SERVER, body: { name: "automation", text: "Review the release notes on Friday" } }, + ]) +}) diff --git a/packages/app/e2e/utils/mock-api.ts b/packages/app/e2e/utils/mock-api.ts index 2119ab48518..22f8798b1c4 100644 --- a/packages/app/e2e/utils/mock-api.ts +++ b/packages/app/e2e/utils/mock-api.ts @@ -242,6 +242,33 @@ const Group = HttpApiGroup.make("mock") .add(HttpApiEndpoint.get("usageLimits", "/api/experimental/usage/limits", { success: Json })) .add(HttpApiEndpoint.get("flagList", "/api/experimental/flag", { success: Json })) .add(HttpApiEndpoint.get("jobList", "/api/experimental/job", { success: Json })) + .add( + HttpApiEndpoint.get("automationList", "/api/experimental/automation", { + query: Schema.Struct({ sessionID: Schema.optional(Schema.String) }), + success: Json, + }), + ) + .add( + HttpApiEndpoint.post("automationPause", "/api/experimental/automation/:automationID/pause", { + params: Schema.Struct({ automationID: Schema.String }), + success: Json, + error: [MockNotFound], + }), + ) + .add( + HttpApiEndpoint.post("automationResume", "/api/experimental/automation/:automationID/resume", { + params: Schema.Struct({ automationID: Schema.String }), + success: Json, + error: [MockNotFound], + }), + ) + .add( + HttpApiEndpoint.delete("automationDelete", "/api/experimental/automation/:automationID", { + params: Schema.Struct({ automationID: Schema.String }), + success: NoContent, + error: [MockNotFound], + }), + ) .add( HttpApiEndpoint.get("worktreeList", "/api/worktree", { query: Schema.Struct({ projectID: Schema.String }), diff --git a/packages/app/e2e/utils/mock-server.ts b/packages/app/e2e/utils/mock-server.ts index e8988b207a6..4b0a7f87faf 100644 --- a/packages/app/e2e/utils/mock-server.ts +++ b/packages/app/e2e/utils/mock-server.ts @@ -1,5 +1,5 @@ import type { Page } from "@playwright/test" -import type { OpenCodeEvent, SessionMessageInfo } from "@opencode/client/promise" +import type { OpenCodeEvent, AutomationInfo, SessionMessageInfo } from "@opencode/client/promise" import { Permission } from "@opencode/schema/permission" import { artifactKind, artifactMime } from "@opencode/util/artifact" import { Model } from "@opencode/schema/model" @@ -151,7 +151,7 @@ export interface MockServerConfig { // Title of created sessions (default: the request's title, else "New session"). createdSessionTitle?: string // Slash commands served by `/api/command`. - commands?: Resolvable + commands?: unknown[] | ((directory: string) => unknown[]) // Records POST /api/session/:id/command (204). Without it, commands answer 501 MockUnsupported. onCommand?: (input: { sessionID: string; body: unknown }) => void fileList?: (path: string) => unknown[] | Promise @@ -168,6 +168,8 @@ export interface MockServerConfig { generate?: (input: { sessionID: string; prompt: string }) => { text: string } | Promise<{ text: string }> onInboxChange?: (input: { sessionID: string; inboxID: string; action: "cancel" | "steer" | "queue" }) => void onBackground?: (input: { sessionID: string }) => void + // Serves `/api/experimental/automation*`; defaults to an empty list. + automations?: AutomationInfo[] // Serves the session-scoped persistent PTY routes and their connect WebSockets (`e2e/utils/persistent-pty.ts`). // Without it, the server has a working daemon and no terminals; `capability: false` makes the routes answer 503. persistentPty?: MockPersistentPtyConfig @@ -924,10 +926,14 @@ function mockHandlers( ), credentialRemove: () => noContent, command: (ctx) => - Effect.sync(() => ({ - location: location(config, requestDirectory(config, ctx.request)), - data: resolve(config.commands ?? []), - })), + Effect.sync(() => { + const directory = requestDirectory(config, ctx.request) + + return { + location: location(config, directory), + data: Predicate.isFunction(config.commands) ? config.commands(directory) : config.commands ?? [], + } + }), skill: () => Effect.sync(() => ({ location: location(config), data: resolve(config.skills ?? []) })), plugin: () => Effect.sync(() => ({ location: location(config), data: resolve(config.plugins ?? []) })), mcp: (ctx) => @@ -972,6 +978,45 @@ function mockHandlers( Effect.sync(() => ({ location: location(config, requestDirectory(config, ctx.request)), data: {} })), // No scenario runs background jobs (Code Mode scripts or subagent work), so none is running. jobList: () => Effect.succeed({ data: [] }), + automationList: (ctx) => + Effect.sync(() => { + const list = config.automations ?? [] + const filtered = ctx.query.sessionID ? list.filter((item) => item.sessionID === ctx.query.sessionID) : list + + return { data: filtered } + }), + automationPause: (ctx) => + Effect.suspend(() => { + const list = config.automations ?? [] + const index = list.findIndex((item) => item.id === ctx.params.automationID) + + if (index === -1) return Effect.fail(new MockNotFound({ message: `Automation not found: ${ctx.params.automationID}` })) + const updated: AutomationInfo = { ...list[index]!, status: "paused", time: { ...list[index]!.time, updated: Date.now() } } + list[index] = updated + + return Effect.succeed({ data: updated }) + }), + automationResume: (ctx) => + Effect.suspend(() => { + const list = config.automations ?? [] + const index = list.findIndex((item) => item.id === ctx.params.automationID) + + if (index === -1) return Effect.fail(new MockNotFound({ message: `Automation not found: ${ctx.params.automationID}` })) + const updated: AutomationInfo = { ...list[index]!, status: "active", time: { ...list[index]!.time, updated: Date.now() } } + list[index] = updated + + return Effect.succeed({ data: updated }) + }), + automationDelete: (ctx) => + Effect.suspend(() => { + const list = config.automations ?? [] + const index = list.findIndex((item) => item.id === ctx.params.automationID) + + if (index === -1) return Effect.fail(new MockNotFound({ message: `Automation not found: ${ctx.params.automationID}` })) + list.splice(index, 1) + + return noContent + }), worktreeList: () => Effect.sync(() => { if (config.worktrees) return resolve(config.worktrees) diff --git a/packages/app/src/automations/format.ts b/packages/app/src/automations/format.ts new file mode 100644 index 00000000000..61df17efcd5 --- /dev/null +++ b/packages/app/src/automations/format.ts @@ -0,0 +1,110 @@ +import type { AutomationInfo } from "@opencode/client/promise" +import { Cron, Result } from "effect" +import type { useLanguage } from "@/runtime/i18n/language" + +type Language = ReturnType + +export function triggerLabel(row: AutomationInfo, language: Language) { + const trigger = row.trigger + + switch (trigger.type) { + case "at": + return language.t("automations.trigger.at", { date: wallClock(trigger.at, row, language) }) + case "every": + return language.t("automations.trigger.every", { interval: trigger.every.replace(/^1 /, "") }) + case "cron": + return describeCron(trigger.cron, language) ?? trigger.cron + case "event": + return language.t("automations.trigger.event", { event: trigger.event, server: trigger.server }) + } +} + +// Covers the shapes people ask for ("every weekday at 9"). Anything else keeps its cron text. +function describeCron(cron: string, language: Language) { + const parsed = Cron.parse(cron) + + if (Result.isFailure(parsed)) return + const minutes = [...parsed.success.minutes] + const hours = [...parsed.success.hours] + const weekdays = [...parsed.success.weekdays].toSorted((a, b) => a - b) + + if (parsed.success.days.size || parsed.success.months.size) return + + if (minutes.length === 1 && hours.length === 1) { + const time = new Intl.DateTimeFormat(language.intl(), { + hour: "numeric", + minute: "2-digit", + timeZone: "UTC", + }).format(Date.UTC(2000, 0, 1, hours[0], minutes[0])) + + if (!weekdays.length) return language.t("automations.trigger.daily", { time }) + + if (weekdays.join() === "1,2,3,4,5") return language.t("automations.trigger.weekdays", { time }) + + if (weekdays.join() === "0,6") return language.t("automations.trigger.weekends", { time }) + + const day = new Intl.DateTimeFormat(language.intl(), { weekday: "long", timeZone: "UTC" }) + // 2 January 2000 was a Sunday, cron's day 0. + const days = new Intl.ListFormat(language.intl()).format(weekdays.map((d) => day.format(Date.UTC(2000, 0, 2 + d)))) + + return language.t("automations.trigger.days", { days, time }) + } + + if (hours.length || weekdays.length) return + + if (minutes.length === 1) + return language.t("automations.trigger.hourly", { minute: String(minutes[0]).padStart(2, "0") }) + + const step = minutes[1]! - minutes[0]! + + if (minutes[0] === 0 && 60 % step === 0 && minutes.every((minute, index) => minute === index * step)) + return language.t("automations.trigger.minutes", { count: step }) +} + +function wallClock(at: string, row: AutomationInfo, language: Language) { + if (row.nextDueAt) return formatDate(row.nextDueAt, row.tz, language) + + // A wall-clock time without an offset is already in the automation's zone, so show it as written. + if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2})?$/.test(at)) return formatDate(Date.parse(`${at}Z`), "UTC", language) + + const instant = Date.parse(at) + + return Number.isNaN(instant) ? at : formatDate(instant, row.tz, language) +} + +export function formatDate(at: number, timeZone: string, language: Language) { + return new Date(at).toLocaleString(language.intl(), { dateStyle: "medium", timeStyle: "short", timeZone }) +} + +export function relativeTime(at: number, language: Language) { + const format = new Intl.RelativeTimeFormat(language.intl(), { numeric: "auto" }) + const seconds = (at - Date.now()) / 1000 + const minutes = seconds / 60 + const hours = minutes / 60 + + if (Math.abs(seconds) < 60) return format.format(0, "second") + + if (Math.abs(minutes) < 60) return format.format(Math.round(minutes), "minute") + + if (Math.abs(hours) < 24) return format.format(Math.round(hours), "hour") + + return format.format(Math.round(hours / 24), "day") +} + +export function statusLabel(row: AutomationInfo, t: Language["t"]) { + if (row.status === "paused" && row.lastOutcome === "failed") return t("automations.status.failed") + + if (row.status === "done" && row.lastOutcome === "expired") return t("automations.status.expired") + + return t(`automations.status.${row.status}`) +} + +const rank = { active: 0, paused: 1, done: 2 } + +export function compareAutomations(a: AutomationInfo, b: AutomationInfo) { + return ( + rank[a.status] - rank[b.status] || + (a.status === "active" ? (a.nextDueAt ?? Infinity) - (b.nextDueAt ?? Infinity) : 0) || + b.time.updated - a.time.updated + ) +} diff --git a/packages/app/src/automations/model.ts b/packages/app/src/automations/model.ts new file mode 100644 index 00000000000..de361329438 --- /dev/null +++ b/packages/app/src/automations/model.ts @@ -0,0 +1,172 @@ +import { displayName } from "@opencode/ui/project-avatar" +import { useMutation, useQueryClient } from "@tanstack/solid-query" +import { createEffect, createMemo, startTransition } from "solid-js" +import { createStore } from "solid-js/store" +import { useLanguage } from "@/runtime/i18n/language" +import { formatServerError } from "@/runtime/server/errors" +import { sessionLabel } from "@/session/title" +import { showToast } from "@/shell/notifications/toast" +import { useLayout } from "@/shell/state/layout" +import { useTabs } from "@/shell/tabs/tabs" +import type { AutomationInfo } from "@opencode/client/promise" +import { compareAutomations, triggerLabel } from "./format" +import { useAutomationSource, type AutomationEntry } from "./source" + +export function createAutomationsController() { + const source = useAutomationSource() + const tabs = useTabs() + const layout = useLayout() + const language = useLanguage() + const cache = useQueryClient() + + const [state, set] = createStore<{ query: string; key?: string; showDone: boolean }>({ + query: "", + showDone: false, + }) + + const entries = createMemo(() => + source + .entries() + .map((item) => { + const row = item.row + + // Sessions may move or be deleted. Neither the creator nor the recipient owns placement. + const project = item.ctx.projects + .list() + .find( + (project) => + project.id === row.projectID && (row.projectID !== "global" || project.worktree === row.directory), + ) + + const name = (id: string) => { + const session = item.ctx.data.session.get(id) + + return session ? sessionLabel(session) : id + } + + return { + ...item, + project, + projectName: project ? displayName(project) : row.projectID, + creator: row.sessionID && name(row.sessionID), + recipient: row.action.type === "prompt" && row.action.to.session ? name(row.action.to.session) : undefined, + trigger: triggerLabel(row, language), + } + }) + .toSorted((a, b) => compareAutomations(a.row, b.row)), + ) + + const filtered = createMemo(() => { + const needle = state.query.trim().toLowerCase() + + return entries().filter(({ row, trigger, projectName, creator, recipient, serverLabel }) => + [ + row.name, + row.id, + trigger, + projectName, + row.directory, + creator, + recipient, + serverLabel, + row.trigger.type === "event" && row.trigger.server, + row.action.type === "prompt" && row.action.prompt, + row.action.type === "code" && row.action.code, + row.action.type === "shell" && row.action.command, + ] + .join(" ") + .toLowerCase() + .includes(needle), + ) + }) + + const groups = createMemo(() => + statuses.flatMap((status) => { + const items = filtered().filter((item) => item.row.status === status) + + return items.length ? [{ status, items }] : [] + }), + ) + + const multiProject = createMemo(() => new Set(entries().map((item) => item.projectName)).size > 1) + + const selected = createMemo(() => filtered().find((item) => item.key === state.key) ?? filtered()[0]) + // Pin even the default selection: pausing it may reorder the list, but must not move its inspector. + createEffect(() => set("key", selected()?.key)) + createEffect(() => { + const entry = selected() + + if (entry) void entry.ctx.data.location.command.sync({ directory: entry.row.directory }).catch(() => undefined) + }) + + const draftTarget = createMemo(() => { + const entry = selected() + + if (entry) { + const directory = entry.row.directory + + if (entry.ctx.data.location.command.list({ directory })?.some((command) => command.name === "automation")) + return { server: entry.server, directory } + + return + } + + const preferred = layout.home.selection().server ?? tabs.lastTarget()?.server + const target = source.enabled().find((entry) => entry.server === preferred) ?? source.enabled()[0] + + if (target) return { server: target.server, directory: target.directories[0]! } + }) + + const change = useMutation(() => ({ + mutationFn: async (input: { entry: AutomationEntry; operation: "pause" | "resume" | "delete" }) => { + await input.entry.ctx.sdk.api.experimental.automation[input.operation]({ automationID: input.entry.row.id }) + }, + onSuccess: (_, { entry }) => + cache.invalidateQueries({ queryKey: [entry.ctx.sdk.scope, "automations"], exact: true }), + onError: (error) => { + showToast({ + variant: "error", + title: language.t("common.requestFailed"), + description: formatServerError(error, language.t), + }) + }, + })) + + return { + ...source, + entries, + filtered, + groups, + multiProject, + selected, + draftTarget, + language, + state, + toggleDone: () => set("showDone", (value) => !value), + setQuery: (query: string) => set("query", query), + select: (key: string) => set("key", key), + // Server and project names only tell rows apart when they differ. + context: (entry: { serverLabel: string; projectName: string }) => [ + ...(source.multiServer() ? [entry.serverLabel] : []), + ...(multiProject() ? [entry.projectName] : []), + ], + busy: () => change.isPending, + update: (entry: AutomationEntry, operation: "pause" | "resume" | "delete") => { + if (!change.isPending) change.mutate({ entry, operation }) + }, + openSession(entry: AutomationEntry, sessionId: string) { + const tab = tabs.addSessionTab({ server: entry.server, sessionId }) + tabs.rememberSessionRoute(tab, sessionId) + void startTransition(() => tabs.select(tab)) + }, + openNewAutomation(prompt = "/automation ") { + const target = draftTarget() + + if (target) void tabs.newDraft({ ...target, worktree: target.directory }, prompt) + }, + } +} + +const statuses: AutomationInfo["status"][] = ["active", "paused", "done"] + +export type AutomationItem = ReturnType["entries"]>[number] diff --git a/packages/app/src/automations/route.tsx b/packages/app/src/automations/route.tsx new file mode 100644 index 00000000000..abd691ace7c --- /dev/null +++ b/packages/app/src/automations/route.tsx @@ -0,0 +1,186 @@ +import { Button } from "@opencode/ui/button" +import { useDialog } from "@opencode/ui/context/dialog" +import { Dialog, DialogFooter, DialogHeader, DialogTitleGroup } from "@opencode/ui/dialog" +import { For, Show } from "solid-js" +import { AutomationInspector, AutomationListRow } from "./view" +import { CollapsedSidebarToggleSpace } from "@/shell/sidebar-toggle" +import { type AutomationItem, createAutomationsController } from "./model" + +export function AutomationsScreen() { + const controller = createAutomationsController() + const dialog = useDialog() + const language = controller.language + + function confirmDelete(entry: AutomationItem) { + const name = entry.row.name + void dialog.show(() => ( + + + + + + + + + + )) + } + + return ( +
+
+ +

+ {language.t("automations.title")} +

+ +
+ controller.setQuery(event.currentTarget.value)} + placeholder={language.t("automations.search")} + aria-label={language.t("automations.search")} + class="hidden h-7 w-44 rounded-[6px] bg-v2-background-bg-layer-01 px-2.5 text-[12px] leading-4 text-v2-text-text-base placeholder:text-v2-text-text-faint focus:outline-none focus-visible:ring-1 focus-visible:ring-v2-border-border-strong md:block lg:w-56" + /> + + + + +
+
+ + 0} + fallback={ +
+

+ {language.t( + !controller.available() + ? "automations.off" + : controller.failed() + ? "automations.failed" + : controller.loading() + ? "automations.loading" + : "automations.empty.title", + )} +

+ +

{language.t("automations.empty.description")}

+ +
+
+ } + > +
+
+
+ 0} + fallback={ +
+ {language.t("automations.empty.filtered")} +
+ } + > + + {(group) => { + const done = () => group.status === "done" + const open = () => !done() || controller.state.showDone || !!controller.state.query.trim() + + return ( +
+ + {language.t(`automations.status.${group.status}`)} + {group.items.length} + + } + > + + + + + {(entry) => ( + controller.select(entry.key)} + /> + )} + + +
+ ) + }} +
+
+
+
+ +
+ + {(entry) => ( + controller.update(entry(), entry().row.status === "paused" ? "resume" : "pause")} + onOpenSession={(id) => controller.openSession(entry(), id)} + onDelete={() => confirmDelete(entry())} + /> + )} + +
+
+
+
+ ) +} diff --git a/packages/app/src/automations/source.ts b/packages/app/src/automations/source.ts new file mode 100644 index 00000000000..8ad0e66fa17 --- /dev/null +++ b/packages/app/src/automations/source.ts @@ -0,0 +1,139 @@ +import type { AutomationInfo } from "@opencode/client/promise" +import { createSimpleContext } from "@opencode/ui/context" +import { useQueries } from "@tanstack/solid-query" +import { createEffect, createMemo } from "solid-js" +import { ServerConnection, useServers } from "@/runtime/server/registry" +import { useGlobal } from "@/runtime/server/runtime" +import { useSettings } from "@/settings/model" +import { useLayout } from "@/shell/state/layout" +import { useTabs } from "@/shell/tabs/tabs" + +export const { use: useAutomationSource, provider: AutomationSourceProvider } = createSimpleContext({ + name: "AutomationSource", + init: () => { + const global = useGlobal() + const servers = useServers() + const layout = useLayout() + const tabs = useTabs() + const settings = useSettings() + + // With the setting off, nothing is synced or polled, so every entry point stays hidden. + const connections = createMemo(() => + (settings.general.automations() ? servers.visible : []).flatMap((conn) => { + const server = ServerConnection.key(conn) + const ctx = global.serverCtx(server) + + if (!ctx || ctx.sdk.connection.status() !== "connected") return [] + const selected = layout.home.selection() + const last = tabs.lastTarget() + const route = layout.route() + const open = route.type === "automations" + + const draft = + route.type === "draft" + ? tabs.store.find((tab) => tab.type === "draft" && tab.draftID === route.draftID) + : undefined + + const active = + route.type === "session" && route.server === server + ? ctx.data.session.get(route.sessionId)?.location.directory + : draft?.type === "draft" && draft.server === server + ? draft.directory + : undefined + + const directories = [ + ...new Set( + [ + active, + selected.server === server ? selected.directory : undefined, + last?.server === server ? last.directory : undefined, + // Each folder asked about is a location the server sets up. Outside the view, ask only + // about the ones already open; the view itself also checks every tab and used project. + ...(open + ? [ + ...tabs.store.flatMap((tab) => + tab.server !== server + ? [] + : tab.type === "draft" + ? [tab.directory] + : [ctx.data.session.get(tab.routeSessionId ?? tab.sessionId)?.location.directory], + ), + ...ctx.projects.used().map((p) => p.worktree), + ] + : []), + ].filter((directory): directory is string => !!directory), + ), + ] + + if (!directories.length && ctx.sync.data.path.home) directories.push(ctx.sync.data.path.home) + + return [{ server, ctx, directories, serverLabel: servers.label(conn) }] + }), + ) + + // The server registers /automation only where the effective flag is on, so it decides where + // New automation can open a draft. The shared catalog also handles command.updated after config changes. + createEffect(() => { + for (const { ctx, directories } of connections()) { + for (const directory of directories) void ctx.data.location.command.sync({ directory }).catch(() => undefined) + } + }) + + const enabled = createMemo(() => + connections().flatMap((item) => { + const directories = item.directories.filter((directory) => + item.ctx.data.location.command.list({ directory })?.some((command) => command.name === "automation"), + ) + + return directories.length ? [{ ...item, directories }] : [] + }), + ) + + // Automations are global per server; the server only drops rows whose folder turned them off. + // Fetch it once per server, not once per project, and never use an empty list as a capability + // signal: an empty server keeps polling only while an open folder offers /automation. + const queries = useQueries(() => ({ + queries: connections().map((item) => { + const open = layout.route().type === "automations" + const offered = enabled().some((target) => target.server === item.server) + const interval = open ? 5_000 : 30_000 + + return { + queryKey: [item.ctx.sdk.scope, "automations"] as const, + queryFn: ({ signal }: { signal: AbortSignal }) => + item.ctx.sdk.api.experimental.automation.list(undefined, { signal }), + select: (rows: AutomationInfo[]) => () => rows, + retry: false, + refetchInterval: (query: { state: { data?: AutomationInfo[] } }) => + query.state.data?.length || offered ? interval : false, + } + }), + })) + + const entries = createMemo(() => + connections().flatMap((item, index) => { + const query = queries[index] + + if (!query?.isSuccess) return [] + + return (query.data?.() ?? []).map((row) => ({ ...item, row, key: `${item.server}\0${row.id}` })) + }), + ) + + return { + enabled, + entries, + // Only the experimental setting hides the view; an empty server just shows no automations. + available: () => settings.general.automations(), + multiServer: () => connections().length > 1, + loading: () => queries.some((query) => query.isPending), + failed: () => + queries.some( + (query, index) => query.isError && enabled().some((target) => target.server === connections()[index]?.server), + ), + active: createMemo(() => entries().filter((entry) => entry.row.status === "active").length), + } + }, +}) + +export type AutomationEntry = ReturnType["entries"]>[number] diff --git a/packages/app/src/automations/view.tsx b/packages/app/src/automations/view.tsx new file mode 100644 index 00000000000..a1c44e31a78 --- /dev/null +++ b/packages/app/src/automations/view.tsx @@ -0,0 +1,258 @@ +import { Button } from "@opencode/ui/button" +import { Predicate } from "effect" +import { createMemo, For, Show, type JSX } from "solid-js" +import { useLanguage } from "@/runtime/i18n/language" +import { formatDate, relativeTime, statusLabel } from "./format" +import type { AutomationItem } from "./model" + +export function AutomationListRow(props: { + entry: AutomationItem + selected: boolean + context: string[] + onSelect: () => void +}) { + const language = useLanguage() + const row = () => props.entry.row + + const note = () => { + if (row().status === "paused" && row().lastOutcome === "failed") return language.t("automations.note.failed") + + if (row().status === "done" && row().lastOutcome === "expired") return language.t("automations.status.expired") + + const next = row().status === "active" ? row().nextDueAt : undefined + + if (next) return relativeTime(next, language) + } + + return ( + + ) +} + +export function AutomationInspector(props: { + entry: AutomationItem + busy: boolean + context: string[] + onTogglePause: () => void + onOpenSession: (id: string) => void + onDelete: () => void +}) { + const language = useLanguage() + const t = language.t + const row = () => props.entry.row + + const event = createMemo(() => { + const trigger = row().trigger + + return trigger.type === "event" ? trigger : undefined + }) + + // Flat filters read as `environment = "staging"`; anything nested keeps its JSON. + const args = createMemo(() => { + const value = event()?.args + + if (!value) return + + const entries = Object.entries(value) + + if (entries.some(([, item]) => Predicate.isObject(item))) return { block: JSON.stringify(value, null, 2) } + + return { inline: entries.map(([key, item]) => `${key} = ${JSON.stringify(item)}`).join(", ") } + }) + + const next = () => (row().status === "active" ? row().nextDueAt : undefined) + + // Takes accessors: `Show` keeps its children when the selection moves to another automation. + const link = (id: () => string, name: () => string) => ( + + ) + + const action = () => { + const value = row().action + + switch (value.type) { + case "prompt": { + const session = value.to.session + + return { + summary: session + ? language.rich("automations.do.prompt", { + session: link( + () => session, + () => props.entry.recipient ?? session, + ), + }) + : t("automations.do.subagent", { agent: value.to.subagent ?? "" }), + body: value.prompt, + } + } + + case "code": + return { + summary: t("automations.do.code"), + hint: t("automations.do.codeHint"), + body: value.code, + code: true, + args: value.args === undefined ? undefined : JSON.stringify(value.args, null, 2), + } + case "shell": + return { + summary: t("automations.do.shell"), + hint: t("automations.do.shellHint"), + body: value.command, + code: true, + } + } + } + + const time = (at: () => number) => ( + + ) + + return ( +
+
+
+

+ {row().name} +

+

+ +

+
+
+ + + + +
+
+ +
+ +
+ {props.entry.trigger} +
+ +
+ {row().tz} + {(at) => <> · {language.rich("automations.nextRun", { time: time(at) })}} +
+
+ + {(text) => ( + + {text()} + + )} + + {(text) => {text()}} +
+ + +
{action().summary}
+ {(hint) =>
{hint()}
}
+ {action().body} + {(text) => {text()}} +
+ + +
+ + {(at) => ( + <> + {time(at)} + + {" "} + · {language.plural("automations.runCount", row().runCount)} + + + )} + +
+ {(output) => {output()}} +
+
+ +
+ + + {row().directory} + + + + {(id) => ( + + {link(id, () => props.entry.creator ?? id())} + + )} + + + {props.entry.serverLabel} + +
+
+ ) +} + +function Parts(props: { items: string[] }) { + return ( + + {(item, index) => ( + <> + 0}> · + {item} + + )} + + ) +} + +function Row(props: { label: string; muted?: boolean; children: JSX.Element }) { + return ( + <> +
{props.label}
+
+ {props.children} +
+ + ) +} + +function Content(props: { code?: boolean; children: JSX.Element }) { + return ( +
+ {props.children} +
+ ) +} diff --git a/packages/app/src/home/projects/view.tsx b/packages/app/src/home/projects/view.tsx index 87f7fbe6865..ba6323d3a80 100644 --- a/packages/app/src/home/projects/view.tsx +++ b/packages/app/src/home/projects/view.tsx @@ -1,4 +1,6 @@ import { createMemo, For, type JSX, onCleanup, Show, splitProps } from "solid-js" +import { useAutomationSource } from "@/automations/source" +import { useNavigate } from "@solidjs/router" import { createStore } from "solid-js/store" import { createResizeObserver } from "@solid-primitives/resize-observer" import { Popover } from "@kobalte/core/popover" @@ -393,11 +395,25 @@ export function HomeUtilityNav(props: { onOpenHelp: () => void language: ReturnType }) { + const navigate = useNavigate() + const automations = useAutomationSource() + return (
button]:w-auto lg:[&>button]:w-full`} classList={props.classList} > + + navigate("/automations")} + > + + {props.language.t("automations.title")} + + { test.each([ + { + name: "the explicitly requested draft directory without a workspace bar", + input: { enabled: false, selected: "/project/docs", directory: "/project/docs", fallback: "create" }, + expected: "/project/docs", + }, { name: "main when the workspace bar is unavailable", input: { enabled: false, selected: "/project/feature" }, diff --git a/packages/app/src/new-session/workspace/controller.ts b/packages/app/src/new-session/workspace/controller.ts index 5f1438db972..b920419cb19 100644 --- a/packages/app/src/new-session/workspace/controller.ts +++ b/packages/app/src/new-session/workspace/controller.ts @@ -16,7 +16,16 @@ import { workspaceSelectionDirectories, } from "@/workspaces/paths" -export function resolveNewSessionWorktree(input: { enabled: boolean; selected?: string; fallback?: string }) { +export function resolveNewSessionWorktree(input: { + enabled: boolean + selected?: string + directory?: string + fallback?: string +}) { + // An explicitly placed draft (for example from an automation) can start in a subdirectory, + // including a non-Git folder. Its initial destination is not the user's default worktree. + if (input.selected && input.directory && sameDirectory(input.selected, input.directory)) return input.directory + if (!input.enabled) return "main" if (input.selected) return input.selected @@ -140,7 +149,11 @@ export function createNewSessionWorkspaceController(input: { const project = currentProject() const worktree = input.selectedWorktree() - if (!project || !worktree) return + if (!worktree) return + + if (sameDirectory(worktree, sdk().directory)) return worktree + + if (!project) return if (isWorkspaceSelection(project, worktree)) return worktree @@ -165,6 +178,7 @@ export function createNewSessionWorkspaceController(input: { const value = createMemo(() => resolveNewSessionWorktree({ enabled: visible(), + directory: sdk().directory, selected: selected(), fallback: fallback(), }), diff --git a/packages/app/src/runtime/i18n/en.ts b/packages/app/src/runtime/i18n/en.ts index c48dc5d0c8a..86d8dfb8985 100644 --- a/packages/app/src/runtime/i18n/en.ts +++ b/packages/app/src/runtime/i18n/en.ts @@ -2,6 +2,54 @@ import { DESKTOP_NATIVE_ENGLISH } from "./desktop-native" export const dict = { "experiment.voiceCalls": "Voice calls", + "automations.title": "Automations", + "automations.new": "New automation", + "automations.search": "Search", + "automations.status.active": "Active", + "automations.status.paused": "Paused", + "automations.status.done": "Completed", + "automations.status.expired": "Timed out", + "automations.status.failed": "Paused after a failure", + "automations.note.failed": "Failed", + "automations.group.show": "Show", + "automations.group.hide": "Hide", + "automations.action.pause": "Pause", + "automations.action.resume": "Resume", + "automations.trigger.at": "Once, {{date}}", + "automations.trigger.every": "Every {{interval}}", + "automations.trigger.daily": "Every day at {{time}}", + "automations.trigger.weekdays": "Weekdays at {{time}}", + "automations.trigger.weekends": "Weekends at {{time}}", + "automations.trigger.days": "{{days}} at {{time}}", + "automations.trigger.hourly": "Every hour at :{{minute}}", + "automations.trigger.minutes": "Every {{count}} minutes", + "automations.trigger.event": "{{event}} from {{server}}", + "automations.when": "When", + "automations.do": "Do", + "automations.do.prompt": "Send a prompt to {{session}}", + "automations.do.subagent": "Send a prompt to a new {{agent}} subagent", + "automations.do.code": "Run Code Mode", + "automations.do.codeHint": "Wakes the creating session only when the code returns send.", + "automations.do.shell": "Run a shell command", + "automations.do.shellHint": "Doesn’t wake a session.", + "automations.nextRun": "next run {{time}}", + "automations.lastRun": "Last run", + "automations.neverRun": "Not yet", + "automations.runCount.one": "{{count}} run", + "automations.runCount.other": "{{count}} runs", + "automations.folder": "Folder", + "automations.creator": "Created by", + "automations.runsOn": "Runs on", + "automations.empty.title": "No automations yet", + "automations.empty.description": "Describe a trigger and what should happen in a new session.", + "automations.example": "Summarize open pull requests every weekday at 9 AM", + "automations.off": "Turn on Automations in Settings → Experimental.", + "automations.loading": "Loading automations…", + "automations.failed": "Couldn’t load automations.", + "automations.empty.filtered": "No automations match your search.", + "automations.delete.title": "Delete automation", + "automations.delete.confirm": "Delete “{{name}}”? It will not fire again.", + "automations.delete.button": "Delete", "voice.call": "Call", "voice.mute": "Mute", "voice.unmute": "Unmute", @@ -909,6 +957,8 @@ export const dict = { "A redesigned session timeline that groups what the agent did, with one status line below the turn", "settings.experimental.row.newQuestionUI.title": "New question UI", "settings.experimental.row.newQuestionUI.description": "Preview the keyboard-first question dock", + "settings.experimental.row.automations.title": "Automations", + "settings.experimental.row.automations.description": "Show the automations each server runs, and pause, resume or delete them", "settings.experimental.row.tabGroups.title": "Tab groups", "settings.experimental.row.tabGroups.description": "Group session tabs in side tabs with inline session search", "settings.experimental.row.sidebarOrganize.title": "Organize vertical sidebar", diff --git a/packages/app/src/settings/experimental/experimental.tsx b/packages/app/src/settings/experimental/experimental.tsx index bb15108eb9e..d89f632a69c 100644 --- a/packages/app/src/settings/experimental/experimental.tsx +++ b/packages/app/src/settings/experimental/experimental.tsx @@ -71,6 +71,20 @@ export const SettingsExperimental: Component = () => {
+ +
+ settings.general.setAutomations(checked)} + hideLabel + > + {language.t("settings.experimental.row.automations.title")} + +
+
store.general?.automations, + import.meta.env.DEV && import.meta.env.VITE_OPENCODE_TEST_FIXTURES !== "1", + ), + setAutomations(value: boolean) { + setStore("general", "automations", value) + }, sharedSidePanel: withFallback(() => store.general?.sharedSidePanel, false), setSharedSidePanel(value: boolean) { setStore("general", "sharedSidePanel", value) diff --git a/packages/app/src/settings/search-catalog.ts b/packages/app/src/settings/search-catalog.ts index 6a101c52d8e..5dd1f44ebe2 100644 --- a/packages/app/src/settings/search-catalog.ts +++ b/packages/app/src/settings/search-catalog.ts @@ -146,6 +146,13 @@ export const clientSettings: Entry[] = [ description: "settings.experimental.row.newTimeline.description", keywords: "new timeline redesign activity explored edited ran grouping status", }, + { + tab: "experimental", + label: "settings.experimental.row.automations.title", + target: "settings-automations", + description: "settings.experimental.row.automations.description", + keywords: "automations schedules timers cron watches events", + }, { tab: "experimental", label: "settings.experimental.row.newQuestionUI.title", diff --git a/packages/app/src/shell/routes/routes.tsx b/packages/app/src/shell/routes/routes.tsx index 4cc7f0ba060..bf0f3fb1e2f 100644 --- a/packages/app/src/shell/routes/routes.tsx +++ b/packages/app/src/shell/routes/routes.tsx @@ -1,5 +1,6 @@ import { Route, useParams } from "@solidjs/router" import { createMemo, lazy, Show, Suspense, type ParentProps } from "solid-js" +import { AutomationSourceProvider } from "@/automations/source" import { Home } from "@/home/route" import { ServerProvider } from "@/runtime/server/current" import { useGlobal } from "@/runtime/server/runtime" @@ -23,6 +24,10 @@ const DraftRoute = lazy(() => import("@/new-session/route").then((module) => ({ const SettingsScreen = lazy(() => import("@/settings/shell").then((module) => ({ default: module.SettingsScreen }))) +const AutomationsScreen = lazy(() => + import("@/automations/route").then((module) => ({ default: module.AutomationsScreen })), +) + const ConnectServerScreen = lazy(() => import("@/servers/connect/screen").then((module) => ({ default: module.ConnectServerScreen })), ) @@ -45,6 +50,8 @@ export function preloadRoute(url: string) { if (pathname === "/settings") return SettingsScreen.preload().then(() => undefined) + if (pathname === "/automations") return AutomationsScreen.preload().then(() => undefined) + if (/^\/server\/[^/]+\/session\/[^/]+$/.test(pathname)) return TargetSessionRouteContent.preload().then(() => undefined) @@ -55,6 +62,7 @@ export function AppRoutes() { return ( + - {props.children} + + {props.children} + diff --git a/packages/app/src/shell/state/layout.test.ts b/packages/app/src/shell/state/layout.test.ts index 96a67c03a5e..1978736720b 100644 --- a/packages/app/src/shell/state/layout.test.ts +++ b/packages/app/src/shell/state/layout.test.ts @@ -7,7 +7,7 @@ import { createSignal } from "solid-js" import { createSessionKeyReader, ensureSessionKey, pruneSessionKeys, sessionKeyOpen } from "./helpers" import { ServerScope, SessionRouteKey, SessionStateKey } from "@/runtime/server/scope" -test.each(["settings", "connect"] as const)("%s has its own layout route", (type) => { +test.each(["automations", "settings", "connect"] as const)("%s has its own layout route", (type) => { expect(currentRoute(`/${type}`, "")).toEqual({ type }) }) diff --git a/packages/app/src/shell/state/layout.tsx b/packages/app/src/shell/state/layout.tsx index cbfc8f82f75..243b859027a 100644 --- a/packages/app/src/shell/state/layout.tsx +++ b/packages/app/src/shell/state/layout.tsx @@ -72,6 +72,7 @@ export type TabRegions = { export type LayoutRoute = | { type: "home" } + | { type: "automations" } | { type: "settings" } | { type: "connect" } | { type: "components" } @@ -83,6 +84,8 @@ export const currentRoute = (pathname: string, search: string): LayoutRoute => { if (parts.length === 0) return { type: "home" } + if (parts[0] === "automations") return { type: "automations" } + if (parts[0] === "settings") return { type: "settings" } if (parts[0] === "connect") return { type: "connect" } diff --git a/packages/app/src/shell/tabs/tabs.tsx b/packages/app/src/shell/tabs/tabs.tsx index 888ea008b63..aa2be8c8ed8 100644 --- a/packages/app/src/shell/tabs/tabs.tsx +++ b/packages/app/src/shell/tabs/tabs.tsx @@ -869,6 +869,27 @@ export const { use: useTabs, provider: TabsProvider } = createSimpleContext({ navigate("/") }, + toggleAutomations(input: { automations: boolean; current?: Tab }) { + if (input.automations) { + const tab = store.find((tab) => tabKey(tab) === recentKey()) + + if (tab) { + navigateTab(tab) + + return + } + + navigate("/") + + return + } + + if (input.current) { + setRecentKey(tabKey(input.current)) + } + + navigate("/automations") + }, state(tab: Tab, name: string, init: () => T) { return memory.ensure(tabKey(tab), name, init) }, diff --git a/packages/app/src/shell/titlebar/titlebar.tsx b/packages/app/src/shell/titlebar/titlebar.tsx index b441d3b6259..343942b826f 100644 --- a/packages/app/src/shell/titlebar/titlebar.tsx +++ b/packages/app/src/shell/titlebar/titlebar.tsx @@ -25,6 +25,7 @@ import { SidebarInbox } from "@/shell/titlebar/inbox" import { SidebarCustomized, type SidebarStripGrouping } from "@/shell/titlebar/sidebar-customized" import { RecentSessions } from "@/shell/titlebar/recent-sessions" import { createNavigationSwitch } from "@/shell/tabs/navigation-switch" +import { useAutomationSource } from "@/automations/source" import { makeEventListener } from "@solid-primitives/event-listener" import { createMediaQuery } from "@solid-primitives/media" import { readSessionTabsRemovedDetail, SESSION_TABS_REMOVED_EVENT } from "@/shell/titlebar/session-events" @@ -87,6 +88,7 @@ function SidebarAction(props: { icon: string label: string keybind: string[] + count?: number pressed?: boolean current?: boolean onClick: () => void @@ -105,6 +107,9 @@ function SidebarAction(props: { > {props.label} + + {props.count} + @@ -339,6 +344,7 @@ export function Titlebar(props: { verticalTabs?: { mount?: HTMLElement } }) { return true } + case "automations": case "settings": case "connect": case "components": @@ -405,6 +411,11 @@ export function Titlebar(props: { verticalTabs?: { mount?: HTMLElement } }) { const homeLabel = () => language.t(settings.appearance.navigationPrototype() ? "sidebar.sessions" : "home.title") + const automations = useAutomationSource() + + const toggleAutomations = () => + tabs.toggleAutomations({ automations: layout.route().type === "automations", current: currentTab() }) + const homeButton = (vertical = false) => ( ) + const automationsButton = (vertical = false) => ( + + + } + state={layout.route().type === "automations" ? "pressed" : undefined} + onClick={toggleAutomations} + aria-label={language.t("automations.title")} + aria-pressed={layout.route().type === "automations"} + /> + + } + > + + + + ) + command.register("titlebar-home", () => [ { id: "home.toggle", @@ -519,6 +563,16 @@ export function Titlebar(props: { verticalTabs?: { mount?: HTMLElement } }) { toggleHome() }, }, + ...(automations.available() + ? [ + { + id: "automations.open", + title: language.t("automations.title"), + category: language.t("command.category.view"), + onSelect: toggleAutomations, + }, + ] + : []), { id: "sessions.search", title: language.t("command.session.search"), @@ -777,6 +831,7 @@ export function Titlebar(props: { verticalTabs?: { mount?: HTMLElement } }) {
{homeButton()} {searchButton()} + {automationsButton()}
@@ -998,6 +1053,7 @@ export function Titlebar(props: { verticalTabs?: { mount?: HTMLElement } }) { fallback={ <> {searchButton(true)} + {automationsButton(true)} {settingsButton()} @@ -1005,6 +1061,7 @@ export function Titlebar(props: { verticalTabs?: { mount?: HTMLElement } }) { } > {homeButton(true)} + {automationsButton(true)} {settingsButton()} diff --git a/packages/plugin/src/gui/icon-name.ts b/packages/plugin/src/gui/icon-name.ts index 7f25f85ec82..1e67cb1cb27 100644 --- a/packages/plugin/src/gui/icon-name.ts +++ b/packages/plugin/src/gui/icon-name.ts @@ -29,6 +29,7 @@ export type AppIconName = | "circle-exclamation" | "circle-x" | "circle-xmark" + | "clock" | "close" | "close-small" | "cloud-upload" diff --git a/packages/ui/src/icons/catalog.ts b/packages/ui/src/icons/catalog.ts index 3ba3f02ef6a..de837d7d369 100644 --- a/packages/ui/src/icons/catalog.ts +++ b/packages/ui/src/icons/catalog.ts @@ -382,6 +382,10 @@ const icons = { viewBox: "0 0 16 16", body: ``, }, + clock: { + viewBox: "0 0 16 16", + body: ``, + }, globe: { viewBox: "0 0 16 16", body: ``,