Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,10 @@ preview arrives in the session that started it (plugin option `notify`).
activity, result) and a Unit (prompt, output, transcript). The session you are in also shows its Runs in a strip above
the prompt, in the sidebar and in a run panel (`/workflows panel`). The header links to the same page in the web app.

Below the Runs, **Saved** lists the project's durable Workflows with the args each one needs, so you do not have to
remember their keys. <kbd>↵</kbd> asks what you want and sends it to your session as `/<key> <request>`: the agent
builds the args and runs it. <kbd>s</kbd> starts a Workflow that needs no args at once.

<p align="center">
<a href="assets/tui-run.webp"><img src="assets/tui-run.webp" alt="The TUI's Run view: a header card for examples:research (done, 1m12s, 8.2k tokens, $0.66) with its phase stepper plan, research, synthesis and a budget meter; five Units with phase, agent, tokens, cost and time; the typed result as highlighted JSON" width="100%"></a><br>
<sub>A Run in the TUI: phases, Units, budget and the typed result.</sub>
Expand All @@ -188,7 +192,7 @@ the prompt, in the sidebar and in a run panel (`/workflows panel`). The header l

| Where | Keys |
| --- | --- |
| Library | <kbd>↵</kbd> open · <kbd>a</kbd> answer · <kbd>f</kbd> filter · <kbd>d</kbd> clean up finished · <kbd>b</kbd> open in the browser · <kbd>p</kbd> pair a device · <kbd>r</kbd> refresh |
| Library | <kbd>↵</kbd> open (on a saved Workflow: run it in your session) · <kbd>s</kbd> start a saved Workflow that needs no args · <kbd>a</kbd> answer · <kbd>f</kbd> filter · <kbd>d</kbd> clean up finished · <kbd>b</kbd> open in the browser · <kbd>p</kbd> pair a device · <kbd>r</kbd> refresh |
| Run, while running | <kbd>↵</kbd> Unit · <kbd>o</kbd> transcript · <kbd>s</kbd> stop Run · <kbd>x</kbd> stop Unit · <kbd>r</kbd> restart Unit · <kbd>b</kbd> open in the browser · <kbd>p</kbd> parent session |
| Run, when finished | <kbd>e</kbd> resume · <kbd>w</kbd> save as a durable Workflow · <kbd>d</kbd> delete its Unit sessions |
| Approval | <kbd>↑</kbd>/<kbd>↓</kbd>, <kbd>PgUp</kbd>/<kbd>PgDn</kbd>, <kbd>Home</kbd>/<kbd>End</kbd> scroll the script · <kbd>←</kbd>/<kbd>→</kbd> choose · <kbd>↵</kbd> confirm |
Expand Down
6 changes: 5 additions & 1 deletion packages/plugin/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,10 @@ preview arrives in the session that started it (plugin option `notify`).
activity, result) and a Unit (prompt, output, transcript). The session you are in also shows its Runs in a strip above
the prompt, in the sidebar and in a run panel (`/workflows panel`). The header links to the same page in the web app.

Below the Runs, **Saved** lists the project's durable Workflows with the args each one needs, so you do not have to
remember their keys. <kbd>↵</kbd> asks what you want and sends it to your session as `/<key> <request>`: the agent
builds the args and runs it. <kbd>s</kbd> starts a Workflow that needs no args at once.

<p align="center">
<a href="https://raw.githubusercontent.com/malhashemi/opencode-dynamic-workflows/main/assets/tui-run.webp"><img src="https://raw.githubusercontent.com/malhashemi/opencode-dynamic-workflows/main/assets/tui-run.webp" alt="The TUI's Run view: a header card for examples:research (done, 1m12s, 8.2k tokens, $0.66) with its phase stepper plan, research, synthesis and a budget meter; five Units with phase, agent, tokens, cost and time; the typed result as highlighted JSON" width="100%"></a><br>
<sub>A Run in the TUI: phases, Units, budget and the typed result.</sub>
Expand All @@ -190,7 +194,7 @@ the prompt, in the sidebar and in a run panel (`/workflows panel`). The header l

| Where | Keys |
| --- | --- |
| Library | <kbd>↵</kbd> open · <kbd>a</kbd> answer · <kbd>f</kbd> filter · <kbd>d</kbd> clean up finished · <kbd>b</kbd> open in the browser · <kbd>p</kbd> pair a device · <kbd>r</kbd> refresh |
| Library | <kbd>↵</kbd> open (on a saved Workflow: run it in your session) · <kbd>s</kbd> start a saved Workflow that needs no args · <kbd>a</kbd> answer · <kbd>f</kbd> filter · <kbd>d</kbd> clean up finished · <kbd>b</kbd> open in the browser · <kbd>p</kbd> pair a device · <kbd>r</kbd> refresh |
| Run, while running | <kbd>↵</kbd> Unit · <kbd>o</kbd> transcript · <kbd>s</kbd> stop Run · <kbd>x</kbd> stop Unit · <kbd>r</kbd> restart Unit · <kbd>b</kbd> open in the browser · <kbd>p</kbd> parent session |
| Run, when finished | <kbd>e</kbd> resume · <kbd>w</kbd> save as a durable Workflow · <kbd>d</kbd> delete its Unit sessions |
| Approval | <kbd>↑</kbd>/<kbd>↓</kbd>, <kbd>PgUp</kbd>/<kbd>PgDn</kbd>, <kbd>Home</kbd>/<kbd>End</kbd> scroll the script · <kbd>←</kbd>/<kbd>→</kbd> choose · <kbd>↵</kbd> confirm |
Expand Down
59 changes: 55 additions & 4 deletions packages/plugin/src/tui/app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,13 @@ import { createSignal } from "solid-js"
import { Show } from "solid-js"

import { formatClock } from "../progress"
import type { PendingInteraction, Run, Unit } from "../protocol"
import type { PendingInteraction, Run, Unit, WorkflowListing } from "../protocol"
import { isTerminal } from "../runs"
import { WorkflowRpc } from "../service/rpc"
import { formAnswer, findForm } from "./answer"
import { bindApi, errorText } from "./api"
import { cleanupPending, cleanupRun, cleanupTargets } from "./cleanup"
import { shortId, workflowName } from "./format"
import { savedArgs, savedCommand, shortId, workflowName } from "./format"
import { anyLive, emptyState, libraryEntries, sessionEntries, waitingRuns, type Effect, type SyncState } from "./state"
import { WorkflowSync } from "./sync"
import { LibraryPage, PANEL, RunPanel, SidebarRuns, Strip, type Actions, type Wf } from "./views"
Expand All @@ -33,6 +33,7 @@ export function setupWorkflowsTui(context: Context): () => void {
const [now, setNow] = createSignal(Date.now())
const [panelTarget, setPanelTarget] = createSignal<{ runId?: string; answer?: boolean } | undefined>(undefined)
const [panelFocus, setPanelFocus] = createSignal(false)
const [savedWorkflows, setSavedWorkflows] = createSignal<readonly WorkflowListing[]>([])
let returnTo: ReturnType<Context["ui"]["router"]["current"]> | null = null

const toast = (
Expand Down Expand Up @@ -95,6 +96,20 @@ export function setupWorkflowsTui(context: Context): () => void {
const route = context.ui.router.current()
return route.type === "session" ? route.sessionID : undefined
}
/** The session the user came from: the one in view, or the one `/workflows` was opened over. */
const originSession = () => sessionInView() ?? (returnTo?.type === "session" ? returnTo.sessionID : undefined)

// Loads can overlap (start, page open, refresh, save): only the newest one's answer is kept.
let savedLoads = 0
const loadSaved = async () => {
const load = ++savedLoads
try {
const { workflows } = await api.listWorkflows()
if (load === savedLoads) setSavedWorkflows(workflows)
} catch (err) {
if (load === savedLoads) setError(`saved Workflows: ${errorText(err)}`)
}
}

const heartbeat = async () => {
const sessionID = sessionInView()
Expand All @@ -107,6 +122,7 @@ export function setupWorkflowsTui(context: Context): () => void {
}

void heartbeat()
void loadSaved()
void sync.start().then(() => {
const waiting = waitingRuns(sync.current)
if (waiting.length > 0)
Expand Down Expand Up @@ -238,7 +254,9 @@ export function setupWorkflowsTui(context: Context): () => void {
})
if (!name) return
const saved = await attempt("Save", () => api.saveRun({ runId: run.runId, name }))
if (saved) toast(`Saved as "${saved.key}" (${saved.path}).`, "success")
if (!saved) return
toast(`Saved as "${saved.key}" (${saved.path}).`, "success")
void loadSaved()
},
async cleanupRun(run) {
if (!isTerminal(run.status)) {
Expand Down Expand Up @@ -331,7 +349,39 @@ export function setupWorkflowsTui(context: Context): () => void {
})
},
async refresh() {
await sync.resync("refresh")
await Promise.all([sync.resync("refresh"), loadSaved()])
},
loadSaved,
async useSaved(listing) {
const { required } = savedArgs(listing)
const request = await context.ui.dialog.prompt({
title: `Run ${listing.key}`,
description: `${listing.description}\nSay what you want: the agent builds the args${required.length ? ` (${required.join(", ")})` : ""} and runs it.`,
placeholder: listing.whenToUse ?? "What should it do?",
})
if (request === undefined) return
const origin = originSession()
const sessionID =
origin ??
(await attempt("New session", () => context.client.session.create({ title: listing.key, location } as never)))
?.id
if (!sessionID) return
const command = savedCommand(listing.key, request)
const sent = await attempt("Run", () =>
context.client.session.command({ sessionID, ...command, delivery: "queue" } as never),
)
if (sent === null) return
returnTo = null
context.ui.router.navigate({ type: "session", sessionID })
toast(`Sent /${command.name} to the session.`, "success")
},
async startSaved(listing) {
const origin = originSession()
const out = await attempt("Start", () =>
api.startRun({ name: listing.key, args: {}, ...(origin ? { parentSessionID: origin } : {}) }),
Comment thread
macroscopeapp[bot] marked this conversation as resolved.
Resolved
)
if (out) toast(`Started ${listing.key}.`, "success")
return out?.runId ?? null
},
openInBrowser(url) {
const command =
Expand Down Expand Up @@ -359,6 +409,7 @@ export function setupWorkflowsTui(context: Context): () => void {
state,
now,
error,
saved: savedWorkflows,
open: (runId) => sync.open(runId),
loadUnit: async (runId, unitId) => (await attempt("Load Unit", () => api.getUnit({ runId, unitId })))?.unit ?? null,
actions,
Expand Down
51 changes: 50 additions & 1 deletion packages/plugin/src/tui/format.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { formatClock, formatDay, formatElapsed, formatTokens, meter, phasePositi
* every width (80 columns is a contract); status is a glyph AND a word, colour only a bonus (an adversarial theme
* can make every feedback colour equal the text colour); never print a figure the system does not know.
*/
import type { LibraryEntry, RunStatus, Unit, UnitStatus, Usage } from "../protocol"
import type { LibraryEntry, RunStatus, Unit, UnitStatus, Usage, WorkflowListing } from "../protocol"

export type Tone = "success" | "error" | "warning" | "info" | "muted" | "base"

Expand Down Expand Up @@ -294,3 +294,52 @@ export function wrapLines(text: string, width: number): string[] {
export function shortId(id: string): string {
return id.replace(/-/g, "").slice(0, 8)
}

/**
* A saved Workflow's args, from its JSON Schema: the names a caller must give, the optional ones, and whether it
* can start with no args at all (`{}`; a Workflow without an args schema ignores them).
*/
export function savedArgs(listing: Pick<WorkflowListing, "args">): {
required: string[]
optional: string[]
startable: boolean
} {
if (!listing.args) return { required: [], optional: [], startable: true }
const schema = listing.args as { type?: unknown; properties?: Record<string, unknown>; required?: unknown }
// A string, an array…: `{}` is never valid.
if (schema.type !== "object") return { required: [], optional: [], startable: false }
const properties = schema.properties ?? {}
const listed = Array.isArray(schema.required)
? schema.required.filter((name): name is string => typeof name === "string")
: []
// zod lists a field with a default as required (its output always has it); a caller may leave it out.
const hasDefault = (name: string) => {
const property = properties[name]
return typeof property === "object" && property !== null && "default" in property
}
const required = listed.filter((name) => !hasDefault(name))
return {
required,
optional: Object.keys(properties).filter((name) => !required.includes(name)),
startable: required.length === 0,
}
}

/** "no args", "needs question", "needs question · 2 optional", "1 optional", "needs args" (not an object). */
export function savedArgsText(listing: Pick<WorkflowListing, "args">): string {
const { required, optional, startable } = savedArgs(listing)
if (!startable && required.length === 0) return "needs args"
if (required.length === 0 && optional.length === 0) return "no args"
return [required.length ? `needs ${required.join(", ")}` : "", optional.length ? `${optional.length} optional` : ""]
.filter(Boolean)
.join(" · ")
}

/** The slash command that runs a saved Workflow (see the server's command list), and the text to send with it. */
export function savedCommand(key: string, request: string): { name: string; text: string } {
const name = key.replaceAll(":", "/")
// `/workflow` and `/workflows` are taken: such a key goes through `/workflow <key> <request>`.
return name === "workflow" || name === "workflows"
? { name: "workflow", text: `${key} ${request}`.trim() }
: { name, text: request }
}
Loading
Loading