diff --git a/README.md b/README.md index f010007..bc13773 100644 --- a/README.md +++ b/README.md @@ -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. ↵ asks what you want and sends it to your session as `/ `: the agent +builds the args and runs it. s starts a Workflow that needs no args at once. +

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
A Run in the TUI: phases, Units, budget and the typed result. @@ -188,7 +192,7 @@ the prompt, in the sidebar and in a run panel (`/workflows panel`). The header l | Where | Keys | | --- | --- | -| Library | ↵ open · a answer · f filter · d clean up finished · b open in the browser · p pair a device · r refresh | +| Library | ↵ open (on a saved Workflow: run it in your session) · s start a saved Workflow that needs no args · a answer · f filter · d clean up finished · b open in the browser · p pair a device · r refresh | | Run, while running | ↵ Unit · o transcript · s stop Run · x stop Unit · r restart Unit · b open in the browser · p parent session | | Run, when finished | e resume · w save as a durable Workflow · d delete its Unit sessions | | Approval | ↑/↓, PgUp/PgDn, Home/End scroll the script · ←/→ choose · ↵ confirm | diff --git a/packages/plugin/README.md b/packages/plugin/README.md index 13dd214..05e278e 100644 --- a/packages/plugin/README.md +++ b/packages/plugin/README.md @@ -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. ↵ asks what you want and sends it to your session as `/ `: the agent +builds the args and runs it. s starts a Workflow that needs no args at once. +

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
A Run in the TUI: phases, Units, budget and the typed result. @@ -190,7 +194,7 @@ the prompt, in the sidebar and in a run panel (`/workflows panel`). The header l | Where | Keys | | --- | --- | -| Library | ↵ open · a answer · f filter · d clean up finished · b open in the browser · p pair a device · r refresh | +| Library | ↵ open (on a saved Workflow: run it in your session) · s start a saved Workflow that needs no args · a answer · f filter · d clean up finished · b open in the browser · p pair a device · r refresh | | Run, while running | ↵ Unit · o transcript · s stop Run · x stop Unit · r restart Unit · b open in the browser · p parent session | | Run, when finished | e resume · w save as a durable Workflow · d delete its Unit sessions | | Approval | ↑/↓, PgUp/PgDn, Home/End scroll the script · ←/→ choose · ↵ confirm | diff --git a/packages/plugin/src/tui/app.tsx b/packages/plugin/src/tui/app.tsx index 3a74c17..5e3c1aa 100644 --- a/packages/plugin/src/tui/app.tsx +++ b/packages/plugin/src/tui/app.tsx @@ -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" @@ -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([]) let returnTo: ReturnType | null = null const toast = ( @@ -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() @@ -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) @@ -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)) { @@ -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 } : {}) }), + ) + if (out) toast(`Started ${listing.key}.`, "success") + return out?.runId ?? null }, openInBrowser(url) { const command = @@ -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, diff --git a/packages/plugin/src/tui/format.ts b/packages/plugin/src/tui/format.ts index 32d179e..496de4c 100644 --- a/packages/plugin/src/tui/format.ts +++ b/packages/plugin/src/tui/format.ts @@ -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" @@ -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): { + required: string[] + optional: string[] + startable: boolean +} { + if (!listing.args) return { required: [], optional: [], startable: true } + const schema = listing.args as { type?: unknown; properties?: Record; 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): 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 `. + return name === "workflow" || name === "workflows" + ? { name: "workflow", text: `${key} ${request}`.trim() } + : { name, text: request } +} diff --git a/packages/plugin/src/tui/views.tsx b/packages/plugin/src/tui/views.tsx index 386fcf8..f514693 100644 --- a/packages/plugin/src/tui/views.tsx +++ b/packages/plugin/src/tui/views.tsx @@ -13,7 +13,7 @@ import { useTerminalDimensions } from "@opentui/solid" import { createEffect, createMemo, createSignal, For, Match, on, onMount, Show, Switch, type Accessor } from "solid-js" import { formatClock, formatElapsed, formatTokens, meter, settledUnits } from "../progress" -import type { LibraryEntry, PendingInteraction, Run, Unit } from "../protocol" +import type { LibraryEntry, PendingInteraction, Run, Unit, WorkflowListing } from "../protocol" import { isTerminal } from "../runs" import { back, @@ -43,6 +43,8 @@ import { libraryCells, renderHeader, runStatus, + savedArgs, + savedArgsText, shortId, sidebarLines, stripText, @@ -97,6 +99,12 @@ export interface Actions { dismiss(run: Run, interaction: PendingInteraction): Promise pair(): Promise refresh(): Promise + /** Re-read the saved (durable) Workflows. */ + loadSaved(): Promise + /** Ask what a saved Workflow should do, send `/ ` to the session the user came from, and go there. */ + useSaved(listing: WorkflowListing): Promise + /** Start a saved Workflow that needs no args; resolves to the new Run's id. */ + startSaved(listing: WorkflowListing): Promise openPanel(runId?: string, sessionID?: string): void openRoute(target?: { runId?: string; answer?: boolean }): void /** Open a web app page in the system browser. */ @@ -108,6 +116,8 @@ export interface Wf { readonly state: Accessor readonly now: Accessor readonly error: Accessor + /** The location's saved (durable) Workflows. */ + readonly saved: Accessor readonly open: (runId: string) => Promise readonly loadUnit: (runId: string, unitId: string) => Promise readonly actions: Actions @@ -145,6 +155,8 @@ export interface ScreenProps { wf: Wf /** Library rows: every Run of the location (page) or of one session (panel). */ entries: () => LibraryEntry[] + /** Saved Workflows, listed after the Runs (the page only). */ + saved?: () => readonly WorkflowListing[] start: () => { runId?: string; unitId?: string; answer?: boolean } | undefined root: "library" | "run" title: string @@ -204,6 +216,31 @@ export function WorkflowsScreen(props: ScreenProps) { const entries = createMemo(() => filterEntries(props.entries(), nav().filter).toSorted((a, b) => Number(b.live) - Number(a.live)), ) + // Saved Workflows follow the Runs in the library, under the "all" filter; one cursor walks both. + const saved = () => (nav().filter === "all" ? (props.saved?.() ?? []) : []) + const libraryRows = () => entries().length + saved().length + const selectedSaved = (): WorkflowListing | undefined => { + if (view().kind !== "library") return undefined + const index = cursor(nav(), libraryRows()) - entries().length + return index >= 0 ? saved()[index] : undefined + } + const [startingSaved, setStartingSaved] = createSignal(false) + const canStartSaved = () => { + const listing = selectedSaved() + return !!listing && savedArgs(listing).startable + } + const startSaved = async () => { + const listing = selectedSaved() + // One start at a time: a repeated key must not start the Workflow twice. + if (!listing || !canStartSaved() || startingSaved()) return + setStartingSaved(true) + try { + const runId = await wf.actions.startSaved(listing) + if (runId) setNav(push(nav(), { kind: "run", runId })) + } finally { + setStartingSaved(false) + } + } const units = () => run()?.units ?? [] const selectedUnit = () => { const list = units() @@ -297,7 +334,7 @@ export function WorkflowsScreen(props: ScreenProps) { const count = () => { const v = view() - if (v.kind === "library") return entries().length + if (v.kind === "library") return libraryRows() if (v.kind === "run") return units().length return Number.MAX_SAFE_INTEGER } @@ -313,7 +350,12 @@ export function WorkflowsScreen(props: ScreenProps) { function openSelected() { const v = view() if (v.kind === "library") { - const entry = entries()[cursor(nav(), entries().length)] + const listing = selectedSaved() + if (listing) { + void wf.actions.useSaved(listing) + return + } + const entry = entries()[cursor(nav(), libraryRows())] if (!entry) return // A queued Run that waits can only be waiting for its approval, and nothing else can happen before it: // open straight onto the script. @@ -376,7 +418,12 @@ export function WorkflowsScreen(props: ScreenProps) { ] if (v.kind === "library") { return [ - { key: "enter", label: "open", run: openSelected }, + ...(selectedSaved() + ? [ + { key: "enter", label: "run in session", run: openSelected }, + ...(canStartSaved() ? [{ key: "s", label: "start now", run: () => void startSaved() }] : []), + ] + : [{ key: "enter", label: "open", run: openSelected }]), { key: "a", label: "answer", run: answerFirst }, { key: "f", label: `filter: ${nav().filter}`, run: () => void setNav(cycleFilter(nav())) }, { key: "d", label: "clean up finished", run: () => void wf.actions.cleanupPending() }, @@ -510,6 +557,13 @@ export function WorkflowsScreen(props: ScreenProps) { enabled: inView("run"), run: withRun((t) => wf.actions.openTranscript(t.parentSessionID)), }, + { + title: "Start the saved Workflow", + group: "Workflows", + bind: "s", + enabled: () => canStartSaved() && !startingSaved(), + run: () => void startSaved(), + }, { title: "Stop Run", group: "Workflows", @@ -671,13 +725,14 @@ export function WorkflowsScreen(props: ScreenProps) { { - if (cursor(nav(), entries().length) === index) openSelected() - else setNav(setCursor(nav(), index, entries().length)) + if (cursor(nav(), libraryRows()) === index) openSelected() + else setNav(setCursor(nav(), index, libraryRows())) }} /> @@ -771,9 +826,37 @@ function libraryRow( ]) } +/** One saved Workflow's row: a marker where the status goes, its key and description, then what args it takes. */ +function savedRow(theme: Context["theme"], listing: WorkflowListing, width: number): Cell[] { + const muted = theme.text.muted + const args = savedArgsText(listing) + const argsWidth = Math.min(Math.max(args.length, 8), Math.floor(width / 3)) + const middle = Math.max(10, width - 13 - argsWidth - 2) + return [ + ...fitCells([{ text: "◇ saved", fg: theme.text.feedback.info.base }], 13), + { text: " ", fg: muted }, + ...fitCells( + [ + { text: listing.key, fg: theme.text.base, bold: true }, + { text: listing.description ? ` ${listing.description}` : "", fg: muted }, + ], + middle, + ), + { text: " ", fg: muted }, + ...fitCells( + [{ text: args, fg: savedArgs(listing).startable ? muted : theme.text.feedback.warning.base }], + argsWidth, + "right", + ), + ] +} + +type LibraryRow = { kind: "run"; entry: LibraryEntry } | { kind: "saved"; listing: WorkflowListing } + function LibraryPane(props: { wf: Wf entries: LibraryEntry[] + saved: readonly WorkflowListing[] filter: string cursor: number width: number @@ -783,19 +866,25 @@ function LibraryPane(props: { const th = () => props.wf.context.theme const columns = () => layout(LIBRARY_COLUMNS, props.width - 2) const live = () => props.entries.filter((entry) => entry.live).length - // Live Runs first (the list is sorted that way), each group under its own title. - const window = () => visibleWindow(props.entries.length, props.cursor, Math.max(3, props.height - 5)) + // Live Runs first (the list is sorted that way), then Recent, then the saved Workflows: each group under a title. + const items = (): LibraryRow[] => [ + ...props.entries.map((entry) => ({ kind: "run" as const, entry })), + ...props.saved.map((listing) => ({ kind: "saved" as const, listing })), + ] + const group = (row: LibraryRow) => (row.kind === "saved" ? "Saved" : row.entry.live ? "Live" : "Recent") + const groupSize = (title: string) => + title === "Saved" ? props.saved.length : title === "Live" ? live() : props.entries.length - live() + const window = () => visibleWindow(items().length, props.cursor, Math.max(3, props.height - 5)) const shown = () => - props.entries.slice(window().start, window().end).map((entry, index) => ({ entry, index: window().start + index })) - const titleBefore = (index: number) => { - const entry = props.entries[index]! - if (index === window().start) return true - return props.entries[index - 1]!.live !== entry.live - } + items() + .slice(window().start, window().end) + .map((row, index) => ({ row, index: window().start + index })) + const titleBefore = (index: number) => + index === window().start || group(items()[index - 1]!) !== group(items()[index]!) return ( 0} + when={items().length > 0} fallback={ @@ -804,7 +893,7 @@ function LibraryPane(props: { {props.filter === "all" - ? "Ask the agent to run a workflow, or type /workflow ." + ? "Ask the agent to write a workflow, or save one under .opencode/workflows/." : "Press f to change the filter."} @@ -815,23 +904,23 @@ function LibraryPane(props: { {(item) => ( <> -

+
props.onPick(item.index)} /> )} - window().end - window().start}> - {` ${props.cursor + 1} of ${props.entries.length}`} + window().end - window().start}> + {` ${props.cursor + 1} of ${items().length}`} @@ -1580,9 +1669,12 @@ export function LibraryPage(props: { onExit: () => void }) { const dims = useTerminalDimensions() + // Workflow files may have changed since the last look. + onMount(() => void props.wf.actions.loadSaved()) return ( Object.values(props.wf.state().runs) .map((slot) => slot.entry) diff --git a/packages/plugin/test/tui/format.test.ts b/packages/plugin/test/tui/format.test.ts index feb1939..810bdf6 100644 --- a/packages/plugin/test/tui/format.test.ts +++ b/packages/plugin/test/tui/format.test.ts @@ -2,6 +2,9 @@ import { describe, expect, test } from "bun:test" import { LIBRARY_COLUMNS, + savedArgs, + savedArgsText, + savedCommand, UNIT_COLUMNS, fit, formatCost, @@ -107,3 +110,30 @@ describe("strip and sidebar", () => { expect(second).toContain("phase 2/2") }) }) + +describe("saved Workflows", () => { + const schema = (properties: string[], required?: string[]) => ({ + args: { type: "object", properties: Object.fromEntries(properties.map((name) => [name, {}])), required }, + }) + test("args from the JSON Schema", () => { + expect(savedArgs({ args: null })).toEqual({ required: [], optional: [], startable: true }) + expect(savedArgs(schema(["question", "depth"], ["question"]))).toEqual({ + required: ["question"], + optional: ["depth"], + startable: false, + }) + // zod marks a defaulted field required; the caller may omit it. + const defaulted = { args: { type: "object", properties: { n: { type: "number", default: 3 } }, required: ["n"] } } + expect(savedArgs(defaulted)).toEqual({ required: [], optional: ["n"], startable: true }) + // Not an object: `{}` would fail, so it cannot start without args. + expect(savedArgs({ args: { type: "string" } }).startable).toBe(false) + expect(savedArgsText({ args: { type: "string" } })).toBe("needs args") + expect(savedArgsText({ args: null })).toBe("no args") + expect(savedArgsText(schema(["question", "depth", "files"], ["question"]))).toBe("needs question · 2 optional") + expect(savedArgsText(schema(["depth"]))).toBe("1 optional") + }) + test("the slash command, with reserved names going through /workflow", () => { + expect(savedCommand("examples:research", "why?")).toEqual({ name: "examples/research", text: "why?" }) + expect(savedCommand("workflows", "go")).toEqual({ name: "workflow", text: "workflows go" }) + }) +}) diff --git a/packages/web/src/components.tsx b/packages/web/src/components.tsx index 1400552..bd72ae1 100644 --- a/packages/web/src/components.tsx +++ b/packages/web/src/components.tsx @@ -2,7 +2,7 @@ import { createMemo, createSignal, For, Show, splitProps, type JSX } from "solid import { ApiError } from "./api" import { useApp } from "./context" -import { prettyValue, tokenizeJson } from "./format" +import { prettyValue, tokenizeJson, tokenizeTs, type CodeToken } from "./format" import { navigate } from "./router" /** An anchor that routes in-app on a plain click and behaves like a link otherwise (new tab, copy link…). */ @@ -98,7 +98,41 @@ export function ValueBlock(props: { value: unknown; label?: string; maxHeight?: ) } -export function CodeBlock(props: { text: string; label?: string; maxHeight?: string; numbered?: boolean }) { +const TOKEN_CLASS: Record = { + comment: "t-comment", + string: "j-string", + number: "j-number", + keyword: "t-keyword", + literal: "j-literal", + type: "t-type", + fn: "t-fn", + plain: undefined, +} + +function CodeLine(props: { tokens: CodeToken[] }) { + return ( + + {(token) => { + const cls = TOKEN_CLASS[token.kind] + return cls ? {token.text} : token.text + }} + + ) +} + +/** Plain or numbered code; `language: "ts"` colours it (as text nodes, never HTML). */ +export function CodeBlock(props: { + text: string + label?: string + maxHeight?: string + numbered?: boolean + language?: "ts" +}) { + const lines = createMemo(() => + props.language === "ts" && props.text.length < 200_000 + ? tokenizeTs(props.text) + : props.text.split("\n").map((line): CodeToken[] => (line ? [{ kind: "plain", text: line }] : [])), + ) return (
@@ -113,14 +147,28 @@ export function CodeBlock(props: { text: string; label?: string; maxHeight?: str style={props.maxHeight ? { "max-height": props.maxHeight } : undefined} aria-label={props.label} > - - + + + {(line, index) => ( + <> + {index() > 0 ? "\n" : ""} + + + )} + + + } + > + {(line, index) => ( - {line} + )} diff --git a/packages/web/src/format.ts b/packages/web/src/format.ts index 13e9809..3599304 100644 --- a/packages/web/src/format.ts +++ b/packages/web/src/format.ts @@ -115,3 +115,61 @@ export function tokenizeJson(text: string): JsonToken[] { } return out } + +export type CodeToken = { + kind: "comment" | "string" | "number" | "keyword" | "literal" | "type" | "fn" | "plain" + text: string +} + +const TS_KEYWORDS = new Set( + ( + "as async await break case catch class const continue debugger declare default delete do else enum export " + + "extends finally for from function if implements import in instanceof interface let new of private protected " + + "public readonly return satisfies static super switch throw try type typeof var void while with yield" + ).split(" "), +) +const TS_LITERALS = new Set(["true", "false", "null", "undefined", "this", "NaN", "Infinity"]) + +/** + * Tokenise TypeScript for highlighting, one token list per line (rendered as text nodes — never as HTML). A light + * lexer, not a parser: comments, strings, template literals, numbers, keywords, types and calls. Joining every + * token of every line with "\n" gives back the source exactly. + */ +export function tokenizeTs(text: string): CodeToken[][] { + const pattern = + /(\/\/[^\n]*|\/\*[\s\S]*?(?:\*\/|$))|("(?:[^"\\\n]|\\.)*"?|'(?:[^'\\\n]|\\.)*'?|`(?:[^`\\]|\\[\s\S])*`?)|(\b(?:0[xXbBoO][\da-fA-F_]+|\d[\d_]*(?:\.\d+)?(?:[eE][+-]?\d+)?)n?\b)|([A-Za-z_$][\w$]*)(?=(\s*\()?)|([\s\S])/g + const lines: CodeToken[][] = [[]] + const push = (kind: CodeToken["kind"], value: string) => { + const parts = value.split("\n") + parts.forEach((part, index) => { + if (index > 0) lines.push([]) + if (!part) return + const line = lines[lines.length - 1]! + const last = line[line.length - 1] + if (last && last.kind === kind) last.text += part + else line.push({ kind, text: part }) + }) + } + let match: RegExpExecArray | null + while ((match = pattern.exec(text))) { + if (match[1] !== undefined) push("comment", match[1]) + else if (match[2] !== undefined) push("string", match[2]) + else if (match[3] !== undefined) push("number", match[3]) + else if (match[4] !== undefined) { + const word = match[4] + push( + TS_KEYWORDS.has(word) + ? "keyword" + : TS_LITERALS.has(word) + ? "literal" + : match[5] + ? "fn" + : /^[A-Z]/.test(word) + ? "type" + : "plain", + word, + ) + } else push("plain", match[6] ?? "") + } + return lines +} diff --git a/packages/web/src/interactions.tsx b/packages/web/src/interactions.tsx index 8b3939a..32f7162 100644 --- a/packages/web/src/interactions.tsx +++ b/packages/web/src/interactions.tsx @@ -127,7 +127,7 @@ function PendingCard(props: { run: Run; interaction: PendingInteraction }) {
{approval().bytes} bytes · sha256 {approval().sha256}
- +
)} diff --git a/packages/web/src/styles.css b/packages/web/src/styles.css index 66a44d3..68c5156 100644 --- a/packages/web/src/styles.css +++ b/packages/web/src/styles.css @@ -39,6 +39,10 @@ --j-string: #0a6b39; --j-number: #953800; --j-literal: #8250df; + --t-comment: #6e7781; + --t-keyword: #cf222e; + --t-type: #953800; + --t-fn: #8250df; } @media (prefers-color-scheme: dark) { @@ -75,6 +79,10 @@ --j-string: #7ee2a8; --j-number: #ffa657; --j-literal: #d2a8ff; + --t-comment: #8b949e; + --t-keyword: #ff7b72; + --t-type: #ffa657; + --t-fn: #d2a8ff; } } @@ -940,6 +948,19 @@ input[type="search"] { .j-literal { color: var(--j-literal); } +.t-comment { + color: var(--t-comment); + font-style: italic; +} +.t-keyword { + color: var(--t-keyword); +} +.t-type { + color: var(--t-type); +} +.t-fn { + color: var(--t-fn); +} /* ---------- activity ---------- */ diff --git a/packages/web/test/format.test.ts b/packages/web/test/format.test.ts index e704062..886a10b 100644 --- a/packages/web/test/format.test.ts +++ b/packages/web/test/format.test.ts @@ -1,6 +1,14 @@ import { describe, expect, test } from "bun:test" -import { formatCost, formatCount, formatDuration, prettyValue, shortLocation, tokenizeJson } from "../src/format" +import { + formatCost, + formatCount, + formatDuration, + prettyValue, + shortLocation, + tokenizeJson, + tokenizeTs, +} from "../src/format" import { describeFields, parseArgs, templateFor, validateJson } from "../src/schema" describe("format", () => { @@ -87,3 +95,45 @@ describe("args schema", () => { ]) }) }) + +describe("code tokens", () => { + test("TypeScript tokens: lines, kinds, and the exact source back", () => { + const source = [ + 'import { defineWorkflow, z } from "@malhashemi/opencode-dynamic-workflows/workflow"', + "/** A doc", + " * comment */", + "const Plan = z.object({ n: z.number().min(2) }) // tail", + "export default defineWorkflow({ async run({ agent }) { return `a", + "b ${1}` ?? null } })", + "", + ].join("\n") + const lines = tokenizeTs(source) + expect(lines).toHaveLength(7) + expect(lines.map((line) => line.map((t) => t.text).join("")).join("\n")).toBe(source) + const kinds = (text: string) => + lines + .flat() + .filter((t) => t.text === text) + .map((t) => t.kind) + expect(kinds("import")).toEqual(["keyword"]) + expect(kinds('"@malhashemi/opencode-dynamic-workflows/workflow"')).toEqual(["string"]) + expect(lines[1]!.map((t) => t.kind)).toEqual(["comment"]) + expect(lines[2]!.map((t) => t.kind)).toEqual(["comment"]) + expect(kinds("Plan")).toEqual(["type"]) + expect(kinds("object")).toEqual(["fn"]) + expect(kinds("2")).toEqual(["number"]) + expect(kinds("// tail")).toEqual(["comment"]) + expect(kinds("null")).toEqual(["literal"]) + expect(lines[4]!.at(-1)).toEqual({ kind: "string", text: "`a" }) + expect(lines[5]![0]).toEqual({ kind: "string", text: "b ${1}`" }) + }) + + test("TypeScript tokens: an unterminated string or comment still round-trips", () => { + for (const source of ['const s = "open', "/* never closed\nstill", "`tick\n\nend", "a / b / c"]) + expect( + tokenizeTs(source) + .map((line) => line.map((t) => t.text).join("")) + .join("\n"), + ).toBe(source) + }) +})