@arkitektio/bsx 4.0.1 → 4.2.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 (74) hide show
  1. package/dist/bsx/references.d.ts.map +1 -1
  2. package/dist/bsx/references.js +17 -4
  3. package/dist/bsx/references.js.map +1 -1
  4. package/dist/ports/dependencies/DependenciesContainer.d.ts +13 -8
  5. package/dist/ports/dependencies/DependenciesContainer.d.ts.map +1 -1
  6. package/dist/ports/dependencies/DependenciesContainer.js +130 -118
  7. package/dist/ports/dependencies/DependenciesContainer.js.map +1 -1
  8. package/dist/ports/dependencies/DependencyTreeNotice.d.ts +3 -2
  9. package/dist/ports/dependencies/DependencyTreeNotice.d.ts.map +1 -1
  10. package/dist/ports/dependencies/DependencyTreeNotice.js +7 -6
  11. package/dist/ports/dependencies/DependencyTreeNotice.js.map +1 -1
  12. package/dist/ports/dependencies/tree.d.ts +24 -0
  13. package/dist/ports/dependencies/tree.d.ts.map +1 -1
  14. package/dist/ports/dependencies/tree.js +52 -0
  15. package/dist/ports/dependencies/tree.js.map +1 -1
  16. package/dist/ports/dependencies/useDependencyTree.d.ts +5 -0
  17. package/dist/ports/dependencies/useDependencyTree.d.ts.map +1 -1
  18. package/dist/ports/dependencies/useDependencyTree.js +11 -5
  19. package/dist/ports/dependencies/useDependencyTree.js.map +1 -1
  20. package/dist/renderer/BlokRenderer.d.ts +3 -1
  21. package/dist/renderer/BlokRenderer.d.ts.map +1 -1
  22. package/dist/renderer/BlokRenderer.js +5 -1
  23. package/dist/renderer/BlokRenderer.js.map +1 -1
  24. package/dist/renderer/bloks/control.d.ts +1 -0
  25. package/dist/renderer/bloks/control.d.ts.map +1 -1
  26. package/dist/renderer/bloks/control.js +10 -0
  27. package/dist/renderer/bloks/control.js.map +1 -1
  28. package/dist/renderer/bloks/run/host.d.ts +2 -0
  29. package/dist/renderer/bloks/run/host.d.ts.map +1 -1
  30. package/dist/renderer/bloks/run/host.js.map +1 -1
  31. package/dist/renderer/runtime/context.d.ts +1 -0
  32. package/dist/renderer/runtime/context.d.ts.map +1 -1
  33. package/dist/renderer/runtime/context.js +4 -0
  34. package/dist/renderer/runtime/context.js.map +1 -1
  35. package/dist/renderer/runtime/hooks.d.ts.map +1 -1
  36. package/dist/renderer/runtime/hooks.js +1 -0
  37. package/dist/renderer/runtime/hooks.js.map +1 -1
  38. package/dist/renderer/runtime/resolution.d.ts +1 -0
  39. package/dist/renderer/runtime/resolution.d.ts.map +1 -1
  40. package/dist/renderer/runtime/resolution.js +13 -2
  41. package/dist/renderer/runtime/resolution.js.map +1 -1
  42. package/dist/renderer/runtime/types.d.ts +5 -0
  43. package/dist/renderer/runtime/types.d.ts.map +1 -1
  44. package/dist/spec/bsx_v2.json +287 -0
  45. package/dist/spec/catalogs/base@2.json +12 -0
  46. package/dist/spec/catalogs/base@2.json.js +12 -0
  47. package/dist/spec/vocabulary.d.ts +1 -1
  48. package/dist/spec/vocabulary.d.ts.map +1 -1
  49. package/dist/spec/vocabulary.js +1 -1
  50. package/dist/spec/vocabulary.js.map +1 -1
  51. package/dist/spec/vocabulary.json +11 -3
  52. package/dist/spec/vocabulary.json.js +11 -3
  53. package/package.json +1 -1
  54. package/src/bsx/references.ts +18 -4
  55. package/src/ports/dependencies/DependenciesContainer.test.tsx +176 -0
  56. package/src/ports/dependencies/DependenciesContainer.tsx +341 -304
  57. package/src/ports/dependencies/DependencyTreeNotice.tsx +7 -15
  58. package/src/ports/dependencies/tree.test.ts +75 -0
  59. package/src/ports/dependencies/tree.ts +54 -0
  60. package/src/ports/dependencies/useDependencyTree.test.tsx +55 -0
  61. package/src/ports/dependencies/useDependencyTree.ts +11 -5
  62. package/src/renderer/BlokRenderer.tsx +8 -0
  63. package/src/renderer/bloks/control.tsx +15 -0
  64. package/src/renderer/bloks/run/host.tsx +2 -0
  65. package/src/renderer/bloks/run/space.test.tsx +17 -1
  66. package/src/renderer/runtime/context.tsx +5 -0
  67. package/src/renderer/runtime/hooks.ts +1 -0
  68. package/src/renderer/runtime/resolution.test.ts +8 -0
  69. package/src/renderer/runtime/resolution.ts +11 -2
  70. package/src/renderer/runtime/types.ts +5 -0
  71. package/src/spec/bsx_v2.json +287 -0
  72. package/src/spec/catalogs/base@2.json +12 -0
  73. package/src/spec/vocabulary.json +11 -3
  74. package/src/spec/vocabulary.ts +2 -2
@@ -1,6 +1,7 @@
1
1
  /**
2
- * What stands between a form and its assign, as the dry run sees it: the
3
- * dependencies anywhere in the tree that are not met yet.
2
+ * What the dependency rows cannot say themselves: that the dry run could not
3
+ * be asked, or that it refuses without naming a dependency. An unmet
4
+ * dependency is said at its own row (`DependenciesContainer`), once.
4
5
  */
5
6
  export const DependencyTreeNotice = ({
6
7
  tree,
@@ -13,20 +14,11 @@ export const DependencyTreeNotice = ({
13
14
  }) => {
14
15
  if (tree.error) {
15
16
  return (
16
- <p className="text-xs text-muted-foreground mb-2">
17
- The dependency tree could not be previewed ({tree.error.message}); the assign itself will tell.
17
+ <p className="text-xs text-muted-foreground">
18
+ Which agents this reaches could not be previewed; starting it will tell.
18
19
  </p>
19
20
  );
20
21
  }
21
- if (tree.satisfied !== false) return null;
22
- return (
23
- <div className="text-xs text-destructive mb-2">
24
- {tree.unmet.length === 0 && "A dependency is not met yet."}
25
- {tree.unmet.map(({ path, reason }) => (
26
- <p key={path.join("/")}>
27
- <span className="font-medium">{path.join(" › ")}</span>: {reason}
28
- </p>
29
- ))}
30
- </div>
31
- );
22
+ if (tree.satisfied !== false || tree.unmet.length > 0) return null;
23
+ return <p className="text-xs text-destructive">A dependency is not met yet.</p>;
32
24
  };
@@ -1,7 +1,14 @@
1
1
  import { describe, expect, it } from "vitest";
2
+ import type { ListDependencyFragment } from "../rekuest";
2
3
  import {
3
4
  type DependencyNode,
5
+ agentLabel,
6
+ agentsOf,
7
+ awaitsPick,
4
8
  levelBelow,
9
+ namesAgents,
10
+ pickHint,
11
+ pickLimits,
5
12
  pinsFromFrozen,
6
13
  toPins,
7
14
  unmetDependencies,
@@ -166,3 +173,71 @@ describe("pinsFromFrozen", () => {
166
173
  ]);
167
174
  });
168
175
  });
176
+
177
+ const declared = (over: Partial<ListDependencyFragment> = {}): ListDependencyFragment => ({
178
+ id: "1",
179
+ key: "stage",
180
+ autoResolvable: false,
181
+ optional: false,
182
+ singular: false,
183
+ ...over,
184
+ });
185
+
186
+ describe("how many agents a dependency takes", () => {
187
+ it("is one for a singular dependency, whatever else it says", () => {
188
+ expect(pickLimits(declared({ singular: true, maxViableInstances: 4 }))).toEqual({ min: 1, max: 1 });
189
+ expect(pickHint(declared({ singular: true }))).toBe("One agent");
190
+ });
191
+
192
+ it("reads its bounds, and says nothing when there are none", () => {
193
+ expect(pickLimits(declared({ minViableInstances: 2, maxViableInstances: 3 }))).toEqual({ min: 2, max: 3 });
194
+ expect(pickHint(declared({ minViableInstances: 2, maxViableInstances: 3 }))).toBe("2–3 agents");
195
+ expect(pickHint(declared({ minViableInstances: 2, maxViableInstances: 2 }))).toBe("2 agents");
196
+ expect(pickHint(declared({ maxViableInstances: 3 }))).toBe("Up to 3 agents");
197
+ expect(pickHint(declared({ minViableInstances: 2 }))).toBe("At least 2 agents");
198
+ expect(pickLimits(declared())).toEqual({ min: 1, max: Infinity });
199
+ expect(pickHint(declared())).toBeNull();
200
+ });
201
+
202
+ it("may be none for an optional one", () => {
203
+ expect(pickLimits(declared({ optional: true })).min).toBe(0);
204
+ });
205
+ });
206
+
207
+ describe("agentLabel", () => {
208
+ const agent = { id: "7", connected: true, app: { identifier: "live.mikro" }, release: { version: "1" }, user: { sub: "1" } };
209
+
210
+ it("is the agent's name, else its app, else its id", () => {
211
+ expect(agentLabel({ ...agent, name: "lab-nas" }, "7")).toBe("lab-nas");
212
+ expect(agentLabel({ ...agent, name: " " }, "7")).toBe("live.mikro");
213
+ expect(agentLabel(undefined, "7")).toBe("7");
214
+ });
215
+ });
216
+
217
+ describe("what waits for the user", () => {
218
+ it("is a required dependency that may not resolve by itself and names nobody", () => {
219
+ expect(awaitsPick(declared(), undefined)).toBe(true);
220
+ expect(awaitsPick(declared(), { key: "stage", mappedAgents: [{ key: "stage", agent: "7" }] })).toBe(false);
221
+ expect(awaitsPick(declared({ optional: true }), undefined)).toBe(false);
222
+ });
223
+
224
+ it("is not one that resolves by itself, until that is switched off", () => {
225
+ const auto = declared({ autoResolvable: true });
226
+ expect(awaitsPick(auto, undefined)).toBe(false);
227
+ expect(awaitsPick(auto, { key: "stage", autoResolve: true, mappedAgents: [] })).toBe(false);
228
+ expect(awaitsPick(auto, { key: "stage", autoResolve: false, mappedAgents: [] })).toBe(true);
229
+ });
230
+ });
231
+
232
+ describe("what a level reaches", () => {
233
+ it("names an agent only where a pin does", () => {
234
+ expect(namesAgents([{ key: "stage", autoResolve: true, mappedAgents: [] }])).toBe(false);
235
+ expect(namesAgents([{ key: "stage", mappedAgents: [{ key: "stage", agent: "7" }] }])).toBe(true);
236
+ expect(namesAgents(undefined)).toBe(false);
237
+ });
238
+
239
+ it("lists every agent once, in the order bound", () => {
240
+ expect(agentsOf([bound("a", "7"), bound("b", "8"), bound("c", "7")]).map((agent) => agent.id)).toEqual(["7", "8"]);
241
+ expect(agentsOf(undefined)).toEqual([]);
242
+ });
243
+ });
@@ -159,3 +159,57 @@ export const pinsFromFrozen = (frozen: readonly FrozenDependency[] | null | unde
159
159
  return [{ key: dependency.key, agent, ...(dependencies.length > 0 ? { dependencies } : {}) }];
160
160
  }),
161
161
  }));
162
+
163
+ /** How many agents a dependency takes. */
164
+ export const pickLimits = (dependency: ListDependencyFragment): { min: number; max: number } => {
165
+ if (dependency.singular) return { min: dependency.optional ? 0 : 1, max: 1 };
166
+ return {
167
+ min: dependency.minViableInstances ?? (dependency.optional ? 0 : 1),
168
+ max: dependency.maxViableInstances ?? Infinity,
169
+ };
170
+ };
171
+
172
+ /** The same, as the picker says it; nothing when any number will do. */
173
+ export const pickHint = (dependency: ListDependencyFragment): string | null => {
174
+ if (dependency.singular) return "One agent";
175
+ const min = dependency.minViableInstances;
176
+ const max = dependency.maxViableInstances;
177
+ if (min != null && max != null) return min === max ? `${min} agents` : `${min}–${max} agents`;
178
+ if (min != null) return `At least ${min} agents`;
179
+ if (max != null) return `Up to ${max} agents`;
180
+ return null;
181
+ };
182
+
183
+ /** An agent as people call it: its name, else the app it runs. */
184
+ export const agentLabel = (agent: DependencyAgent | null | undefined, id: string): string =>
185
+ agent?.name?.trim() || agent?.app.identifier || id;
186
+
187
+ /**
188
+ * Whether these pins name an agent: the user chose, where the default is
189
+ * "whoever is there". Pins below sit under a named agent, so this level tells.
190
+ */
191
+ export const namesAgents = (level: readonly Pin[] | null | undefined): boolean =>
192
+ (level ?? []).some((pin) => (pin.mappedAgents ?? []).length > 0);
193
+
194
+ /** The agents a level reaches, each once, in the order they are bound. */
195
+ export const agentsOf = (
196
+ nodes: readonly DependencyNode[] | null | undefined,
197
+ ): { id: string; agent?: DependencyAgent | null }[] => {
198
+ const seen = new Map<string, { id: string; agent?: DependencyAgent | null }>();
199
+ for (const node of nodes ?? []) {
200
+ for (const binding of node.mappedAgents) {
201
+ if (!seen.has(binding.agentId)) seen.set(binding.agentId, { id: binding.agentId, agent: binding.agent });
202
+ }
203
+ }
204
+ return [...seen.values()];
205
+ };
206
+
207
+ /**
208
+ * Whether a dependency still waits for the user: it is required, it may not
209
+ * resolve by itself, and no agent is pinned. The form refuses to submit it.
210
+ */
211
+ export const awaitsPick = (dependency: ListDependencyFragment, pin: Pin | undefined): boolean => {
212
+ if (dependency.optional) return false;
213
+ if ((pin?.mappedAgents ?? []).length > 0) return false;
214
+ return !(dependency.autoResolvable && (pin?.autoResolve || !pin));
215
+ };
@@ -0,0 +1,55 @@
1
+ // @vitest-environment jsdom
2
+ import { act, cleanup, renderHook, waitFor } from "@testing-library/react";
3
+ import { useForm } from "react-hook-form";
4
+ import { afterEach, describe, expect, it, vi } from "vitest";
5
+ import { configurePortHost } from "../host";
6
+ import type { ResolvedDependencyInput } from "./tree";
7
+ import { useDependencyTree } from "./useDependencyTree";
8
+
9
+ afterEach(() => {
10
+ cleanup();
11
+ configurePortHost({});
12
+ });
13
+
14
+ const IMPLEMENTATION = { id: "1", dependencies: [{}] };
15
+
16
+ describe("the dry run of an assign", () => {
17
+ it("keeps the tree of the pins before while a changed pin is asked about", async () => {
18
+ let answerSecond: (data: Record<string, unknown>) => void = () => undefined;
19
+ const query = vi
20
+ .fn()
21
+ .mockResolvedValueOnce({ dependencyTree: { satisfied: false, dependencies: [{ key: "stage", unmet: "Nobody.", mappedAgents: [] }] } })
22
+ .mockImplementationOnce(() => new Promise((resolve) => (answerSecond = resolve)));
23
+ configurePortHost({ useServiceQuery: () => query });
24
+
25
+ const { result } = renderHook(() => {
26
+ const form = useForm<{ dependencies: ResolvedDependencyInput[] }>({ defaultValues: { dependencies: [] } });
27
+ return { form, tree: useDependencyTree(IMPLEMENTATION, form.control) };
28
+ });
29
+ await waitFor(() => expect(result.current.tree.satisfied).toBe(false));
30
+ expect(result.current.tree.pending).toBe(false);
31
+
32
+ act(() => result.current.form.setValue("dependencies", [{ key: "stage", mappedAgents: [{ key: "stage", agent: "7" }] }]));
33
+ await waitFor(() => expect(query).toHaveBeenCalledTimes(2));
34
+ // Still unmet as far as anyone knows: not "met" for the length of a round trip.
35
+ expect(result.current.tree.satisfied).toBe(false);
36
+ expect(result.current.tree.unmet).toHaveLength(1);
37
+ expect(result.current.tree.pending).toBe(true);
38
+
39
+ await act(async () => answerSecond({ dependencyTree: { satisfied: true, dependencies: [{ key: "stage", mappedAgents: [] }] } }));
40
+ expect(result.current.tree.satisfied).toBe(true);
41
+ expect(result.current.tree.pending).toBe(false);
42
+ });
43
+
44
+ it("asks nothing for an implementation without dependencies", () => {
45
+ const query = vi.fn();
46
+ configurePortHost({ useServiceQuery: () => query });
47
+ const { result } = renderHook(() => {
48
+ const form = useForm<{ dependencies: ResolvedDependencyInput[] }>({ defaultValues: { dependencies: [] } });
49
+ return useDependencyTree({ id: "1", dependencies: [] }, form.control);
50
+ });
51
+ expect(query).not.toHaveBeenCalled();
52
+ expect(result.current.pending).toBe(false);
53
+ expect(result.current.satisfied).toBeUndefined();
54
+ });
55
+ });
@@ -46,6 +46,10 @@ type Answer = { dependencyTree?: { satisfied: boolean; dependencies: DependencyN
46
46
  * Asked again whenever a pin changes, and now and then, since agents come
47
47
  * and go.
48
48
  *
49
+ * While a changed pin is asked about, the tree of the pins before it stays
50
+ * (`pending` says so): the rows keep what they show, and an unmet tree does
51
+ * not read as met for the length of a round trip.
52
+ *
49
53
  * A server that cannot answer (an older one) leaves `satisfied` undefined:
50
54
  * the form then shows the root level alone and the assign itself decides.
51
55
  */
@@ -57,11 +61,11 @@ export const useDependencyTree = <TValues extends FieldValues>(
57
61
  const key = JSON.stringify(toPins(watched));
58
62
  const run = portHost().useServiceQuery("rekuest");
59
63
  const id = implementation && implementation.dependencies.length > 0 ? implementation.id : null;
60
- const [answer, setAnswer] = useState<Answer["dependencyTree"]>(undefined);
64
+ // Kept with what it answers: another implementation's tree is nobody's, and an older pin's is stale.
65
+ const [answer, setAnswer] = useState<{ id: string; key: string; tree: Answer["dependencyTree"] } | null>(null);
61
66
  const [error, setError] = useState<Error | null>(null);
62
67
 
63
68
  useEffect(() => {
64
- setAnswer(undefined);
65
69
  setError(null);
66
70
  if (!id) return undefined;
67
71
  let live = true;
@@ -70,7 +74,7 @@ export const useDependencyTree = <TValues extends FieldValues>(
70
74
  run(DEPENDENCY_TREE, { input: { implementation: id, dependencies: JSON.parse(key) } })
71
75
  .then((data) => {
72
76
  if (!live) return;
73
- setAnswer((data as Answer).dependencyTree);
77
+ setAnswer({ id, key, tree: (data as Answer).dependencyTree });
74
78
  timer = setTimeout(ask, POLL_MS);
75
79
  })
76
80
  // A server that refuses once will refuse again: no use asking every ten seconds.
@@ -87,7 +91,9 @@ export const useDependencyTree = <TValues extends FieldValues>(
87
91
  // eslint-disable-next-line react-hooks/exhaustive-deps
88
92
  }, [id, key]);
89
93
 
90
- const nodes = error ? undefined : answer?.dependencies;
94
+ const tree = !error && id && answer?.id === id ? answer.tree : undefined;
95
+ const nodes = tree?.dependencies;
91
96
  const unmet = useMemo(() => unmetDependencies(nodes), [nodes]);
92
- return { nodes, satisfied: error ? undefined : answer?.satisfied, unmet, error };
97
+ const pending = Boolean(id) && !error && answer?.key !== key;
98
+ return { nodes, satisfied: tree?.satisfied, unmet, error, pending };
93
99
  };
@@ -82,6 +82,8 @@ type BlokRendererProps = {
82
82
  readExecutor?: BlokReadExecutor;
83
83
  /** Answers the open ask of `task` (`task.answer(values)`). */
84
84
  answerTask?: (values: Record<string, unknown>) => unknown;
85
+ /** Starts the run an assign blok prepares (`assign.start()`). */
86
+ startRun?: () => unknown;
85
87
  /** Where `persist` components keep their state by id; none: they keep nothing. */
86
88
  componentState?: BlokComponentStateStore | null;
87
89
  children?: React.ReactNode;
@@ -145,6 +147,7 @@ export default function BlokRenderer({
145
147
  subscriptions = NO_SUBSCRIPTIONS,
146
148
  readExecutor,
147
149
  answerTask,
150
+ startRun,
148
151
  componentState = null,
149
152
  children,
150
153
  }: BlokRendererProps) {
@@ -198,6 +201,7 @@ export default function BlokRenderer({
198
201
  statuses: unboundDependencies?.length ? {...statuses, ...unboundDependencyStatuses(unboundDependencies)} : statuses,
199
202
  travelAt,
200
203
  answerTask,
204
+ startRun,
201
205
  });
202
206
  return store;
203
207
  });
@@ -221,6 +225,10 @@ export default function BlokRenderer({
221
225
  runtimeStore.getState().setAnswerTask(answerTask);
222
226
  }, [answerTask, runtimeStore]);
223
227
 
228
+ useEffect(() => {
229
+ runtimeStore.getState().setStartRun(startRun);
230
+ }, [startRun, runtimeStore]);
231
+
224
232
  useEffect(() => {
225
233
  if (keptRoots) runtimeStore.getState().setKeptRoots(keptRoots);
226
234
  }, [keptRoots, runtimeStore]);
@@ -420,6 +420,20 @@ export const Ask = createBlokComponent(
420
420
  () => <>{useBlokRunHost().renderAsk()}</>,
421
421
  );
422
422
 
423
+ /* -------------------------------------------------------------------------- */
424
+ /* args */
425
+ /* -------------------------------------------------------------------------- */
426
+
427
+ export const Args = createBlokComponent(
428
+ {
429
+ name: 'args',
430
+ schema: z
431
+ .object({})
432
+ .describe("The arguments of the run an assign blok starts, as a form generated from the action's ports: filled in right here, read as `args.<key>`."),
433
+ },
434
+ () => <>{useBlokRunHost().renderArgs?.() ?? null}</>,
435
+ );
436
+
423
437
  export const controlBlokComponents = [
424
438
  Foreach,
425
439
  If,
@@ -433,4 +447,5 @@ export const controlBlokComponents = [
433
447
  Fallback,
434
448
  ErrorSlot,
435
449
  Ask,
450
+ Args,
436
451
  ];
@@ -21,6 +21,8 @@ export type BlokRunHost = {
21
21
  agentsFor: (key: string) => readonly BlokRunAgent[];
22
22
  /** The run's open ask, answered in place (answering resumes the run); nothing while none is open. */
23
23
  renderAsk: () => React.ReactNode;
24
+ /** The form of the arguments of the run an assign blok starts (`<args />`); absent where no run is being started. */
25
+ renderArgs?: () => React.ReactNode;
24
26
  };
25
27
 
26
28
  const NO_AGENTS: readonly BlokRunAgent[] = Object.freeze([]);
@@ -3,7 +3,7 @@ import * as React from 'react';
3
3
  import {render, screen} from '@testing-library/react';
4
4
  import {describe, expect, it, vi} from 'vitest';
5
5
  import BlokRenderer from '../../BlokRenderer';
6
- import {BlokSpaceHostProvider, type BlokSpaceHost} from './host';
6
+ import {BlokRunHostProvider, BlokSpaceHostProvider, type BlokRunHost, type BlokSpaceHost} from './host';
7
7
  import {testCatalog} from '../testing';
8
8
 
9
9
  // No WebGL in jsdom: the canvas holds nothing here. What is checked is the frame
@@ -49,3 +49,19 @@ describe('a space shown on its own', () => {
49
49
  expect(screen.getByTestId('canvas')).toBeTruthy();
50
50
  });
51
51
  });
52
+
53
+ describe('the argument form an assign blok places', () => {
54
+ it('draws what the host gives for <args />, and nothing without a host', () => {
55
+ const tree = [{id: 'root', component: 'Html', children: [{id: 'form', component: 'args'}]}];
56
+ const run: BlokRunHost = {agentsFor: () => [], renderAsk: () => null, renderArgs: () => <div data-testid="args-form" />};
57
+ const hosted = render(
58
+ <BlokRunHostProvider value={run}>
59
+ <BlokRenderer catalog={testCatalog()} uiComponents={tree} />
60
+ </BlokRunHostProvider>,
61
+ );
62
+ expect(hosted.getByTestId('args-form')).toBeTruthy();
63
+ hosted.unmount();
64
+ const bare = render(<BlokRenderer catalog={testCatalog()} uiComponents={tree} />);
65
+ expect(bare.queryByTestId('args-form')).toBeNull();
66
+ });
67
+ });
@@ -150,6 +150,7 @@ export const createBlokRuntimeStore = (config?: {
150
150
  statuses?: Readonly<Record<string, BlokSourceStatus>>;
151
151
  travelAt?: string | null;
152
152
  answerTask?: (values: Record<string, unknown>) => unknown;
153
+ startRun?: () => unknown;
153
154
  }): BlokRuntimeStore => {
154
155
  const initialDataModel = config?.initialDataModel;
155
156
  const keptValues = config?.keptValues ?? {};
@@ -173,6 +174,7 @@ export const createBlokRuntimeStore = (config?: {
173
174
  refetchQuery: undefined,
174
175
  fetchMoreQuery: undefined,
175
176
  answerTask: config?.answerTask,
177
+ startRun: config?.startRun,
176
178
  setStatus: (path, status) => {
177
179
  const key = canonicalStatusPath(path);
178
180
  set(currentState => {
@@ -209,6 +211,9 @@ export const createBlokRuntimeStore = (config?: {
209
211
  setAnswerTask: answer => {
210
212
  set({answerTask: answer});
211
213
  },
214
+ setStartRun: start => {
215
+ set({startRun: start});
216
+ },
212
217
  setInitialDataModel: nextInitialDataModel => {
213
218
  set(currentState => {
214
219
  if (Object.is(currentState.initialDataModel, nextInitialDataModel)) {
@@ -194,6 +194,7 @@ const createLiveResolutionContext = (
194
194
  refetchQuery: name => store.getState().refetchQuery?.(name),
195
195
  fetchMoreQuery: (name, variables) => store.getState().fetchMoreQuery?.(name, variables),
196
196
  answerTask: values => store.getState().answerTask?.(values),
197
+ startRun: () => store.getState().startRun?.(),
197
198
  travelling: store.getState().travelAt !== null,
198
199
  invokeFunction: (name, args, options) => store.getState().invokeFunction(name, args, options),
199
200
  dispatchAction: (action, component, observe) =>
@@ -433,6 +433,14 @@ describe("a callback does exactly one thing (v2)", () => {
433
433
  expect(answerTask).toHaveBeenCalledWith({image: "7"});
434
434
  });
435
435
 
436
+ it("starts the run an assign blok prepares with assign.start, where a host starts one", () => {
437
+ const startRun = vi.fn(() => "starting");
438
+ const call = {type: "util" as const, call: {operation: "assign.start", arguments: []}};
439
+ expect(runActionCall(call, createContext({}, {startRun}), component)).toEqual({ok: true, value: "starting"});
440
+ expect(startRun).toHaveBeenCalledTimes(1);
441
+ expect(runActionCall(call, createContext({}), component).ok).toBe(false);
442
+ });
443
+
436
444
  it("refuses a pure function as a callback", () => {
437
445
  const result = runActionCall({type: "util", call: {operation: "str.upper", arguments: []}}, createContext({}), component);
438
446
  expect(result.ok).toBe(false);
@@ -390,6 +390,7 @@ const resolvePropValue = (
390
390
  /** The effects a callback may hold besides a task call (vocabulary functions flagged `effect`). */
391
391
  export const COPY_EFFECT = 'ui.copy';
392
392
  export const ANSWER_EFFECT = 'task.answer';
393
+ export const START_EFFECT = 'assign.start';
393
394
  export const REFETCH_EFFECT = 'query.refetch';
394
395
  export const FETCH_MORE_EFFECT = 'query.fetch_more';
395
396
 
@@ -414,7 +415,9 @@ const getPropActionCall = (
414
415
 
415
416
  /** Whether a callback is a command: it is refused while the blok shows the past. */
416
417
  export const isCommand = (actionCall: BlokActionCall | undefined): boolean =>
417
- actionCall !== undefined && (actionCall.type === 'agent' || (actionCall.type === 'util' && actionCall.call.operation === ANSWER_EFFECT));
418
+ actionCall !== undefined &&
419
+ (actionCall.type === 'agent' ||
420
+ (actionCall.type === 'util' && (actionCall.call.operation === ANSWER_EFFECT || actionCall.call.operation === START_EFFECT)));
418
421
 
419
422
  const copyToClipboard = (value: unknown): void => {
420
423
  const text = value === null || value === undefined ? '' : typeof value === 'string' ? value : JSON.stringify(value);
@@ -506,9 +509,15 @@ const runActionCall = (
506
509
  );
507
510
  return {ok: true, value: answered};
508
511
  }
512
+ if (operation === START_EFFECT) {
513
+ if (context.travelling) return {ok: true, value: undefined};
514
+ if (!context.startRun) return {ok: false, error: 'assign.start: nothing here starts a run.'};
515
+ // What the host returns (a promise, while the run is being started) keeps the control busy.
516
+ return {ok: true, value: context.startRun()};
517
+ }
509
518
  return {
510
519
  ok: false,
511
- error: `${operation} is not a callback's one thing: a callback holds one task call or one effect (queries.<name>.refetch(), queries.<name>.fetch_more(...), ui.copy, task.answer).`,
520
+ error: `${operation} is not a callback's one thing: a callback holds one task call or one effect (queries.<name>.refetch(), queries.<name>.fetch_more(...), ui.copy, task.answer, assign.start).`,
512
521
  };
513
522
  };
514
523
 
@@ -214,6 +214,8 @@ export type BlokResolutionContext = {
214
214
  fetchMoreQuery?: (name: string, variables: Record<string, unknown>) => void;
215
215
  /** Answers the open ask of `task` (`task.answer(values)`). */
216
216
  answerTask?: (values: Record<string, unknown>) => unknown;
217
+ /** Starts the run an assign blok prepares (`assign.start()`); undefined where the host starts none. */
218
+ startRun?: () => unknown;
217
219
  /** Set while the blok shows a moment in the past: no command runs. */
218
220
  travelling?: boolean;
219
221
  resolvePath: (path: string) => string;
@@ -248,11 +250,14 @@ export type BlokRuntimeContext = {
248
250
  fetchMoreQuery: ((name: string, variables: Record<string, unknown>) => void) | undefined;
249
251
  /** Answers the open ask of `task`; set by a host that holds one. */
250
252
  answerTask: ((values: Record<string, unknown>) => unknown) | undefined;
253
+ /** Starts the run an assign blok prepares; set by a host that can start one. */
254
+ startRun: (() => unknown) | undefined;
251
255
  setStatus: (path: string, status: BlokSourceStatus | null) => void;
252
256
  setTravelAt: (at: string | null) => void;
253
257
  setRefetchQuery: (refetch: ((name: string) => void) | undefined) => void;
254
258
  setFetchMoreQuery: (fetchMore: ((name: string, variables: Record<string, unknown>) => void) | undefined) => void;
255
259
  setAnswerTask: (answer: ((values: Record<string, unknown>) => unknown) | undefined) => void;
260
+ setStartRun: (start: (() => unknown) | undefined) => void;
256
261
  agentMappingStateUpdates: BlokAgentMappingStateUpdates;
257
262
  invokeFunction: BlokInvokeFunctionHandler;
258
263
  dispatchAction: BlokDispatchActionHandler;