@niwa-labs/workflow 0.0.0-stage → 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +13 -2
  3. package/package.json +55 -4
  4. package/src/actions.ts +408 -0
  5. package/src/agent.ts +211 -0
  6. package/src/ask.ts +84 -0
  7. package/src/bridge.ts +710 -0
  8. package/src/catalogue.ts +74 -0
  9. package/src/check.ts +880 -0
  10. package/src/child.ts +1378 -0
  11. package/src/cockpit/actions.ts +128 -0
  12. package/src/cockpit/catalogue-actions.ts +97 -0
  13. package/src/cockpit/dashboard.tsx +134 -0
  14. package/src/cockpit/groups.ts +45 -0
  15. package/src/cockpit/index.tsx +50 -0
  16. package/src/cockpit/launch.tsx +136 -0
  17. package/src/cockpit/plan.ts +101 -0
  18. package/src/cockpit/run-commands.tsx +102 -0
  19. package/src/cockpit/run-page.tsx +140 -0
  20. package/src/cockpit/run-summary.ts +16 -0
  21. package/src/cockpit/runs.tsx +73 -0
  22. package/src/cockpit/statistics.tsx +176 -0
  23. package/src/cockpit/track.tsx +159 -0
  24. package/src/cockpit/workflows.tsx +383 -0
  25. package/src/describe-cache.ts +122 -0
  26. package/src/describe.ts +174 -0
  27. package/src/guide.ts +213 -0
  28. package/src/index.ts +2813 -0
  29. package/src/inspect.ts +235 -0
  30. package/src/installation.ts +90 -0
  31. package/src/language.ts +217 -0
  32. package/src/records-entry.ts +63 -0
  33. package/src/records.ts +574 -0
  34. package/src/registry.ts +250 -0
  35. package/src/revise.ts +89 -0
  36. package/src/runner.ts +339 -0
  37. package/src/script-types.ts +549 -0
  38. package/src/stats.ts +460 -0
  39. package/src/status.ts +512 -0
  40. package/src/store.ts +259 -0
  41. package/src/subscriptions.ts +102 -0
  42. package/src/waiting.ts +61 -0
  43. package/test/cockpit-actions.test.ts +20 -0
  44. package/test/cockpit-groups.test.ts +42 -0
  45. package/test/cockpit-plan.test.ts +118 -0
  46. package/test/fixtures/branches-host.ts +58 -0
  47. package/test/fixtures/branches-script.js +23 -0
  48. package/test/fixtures/bridge-host.ts +23 -0
  49. package/test/fixtures/bridge-keys-script.js +15 -0
  50. package/test/fixtures/bridge-wait-script.js +8 -0
  51. package/test/fixtures/cancel-host.ts +58 -0
  52. package/test/fixtures/cancel-script.js +12 -0
  53. package/test/fixtures/crash-host.ts +61 -0
  54. package/test/fixtures/crash-script.js +14 -0
  55. package/test/fixtures/ping-records.ts +20 -0
  56. package/test/fixtures/revision-host.ts +57 -0
  57. package/test/fixtures/revision-script.js +11 -0
  58. package/test/fixtures/running-host.ts +61 -0
  59. package/test/fixtures/running-script.js +12 -0
  60. package/test/fixtures/with-data/flow.ts +2 -0
  61. package/test/fixtures/with-data/table.json +1 -0
  62. package/test/git-repo.ts +45 -0
  63. package/test/git-worktree.test.ts +413 -0
  64. package/test/question-format.test.ts +279 -0
  65. package/test/workflow-agent-caps.test.ts +91 -0
  66. package/test/workflow-agent-lifetime.test.ts +93 -0
  67. package/test/workflow-agent-options.test.ts +216 -0
  68. package/test/workflow-agent-schema.test.ts +386 -0
  69. package/test/workflow-agent-typings.test.ts +241 -0
  70. package/test/workflow-ask-resume.test.ts +145 -0
  71. package/test/workflow-branch-keys.test.ts +133 -0
  72. package/test/workflow-bridge-inproc.test.ts +230 -0
  73. package/test/workflow-bridge.test.ts +141 -0
  74. package/test/workflow-builtin-candidate.test.ts +230 -0
  75. package/test/workflow-builtin.test.ts +197 -0
  76. package/test/workflow-cancel-agent.test.ts +144 -0
  77. package/test/workflow-cancel.test.ts +166 -0
  78. package/test/workflow-chain.test.ts +84 -0
  79. package/test/workflow-check-options.test.ts +144 -0
  80. package/test/workflow-check-uses.test.ts +148 -0
  81. package/test/workflow-check.test.ts +282 -0
  82. package/test/workflow-contract.test.ts +295 -0
  83. package/test/workflow-crash-resume.test.ts +141 -0
  84. package/test/workflow-deadline.test.ts +102 -0
  85. package/test/workflow-describe-cache.test.ts +240 -0
  86. package/test/workflow-directory.test.ts +73 -0
  87. package/test/workflow-emits.test.ts +261 -0
  88. package/test/workflow-group-keys.test.ts +72 -0
  89. package/test/workflow-harnesses.test.ts +262 -0
  90. package/test/workflow-inspect.test.ts +152 -0
  91. package/test/workflow-language-types.test.ts +148 -0
  92. package/test/workflow-manifest.test.ts +93 -0
  93. package/test/workflow-manual-pause.test.ts +116 -0
  94. package/test/workflow-owners.test.ts +154 -0
  95. package/test/workflow-pause.test.ts +200 -0
  96. package/test/workflow-phases.test.ts +445 -0
  97. package/test/workflow-plugin-entries.test.ts +59 -0
  98. package/test/workflow-record-refs.test.ts +310 -0
  99. package/test/workflow-replay.test.ts +206 -0
  100. package/test/workflow-resume-once.test.ts +188 -0
  101. package/test/workflow-revision.test.ts +216 -0
  102. package/test/workflow-scope.test.ts +505 -0
  103. package/test/workflow-script-defaults.test.ts +119 -0
  104. package/test/workflow-script-error.test.ts +228 -0
  105. package/test/workflow-script-libraries.test.ts +88 -0
  106. package/test/workflow-script-packages.test.ts +119 -0
  107. package/test/workflow-stdout.test.ts +89 -0
  108. package/test/workflow-stop.test.ts +299 -0
  109. package/test/workflow-store.test.ts +220 -0
  110. package/test/workflow-visible.test.ts +136 -0
  111. package/test/workflow-wait-version.test.ts +54 -0
  112. package/test/workflow-wait.test.ts +224 -0
  113. package/test/workflow-waiting-agent.test.ts +64 -0
  114. package/tsconfig.json +15 -0
@@ -0,0 +1,128 @@
1
+ /**
2
+ * The workflow actions as the cockpit calls them: name and the part of each schema the pages read.
3
+ *
4
+ * The module runs in the browser and cannot import the host-side schemas, which reach for Node. These are the
5
+ * fields the pages use; what the host answers with beyond them is ignored, and a field the host stopped
6
+ * sending fails the page that reads it, which `test/cockpit-actions.test.ts` checks against the real actions.
7
+ */
8
+
9
+ import { z } from "zod";
10
+
11
+ export const RunState = z.enum(["running", "paused", "finished"]);
12
+
13
+ export const RunEntry = z.object({
14
+ run: z.string(),
15
+ name: z.string(),
16
+ state: RunState,
17
+ directory: z.string().optional(),
18
+ requestedAt: z.string(),
19
+ workflow: z.string().optional(),
20
+ phases: z.array(z.object({ title: z.string(), detail: z.string().optional(), state: z.enum(["done", "current", "ahead"]) })).optional(),
21
+ waiting: z.string().optional(),
22
+ manualPause: z.boolean().optional(),
23
+ about: z.string(),
24
+ requests: z.number(),
25
+ });
26
+ export type RunEntry = z.infer<typeof RunEntry>;
27
+
28
+ export const runsAction = {
29
+ name: "workflow.runs",
30
+ input: z.object({ state: RunState.optional(), limit: z.number().int().positive().optional() }),
31
+ output: z.object({ entries: z.array(RunEntry) }),
32
+ } as const;
33
+
34
+ const StepStatus = z.enum(["running", "paused", "completed", "failed", "unknown", "skipped", "cancelled"]);
35
+
36
+ export const Step = z.object({
37
+ id: z.string(),
38
+ label: z.string(),
39
+ key: z.string(),
40
+ action: z.string(),
41
+ prompt: z.string().optional(),
42
+ waitEvent: z.string().optional(),
43
+ dueAt: z.string().optional(),
44
+ timerName: z.string().optional(),
45
+ historical: z.boolean().optional(),
46
+ startedAt: z.string(),
47
+ endedAt: z.string().optional(),
48
+ status: StepStatus,
49
+ session: z.string().optional(),
50
+ phase: z.string().optional(),
51
+ /** The path of the branch the step is in, when it is in one. */
52
+ branch: z.string().optional(),
53
+ /** The call acts outside the run: once done, a recompute takes it instead of making it again. */
54
+ effect: z.boolean().optional(),
55
+ /** A later start of the run took the answer of this step instead of making the call again. */
56
+ reused: z.boolean().optional(),
57
+ });
58
+ export type Step = z.infer<typeof Step>;
59
+
60
+ const PhaseState = z.enum(["done", "current", "ahead"]);
61
+
62
+ export const Inspection = z.object({
63
+ observedAt: z.string().optional(),
64
+ run: z.string(),
65
+ status: z.object({
66
+ run: z.string(),
67
+ state: RunState,
68
+ outcome: z
69
+ .discriminatedUnion("status", [
70
+ z.object({ status: z.literal("done"), result: z.unknown().optional() }),
71
+ z.object({ status: z.literal("failed"), error: z.object({ message: z.string() }) }),
72
+ z.object({ status: z.literal("cancelled") }),
73
+ ])
74
+ .optional(),
75
+ reason: z.string().optional(),
76
+ manualPause: z.object({ id: z.string(), state: z.string() }).optional(),
77
+ choices: z.array(z.string()).optional(),
78
+ requests: z.array(z.string()),
79
+ waiting: z.string().optional(),
80
+ }),
81
+ origin: z.object({
82
+ file: z.string(),
83
+ sourceSeq: z.number().optional(),
84
+ workflow: z.string().optional(),
85
+ version: z.string().optional(),
86
+ args: z.unknown().optional(),
87
+ label: z.string().optional(),
88
+ directory: z.string().optional(),
89
+ requestedAt: z.string(),
90
+ startedAt: z.string().optional(),
91
+ finishedAt: z.string().optional(),
92
+ }),
93
+ phases: z.array(z.object({ title: z.string(), detail: z.string().optional(), state: PhaseState, steps: z.array(Step) })),
94
+ steps: z.array(Step),
95
+ sessions: z.array(z.object({
96
+ id: z.string(),
97
+ ref: z.string(),
98
+ parentSession: z.string().optional(),
99
+ startedAt: z.string(),
100
+ })),
101
+ });
102
+ export type Inspection = z.infer<typeof Inspection>;
103
+
104
+ export const inspectAction = {
105
+ name: "workflow.inspect",
106
+ input: z.object({ run: z.string() }),
107
+ output: Inspection,
108
+ } as const;
109
+
110
+ export const resumeAction = {
111
+ name: "workflow.resume",
112
+ /** `from`: the step key, or the title of a phase, to run again from; absent, the run is started again from the top. */
113
+ input: z.object({ run: z.string(), from: z.string().min(1).optional() }),
114
+ output: z.object({ run: z.string() }),
115
+ } as const;
116
+
117
+ export const stopAction = {
118
+ name: "workflow.stop",
119
+ /** `at`: the key of the step or branch to stop; absent, the whole run. */
120
+ input: z.object({ run: z.string(), at: z.string().min(1).optional() }),
121
+ output: z.object({ run: z.string() }),
122
+ } as const;
123
+
124
+ export const cancelAction = {
125
+ name: "workflow.cancel",
126
+ input: z.object({ run: z.string() }),
127
+ output: z.object({ run: z.string() }),
128
+ } as const;
@@ -0,0 +1,97 @@
1
+ import { z } from "zod";
2
+ import type { ActionRefLike } from "@niwa-labs/cockpit-sdk";
3
+ import type * as host from "../actions.ts";
4
+ import type { workflowStats } from "../stats.ts";
5
+
6
+ // Browser calls use the name on the wire. Take both wire types from the real
7
+ // host reference without bundling its filesystem and journal implementations.
8
+ function reference<T extends ActionRefLike<unknown, unknown>>(
9
+ name: string,
10
+ ): T extends ActionRefLike<infer I, infer O, infer In> ? ActionRefLike<I, O, In> : never;
11
+ function reference(name: string) {
12
+ return { name, input: { "~standard": {} }, output: { "~standard": {} } };
13
+ }
14
+
15
+ const problem = z.object({ file: z.string(), line: z.number(), column: z.number(), message: z.string() });
16
+ const version = z.object({
17
+ version: z.string(),
18
+ description: z.string(),
19
+ file: z.string(),
20
+ broken: z.string().optional(),
21
+ candidate: z.boolean().optional(),
22
+ superseded: z.boolean().optional(),
23
+ input: z.record(z.string(), z.unknown()).optional(),
24
+ output: z.unknown().optional(),
25
+ phases: z.array(z.object({ title: z.string(), detail: z.string().optional() })).optional(),
26
+ uses: z.array(z.string()),
27
+ calls: z.array(z.unknown()),
28
+ emits: z.array(z.unknown()).optional(),
29
+ on: z.array(z.unknown()).optional(),
30
+ });
31
+ export const catalogue = {
32
+ list: reference<typeof host.workflowList>("workflow.list"),
33
+ get: {
34
+ name: "workflow.get",
35
+ input: z.object({ id: z.string() }),
36
+ output: z.object({
37
+ id: z.string(),
38
+ description: z.string(),
39
+ builtin: z.unknown().optional(),
40
+ installations: z.array(z.string()),
41
+ versions: z.array(version),
42
+ }),
43
+ },
44
+ check: {
45
+ name: "workflow.check",
46
+ input: z.object({ file: z.string() }),
47
+ output: z.object({
48
+ ok: z.boolean(),
49
+ description: z.string().optional(),
50
+ file: z.string(),
51
+ errors: z.array(problem),
52
+ warnings: z.array(problem).optional(),
53
+ input: z.unknown().optional(),
54
+ output: z.unknown().optional(),
55
+ emits: z.array(z.unknown()).optional(),
56
+ }),
57
+ },
58
+ register: reference<typeof host.workflowRegister>("workflow.register"),
59
+ start: {
60
+ name: "workflow.start",
61
+ input: z.object({
62
+ id: z.string().optional(),
63
+ file: z.string().optional(),
64
+ directory: z.string().optional(),
65
+ label: z.string().optional(),
66
+ args: z.unknown().optional(),
67
+ }),
68
+ output: z.object({ run: z.string() }),
69
+ },
70
+ install: {
71
+ name: "workflow.install",
72
+ input: z.object({ id: z.string(), description: z.string() }),
73
+ output: z.object({ id: z.string() }),
74
+ },
75
+ installation: {
76
+ name: "workflow.installation.get",
77
+ input: z.object({ id: z.string() }),
78
+ output: z.object({ description: z.string(), on: z.array(z.unknown()), builtin: z.unknown().optional() }),
79
+ },
80
+ uninstall: reference<typeof host.workflowUninstall>("workflow.uninstall"),
81
+ stats: reference<typeof workflowStats>("workflow.stats"),
82
+ revise: {
83
+ name: "workflow.revise",
84
+ input: z.object({ run: z.string(), file: z.string() }),
85
+ output: z.object({ revision: z.unknown() }),
86
+ },
87
+ pause: { name: "workflow.pause", input: z.object({ run: z.string() }), output: z.unknown() },
88
+ resume: {
89
+ name: "workflow.resume",
90
+ input: z.object({ run: z.string(), choice: z.enum(["retry", "skip"]) }),
91
+ output: z.unknown(),
92
+ },
93
+ continue: { name: "workflow.continue", input: z.object({ run: z.string(), pause: z.string() }), output: z.unknown() },
94
+ };
95
+
96
+ export const catalogueEvents = { types: ["workflow.*", "request.*", "niwa.invocation.state", "niwa.step.*", "session.turn.*", "session.started", "timer.sleep.requested", "timer.fired"] };
97
+ export const workflowPath = (id: string) => "/workflows/" + encodeURIComponent(id);
@@ -0,0 +1,134 @@
1
+ import { runSummary } from "./run-summary.ts";
2
+ import { PageLink, useCall, useViewer, type HomeTileProps } from "@niwa-labs/cockpit-sdk";
3
+ import { useEffect, useMemo } from "react";
4
+ import { runsAction, type RunEntry } from "./actions.ts";
5
+ import { catalogueEvents } from "./catalogue-actions.ts";
6
+ import { ActivityLabel, MiniPhaseTrack, CopyValue } from "@niwa-labs/ui-kit";
7
+ import { RunTrack } from "./track.tsx";
8
+ import { RunCommands } from "./run-commands.tsx";
9
+
10
+ const groups = [
11
+ ["decision", "Ожидают решения"],
12
+ ["running", "В работе"],
13
+ ["waiting", "Ожидают события"],
14
+ ["finished", "Завершились"],
15
+ ] as const;
16
+ function bucket(run: RunEntry) {
17
+ if (run.state === "finished") return "finished";
18
+ if (run.requests || run.manualPause || run.state === "paused") return "decision";
19
+ return /^(sleep |wait )/.test(run.waiting ?? "") ? "waiting" : "running";
20
+ }
21
+ function useRuns() {
22
+ return useCall(runsAction, {}, { refreshOn: catalogueEvents });
23
+ }
24
+
25
+ export function RunSummary({ project }: HomeTileProps) {
26
+ const runs = useRuns();
27
+ const visible = runs.data?.entries.filter((r) => !project || r.directory === project);
28
+ return (
29
+ <div className="desk-strip">
30
+ {groups.map(([key, title]) => {
31
+ const count = visible?.filter((r) => bucket(r) === key).length;
32
+ return (
33
+ <button
34
+ key={key}
35
+ data-kind={key}
36
+ disabled={!count}
37
+ onClick={() => document.getElementById("group-" + key)?.scrollIntoView({ block: "start" })}
38
+ >
39
+ <span>{title}</span>
40
+ <b>{count ?? "—"}</b>
41
+ <span className="desk-meter" aria-hidden>
42
+ {Array.from({ length: Math.min(count ?? 0, 24) }, (_, i) => (
43
+ <i key={i} />
44
+ ))}
45
+ </span>
46
+ </button>
47
+ );
48
+ })}
49
+ </div>
50
+ );
51
+ }
52
+
53
+ export function DashboardRuns({ project, reportProjects }: HomeTileProps) {
54
+ const runs = useRuns();
55
+ const viewer = useViewer();
56
+ const directories = useMemo(
57
+ () => [...new Set(runs.data?.entries.flatMap((r) => (r.directory ? [r.directory] : [])))],
58
+ [runs.data],
59
+ );
60
+ useEffect(() => reportProjects?.(directories), [directories, reportProjects]);
61
+ const visible = runs.data?.entries.filter((r) => !project || r.directory === project);
62
+ return (
63
+ <section className="desk-section" data-slot="runs-tile">
64
+ <header className="desk-tools">
65
+ <h2>Сценарии</h2>
66
+ {viewer.can("workflow.start") && (
67
+ <PageLink
68
+ className="desk-primary"
69
+ to={"/workflows/launch" + (project ? "?project=" + encodeURIComponent(project) : "")}
70
+ >
71
+ Запустить сценарий
72
+ </PageLink>
73
+ )}
74
+ <PageLink to="/workflows">Каталог сценариев</PageLink>
75
+ </header>
76
+ {runs.error ? (
77
+ <p role="alert">{runs.error.message}</p>
78
+ ) : !visible ? (
79
+ <p>Загружаю запуски…</p>
80
+ ) : (
81
+ !visible.length && <p>Пока нет запусков</p>
82
+ )}
83
+ {groups.map(([key, title]) => {
84
+ const entries = visible?.filter((r) => bucket(r) === key);
85
+ if (!entries?.length) return null;
86
+ return (
87
+ <section className="desk-group" id={"group-" + key} key={key}>
88
+ <h3>
89
+ {title} · {entries.length}
90
+ </h3>
91
+ {entries
92
+ .toSorted((a, b) => b.requestedAt.localeCompare(a.requestedAt))
93
+ .map((r, index) => {
94
+ const compact = entries.length > 4 && index >= 3;
95
+ return (
96
+ <article
97
+ data-slot="run-row"
98
+ data-kind={key}
99
+ key={r.run}
100
+ className={compact ? "desk-run compact-run" : "desk-run"}
101
+ >
102
+ <div className="desk-tools">
103
+ <PageLink to={"/runs/" + r.run}>{r.name}</PageLink>
104
+ {compact && r.phases && (
105
+ <MiniPhaseTrack
106
+ phases={r.phases.map((p) => ({
107
+ ...p,
108
+ activity: p.state === "current" && key === "waiting" ? "timer" : undefined,
109
+ }))}
110
+ />
111
+ )}
112
+ <small title={r.directory}>
113
+ {r.directory?.split("/").filter(Boolean).at(-1)} ·{" "}
114
+ {new Date(r.requestedAt).toLocaleTimeString("ru", { hour: "2-digit", minute: "2-digit" })}
115
+ </small>
116
+ <CopyValue value={r.run}/>
117
+ <RunCommands run={r.run} state={r.state} workflow={r.workflow} compact={compact} />
118
+ </div>
119
+ {compact ? (
120
+ <ActivityLabel activity={key === "waiting" ? "timer" : key === "running" ? "working" : undefined}>
121
+ {r.requests ? <PageLink to="/requests">Ждут ответа · {r.requests}</PageLink> : runSummary(r)}
122
+ </ActivityLabel>
123
+ ) : (
124
+ <RunTrack entry={r} />
125
+ )}
126
+ </article>
127
+ );
128
+ })}
129
+ </section>
130
+ );
131
+ })}
132
+ </section>
133
+ );
134
+ }
@@ -0,0 +1,45 @@
1
+ /** Runs grouped in blocks by the directory they were started for: one block per project. */
2
+
3
+ import type { RunEntry } from "./actions.ts";
4
+
5
+ export type RunGroup = {
6
+ /** The directory, or undefined for the runs that were started with none. */
7
+ directory: string | undefined;
8
+ /** The last part of the path: what the block is called. */
9
+ name: string;
10
+ /** The runs of the block, the latest first. */
11
+ runs: readonly RunEntry[];
12
+ };
13
+
14
+ /** The last part of a path, `/work/niwa` as `niwa`; the path itself for a root. */
15
+ export function directoryName(directory: string): string {
16
+ const parts = directory.split(/[\\/]+/).filter((part) => part !== "");
17
+ return parts.at(-1) ?? directory;
18
+ }
19
+
20
+ const NO_DIRECTORY = "No directory";
21
+
22
+ /**
23
+ * Blocks of runs by directory. A block is ordered by its latest run, the blocks without a directory come last, and
24
+ * inside a block the latest run is first. Two paths that differ only by a trailing separator are one directory.
25
+ */
26
+ export function groupByDirectory(entries: readonly RunEntry[]): RunGroup[] {
27
+ const blocks = new Map<string | undefined, RunEntry[]>();
28
+ for (const entry of entries) {
29
+ const key = entry.directory === undefined || entry.directory === "" ? undefined : entry.directory.replace(/(.)[\\/]+$/, "$1");
30
+ const block = blocks.get(key);
31
+ if (block === undefined) blocks.set(key, [entry]);
32
+ else block.push(entry);
33
+ }
34
+ const latest = (runs: readonly RunEntry[]): string => runs.map((run) => run.requestedAt).sort().at(-1) ?? "";
35
+ return [...blocks.entries()]
36
+ .map(([directory, runs]): RunGroup => ({
37
+ directory,
38
+ name: directory === undefined ? NO_DIRECTORY : directoryName(directory),
39
+ runs: [...runs].sort((a, b) => b.requestedAt.localeCompare(a.requestedAt)),
40
+ }))
41
+ .sort((a, b) => {
42
+ if ((a.directory === undefined) !== (b.directory === undefined)) return a.directory === undefined ? 1 : -1;
43
+ return latest(b.runs).localeCompare(latest(a.runs));
44
+ });
45
+ }
@@ -0,0 +1,50 @@
1
+ /** The cockpit module of the workflow plugin: its runs on the home page, the list of runs and the page of one run. */
2
+
3
+ import { definePlugin, PageLink, useViewer } from "@niwa-labs/cockpit-sdk";
4
+
5
+ import { RunPage } from "./run-page.tsx";
6
+ import { LaunchPage } from "./launch.tsx";
7
+ import { WorkflowCatalogue, WorkflowDetails } from "./workflows.tsx";
8
+ import { DashboardRuns, RunSummary } from "./dashboard.tsx";
9
+ import { Runs } from "./runs.tsx";
10
+
11
+ function RunsPage() {
12
+ const viewer = useViewer();
13
+ return (
14
+ <div className="desk-page">
15
+ <header className="desk-heading">
16
+ <h1>Запуски по проектам</h1>
17
+ <div className="desk-tools">
18
+ <PageLink to="/workflows">Каталог сценариев</PageLink>
19
+ {viewer.can("workflow.start") && (
20
+ <PageLink className="desk-primary" to="/workflows/launch">
21
+ Запустить сценарий
22
+ </PageLink>
23
+ )}
24
+ </div>
25
+ </header>
26
+ <Runs />
27
+ </div>
28
+ );
29
+ }
30
+
31
+ export default definePlugin({
32
+ id: "workflow",
33
+ setup(ctx) {
34
+ ctx.pages.add({ path: "/runs", title: "Запуски", nav: { order: 10 }, component: RunsPage });
35
+ ctx.pages.add({ path: "/runs/$runId", panel: true, title: "Запуск", component: RunPage });
36
+ ctx.pages.add({ path: "/workflows", title: "Сценарии", nav: { order: 9 }, component: WorkflowCatalogue });
37
+ ctx.pages.add({ path: "/workflows/launch", panel: true, title: "Запустить workflow", component: LaunchPage });
38
+ ctx.pages.add({ path: "/workflows/$workflowId", panel: true, title: "Сценарий", component: WorkflowDetails });
39
+ if (ctx.viewer.can("workflow.runs")) {
40
+ ctx.slots.register("home.summary", { key: "states", component: RunSummary });
41
+ ctx.slots.register("home.main", { key: "runs", order: 0, component: DashboardRuns });
42
+ }
43
+ ctx.entities.register("workflow", {
44
+ label: "Сценарий",
45
+ prefix: "wf",
46
+ href: (id) => "/workflows/" + encodeURIComponent(id),
47
+ });
48
+ ctx.entities.register("run", { label: "Запуск", prefix: "run", href: (id) => `/runs/${encodeURIComponent(id)}` });
49
+ },
50
+ });
@@ -0,0 +1,136 @@
1
+ import {
2
+ SchemaFields,
3
+ readFields,
4
+ type FormSchema,
5
+ PageLink,
6
+ useAction,
7
+ useCall,
8
+ useNavigate,
9
+ useViewer,
10
+ type PageProps,
11
+ } from "@niwa-labs/cockpit-sdk";
12
+ import { useState, type FormEvent } from "react";
13
+ import { inspectAction as catalogueRunArgs } from "./actions.ts";
14
+ import { catalogue, catalogueEvents } from "./catalogue-actions.ts";
15
+
16
+ const FILE_ARGS: FormSchema = {
17
+ title: "Аргументы",
18
+ type: ["object", "array", "string", "number", "boolean", "null"],
19
+ };
20
+
21
+ export function LaunchPage({ search }: PageProps) {
22
+ const viewer = useViewer();
23
+ const navigate = useNavigate();
24
+ const [id, setId] = useState(search.id ?? "");
25
+ const [error, setError] = useState("");
26
+ const list = useCall(catalogue.list, {}, { enabled: viewer.can(catalogue.list), refreshOn: catalogueEvents });
27
+ const entity = useCall(
28
+ catalogue.get,
29
+ { id },
30
+ { enabled: !!id && viewer.can(catalogue.get), refreshOn: catalogueEvents },
31
+ );
32
+ const start = useAction(catalogue.start);
33
+ const latest = entity.data?.versions.filter((v) => !v.candidate && !v.superseded).at(-1);
34
+ const fields = latest?.input as FormSchema | undefined;
35
+ const original = useCall(
36
+ catalogueRunArgs,
37
+ { run: search.run ?? "" },
38
+ { enabled: !!search.run && viewer.can(catalogueRunArgs) },
39
+ );
40
+ const previous = original.data?.origin;
41
+ const args = previous?.args;
42
+ const showArguments = !!fields || !id || args !== undefined;
43
+ const schema = fields ?? FILE_ARGS;
44
+ const submit = (event: FormEvent<HTMLFormElement>) => {
45
+ event.preventDefault();
46
+ if (start.isPending) return;
47
+ const form = new FormData(event.currentTarget);
48
+ const label = String(form.get("label") ?? "").trim();
49
+ const directory = String(form.get("directory") ?? "").trim();
50
+ try {
51
+ const file = String(form.get("file") ?? "").trim();
52
+ if (!id && !file) throw new Error("Укажите файл сценария.");
53
+ const input = showArguments ? readFields(schema, form) : undefined;
54
+ setError("");
55
+ start.mutate(
56
+ {
57
+ ...(id ? { id } : { file }),
58
+ ...(input === undefined ? {} : { args: input }),
59
+ ...(label ? { label } : {}),
60
+ ...(directory ? { directory } : {}),
61
+ },
62
+ { onSuccess: (result) => navigate("/runs/" + encodeURIComponent(result.run)) },
63
+ );
64
+ } catch (error) {
65
+ setError(error instanceof Error ? error.message : "Проверьте аргументы запуска.");
66
+ }
67
+ };
68
+ return (
69
+ <article className="desk-page">
70
+ <PageLink to="/workflows">← Сценарии</PageLink>
71
+ <h1>Запустить сценарий</h1>
72
+ {!viewer.can(catalogue.start) ? (
73
+ <p>Нет доступа к запуску.</p>
74
+ ) : (
75
+ <form className="desk-form" onSubmit={submit} key={previous?.requestedAt ?? ""}>
76
+ <label>
77
+ Сценарий
78
+ <select
79
+ value={id}
80
+ onChange={(event) => {
81
+ setId(event.target.value);
82
+ setError("");
83
+ start.reset();
84
+ }}
85
+ >
86
+ <option value="">Локальный файл TypeScript</option>
87
+ {list.data?.items.map((item) => (
88
+ <option key={item.id} value={item.id} disabled={item.broken}>
89
+ {item.description} · {item.id}
90
+ </option>
91
+ ))}
92
+ </select>
93
+ </label>
94
+ {list.error && <p role="alert">{list.error.message}</p>}
95
+ {!id && (
96
+ <label>
97
+ Файл на хосте
98
+ <input name="file" placeholder="/путь/workflow.ts" defaultValue={previous?.file ?? ""} required />
99
+ </label>
100
+ )}
101
+ <label>
102
+ Название запуска
103
+ <input name="label" defaultValue={previous?.label ?? ""} placeholder="По имени сценария" />
104
+ </label>
105
+ <label>
106
+ Проект
107
+ <input
108
+ name="directory"
109
+ defaultValue={search.project ?? previous?.directory ?? ""}
110
+ placeholder="/путь/к/проекту"
111
+ />
112
+ </label>
113
+ {showArguments && (
114
+ <fieldset key={id + (latest?.version ?? "")}>
115
+ <SchemaFields schema={schema} initial={args} optional={!fields} />
116
+ </fieldset>
117
+ )}
118
+ {entity.error && <p role="alert">{entity.error.message}</p>}
119
+ {latest?.broken && <p role="alert">{latest.broken}</p>}
120
+ {!!latest?.on?.length && <p>Этот сценарий запускается по подписке.</p>}
121
+ {(error || start.error) && <p role="alert">{error || start.error?.message}</p>}
122
+ <button
123
+ className="desk-primary"
124
+ disabled={
125
+ start.isPending ||
126
+ (!!search.run && original.isLoading) ||
127
+ (!!id && (!latest || !!latest.broken || !!latest.on?.length))
128
+ }
129
+ >
130
+ ▶ Запустить
131
+ </button>
132
+ </form>
133
+ )}
134
+ </article>
135
+ );
136
+ }