@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,159 @@
1
+ import { runSummary } from "./run-summary.ts";
2
+ import { EntityLink, PageLink, useCall, useViewer } from "@niwa-labs/cockpit-sdk";
3
+ import {
4
+ ActivityLabel,
5
+ DataValue,
6
+ ExecutionTrack,
7
+ type Activity,
8
+ type ExecutionPhase,
9
+ type ExecutionStep,
10
+ } from "@niwa-labs/ui-kit";
11
+ import { z } from "zod";
12
+ import { inspectAction, type Inspection, type RunEntry, type Step } from "./actions.ts";
13
+ import { catalogueEvents } from "./catalogue-actions.ts";
14
+ import { phaseState, stepState } from "./plan.ts";
15
+
16
+ function kindOf(s: Step): ExecutionStep["kind"] {
17
+ if (s.session || s.action.startsWith("session.start") || s.action === "session.ask") return "agent";
18
+ if (s.action === "request.ask") return "question";
19
+ if (s.waitEvent?.startsWith("timer.")) return "timer";
20
+ if (s.waitEvent || ["niwa.wait", "workflow.script.wait"].includes(s.action)) return "wait";
21
+ return "action";
22
+ }
23
+ function runActivity(status: Inspection["status"], open: Step[]): Activity | undefined {
24
+ if (status.state === "finished") return undefined;
25
+ if (status.manualPause) return "paused";
26
+ if (status.requests.length) return "human";
27
+ if (status.state === "paused") return "paused";
28
+ if (open.length && open.every((s) => ["wait", "timer"].includes(kindOf(s)))) return "timer";
29
+ return open.length ? "working" : "starting";
30
+ }
31
+
32
+ const schedule = {
33
+ name: "timer.list",
34
+ input: z.object({}),
35
+ output: z.object({ timers: z.array(z.object({ name: z.string(), nextDue: z.number().nullable() })) }),
36
+ };
37
+ type Timers = z.infer<typeof schedule.output>["timers"];
38
+ function executionStep(s: Step, status: Inspection["status"], timers: Timers, answerStep: Step | undefined): ExecutionStep {
39
+ const kind = kindOf(s);
40
+ const live =
41
+ status.state === "running" && !status.manualPause && s.status === "running" && !s.historical && !s.endedAt;
42
+ const activity = live
43
+ ? ({ agent: "working", action: "working", timer: "timer", question: "human", wait: undefined } as const)[kind]
44
+ : undefined;
45
+ const label = s.label === s.action && kind === "question" ? "Ответ владельца" : s.label || s.action;
46
+ let title = <PageLink to={"/journal?record=" + encodeURIComponent(s.id)}>{label}</PageLink>;
47
+ if (s.session) title = <EntityLink entity={{ kind: "session", id: s.session }} label={label} />;
48
+ if (s.id === answerStep?.id)
49
+ title = <PageLink to={"/requests/" + encodeURIComponent(status.requests[0]!)}>Ответить · {label}</PageLink>;
50
+ const scheduled =
51
+ s.timerName === undefined
52
+ ? []
53
+ : timers.flatMap((t) => ((!s.timerName || s.timerName === t.name) && t.nextDue !== null ? [t.nextDue] : []));
54
+ const due = Math.min(s.dueAt ? Date.parse(s.dueAt) : Infinity, ...scheduled);
55
+ return {
56
+ id: s.id,
57
+ title,
58
+ kind,
59
+ state: stepState(s),
60
+ activity,
61
+ detail: s.prompt,
62
+ branch: s.branch,
63
+ start: Date.parse(s.startedAt),
64
+ end: s.endedAt ? Date.parse(s.endedAt) : undefined,
65
+ due: Number.isFinite(due) ? due : undefined,
66
+ };
67
+ }
68
+
69
+ function describeRun(status: Inspection["status"], activity: Activity | undefined, open: Step[]) {
70
+ if (status.outcome?.status === "failed") return status.outcome.error.message;
71
+ if (status.outcome?.status === "cancelled") return "Остановлен";
72
+ if (status.state === "finished") return "Выполнение окончено";
73
+ if (status.reason) return status.reason;
74
+ if (activity === "human") return "Ждёт ответа владельца";
75
+ if (activity === "timer") return open.some((s) => kindOf(s) === "timer") ? "Ждёт таймер" : "Ждёт события";
76
+ if (activity === "paused") return "На паузе";
77
+ return status.waiting ?? "Запуск выполняется";
78
+ }
79
+
80
+ export function InspectedTrack({ inspection, detail = false }: { inspection: Inspection; detail?: boolean }) {
81
+ const { status } = inspection;
82
+ const all = [...inspection.steps, ...inspection.phases.flatMap((p) => p.steps)];
83
+ const open = all.filter((s) => !s.historical && !s.endedAt && s.status === "running");
84
+ const viewer = useViewer();
85
+ const schedules = useCall(
86
+ schedule,
87
+ {},
88
+ { enabled: viewer.can(schedule) && open.some((s) => s.timerName !== undefined), refreshOn: { types: ["timer.*"] } },
89
+ );
90
+ const timers = schedules.data?.timers ?? [];
91
+ const activity = runActivity(status, open);
92
+ const questions = open.filter(step => kindOf(step) === "question");
93
+ const answerStep = status.state === "running" && !status.manualPause && status.requests.length === 1 && questions.length === 1
94
+ ? questions[0] : undefined;
95
+ const phases: ExecutionPhase[] = inspection.phases.map((p) => {
96
+ const active = open.filter((s) => s.phase === p.title);
97
+ return {
98
+ id: p.title,
99
+ title: p.title,
100
+ detail: p.detail,
101
+ state: phaseState(p, status),
102
+ activity: p.state === "current" ? runActivity(status, active) : undefined,
103
+ steps: p.steps.map((s) => executionStep(s, status, timers, answerStep)),
104
+ };
105
+ });
106
+ const looseSteps = inspection.steps.map(s => executionStep(s, status, timers, answerStep));
107
+ const why = describeRun(status, activity, open);
108
+ return (
109
+ <>
110
+ {phases.length || looseSteps.length ? (
111
+ <ExecutionTrack
112
+ phases={phases}
113
+ looseSteps={looseSteps}
114
+ detail={detail}
115
+ observedAt={inspection.observedAt ? Date.parse(inspection.observedAt) : undefined}
116
+ />
117
+ ) : (
118
+ <p>{status.state === "finished" ? "Фазы не записаны" : "Ожидает первого шага"}</p>
119
+ )}
120
+ {!answerStep && <p className="nw-run-status">
121
+ {status.requests.length ? <PageLink to={status.requests.length === 1 ? "/requests/"+encodeURIComponent(status.requests[0]!) : "/requests"}>Ждут ответа · {status.requests.length}</PageLink> : <ActivityLabel activity={activity}>{why}</ActivityLabel>}
122
+ </p>}
123
+ {!detail && status.outcome?.status === "done" && status.outcome.result != null &&
124
+ <details className="nw-run-result"><summary>Результат запуска</summary><DataValue value={status.outcome.result} /></details>}
125
+ </>
126
+ );
127
+ }
128
+
129
+ export function RunTrack({ entry }: { entry: RunEntry }) {
130
+ const viewer = useViewer();
131
+ const inspection = useCall(
132
+ inspectAction,
133
+ { run: entry.run },
134
+ { enabled: viewer.can(inspectAction), refreshOn: catalogueEvents },
135
+ );
136
+ if (inspection.data) return <InspectedTrack inspection={inspection.data} />;
137
+ const phases: ExecutionPhase[] = (entry.phases ?? []).map((p) => ({
138
+ id: p.title,
139
+ title: p.title,
140
+ detail: p.detail,
141
+ state:
142
+ p.state === "ahead"
143
+ ? "pending"
144
+ : p.state === "done"
145
+ ? "done"
146
+ : entry.state === "paused"
147
+ ? "waiting"
148
+ : entry.state === "finished"
149
+ ? "stopped"
150
+ : "running",
151
+ steps: [],
152
+ }));
153
+ return (
154
+ <>
155
+ {!!phases.length && <ExecutionTrack phases={phases} />}
156
+ <p>{entry.requests ? <PageLink to="/requests">Ждут ответа · {entry.requests}</PageLink> : inspection.error?.message ?? runSummary(entry)}</p>
157
+ </>
158
+ );
159
+ }
@@ -0,0 +1,383 @@
1
+ import { runSummary } from "./run-summary.ts";
2
+ import { SchemaView, DataValue, CopyValue, FileRef } from "@niwa-labs/ui-kit";
3
+ import { PageHeading, PageSection } from "@niwa-labs/ui-kit";
4
+ import { PageLink, useAction, useCall, useViewer, type PageProps } from "@niwa-labs/cockpit-sdk";
5
+ import { useState } from "react";
6
+ import { useQueryClient } from "@tanstack/react-query";
7
+ import { catalogue, catalogueEvents, workflowPath } from "./catalogue-actions.ts";
8
+ import { Statistics } from "./statistics.tsx";
9
+ import { runsAction } from "./actions.ts";
10
+
11
+ function Contract({ title, value }: { title: string; value: unknown }) {
12
+ if (value === undefined || (Array.isArray(value) && value.length === 0)) return null;
13
+ return (
14
+ <details className="nw-contract" open={title === "Вход"}>
15
+ <summary>{title}</summary>
16
+ {title === "Вход" || title === "Выход" ? <SchemaView schema={value} /> : <DataValue value={value} />}
17
+ </details>
18
+ );
19
+ }
20
+
21
+ export function WorkflowCatalogue({ search }: PageProps<"/workflows">) {
22
+ const viewer = useViewer();
23
+ const client = useQueryClient();
24
+ const list = useCall(catalogue.list, {}, { enabled: viewer.can(catalogue.list), refreshOn: catalogueEvents });
25
+ const check = useAction(catalogue.check);
26
+ const register = useAction(catalogue.register);
27
+ const [query, setQuery] = useState("");
28
+ const [file, setFile] = useState("");
29
+ const [id, setId] = useState("");
30
+ const busy = check.isPending || register.isPending;
31
+ const tabs = [
32
+ { key: "catalogue", label: "Каталог", allowed: viewer.can(catalogue.list) },
33
+ { key: "statistics", label: "Статистика", allowed: viewer.can(catalogue.stats) },
34
+ { key: "register", label: "Регистрация", allowed: viewer.can(catalogue.check) || viewer.can(catalogue.register) },
35
+ ].filter((tab) => tab.allowed);
36
+ const current = tabs.find((tab) => tab.key === search.view)?.key ?? tabs[0]?.key;
37
+ const needle = query.trim().toLowerCase();
38
+ const matches = list.data?.items.filter((w) =>
39
+ [w.description, w.id, w.builtin?.name, ...(w.phases ?? []).map((p) => p.title)]
40
+ .join(" ")
41
+ .toLowerCase()
42
+ .includes(needle),
43
+ );
44
+ return (
45
+ <article className="desk-page" data-slot="workflows">
46
+ <PageHeading title="Сценарии">
47
+ {viewer.can(catalogue.start) && (
48
+ <PageLink to="/workflows/launch" className="desk-primary">
49
+ Запустить сценарий
50
+ </PageLink>
51
+ )}
52
+ </PageHeading>
53
+ <nav className="nw-tabs" aria-label="Разделы сценариев">
54
+ {tabs.map((tab) => (
55
+ <PageLink
56
+ key={tab.key}
57
+ to={tab.key === "catalogue" ? "/workflows" : "/workflows?view=" + tab.key}
58
+ aria-current={current === tab.key ? "page" : undefined}
59
+ >
60
+ {tab.label}
61
+ </PageLink>
62
+ ))}
63
+ </nav>
64
+ {!current && <p>Нет доступных разделов сценариев.</p>}
65
+ {current === "catalogue" && (
66
+ <PageSection title={<>Зарегистрированные сценарии {list.data && <small>{list.data.items.length}</small>}</>}>
67
+ <label className="nw-search">
68
+ <span>Найти сценарий</span>
69
+ <input
70
+ type="search"
71
+ value={query}
72
+ onChange={(e) => setQuery(e.target.value)}
73
+ placeholder="Название, фаза или ID"
74
+ />
75
+ </label>
76
+ {!viewer.can(catalogue.list) ? (
77
+ <p>Каталог недоступен для этого пользователя.</p>
78
+ ) : list.error ? (
79
+ <p role="alert">{list.error.message}</p>
80
+ ) : !list.data ? (
81
+ <p>Загружаю сценарии…</p>
82
+ ) : !list.data.items.length ? (
83
+ <p>Сценариев ещё нет. Зарегистрируйте файл сценария.</p>
84
+ ) : (
85
+ <div className="desk-catalogue">
86
+ {matches?.map((w) => (
87
+ <article key={w.id} className="desk-card">
88
+ <PageLink to={workflowPath(w.id)}>{w.description}</PageLink>
89
+ {w.candidate && (
90
+ <span className="nw-tag" data-tone="amber">
91
+ Кандидат
92
+ </span>
93
+ )}{" "}
94
+ <CopyValue value={w.id} />
95
+ <small>
96
+ Версия {w.version.slice(0, 8)} · версий {w.versions} · установок {w.installations.length}
97
+ </small>
98
+ {!!w.phases?.length && <p>{w.phases.map((p) => p.title).join(" → ")}</p>}
99
+ {w.broken && <p role="alert">Сценарий требует исправления</p>}
100
+ </article>
101
+ ))}
102
+ {!matches?.length && <p>Совпадений нет.</p>}
103
+ </div>
104
+ )}
105
+ </PageSection>
106
+ )}
107
+ {current === "statistics" && <Statistics />}
108
+ {current === "register" && (
109
+ <PageSection title="Файл сценария">
110
+ <form
111
+ className="desk-form"
112
+ onSubmit={(event) => {
113
+ event.preventDefault();
114
+ if (busy) return;
115
+ const submitter = (event.nativeEvent as SubmitEvent).submitter as HTMLButtonElement | null;
116
+ if (submitter?.value === "register")
117
+ register.mutate(
118
+ { file: file.trim(), ...(id ? { id } : {}) },
119
+ { onSuccess: () => void client.invalidateQueries({ queryKey: ["niwa", "call"] }) },
120
+ );
121
+ else if (viewer.can(catalogue.check)) check.mutate({ file: file.trim() });
122
+ }}
123
+ >
124
+ <label>
125
+ Файл сценария на хосте
126
+ <input
127
+ value={file}
128
+ onChange={(e) => {
129
+ setFile(e.target.value);
130
+ check.reset();
131
+ register.reset();
132
+ }}
133
+ required
134
+ placeholder="/путь/workflow.ts"
135
+ />
136
+ </label>
137
+ {viewer.can(catalogue.register) && (
138
+ <label>
139
+ Зарегистрировать как
140
+ <select
141
+ value={id}
142
+ onChange={(e) => {
143
+ setId(e.target.value);
144
+ register.reset();
145
+ }}
146
+ >
147
+ <option value="">Новый сценарий</option>
148
+ {list.data?.items
149
+ .filter((w) => !w.builtin)
150
+ .map((w) => (
151
+ <option key={w.id} value={w.id}>
152
+ {w.description} · {w.id}
153
+ </option>
154
+ ))}
155
+ </select>
156
+ </label>
157
+ )}
158
+ <div className="desk-tools">
159
+ {viewer.can(catalogue.check) && (
160
+ <button value="check" disabled={busy}>
161
+ Проверить
162
+ </button>
163
+ )}
164
+ {viewer.can(catalogue.register) && (
165
+ <button value="register" disabled={busy}>
166
+ Зарегистрировать
167
+ </button>
168
+ )}
169
+ </div>
170
+ </form>
171
+ {check.data && (
172
+ <div role="status">
173
+ <strong>{check.data.ok ? "Проверка пройдена" : "Ошибка проверки"}</strong> ·{" "}
174
+ <FileRef path={check.data.file} />
175
+ {[...check.data.errors, ...(check.data.warnings ?? [])].map((e, i) => (
176
+ <p key={i}>
177
+ <FileRef path={e.file} /> · строка {e.line}, столбец {e.column} · {e.message}
178
+ </p>
179
+ ))}
180
+ <p>{check.data.description}</p>
181
+ <Contract title="Вход" value={check.data.input} />
182
+ <Contract title="Выход" value={check.data.output} />
183
+ <Contract title="События" value={check.data.emits} />
184
+ </div>
185
+ )}
186
+ {register.data && (
187
+ <p role="status">
188
+ {register.data.added ? "Зарегистрирована версия" : "Уже зарегистрирована"}{" "}
189
+ {register.data.version.slice(0, 8)} ·{" "}
190
+ <PageLink to={workflowPath(register.data.id)}>{register.data.description}</PageLink>
191
+ {register.data.rechecked.map((r) => (
192
+ <span key={r.id}>
193
+ {" "}
194
+ · {r.id} {r.ok ? "✓" : "сломан"}
195
+ </span>
196
+ ))}
197
+ </p>
198
+ )}
199
+ {(check.error || register.error) && <p role="alert">{(check.error ?? register.error)?.message}</p>}
200
+ </PageSection>
201
+ )}
202
+ </article>
203
+ );
204
+ }
205
+
206
+ function Installation({ id, builtin }: { id: string; builtin: boolean }) {
207
+ const viewer = useViewer();
208
+ const client = useQueryClient();
209
+ const got = useCall(
210
+ catalogue.installation,
211
+ { id },
212
+ { enabled: viewer.can(catalogue.installation), refreshOn: catalogueEvents },
213
+ );
214
+ const remove = useAction(catalogue.uninstall);
215
+ return (
216
+ <li>
217
+ <b>{got.data?.description ?? id}</b> <CopyValue value={id} />
218
+ {got.data && <Contract title="Условия запуска" value={got.data.on} />}
219
+ {got.error && <p role="alert">{got.error.message}</p>}
220
+ {!builtin && viewer.can(catalogue.uninstall) && (
221
+ <button
222
+ disabled={remove.isPending}
223
+ onClick={() => {
224
+ if (window.confirm("Снять установку " + id + "?"))
225
+ remove.mutate({ id }, { onSuccess: () => void client.invalidateQueries({ queryKey: ["niwa", "call"] }) });
226
+ }}
227
+ >
228
+ Снять установку
229
+ </button>
230
+ )}
231
+ {remove.error && <p role="alert">{remove.error.message}</p>}
232
+ </li>
233
+ );
234
+ }
235
+
236
+ export function WorkflowDetails({ params }: PageProps<"/workflows/$workflowId">) {
237
+ const id = params.workflowId;
238
+ const viewer = useViewer();
239
+ const got = useCall(catalogue.get, { id }, { enabled: viewer.can(catalogue.get), refreshOn: catalogueEvents });
240
+ const history = useCall(runsAction, {}, { enabled: viewer.can(runsAction), refreshOn: catalogueEvents });
241
+ const install = useAction(catalogue.install);
242
+ const client = useQueryClient();
243
+ const entity = got.data;
244
+ if (!entity)
245
+ return (
246
+ <article className="desk-page">
247
+ <PageLink className="nw-parent" to="/workflows">
248
+ ← Сценарии
249
+ </PageLink>
250
+ <p>{!viewer.can(catalogue.get) ? "Нет доступа к сценарию." : (got.error?.message ?? "Загружаю сценарий…")}</p>
251
+ </article>
252
+ );
253
+ const latest = entity.versions.filter((v) => !v.candidate && !v.superseded).at(-1);
254
+ const runs = history.data?.entries.filter((r) => r.workflow === id);
255
+ return (
256
+ <article className="desk-page" data-slot="workflow-detail">
257
+ <PageLink className="nw-parent" to="/workflows">
258
+ ← Сценарии
259
+ </PageLink>
260
+ <header className="desk-heading">
261
+ <div>
262
+ <h1>
263
+ {(latest ?? entity.versions.at(-1))?.file
264
+ .split(/[\\/]/)
265
+ .at(-1)
266
+ ?.replace(/\.[^.]+$/, "") ?? entity.description}
267
+ </h1>
268
+ <p className="nw-purpose">{entity.description}</p>
269
+ <CopyValue value={id} />
270
+ </div>
271
+ {viewer.can(catalogue.start) && latest && !latest.broken && !latest.on?.length && (
272
+ <PageLink to={"/workflows/launch?id=" + encodeURIComponent(id)} className="desk-primary">
273
+ ▶ Запустить
274
+ </PageLink>
275
+ )}
276
+ </header>
277
+ <section className="desk-section">
278
+ <h2>
279
+ Версии <small>{entity.versions.length}</small>
280
+ </h2>
281
+ {entity.versions.toReversed().map((v) => (
282
+ <details
283
+ className="desk-version"
284
+ key={v.version}
285
+ open={v.version === (latest ?? entity.versions.at(-1))?.version}
286
+ >
287
+ <summary>
288
+ <span className="nw-tag" data-tone="blue">
289
+ {v.version.slice(0, 8)}
290
+ </span>{" "}
291
+ {v.superseded
292
+ ? "Заменена"
293
+ : v.candidate
294
+ ? "Кандидат"
295
+ : v.version === latest?.version
296
+ ? "Текущая версия"
297
+ : v.description}
298
+ </summary>
299
+ <div className="nw-file-row">
300
+ <FileRef path={v.file} />
301
+ <CopyValue value={v.version} label="Хеш версии" />
302
+ </div>
303
+ {v.candidate && (
304
+ <p className="nw-candidate">До принятия эта версия доступна только для проверочного запуска комплекта.</p>
305
+ )}
306
+ {v.broken && <p role="alert">{v.broken}</p>}
307
+ {!!v.phases?.length && (
308
+ <ol className="desk-phases">
309
+ {v.phases.map((p) => (
310
+ <li key={p.title}>
311
+ <b>{p.title}</b>
312
+ {p.detail && <small>{p.detail}</small>}
313
+ </li>
314
+ ))}
315
+ </ol>
316
+ )}
317
+ <Contract title="Вход" value={v.input} />
318
+ <Contract title="Выход" value={v.output} />
319
+ <Contract title="События" value={v.emits} />
320
+ <Contract title="Разрешения" value={v.uses} />
321
+ <Contract title="Вызывает" value={v.calls} />
322
+ <Contract title="Триггеры" value={v.on} />
323
+ </details>
324
+ ))}
325
+ </section>
326
+ <section className="desk-section">
327
+ <h2>
328
+ Установки <small>{entity.installations.length}</small>
329
+ </h2>
330
+ {!entity.installations.length && (
331
+ <p>{latest?.on?.length ? "Подписок пока нет." : "У этой версии нет подписок."}</p>
332
+ )}
333
+ <ul>
334
+ {entity.installations.map((sub) => (
335
+ <Installation key={sub} id={sub} builtin={!!entity.builtin} />
336
+ ))}
337
+ </ul>
338
+ {viewer.can(catalogue.install) && !!latest?.on?.length && !latest.broken && (
339
+ <form
340
+ className="desk-form"
341
+ onSubmit={(e) => {
342
+ e.preventDefault();
343
+ const data = new FormData(e.currentTarget);
344
+ install.mutate(
345
+ { id, description: String(data.get("description")).trim() },
346
+ { onSuccess: () => void client.invalidateQueries({ queryKey: ["niwa", "call"] }) },
347
+ );
348
+ }}
349
+ >
350
+ <label>
351
+ Описание установки
352
+ <input name="description" minLength={3} maxLength={60} required />
353
+ </label>
354
+ <button disabled={install.isPending}>Установить последнюю версию</button>
355
+ {install.error && <p role="alert">{install.error.message}</p>}
356
+ </form>
357
+ )}
358
+ </section>
359
+ {viewer.can(runsAction) && (
360
+ <section className="desk-section">
361
+ <h2>Запуски</h2>
362
+ {history.error ? (
363
+ <p role="alert">{history.error.message}</p>
364
+ ) : !runs ? (
365
+ <p>Загружаю…</p>
366
+ ) : runs.length ? (
367
+ runs.map((r) => (
368
+ <p key={r.run}>
369
+ <PageLink to={"/runs/" + r.run}>
370
+ {r.name} · {r.run}
371
+ </PageLink>{" "}
372
+ · {runSummary(r)}
373
+ </p>
374
+ ))
375
+ ) : (
376
+ <p>Запусков по этому сценарию ещё не было.</p>
377
+ )}
378
+ </section>
379
+ )}
380
+ {viewer.can(catalogue.stats) && <Statistics key={id} id={id} versions={entity.versions.map((v) => v.version)} />}
381
+ </article>
382
+ );
383
+ }
@@ -0,0 +1,122 @@
1
+ /**
2
+ * What a script declares, read once for one version of its code.
3
+ *
4
+ * Reading a module is a process of its own (`describe.ts`), and a check, an install, a registration and the start
5
+ * of a run each ask for it. The same code declares the same thing, so what was read is kept under the version of the
6
+ * script, the hash of its source closure (`registry.ts`): an edit of the script or of a file it imports is another
7
+ * version, and is read again. A version a registration of the journal holds is known without reading it.
8
+ *
9
+ * Only what a module did declare is kept; a module that could not be read is read again by the next ask. The box
10
+ * is part of the key: a module that reads outside its folder is read in a box, and fails there.
11
+ *
12
+ * The readings that are going are bounded: each is a process, and the checker shares the cores with them.
13
+ */
14
+
15
+ import type { WorkflowVersion } from "./records.ts";
16
+ import { versionOf } from "./registry.ts";
17
+ import { describeScript } from "./describe.ts";
18
+ import type { DescribeResult, Described } from "./describe.ts";
19
+ import type { ScriptBox } from "./runner.ts";
20
+
21
+ /** Read a script's module: `describeScript`, or what stands in for it. */
22
+ export type ReadModule = (file: string, box?: ScriptBox, run?: string) => Promise<DescribeResult>;
23
+
24
+ /** How many modules are read at once. */
25
+ const READ_BOUND = 4;
26
+
27
+ /** How many versions are kept. */
28
+ const KEPT_LIMIT = 256;
29
+
30
+ /** Run the work when fewer than `bound` are going; the rest wait their turn, in the order they came. */
31
+ function bounded(bound: number): <T>(work: () => Promise<T>) => Promise<T> {
32
+ let going = 0;
33
+ const waiting: Array<() => void> = [];
34
+ return async (work) => {
35
+ // A slot that is handed over stays counted: it goes from the one that ends to the one that waited longest.
36
+ if (going >= bound) await new Promise<void>((turn) => waiting.push(turn));
37
+ else going += 1;
38
+ try {
39
+ return await work();
40
+ } finally {
41
+ const next = waiting.shift();
42
+ if (next === undefined) going -= 1;
43
+ else next();
44
+ }
45
+ };
46
+ }
47
+
48
+ /** The version of the script, or none when a file of it cannot be read: the module then says what stops it. */
49
+ function versionNow(file: string): WorkflowVersion | undefined {
50
+ try {
51
+ return versionOf(file);
52
+ } catch {
53
+ return undefined;
54
+ }
55
+ }
56
+
57
+ /** What has been read: by version and box, what the modules declared, and the readings that are going. */
58
+ export interface Readings {
59
+ readonly kept: Map<string, Described>;
60
+ readonly going: Map<string, Promise<DescribeResult>>;
61
+ /** Hold a reading to its turn. */
62
+ readonly turn: <T>(work: () => Promise<T>) => Promise<T>;
63
+ }
64
+
65
+ /** The readings of a store of its own. */
66
+ export const readings = (bound: number = READ_BOUND): Readings => ({ kept: new Map(), going: new Map(), turn: bounded(bound) });
67
+
68
+ /** The readings of the process: every host in it asks the same cores. */
69
+ const shared = readings();
70
+
71
+ /** What a describer is given. */
72
+ export interface DescriberOptions {
73
+ /** How a module is read; the process of `describeScript` by default. */
74
+ read?: ReadModule;
75
+ /** Where the readings are kept; the process's own by default. */
76
+ readings?: Readings;
77
+ /** What a version declared, when the journal says so: it is then not read. */
78
+ known?: (version: WorkflowVersion, boxed: boolean) => Described | undefined;
79
+ }
80
+
81
+ /** A reading of what a script declares: from what was kept for its version, or from its module. */
82
+ export type Describer = (file: string, box?: ScriptBox, run?: string) => Promise<DescribeResult>;
83
+
84
+ /** A describer over the readings of the process, or over the ones it is given. */
85
+ export function describer(options: DescriberOptions = {}): Describer {
86
+ const read = options.read ?? describeScript;
87
+ const { kept, going, turn } = options.readings ?? shared;
88
+ const remember = (key: string, described: Described): void => {
89
+ if (kept.size >= KEPT_LIMIT) {
90
+ for (const oldest of kept.keys()) {
91
+ kept.delete(oldest);
92
+ break;
93
+ }
94
+ }
95
+ kept.set(key, described);
96
+ };
97
+ return async (file, box, run) => {
98
+ const version = versionNow(file);
99
+ // A script that cannot be read has no version: the module says what stopped it.
100
+ if (version === undefined) return turn(() => read(file, box, run));
101
+ const key = `${version}:${box === undefined ? "plain" : "boxed"}`;
102
+ const had = kept.get(key);
103
+ if (had !== undefined) return { described: had };
104
+ const registered = options.known?.(version, box !== undefined);
105
+ if (registered !== undefined) {
106
+ remember(key, registered);
107
+ return { described: registered };
108
+ }
109
+ let reading = going.get(key);
110
+ if (reading === undefined) {
111
+ reading = turn(() => read(file, box, run))
112
+ .then((result) => {
113
+ // A file edited while it was read has another version now: what was read says nothing of it.
114
+ if ("described" in result && versionNow(file) === version) remember(key, result.described);
115
+ return result;
116
+ })
117
+ .finally(() => going.delete(key));
118
+ going.set(key, reading);
119
+ }
120
+ return reading;
121
+ };
122
+ }