diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 1417694..0ee04ea 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -3,5 +3,6 @@ "plugins/claude-tty": "0.6.0", "plugins/discord-rich-presence": "0.3.0", "plugins/guided-review": "0.3.0", + "plugins/task-runner": "0.0.0", "apps/claude-tty-acp": "0.6.0" } diff --git a/README.md b/README.md index 1c40879..f0431a6 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,7 @@ My plugins for [Paseo](https://github.com/getpaseo/paseo). | [Catppuccin theme](plugins/catppuccin-theme) | Add all four Catppuccin flavours as app themes. | | [Claude TTY](plugins/claude-tty) | Deprecated: offer the Claude TTY ACP adapter as a Paseo provider, and manage it on the daemon host. | | [Guided Review](plugins/guided-review) | Show a trunk-first guide to a pull request or merge request, and build your draft review alongside it. | +| [Task Runner](plugins/task-runner) | Run a project's own scripts from a sidebar panel. | | ACP | Description | | ------------------------------------- | -------------------------------------------------------------------------------------- | diff --git a/plugins/task-runner/CLAUDE.md b/plugins/task-runner/CLAUDE.md new file mode 100644 index 0000000..2a2f4cf --- /dev/null +++ b/plugins/task-runner/CLAUDE.md @@ -0,0 +1,11 @@ +# Working on this plugin + +Run `paseo plugin reload task-runner` after every change, then `paseo plugin logs task-runner`. +The reload is the only compile check of the two bundles the daemon builds. + +## Traps + +- A dependency whose entry is a UMD build fails at load with `Cannot find module`, because the daemon's bundler cannot follow its dynamic `require`, while typecheck and tests pass. + `jsonc-parser` is one, which is why `server/discovery/files.ts` reads JSONC itself. +- A change to `WRAPPER` in `server/runs/shell-wrapper.ts` has to be tried on real terminals with both zsh and bash, with a single-command task and with Ctrl+C. +- `pnpm test` runs `node --test` with Node's type stripping: write only erasable TypeScript and keep the `.ts` extension on relative imports. diff --git a/plugins/task-runner/README.md b/plugins/task-runner/README.md new file mode 100644 index 0000000..cfeb680 --- /dev/null +++ b/plugins/task-runner/README.md @@ -0,0 +1,56 @@ +# Task Runner + +Run the scripts your project already defines from a **Tasks** panel in the Explorer, without declaring them again in `paseo.json`. +It lists `package.json` scripts, Makefile targets, Nx targets and `.vscode/tasks.json` tasks. + +## Screenshots + +![Tasks grouped by package in a monorepo](./docs/screenshots/panel.png) + +![A finished task expanded to its output](./docs/screenshots/output.png) + +![A running task with Stop and Restart](./docs/screenshots/running.png) + +## Installation + +Requires: + +- Paseo 0.15 or newer +- A macOS or Linux host + +```sh +paseo plugin add github:sleeyax/paseo-plugins:plugins/task-runner +``` + +Update with `paseo plugin update task-runner`. +To install from source, see the [root README](../../README.md#from-source). + +## Usage + +### Run a task + +Open **Tasks** in the Explorer, or choose **Run Task...** in the Command Center. +Select the play button on a task. +It runs in its own workspace terminal, which opens as a tab without taking focus. + +### Run a task from the keyboard + +Choose **Run Task...** in the Command Center, pick a task with the arrow keys, and press Enter. +Recently run tasks are listed first. +**Rerun Last Task** in the Command Center runs the last one again. + +### List targets inferred by Nx plugins + +Select **Load inferred targets** in the panel, which runs the repository's own `nx`. +The choice is remembered per workspace. + +### Run a command that has no script + +Add it to `.vscode/tasks.json`. +The `label`, `command`, `args` and `options.cwd` fields are read, and only `${workspaceFolder}` is filled in. + +## Development + +For development instructions, see the [root README](../../README.md#development). + +Design decisions are in [docs/adr](docs/adr). diff --git a/plugins/task-runner/client/task-list.test.ts b/plugins/task-runner/client/task-list.test.ts new file mode 100644 index 0000000..a9cd907 --- /dev/null +++ b/plugins/task-runner/client/task-list.test.ts @@ -0,0 +1,108 @@ +import assert from "node:assert/strict"; +import { describe, it } from "node:test"; +import type { Task } from "../shared/task.ts"; +import { buildSections, filterTasks, groupTasks } from "./task-list.ts"; + +const task = (label: string, group = "app", source = "pnpm"): Task => ({ + id: `task: ${group}: ${label}`, + label, + group, + source, + command: source, + args: [], + cwd: "/repo", + description: null, + disabledReason: null, +}); + +const tasks = [task("build"), task("dev"), task("build", "web", "nx"), task("image", "web", "make")]; +const shown = (query: string) => filterTasks(tasks, query).map((item) => `${item.group}/${item.label}`); + +describe("filterTasks", () => { + it("keeps everything for an empty query", () => { + assert.equal(filterTasks(tasks, " ").length, 4); + }); + + it("matches the label regardless of case", () => { + assert.deepEqual(shown("BUI"), ["app/build", "web/build"]); + }); + + it("requires every word, which may match the group or source", () => { + assert.deepEqual(shown("web build"), ["web/build"]); + assert.deepEqual(shown("make"), ["web/image"]); + }); + + it("finds nothing when a word matches nothing", () => { + assert.deepEqual(shown("build zzz"), []); + }); +}); + +describe("groupTasks", () => { + it("keeps groups in the order they first appear", () => { + assert.deepEqual(groupTasks(tasks).map((group) => [group.name, group.tasks.length]), [["app", 2], ["web", 2]]); + }); +}); + +describe("buildSections", () => { + const layout = (options: Partial[1]> = {}) => + buildSections(tasks, { query: "", recentIds: [], collapsed: new Set(), ...options }); + const rows = (result: ReturnType) => + result.sections.map((section) => [section.title, section.rows.map((row) => `${row.index}:${row.task.group}/${row.task.label}`)]); + + it("numbers the rows of every group in order for the keyboard", () => { + assert.deepEqual(rows(layout()), [ + ["app", ["0:app/build", "1:app/dev"]], + ["web", ["2:web/build", "3:web/image"]], + ]); + assert.deepEqual(layout().navigable.map((item) => item.label), ["build", "dev", "build", "image"]); + }); + + it("puts recently run tasks first, under recent, with their group shown", () => { + const result = layout({ recentIds: ["task: web: image", "task: app: dev"] }); + assert.deepEqual(rows(result)[0], ["recent", ["0:web/image", "1:app/dev"]]); + assert.equal(result.sections[0]?.rows[0]?.showGroup, true); + assert.equal(result.sections[1]?.rows[0]?.index, 2); + }); + + it("filters recent tasks too, and skips ones no longer listed", () => { + const result = layout({ query: "image", recentIds: ["task: gone: x", "task: web: image", "task: app: dev"] }); + assert.deepEqual(rows(result), [ + ["recent", ["0:web/image"]], + ["web", ["1:web/image"]], + ]); + }); + + it("shows at most five recent tasks", () => { + const many = Array.from({ length: 7 }, (_, index) => task(`t${index}`)); + const result = buildSections(many, { query: "", recentIds: many.map((item) => item.id), collapsed: new Set() }); + assert.equal(result.sections[0]?.rows.length, 5); + }); + + it("leaves a collapsed group's rows out of the keyboard order, unless searching", () => { + assert.deepEqual(rows(layout({ collapsed: new Set(["group:app"]) })), [ + ["app", []], + ["web", ["0:web/build", "1:web/image"]], + ]); + assert.equal(layout({ collapsed: new Set(["group:app"]) }).sections[0]?.open, false); + assert.equal(layout({ collapsed: new Set(["group:app"]), query: "dev" }).sections[0]?.open, true); + }); + + it("collapses recent like a group, leaving its rows out of the keyboard order", () => { + const result = layout({ recentIds: ["task: app: dev"], collapsed: new Set(["recent"]) }); + assert.equal(result.sections[0]?.title, "recent"); + assert.equal(result.sections[0]?.collapsible, true); + assert.equal(result.sections[0]?.open, false); + assert.equal(result.sections[1]?.rows[0]?.index, 0); + }); + + it("does not confuse a package named recent with the recent section", () => { + const named = [task("a", "recent"), task("b", "other")]; + const result = buildSections(named, { query: "", recentIds: ["task: recent: a"], collapsed: new Set(["group:recent"]) }); + assert.deepEqual(result.sections.map((section) => [section.title, section.open]), [["recent", true], ["recent", false], ["other", true]]); + }); + + it("gives a single group no title", () => { + const result = buildSections([task("a"), task("b")], { query: "", recentIds: [], collapsed: new Set() }); + assert.deepEqual(result.sections.map((section) => section.title), [null]); + }); +}); diff --git a/plugins/task-runner/client/task-list.ts b/plugins/task-runner/client/task-list.ts new file mode 100644 index 0000000..40d1b6e --- /dev/null +++ b/plugins/task-runner/client/task-list.ts @@ -0,0 +1,70 @@ +import type { Task } from "../shared/task.ts"; + +export type TaskGroup = { name: string; tasks: Task[] }; + +export function filterTasks(tasks: Task[], query: string): Task[] { + const words = query.toLowerCase().split(/\s+/).filter(Boolean); + if (words.length === 0) return tasks; + return tasks.filter((task) => { + const haystack = `${task.label} ${task.group} ${task.source}`.toLowerCase(); + return words.every((word) => haystack.includes(word)); + }); +} + +export function groupTasks(tasks: Task[]): TaskGroup[] { + const groups = new Map(); + for (const task of tasks) groups.set(task.group, [...(groups.get(task.group) ?? []), task]); + return [...groups].map(([name, grouped]) => ({ name, tasks: grouped })); +} + +const RECENT_SHOWN = 5; + +export type TaskSectionRow = { + task: Task; + /** The row's place in the keyboard order. */ + index: number; + /** Whether the row sits outside its group, so its group needs naming. */ + showGroup: boolean; +}; + +export type TaskSection = { + key: string; + /** Null for the only group, which needs no header. */ + title: string | null; + collapsible: boolean; + open: boolean; + rows: TaskSectionRow[]; +}; + +export type SectionOptions = { + query: string; + recentIds: string[]; + /** Section keys, so a package named recent does not share the recent section's state. */ + collapsed: ReadonlySet; +}; + +export function buildSections(tasks: Task[], { query, recentIds, collapsed }: SectionOptions): { sections: TaskSection[]; navigable: Task[] } { + const shown = filterTasks(tasks, query); + const grouped = groupTasks(tasks).length > 1; + const searching = query.trim() !== ""; + const navigable: Task[] = []; + const rowsOf = (sectionTasks: Task[], showGroup: boolean) => + sectionTasks.map((task) => { + navigable.push(task); + return { task, index: navigable.length - 1, showGroup }; + }); + + const sections: TaskSection[] = []; + const isOpen = (key: string) => searching || !collapsed.has(key); + const recent = recentIds.flatMap((id) => shown.find((task) => task.id === id) ?? []).slice(0, RECENT_SHOWN); + if (recent.length > 0) { + const open = isOpen("recent"); + sections.push({ key: "recent", title: "recent", collapsible: true, open, rows: open ? rowsOf(recent, grouped) : [] }); + } + for (const group of groupTasks(shown)) { + const key = `group:${group.name}`; + const open = isOpen(key); + sections.push({ key, title: grouped ? group.name : null, collapsible: grouped, open, rows: open ? rowsOf(group.tasks, false) : [] }); + } + return { sections, navigable }; +} diff --git a/plugins/task-runner/client/task-row.tsx b/plugins/task-runner/client/task-row.tsx new file mode 100644 index 0000000..3b9b442 --- /dev/null +++ b/plugins/task-runner/client/task-row.tsx @@ -0,0 +1,123 @@ +import type { PluginTheme } from "@getpaseo/plugin"; +import { Icon } from "@getpaseo/plugin/client/ui"; +import { useState } from "react"; +import { Platform, Pressable, Text, View } from "react-native"; +import { isRunActive, type RunState, type Task } from "../shared/task.ts"; + +type Colors = PluginTheme["colors"]; + +const MONOSPACE = Platform.select({ ios: "Menlo", android: "monospace", default: "monospace" }); + +export type TaskActions = { + run(task: Task): void; + stop(run: RunState): void; + forceKill(run: RunState): void; +}; + +function statusText(run: RunState): string { + switch (run.status) { + case "running": + return "Running"; + case "stopping": + return "Stopping…"; + case "stopped": + return "Stopped"; + case "succeeded": + return "Done"; + case "failed": + return `Failed (exit ${run.exitCode ?? "?"})`; + } +} + +function statusColor(run: RunState, colors: Colors): string { + switch (run.status) { + case "running": + case "stopping": + return colors.accent; + case "succeeded": + return colors.statusSuccess; + case "failed": + return colors.statusDanger; + case "stopped": + return colors.statusWarning; + } +} + +function IconButton({ colors, icon, label, disabled, onPress }: { colors: Colors; icon: string; label: string; disabled?: boolean; onPress: () => void }) { + return ( + + + + ); +} + +function Controls({ colors, task, run, busy, actions }: { colors: Colors; task: Task; run: RunState | null; busy: boolean; actions: TaskActions }) { + if (task.disabledReason !== null) return null; + if (run === null || !isRunActive(run)) return actions.run(task)} />; + return ( + + {run.canForceKill ? ( + actions.forceKill(run)} hitSlop={4} style={{ paddingHorizontal: 4 }}> + Force kill + + ) : null} + {run.status === "running" ? actions.stop(run)} /> : null} + actions.run(task)} /> + + ); +} + +export type TaskRowProps = { + colors: Colors; + task: Task; + /** Named when the row is listed outside its group, as under recent. */ + groupName: string | null; + /** The row Enter runs from the search box. */ + highlighted: boolean; + run: RunState | null; + busy: boolean; + actions: TaskActions; +}; + +export function TaskRow({ colors, task, groupName, highlighted, run, busy, actions }: TaskRowProps) { + const [expanded, setExpanded] = useState(false); + const lastLine = run?.output.at(-1) ?? null; + const hasOutput = lastLine !== null; + const muted = task.disabledReason !== null; + return ( + + + setExpanded(!expanded)} style={{ flex: 1, flexDirection: "row", alignItems: "center", gap: 6, minWidth: 0 }}> + + {groupName !== null ? ( + + {groupName} › + + ) : null} + + {task.label} + + + {run === null ? task.source : statusText(run)} + + + + + {task.disabledReason !== null || task.description !== null ? ( + + {task.disabledReason ?? task.description} + + ) : null} + {hasOutput && !expanded ? ( + + {lastLine} + + ) : null} + {hasOutput && expanded ? ( + + {run?.output.join("\n")} + + ) : null} + + ); +} diff --git a/plugins/task-runner/client/tasks-panel.tsx b/plugins/task-runner/client/tasks-panel.tsx new file mode 100644 index 0000000..8388f5d --- /dev/null +++ b/plugins/task-runner/client/tasks-panel.tsx @@ -0,0 +1,219 @@ +import type { PluginTheme } from "@getpaseo/plugin"; +import { useRpc, useSettings, type PluginWorkspacePanelProps } from "@getpaseo/plugin/client"; +import { Icon, ScrollView, TextInput, useToast } from "@getpaseo/plugin/client/ui"; +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import { useEffect, useRef, useState } from "react"; +import { Pressable, Text, View, type TextInput as NativeTextInput } from "react-native"; +import * as contracts from "../shared/contracts.ts"; +import { PLUGIN_ID } from "../shared/identity.ts"; +import { settingsDocument } from "../shared/settings.ts"; +import { isRunActive, type NxStatus, type RunState, type Task } from "../shared/task.ts"; +import { buildSections, type TaskSection } from "./task-list.ts"; +import { TaskRow, type TaskActions } from "./task-row.tsx"; + +type Colors = PluginTheme["colors"]; + +const RUNS_POLL_MS = 1_500; +const INFERRED_POLL_MS = 3_000; +const GROUP_HEADER_PADDING = 6; +const CHEVRON_SIZE = 14; +/** Puts a group's guide line under its chevron's centre. */ +const GROUP_GUIDE_INSET = GROUP_HEADER_PADDING + CHEVRON_SIZE / 2 - 1; + +const message = (error: unknown) => (error instanceof Error ? error.message : String(error)); + +function LinkButton({ colors, label, onPress }: { colors: Colors; label: string; onPress: () => void }) { + return ( + + {label} + + ); +} + +function NxNotice({ colors, status, onChange }: { colors: Colors; status: NxStatus; onChange: (enabled: boolean) => void }) { + const text = { + off: "Targets inferred by Nx plugins are hidden.", + loading: "Loading inferred targets…", + on: "Showing targets inferred by Nx plugins.", + failed: `Could not load inferred targets, so these come from the files. ${status.failure ?? ""}`, + }[status.inferred]; + return ( + + {text} + {status.inferred === "off" ? onChange(true)} /> : onChange(false)} />} + + ); +} + +export function TasksPanel({ theme, layout, workspaceId, revision }: PluginWorkspacePanelProps) { + const { colors } = theme; + const search = useRef(null); + const [searchFocused, setSearchFocused] = useState(false); + const [selected, setSelected] = useState(0); + const toast = useToast(); + const queryClient = useQueryClient(); + const settings = useSettings(settingsDocument); + const [query, setQuery] = useState(""); + const [collapsed, setCollapsed] = useState>(new Set()); + + const listTasks = useRpc(contracts.listTasks); + const getRuns = useRpc(contracts.getRuns); + const runTask = useRpc(contracts.runTask); + const stopTask = useRpc(contracts.stopTask); + const forceKillTask = useRpc(contracts.forceKillTask); + + const tasks = useQuery({ + queryKey: [PLUGIN_ID, "tasks", workspaceId], + queryFn: () => listTasks({ workspaceId }), + staleTime: 0, + refetchOnMount: "always", + refetchOnWindowFocus: false, + refetchInterval: (current) => (current.state.data?.kind === "ready" && current.state.data.nx?.inferred === "loading" ? INFERRED_POLL_MS : false), + }); + + const runsKey = [PLUGIN_ID, "runs", workspaceId]; + const runs = useQuery({ + queryKey: runsKey, + queryFn: () => getRuns({ workspaceId }), + staleTime: 0, + refetchOnMount: "always", + refetchOnWindowFocus: false, + refetchInterval: (current) => (current.state.data?.runs.some(isRunActive) ? RUNS_POLL_MS : false), + }); + + const refreshRuns = () => queryClient.invalidateQueries({ queryKey: runsKey }); + const action = useMutation({ + mutationFn: (perform: () => Promise) => perform(), + onError: (error) => toast.error(message(error)), + onSettled: refreshRuns, + }); + + const actions: TaskActions = { + run: (task: Task) => action.mutate(() => runTask({ workspaceId, task })), + stop: (run: RunState) => action.mutate(() => stopTask({ workspaceId, terminalId: run.terminalId })), + forceKill: (run: RunState) => action.mutate(() => forceKillTask({ workspaceId, terminalId: run.terminalId })), + }; + + const setInferredTargets = async (enabled: boolean) => { + if (settings.status !== "ready") return; + const others = settings.values.inferredTargetWorkspaces.filter((id) => id !== workspaceId); + const saved = await settings.save({ ...settings.values, inferredTargetWorkspaces: enabled ? [...others, workspaceId] : others }, settings.revision); + if (saved) await tasks.refetch(); + else toast.error("Could not save that choice."); + }; + + const rescan = () => { + void tasks.refetch(); + void refreshRuns(); + }; + + // Opening the panel again, as Run Task... does, bumps the revision: that is a rescan and a fresh start at the top. + const seenRevision = useRef(revision); + useEffect(() => { + if (!layout.compact) search.current?.focus(); + setSelected(0); + if (seenRevision.current !== revision) rescan(); + seenRevision.current = revision; + }, [revision]); + + const ready = tasks.data?.kind === "ready" ? tasks.data : null; + const { sections, navigable } = buildSections(ready?.tasks ?? [], { query, recentIds: ready?.recentTaskIds ?? [], collapsed }); + const highlighted = searchFocused ? Math.min(selected, navigable.length - 1) : -1; + + const moveSelection = (key: string): boolean => { + if (key !== "ArrowDown" && key !== "ArrowUp") return false; + setSelected((current) => Math.max(0, Math.min(navigable.length - 1, Math.min(current, navigable.length - 1) + (key === "ArrowDown" ? 1 : -1)))); + return true; + }; + const runHighlighted = () => { + const task = navigable[highlighted]; + if (task !== undefined && task.disabledReason === null) actions.run(task); + }; + + const runsByTask = new Map((runs.data?.runs ?? []).map((run) => [run.taskId, run])); + const toggleSection = (key: string) => { + const next = new Set(collapsed); + if (!next.delete(key)) next.add(key); + setCollapsed(next); + }; + + const sectionHeader = (section: TaskSection) => { + if (section.title === null || !section.collapsible) return null; + return ( + toggleSection(section.key)} style={{ flexDirection: "row", alignItems: "center", gap: 4, paddingHorizontal: GROUP_HEADER_PADDING, paddingVertical: 4 }}> + + {section.key === "recent" ? : null} + + {section.title} + + + ); + }; + + const body = () => { + if (tasks.isPending) return Scanning…; + if (tasks.isError) return {message(tasks.error)}; + if (tasks.data.kind === "unsupported") return {tasks.data.message}; + + const { nx, tasks: all } = tasks.data; + return ( + <> + {nx !== null ? void setInferredTargets(enabled)} /> : null} + {all.length === 0 ? No tasks found in package.json, a Makefile, Nx or .vscode/tasks.json. : null} + {all.length > 0 && sections.length === 0 ? No tasks match. : null} + {sections.map((section) => ( + + {sectionHeader(section)} + {section.rows.length > 0 ? ( + + {section.rows.map(({ task, index, showGroup }) => ( + + ))} + + ) : null} + + ))} + + ); + }; + + return ( + + + { + setQuery(text); + setSelected(0); + }} + onFocus={() => setSearchFocused(true)} + onBlur={() => setSearchFocused(false)} + onKeyPress={(event) => { + if (moveSelection(event.nativeEvent.key)) event.preventDefault(); + }} + onSubmitEditing={runHighlighted} + submitBehavior="submit" + placeholder="Search tasks" + placeholderTextColor={colors.foregroundMuted} + accessibilityLabel="Search tasks" + style={{ flex: 1, minWidth: 0, color: colors.foreground, backgroundColor: colors.surface2, borderRadius: 4, paddingHorizontal: 8, paddingVertical: 4, fontSize: 13 }} /> + + + + + + {body()} + + + ); +} diff --git a/plugins/task-runner/docs/adr/0001-tasks-run-in-their-own-terminals.md b/plugins/task-runner/docs/adr/0001-tasks-run-in-their-own-terminals.md new file mode 100644 index 0000000..8a35ea4 --- /dev/null +++ b/plugins/task-runner/docs/adr/0001-tasks-run-in-their-own-terminals.md @@ -0,0 +1,6 @@ +# Tasks run in terminals the plugin owns + +Each task runs in a workspace terminal the plugin creates through the SDK, named `task: