@arkitektio/bsx 4.1.0 → 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.
@@ -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
  };