mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-26 23:28:43 +00:00
feat(app): show where automations run and which session they wake (#66393)
Some checks are pending
check-nix / nix-eval (push) Waiting to run
check / typecheck (push) Waiting to run
deploy-files / files-build (push) Waiting to run
deploy-files / files-deploy (push) Blocked by required conditions
deploy-site / site-build (push) Waiting to run
deploy-site / site-deploy (push) Blocked by required conditions
deploy / legacy-build (push) Waiting to run
deploy / legacy-deploy (push) Blocked by required conditions
deploy / data-build (push) Waiting to run
deploy / data-deploy (push) Blocked by required conditions
Some checks are pending
check-nix / nix-eval (push) Waiting to run
check / typecheck (push) Waiting to run
deploy-files / files-build (push) Waiting to run
deploy-files / files-deploy (push) Blocked by required conditions
deploy-site / site-build (push) Waiting to run
deploy-site / site-deploy (push) Blocked by required conditions
deploy / legacy-build (push) Waiting to run
deploy / legacy-deploy (push) Blocked by required conditions
deploy / data-build (push) Waiting to run
deploy / data-deploy (push) Blocked by required conditions
This commit is contained in:
parent
c39ad3b75c
commit
782125f72a
22 changed files with 1431 additions and 10 deletions
273
packages/app/e2e/regression/automations.spec.ts
Normal file
273
packages/app/e2e/regression/automations.spec.ts
Normal file
|
|
@ -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" } },
|
||||
])
|
||||
})
|
||||
|
|
@ -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 }),
|
||||
|
|
|
|||
|
|
@ -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<unknown[]>
|
||||
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<unknown[]>
|
||||
|
|
@ -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)
|
||||
|
|
|
|||
110
packages/app/src/automations/format.ts
Normal file
110
packages/app/src/automations/format.ts
Normal file
|
|
@ -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<typeof useLanguage>
|
||||
|
||||
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
|
||||
)
|
||||
}
|
||||
172
packages/app/src/automations/model.ts
Normal file
172
packages/app/src/automations/model.ts
Normal file
|
|
@ -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<ReturnType<typeof createAutomationsController>["entries"]>[number]
|
||||
186
packages/app/src/automations/route.tsx
Normal file
186
packages/app/src/automations/route.tsx
Normal file
|
|
@ -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(() => (
|
||||
<Dialog fit>
|
||||
<DialogHeader hideClose>
|
||||
<DialogTitleGroup
|
||||
title={language.t("automations.delete.title")}
|
||||
description={language.t("automations.delete.confirm", { name })}
|
||||
/>
|
||||
</DialogHeader>
|
||||
<DialogFooter>
|
||||
<Button variant="ghost" autofocus onClick={() => dialog.close()}>
|
||||
{language.t("common.cancel")}
|
||||
</Button>
|
||||
<Button
|
||||
variant="danger"
|
||||
onClick={() => {
|
||||
void controller.update(entry, "delete")
|
||||
dialog.close()
|
||||
}}
|
||||
>
|
||||
{language.t("automations.delete.button")}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</Dialog>
|
||||
))
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
data-slot="automations-panel"
|
||||
class="mx-[var(--shell-inline-inset,8px)] mb-[var(--shell-bottom-inset,8px)] mt-[var(--shell-top-inset,8px)] flex min-h-0 flex-1 flex-col self-stretch overflow-hidden rounded-[10px] bg-v2-background-bg-base shadow-[var(--v2-elevation-raised)]"
|
||||
>
|
||||
<div
|
||||
data-slot="automations-header"
|
||||
data-tauri-drag-region
|
||||
class="flex h-12 shrink-0 items-center gap-2 border-b border-v2-border-border-base px-2.5"
|
||||
>
|
||||
<CollapsedSidebarToggleSpace />
|
||||
<h1 class="truncate text-[14px] leading-5 font-medium text-v2-text-text-base">
|
||||
{language.t("automations.title")}
|
||||
</h1>
|
||||
|
||||
<div class="ms-auto flex items-center gap-2">
|
||||
<input
|
||||
type="search"
|
||||
value={controller.state.query}
|
||||
onInput={(event) => 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"
|
||||
/>
|
||||
|
||||
<Show when={controller.draftTarget()}>
|
||||
<Button
|
||||
type="button"
|
||||
variant="contrast"
|
||||
size="small"
|
||||
data-action="automations-new"
|
||||
onClick={() => controller.openNewAutomation()}
|
||||
>
|
||||
{language.t("automations.new")}
|
||||
</Button>
|
||||
</Show>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Show
|
||||
when={controller.entries().length > 0}
|
||||
fallback={
|
||||
<div class="mx-auto flex max-w-[480px] flex-1 flex-col items-center justify-center gap-3 px-6 text-center">
|
||||
<h2 class="text-14-medium text-v2-text-text-base">
|
||||
{language.t(
|
||||
!controller.available()
|
||||
? "automations.off"
|
||||
: controller.failed()
|
||||
? "automations.failed"
|
||||
: controller.loading()
|
||||
? "automations.loading"
|
||||
: "automations.empty.title",
|
||||
)}
|
||||
</h2>
|
||||
<Show when={controller.draftTarget() && !controller.loading() && !controller.failed()}>
|
||||
<p class="text-13-regular text-v2-text-text-muted">{language.t("automations.empty.description")}</p>
|
||||
<Button
|
||||
size="small"
|
||||
onClick={() => controller.openNewAutomation(`/automation ${language.t("automations.example")}`)}
|
||||
>
|
||||
{language.t("automations.example")}
|
||||
</Button>
|
||||
</Show>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div class="grid min-h-0 flex-1 grid-cols-1 divide-y divide-v2-border-border-base lg:grid-cols-[minmax(300px,360px)_minmax(0,1fr)] lg:divide-x lg:divide-y-0 rtl:divide-x-reverse">
|
||||
<div data-scrollable class="min-h-0 overflow-y-auto">
|
||||
<div class="flex flex-col gap-0.5 p-2">
|
||||
<Show
|
||||
when={controller.filtered().length > 0}
|
||||
fallback={
|
||||
<div class="px-3 py-8 text-center text-[13px] leading-5 text-v2-text-text-faint">
|
||||
{language.t("automations.empty.filtered")}
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<For each={controller.groups()}>
|
||||
{(group) => {
|
||||
const done = () => group.status === "done"
|
||||
const open = () => !done() || controller.state.showDone || !!controller.state.query.trim()
|
||||
|
||||
return (
|
||||
<section class="flex flex-col gap-0.5 pb-3 last:pb-0">
|
||||
<Show
|
||||
when={done()}
|
||||
fallback={
|
||||
<h2 class="flex h-7 items-center gap-1.5 px-2.5 text-[12px] leading-4 text-v2-text-text-faint">
|
||||
{language.t(`automations.status.${group.status}`)}
|
||||
<span class="tabular-nums">{group.items.length}</span>
|
||||
</h2>
|
||||
}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
aria-expanded={open()}
|
||||
onClick={controller.toggleDone}
|
||||
class="flex h-7 items-center gap-1.5 rounded-[6px] px-2.5 text-start text-[12px] leading-4 text-v2-text-text-faint hover:text-v2-text-text-muted"
|
||||
>
|
||||
{language.t("automations.status.done")}
|
||||
<span class="tabular-nums">{group.items.length}</span>
|
||||
<span class="ms-auto">
|
||||
{language.t(open() ? "automations.group.hide" : "automations.group.show")}
|
||||
</span>
|
||||
</button>
|
||||
</Show>
|
||||
<Show when={open()}>
|
||||
<For each={group.items}>
|
||||
{(entry) => (
|
||||
<AutomationListRow
|
||||
entry={entry}
|
||||
selected={controller.selected()?.key === entry.key}
|
||||
context={controller.context(entry)}
|
||||
onSelect={() => controller.select(entry.key)}
|
||||
/>
|
||||
)}
|
||||
</For>
|
||||
</Show>
|
||||
</section>
|
||||
)
|
||||
}}
|
||||
</For>
|
||||
</Show>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div data-scrollable class="min-h-0 overflow-y-auto">
|
||||
<Show when={controller.selected()}>
|
||||
{(entry) => (
|
||||
<AutomationInspector
|
||||
entry={entry()}
|
||||
busy={controller.busy()}
|
||||
context={controller.context(entry())}
|
||||
onTogglePause={() => controller.update(entry(), entry().row.status === "paused" ? "resume" : "pause")}
|
||||
onOpenSession={(id) => controller.openSession(entry(), id)}
|
||||
onDelete={() => confirmDelete(entry())}
|
||||
/>
|
||||
)}
|
||||
</Show>
|
||||
</div>
|
||||
</div>
|
||||
</Show>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
139
packages/app/src/automations/source.ts
Normal file
139
packages/app/src/automations/source.ts
Normal file
|
|
@ -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<ReturnType<typeof useAutomationSource>["entries"]>[number]
|
||||
258
packages/app/src/automations/view.tsx
Normal file
258
packages/app/src/automations/view.tsx
Normal file
|
|
@ -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 (
|
||||
<button
|
||||
type="button"
|
||||
aria-pressed={props.selected}
|
||||
onClick={props.onSelect}
|
||||
class="flex w-full flex-col gap-0.5 rounded-[7px] px-2.5 py-2 text-start hover:bg-v2-overlay-simple-overlay-hover aria-pressed:bg-v2-background-bg-layer-02"
|
||||
>
|
||||
<span class="flex w-full min-w-0 items-baseline gap-3">
|
||||
<bdi class="min-w-0 flex-1 truncate text-[13px] leading-5 font-medium text-v2-text-text-base">{row().name}</bdi>
|
||||
<Show when={note()}>
|
||||
{(text) => <span class="shrink-0 text-[12px] leading-5 text-v2-text-text-muted">{text()}</span>}
|
||||
</Show>
|
||||
</span>
|
||||
<span class="w-full truncate text-[12px] leading-4 text-v2-text-text-faint">
|
||||
<Parts items={[...props.context, props.entry.trigger]} />
|
||||
</span>
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
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) => (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => props.onOpenSession(id())}
|
||||
class="inline max-w-full text-start font-medium text-v2-text-text-base underline decoration-v2-border-border-strong underline-offset-[3px] hover:decoration-current"
|
||||
>
|
||||
<bdi>{name()}</bdi>
|
||||
</button>
|
||||
)
|
||||
|
||||
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) => (
|
||||
<time title={formatDate(at(), row().tz, language)}>{relativeTime(at(), language)}</time>
|
||||
)
|
||||
|
||||
return (
|
||||
<article class="mx-auto flex w-full max-w-[720px] flex-col gap-7 px-6 py-6 lg:px-8">
|
||||
<header class="flex flex-wrap items-start justify-between gap-3">
|
||||
<div class="flex min-w-0 flex-col gap-0.5">
|
||||
<h2 dir="auto" class="text-[16px] leading-6 font-semibold text-v2-text-text-base">
|
||||
{row().name}
|
||||
</h2>
|
||||
<p class="text-[13px] leading-5 text-v2-text-text-muted">
|
||||
<Parts items={[statusLabel(row(), t), ...props.context]} />
|
||||
</p>
|
||||
</div>
|
||||
<div class="flex items-center gap-1">
|
||||
<Show when={row().status !== "done"}>
|
||||
<Button type="button" variant="neutral" size="small" disabled={props.busy} onClick={props.onTogglePause}>
|
||||
{t(row().status === "paused" ? "automations.action.resume" : "automations.action.pause")}
|
||||
</Button>
|
||||
</Show>
|
||||
<Button type="button" variant="ghost-muted" size="small" disabled={props.busy} onClick={props.onDelete}>
|
||||
{t("automations.delete.button")}
|
||||
</Button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<dl class="grid grid-cols-[88px_minmax(0,1fr)] gap-x-4 gap-y-5 text-[13px] leading-5">
|
||||
<Row label={t("automations.when")}>
|
||||
<div class="text-v2-text-text-base">
|
||||
<bdi>{props.entry.trigger}</bdi>
|
||||
</div>
|
||||
<Show when={!event()}>
|
||||
<div class="text-v2-text-text-muted">
|
||||
<bdi>{row().tz}</bdi>
|
||||
<Show when={next()}>{(at) => <> · {language.rich("automations.nextRun", { time: time(at) })}</>}</Show>
|
||||
</div>
|
||||
</Show>
|
||||
<Show when={args()?.inline}>
|
||||
{(text) => (
|
||||
<bdi dir="ltr" class="block font-mono text-[12px] text-v2-text-text-muted">
|
||||
{text()}
|
||||
</bdi>
|
||||
)}
|
||||
</Show>
|
||||
<Show when={args()?.block}>{(text) => <Content code>{text()}</Content>}</Show>
|
||||
</Row>
|
||||
|
||||
<Row label={t("automations.do")}>
|
||||
<div class="text-v2-text-text-base">{action().summary}</div>
|
||||
<Show when={action().hint}>{(hint) => <div class="text-v2-text-text-muted">{hint()}</div>}</Show>
|
||||
<Content code={action().code}>{action().body}</Content>
|
||||
<Show when={action().args}>{(text) => <Content code>{text()}</Content>}</Show>
|
||||
</Row>
|
||||
|
||||
<Row label={t("automations.lastRun")}>
|
||||
<div class="text-v2-text-text-base">
|
||||
<Show when={row().lastRunAt} fallback={t("automations.neverRun")}>
|
||||
{(at) => (
|
||||
<>
|
||||
{time(at)}
|
||||
<span class="text-v2-text-text-muted">
|
||||
{" "}
|
||||
· {language.plural("automations.runCount", row().runCount)}
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
</Show>
|
||||
</div>
|
||||
<Show when={row().lastOutput}>{(output) => <Content code>{output()}</Content>}</Show>
|
||||
</Row>
|
||||
</dl>
|
||||
|
||||
<dl class="grid grid-cols-[88px_minmax(0,1fr)] gap-x-4 gap-y-2 border-t border-v2-border-border-base pt-5 text-[12px] leading-5">
|
||||
<Row label={t("automations.folder")} muted>
|
||||
<bdi dir="ltr" class="break-all font-mono">
|
||||
{row().directory}
|
||||
</bdi>
|
||||
</Row>
|
||||
<Show when={row().sessionID}>
|
||||
{(id) => (
|
||||
<Row label={t("automations.creator")} muted>
|
||||
{link(id, () => props.entry.creator ?? id())}
|
||||
</Row>
|
||||
)}
|
||||
</Show>
|
||||
<Row label={t("automations.runsOn")} muted>
|
||||
<bdi>{props.entry.serverLabel}</bdi>
|
||||
</Row>
|
||||
</dl>
|
||||
</article>
|
||||
)
|
||||
}
|
||||
|
||||
function Parts(props: { items: string[] }) {
|
||||
return (
|
||||
<For each={props.items}>
|
||||
{(item, index) => (
|
||||
<>
|
||||
<Show when={index() > 0}> · </Show>
|
||||
<bdi>{item}</bdi>
|
||||
</>
|
||||
)}
|
||||
</For>
|
||||
)
|
||||
}
|
||||
|
||||
function Row(props: { label: string; muted?: boolean; children: JSX.Element }) {
|
||||
return (
|
||||
<>
|
||||
<dt class="text-v2-text-text-faint">{props.label}</dt>
|
||||
<dd class="flex min-w-0 flex-col gap-1.5 break-words" classList={{ "text-v2-text-text-muted": props.muted }}>
|
||||
{props.children}
|
||||
</dd>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function Content(props: { code?: boolean; children: JSX.Element }) {
|
||||
return (
|
||||
<div
|
||||
data-scrollable
|
||||
dir={props.code ? "ltr" : "auto"}
|
||||
class="mt-1 max-h-56 overflow-auto whitespace-pre-wrap break-words rounded-[6px] bg-v2-background-bg-layer-01 px-3 py-2.5 text-[13px] leading-5 text-v2-text-text-base select-text"
|
||||
classList={{ "font-mono text-[12px]": props.code }}
|
||||
>
|
||||
{props.children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
|
@ -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<typeof useLanguage>
|
||||
}) {
|
||||
const navigate = useNavigate()
|
||||
const automations = useAutomationSource()
|
||||
|
||||
return (
|
||||
<div
|
||||
class={`${props.class ?? ""} min-w-0 flex-row justify-between gap-1 lg:flex-col lg:justify-start lg:pr-3 [&>button]:w-auto lg:[&>button]:w-full`}
|
||||
classList={props.classList}
|
||||
>
|
||||
<Show when={automations.available()}>
|
||||
<HomeProjectNavButton
|
||||
type="button"
|
||||
data-action="home-automations"
|
||||
class="text-v2-text-text-faint [&>[data-slot=icon-svg]]:text-v2-icon-icon-muted"
|
||||
onClick={() => navigate("/automations")}
|
||||
>
|
||||
<Icon name="clock" size="small" />
|
||||
<span class={HOME_PROJECT_NAV_LABEL}>{props.language.t("automations.title")}</span>
|
||||
</HomeProjectNavButton>
|
||||
</Show>
|
||||
<HomeProjectNavButton
|
||||
type="button"
|
||||
class="text-v2-text-text-faint [&>[data-slot=icon-svg]]:text-v2-icon-icon-muted"
|
||||
|
|
|
|||
|
|
@ -8,6 +8,11 @@ import {
|
|||
|
||||
describe("new session workspace selection", () => {
|
||||
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" },
|
||||
|
|
|
|||
|
|
@ -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(),
|
||||
}),
|
||||
|
|
|
|||
|
|
@ -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",
|
||||
|
|
|
|||
|
|
@ -71,6 +71,20 @@ export const SettingsExperimental: Component = () => {
|
|||
</Switch>
|
||||
</div>
|
||||
</SettingsRow>
|
||||
<SettingsRow
|
||||
title={language.t("settings.experimental.row.automations.title")}
|
||||
description={language.t("settings.experimental.row.automations.description")}
|
||||
>
|
||||
<div data-action="settings-automations">
|
||||
<Switch
|
||||
checked={settings.general.automations()}
|
||||
onChange={(checked) => settings.general.setAutomations(checked)}
|
||||
hideLabel
|
||||
>
|
||||
{language.t("settings.experimental.row.automations.title")}
|
||||
</Switch>
|
||||
</div>
|
||||
</SettingsRow>
|
||||
<SettingsRow
|
||||
title={language.t("settings.experimental.row.newQuestionUI.title")}
|
||||
description={language.t("settings.experimental.row.newQuestionUI.description")}
|
||||
|
|
|
|||
|
|
@ -139,6 +139,8 @@ const generalSchema = Persistence.struct({
|
|||
newTimeline: Persistence.optional(Schema.Boolean),
|
||||
// Browser-style session tab grouping across vertical and horizontal tabs.
|
||||
tabGroups: Persistence.optional(Schema.Boolean),
|
||||
// The Automations view in the sidebar and Home, off in releases until it ships.
|
||||
automations: Persistence.optional(Schema.Boolean),
|
||||
// One side panel open state for every session tab, instead of one per tab.
|
||||
sharedSidePanel: Persistence.optional(Schema.Boolean),
|
||||
// "projects" is retired; `resolveSidebarOrganize` moves it to its replacement.
|
||||
|
|
@ -472,6 +474,13 @@ export const { use: useSettings, provider: SettingsProvider } = createSimpleCont
|
|||
setTabGroups(value: boolean) {
|
||||
setStore("general", "tabGroups", value)
|
||||
},
|
||||
automations: withFallback(
|
||||
() => 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)
|
||||
|
|
|
|||
|
|
@ -146,6 +146,13 @@ export const clientSettings: Entry<SettingsRootTab>[] = [
|
|||
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",
|
||||
|
|
|
|||
|
|
@ -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 (
|
||||
<Route component={AppLayout}>
|
||||
<Route path="/" component={Home} />
|
||||
<Route path="/automations" component={AutomationsScreen} />
|
||||
<Route path="/settings" component={SettingsScreen} />
|
||||
<Route
|
||||
path="/server/:serverKey/session/:id"
|
||||
|
|
@ -131,7 +139,9 @@ function AppLayout(props: ParentProps) {
|
|||
<LayoutProvider open={open}>
|
||||
<SettingsSurfaceProvider>
|
||||
<PluginAttachment>
|
||||
<Shell>{props.children}</Shell>
|
||||
<AutomationSourceProvider>
|
||||
<Shell>{props.children}</Shell>
|
||||
</AutomationSourceProvider>
|
||||
</PluginAttachment>
|
||||
</SettingsSurfaceProvider>
|
||||
</LayoutProvider>
|
||||
|
|
|
|||
|
|
@ -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 })
|
||||
})
|
||||
|
||||
|
|
|
|||
|
|
@ -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" }
|
||||
|
|
|
|||
|
|
@ -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<T>(tab: Tab, name: string, init: () => T) {
|
||||
return memory.ensure(tabKey(tab), name, init)
|
||||
},
|
||||
|
|
|
|||
|
|
@ -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: {
|
|||
>
|
||||
<Icon name={props.icon} class="shrink-0" />
|
||||
<span class="min-w-0 truncate">{props.label}</span>
|
||||
<Show when={props.count}>
|
||||
<span class="ms-auto text-[12px] tabular-nums">{props.count}</span>
|
||||
</Show>
|
||||
<div class="ms-auto hidden shrink-0 group-hover:block group-focus-visible:block" aria-hidden="true">
|
||||
<Keybind keys={props.keybind} variant="neutral" dir="ltr" />
|
||||
</div>
|
||||
|
|
@ -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) => (
|
||||
<Show
|
||||
when={vertical}
|
||||
|
|
@ -505,6 +516,39 @@ export function Titlebar(props: { verticalTabs?: { mount?: HTMLElement } }) {
|
|||
</Show>
|
||||
)
|
||||
|
||||
const automationsButton = (vertical = false) => (
|
||||
<Show when={automations.available()}>
|
||||
<Show
|
||||
when={vertical}
|
||||
fallback={
|
||||
<Tooltip placement="bottom" value={language.t("automations.title")} class="shrink-0">
|
||||
<IconButton
|
||||
type="button"
|
||||
variant="ghost-muted"
|
||||
size="large"
|
||||
class="!w-9 shrink-0"
|
||||
icon={<Icon name="clock" />}
|
||||
state={layout.route().type === "automations" ? "pressed" : undefined}
|
||||
onClick={toggleAutomations}
|
||||
aria-label={language.t("automations.title")}
|
||||
aria-pressed={layout.route().type === "automations"}
|
||||
/>
|
||||
</Tooltip>
|
||||
}
|
||||
>
|
||||
<SidebarAction
|
||||
action="vertical-tabs-automations"
|
||||
icon="clock"
|
||||
label={language.t("automations.title")}
|
||||
keybind={command.keybindParts("automations.open")}
|
||||
count={automations.active()}
|
||||
pressed={layout.route().type === "automations"}
|
||||
onClick={toggleAutomations}
|
||||
/>
|
||||
</Show>
|
||||
</Show>
|
||||
)
|
||||
|
||||
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 } }) {
|
|||
<div class="-me-0.5 flex shrink-0 items-center gap-0.5">
|
||||
{homeButton()}
|
||||
<Show when={!settings.appearance.navigationPrototype()}>{searchButton()}</Show>
|
||||
{automationsButton()}
|
||||
</div>
|
||||
</Show>
|
||||
|
||||
|
|
@ -998,6 +1053,7 @@ export function Titlebar(props: { verticalTabs?: { mount?: HTMLElement } }) {
|
|||
fallback={
|
||||
<>
|
||||
{searchButton(true)}
|
||||
{automationsButton(true)}
|
||||
<Show when={projectNavigation()} fallback={newSessionButton()}>
|
||||
{settingsButton()}
|
||||
</Show>
|
||||
|
|
@ -1005,6 +1061,7 @@ export function Titlebar(props: { verticalTabs?: { mount?: HTMLElement } }) {
|
|||
}
|
||||
>
|
||||
{homeButton(true)}
|
||||
{automationsButton(true)}
|
||||
{settingsButton()}
|
||||
</Show>
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -29,6 +29,7 @@ export type AppIconName =
|
|||
| "circle-exclamation"
|
||||
| "circle-x"
|
||||
| "circle-xmark"
|
||||
| "clock"
|
||||
| "close"
|
||||
| "close-small"
|
||||
| "cloud-upload"
|
||||
|
|
|
|||
|
|
@ -382,6 +382,10 @@ const icons = {
|
|||
viewBox: "0 0 16 16",
|
||||
body: `<path d="M2.5 14.5V7.5H13.5V14.5H2.5Z" stroke-linecap="round" stroke-linejoin="round" stroke="currentColor"/><path d="M5.5 7.5V4C5.5 2.61929 6.61929 1.5 8 1.5C9.38071 1.5 10.5 2.61929 10.5 4V7.5" stroke-linecap="round" stroke-linejoin="round" stroke="currentColor"/><path d="M7.5 10.5C7.5 10.2239 7.72386 10 8 10C8.27614 10 8.5 10.2239 8.5 10.5V12.5C8.5 12.7761 8.27614 13 8 13C7.72386 13 7.5 12.7761 7.5 12.5V10.5Z" fill="currentColor"/>`,
|
||||
},
|
||||
clock: {
|
||||
viewBox: "0 0 16 16",
|
||||
body: `<path d="M14.5 8C14.5 11.5899 11.5899 14.5 8 14.5C4.41015 14.5 1.5 11.5899 1.5 8C1.5 4.41015 4.41015 1.5 8 1.5C11.5899 1.5 14.5 4.41015 14.5 8Z" stroke="currentColor"/><path d="M8 4.5V8L10.5 9.75" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"/>`,
|
||||
},
|
||||
globe: {
|
||||
viewBox: "0 0 16 16",
|
||||
body: `<path d="M14.5 8C14.5 11.5899 11.5899 14.5 8 14.5C4.41015 14.5 1.5 11.5899 1.5 8C1.5 4.41015 4.41015 1.5 8 1.5C11.5899 1.5 14.5 4.41015 14.5 8Z" stroke="currentColor"/><path d="M1.5 8H14.5" stroke-linecap="round" stroke-linejoin="round" stroke="currentColor"/><path d="M8 1.5C6.5 3 5.5 5.5 5.5 8C5.5 10.5 6.5 13 8 14.5C9.5 13 10.5 10.5 10.5 8C10.5 5.5 9.5 3 8 1.5Z" stroke-linecap="round" stroke-linejoin="round" stroke="currentColor"/>`,
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue