@olenbetong/synergi-react 5.7.0 → 5.9.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.
@@ -35,14 +35,43 @@ export type AssistantTool<TArgs = Record<string, unknown>> = {
35
35
  handler: (args: TArgs) => unknown | Promise<unknown>;
36
36
  /**
37
37
  * Ask the user before running: `true` for a generic question, or a function returning the
38
- * question for these arguments. Use it for every tool that changes something.
38
+ * question for these arguments. Use it for every tool that changes something. A function may
39
+ * return null for arguments the handler refuses anyway: nothing is asked, and the handler
40
+ * returns the error (chrome versions before this ask with a generic question instead).
39
41
  */
40
- confirm?: boolean | ((args: TArgs) => string);
42
+ confirm?: boolean | ((args: TArgs) => string | null);
41
43
  };
42
44
 
45
+ /**
46
+ * Tools for one task on the page (editing the open slide, the quiz, media) that are not sent with
47
+ * every question. The model sees one line per group and loads a group when a question needs it;
48
+ * its tools are then sent for the rest of the conversation.
49
+ */
50
+ export type AssistantToolGroup = {
51
+ /** Letters, digits, `_` and `-`, at most 64 characters; unique on the page. */
52
+ name: string;
53
+ /** A few words for the user, shown in the panel when the group is loaded, in their language. */
54
+ title?: string;
55
+ /**
56
+ * One line for the model: what the tools do and when to load them ("Edit the open slide: text,
57
+ * layout and images. Load to change a slide."). Every question carries it, so keep it short.
58
+ */
59
+ summary: string;
60
+ /**
61
+ * Capability codes (the organization setup) the group is meant for. It is listed when the user
62
+ * has any of them, in any company. Leave out to list it for everyone.
63
+ */
64
+ capabilities?: string[];
65
+ tools: AssistantTool<any>[];
66
+ };
67
+
68
+ type ChromeToolGroup = Omit<AssistantToolGroup, "tools"> & { load: () => AssistantTool<any>[] };
69
+
43
70
  type AssistantApi = {
44
71
  readonly enabled: boolean;
45
72
  registerTool: (tool: AssistantTool<any>) => () => void;
73
+ /** Missing in chrome versions before tool groups. */
74
+ registerToolGroup?: (group: ChromeToolGroup) => () => void;
46
75
  setInstructions?: (instructions: string | null) => void;
47
76
  setContext: (context: unknown) => void;
48
77
  open: () => void;
@@ -115,34 +144,107 @@ export function useAssistantTool<TArgs = Record<string, unknown>>(
115
144
  latest.current = tool;
116
145
  });
117
146
 
118
- let key = tool
119
- ? JSON.stringify([tool.name, tool.description, tool.label ?? null, tool.parameters ?? null, Boolean(tool.confirm)])
147
+ let key = tool ? toolKey(tool) : null;
148
+
149
+ useEffect(() => {
150
+ let current = latest.current;
151
+ if (!key || !current) return;
152
+ let tool = liveTool(current, () => latest.current);
153
+ return withAssistant((assistant) => assistant.registerTool(tool));
154
+ }, [key]);
155
+ }
156
+
157
+ /** What the model sees of a tool; a tool is registered again only when this changes. */
158
+ function toolKey(tool: AssistantTool<any>) {
159
+ return JSON.stringify([
160
+ tool.name,
161
+ tool.description,
162
+ tool.label ?? null,
163
+ tool.parameters ?? null,
164
+ Boolean(tool.confirm),
165
+ ]);
166
+ }
167
+
168
+ /**
169
+ * The tool as the chrome gets it: the definition from registration, and a handler and confirm text
170
+ * that read the latest render's tool, since they are called long after.
171
+ */
172
+ function liveTool<TArgs>(
173
+ tool: AssistantTool<TArgs>,
174
+ latest: () => AssistantTool<TArgs> | null | false | undefined,
175
+ ): AssistantTool<TArgs> {
176
+ let { name, description, label, parameters, confirm } = tool;
177
+ return {
178
+ name,
179
+ description,
180
+ label,
181
+ parameters,
182
+ handler: (args: TArgs) => {
183
+ let live = latest();
184
+ if (!live) throw new Error(`The tool "${name}" is no longer available.`);
185
+ return live.handler(args);
186
+ },
187
+ confirm: confirm
188
+ ? (args: TArgs) => {
189
+ let live = latest();
190
+ let question = live ? live.confirm : undefined;
191
+ return typeof question === "function" ? question(args) : "";
192
+ }
193
+ : undefined,
194
+ };
195
+ }
196
+
197
+ /**
198
+ * Offers a group of tools while the component is mounted. The model sees only the group's name and
199
+ * summary until a question needs it; then it loads the group, and the tools are sent for the rest of
200
+ * the conversation. Use it for everything beyond the few tools that read what the page shows: a page
201
+ * registers those with `useAssistantTool` and puts the rest in groups by task, 5-15 tools each.
202
+ *
203
+ * Handlers and confirm texts use the latest render's values, as with `useAssistantTool`. The group is
204
+ * registered again when its name, title, summary, capabilities or a tool's definition change. On a
205
+ * chrome without tool groups the tools are registered one by one instead.
206
+ *
207
+ * @example
208
+ * ```tsx
209
+ * useAssistantToolGroup({
210
+ * name: "slide_editing",
211
+ * title: getLocalizedString("Edit slides"),
212
+ * summary: "Edit the open slide: text, layout and images. Load to change a slide.",
213
+ * tools: [setSlideTitle, setSlideLayout, replaceImage],
214
+ * });
215
+ * ```
216
+ */
217
+ export function useAssistantToolGroup(group: AssistantToolGroup | null | false | undefined) {
218
+ let latest = useRef(group);
219
+ useLayoutEffect(() => {
220
+ latest.current = group;
221
+ });
222
+
223
+ let key = group
224
+ ? JSON.stringify([
225
+ group.name,
226
+ group.title ?? null,
227
+ group.summary,
228
+ group.capabilities ?? null,
229
+ group.tools.map(toolKey),
230
+ ])
120
231
  : null;
121
232
 
122
233
  useEffect(() => {
123
234
  let current = latest.current;
124
235
  if (!key || !current) return;
125
- let { name, description, label, parameters, confirm } = current;
126
-
127
- return withAssistant((assistant) =>
128
- assistant.registerTool({
129
- name,
130
- description,
131
- label,
132
- parameters,
133
- handler: (args: TArgs) => {
134
- let live = latest.current;
135
- if (!live) throw new Error(`The tool "${name}" is no longer available.`);
136
- return live.handler(args);
137
- },
138
- confirm: confirm
139
- ? (args: TArgs) => {
140
- let live = latest.current ? latest.current.confirm : undefined;
141
- return typeof live === "function" ? live(args) : "";
142
- }
143
- : undefined,
144
- }),
236
+ let tools = current.tools.map((tool) =>
237
+ liveTool(tool, () => (latest.current ? latest.current.tools.find((item) => item.name === tool.name) : undefined)),
145
238
  );
239
+ let { name, title, summary, capabilities } = current;
240
+
241
+ return withAssistant((assistant) => {
242
+ if (assistant.registerToolGroup) {
243
+ return assistant.registerToolGroup({ name, title, summary, capabilities, load: () => tools });
244
+ }
245
+ let unregister = tools.map((tool) => assistant.registerTool(tool));
246
+ return () => unregister.forEach((undo) => undo());
247
+ });
146
248
  }, [key]);
147
249
  }
148
250
 
@@ -0,0 +1,162 @@
1
+ import { render } from "@testing-library/react";
2
+ import { afterEach, describe, expect, it, vi } from "vitest";
3
+
4
+ vi.mock("@olenbetong/appframe-core", () => ({
5
+ createLocalizer: () => ({
6
+ getLocalizedString: (value: string) => value,
7
+ localize: (strings: TemplateStringsArray, ...values: unknown[]) =>
8
+ strings.reduce((text, part, index) => text + part + (index < values.length ? String(values[index]) : ""), ""),
9
+ }),
10
+ }));
11
+
12
+ import { useAssistantDataObject } from "./assistantDataObjects";
13
+
14
+ let globals = globalThis as { ob?: unknown };
15
+
16
+ type Row = { PrimKey: string; Title: string; Status: number; Secret: string; Computed: string };
17
+
18
+ const FIELDS = [
19
+ { name: "PrimKey", type: "uniqueidentifier" },
20
+ { name: "Title", type: "string", maxLength: 10 },
21
+ { name: "Status", type: "number" },
22
+ { name: "Secret", type: "string" },
23
+ { name: "Computed", type: "string", computed: true },
24
+ ];
25
+
26
+ function fakeDataObject(rows: Row[], { updatable = true } = {}) {
27
+ let data = rows.map((row) => ({ ...row }));
28
+ let current = 0;
29
+ let dirty = false;
30
+ return {
31
+ data,
32
+ getData: (index?: number) => (index === undefined ? data : data[index]),
33
+ getDataLength: () => data.length,
34
+ getCurrentIndex: () => current,
35
+ setCurrentIndex: vi.fn(async (index: number) => {
36
+ current = index;
37
+ return true;
38
+ }),
39
+ getUniqueIdField: () => "PrimKey",
40
+ getFields: (name: string) => FIELDS.find((field) => field.name === name),
41
+ hasField: (name: string) => FIELDS.some((field) => field.name === name),
42
+ isNullable: () => false,
43
+ isUpdateAllowed: () => updatable,
44
+ isDirty: () => dirty,
45
+ setDirty: (value: boolean) => {
46
+ dirty = value;
47
+ },
48
+ save: vi.fn(async (fields: Partial<Row>) => {
49
+ Object.assign(data[current], fields);
50
+ return data[current];
51
+ }),
52
+ cancelEdit: vi.fn(),
53
+ };
54
+ }
55
+
56
+ function fakeAssistant() {
57
+ let tools = new Map<string, any>();
58
+ return {
59
+ enabled: true,
60
+ tools,
61
+ registerTool: vi.fn((tool: any) => {
62
+ tools.set(tool.name, tool);
63
+ return () => {
64
+ if (tools.get(tool.name) === tool) tools.delete(tool.name);
65
+ };
66
+ }),
67
+ setContext: vi.fn(),
68
+ open: vi.fn(),
69
+ close: vi.fn(),
70
+ };
71
+ }
72
+
73
+ function Issues({ dataObject }: { dataObject: any }) {
74
+ useAssistantDataObject<Row>(dataObject, {
75
+ name: "issues",
76
+ label: "Avvik",
77
+ description: "The issues in the list.",
78
+ titleField: "Title",
79
+ fields: {
80
+ Title: { label: "Tittel", editable: true },
81
+ Status: { label: "Status", description: "1 open, 2 closed" },
82
+ Computed: { label: "Beregnet", editable: true },
83
+ },
84
+ });
85
+ return null;
86
+ }
87
+
88
+ afterEach(() => {
89
+ delete globals.ob;
90
+ });
91
+
92
+ describe("useAssistantDataObject", () => {
93
+ it("reads only the listed fields and the id", async () => {
94
+ let assistant = fakeAssistant();
95
+ globals.ob = { chrome: { assistant } };
96
+ let dataObject = fakeDataObject([{ PrimKey: "a", Title: "Lekk", Status: 1, Secret: "x", Computed: "c" }]);
97
+ let view = render(<Issues dataObject={dataObject} />);
98
+
99
+ let read = assistant.tools.get("read_records");
100
+ expect(read.description).toContain("Status (1 open, 2 closed)");
101
+ let result = await read.handler({ data_object: "issues" });
102
+ expect(result.records).toEqual([{ index: 0, id: "a", Title: "Lekk", Status: 1, Computed: "c" }]);
103
+
104
+ view.unmount();
105
+ expect(assistant.tools.size).toBe(0);
106
+ });
107
+
108
+ it("changes only editable, writable fields, asking with labels and the old and new values", async () => {
109
+ let assistant = fakeAssistant();
110
+ globals.ob = { chrome: { assistant } };
111
+ let dataObject = fakeDataObject([
112
+ { PrimKey: "a", Title: "Lekk", Status: 1, Secret: "x", Computed: "c" },
113
+ { PrimKey: "b", Title: "Brudd", Status: 1, Secret: "y", Computed: "c" },
114
+ ]);
115
+ let view = render(<Issues dataObject={dataObject} />);
116
+ let update = assistant.tools.get("update_records");
117
+ expect(update.description).toContain("Title [editable]");
118
+ expect(update.description).not.toContain("Computed [editable]");
119
+
120
+ let args = { data_object: "issues", changes: [{ id: "b", fields: { Title: "Sprekk" } }] };
121
+ expect(update.confirm(args)).toBe("Save changes to 1 records in Avvik?\n- Brudd: Tittel: «Brudd» → «Sprekk»");
122
+ expect(await update.handler(args)).toEqual({ saved: ["b"] });
123
+ expect(dataObject.data[1].Title).toBe("Sprekk");
124
+
125
+ for (let fields of [{ Status: 2 }, { Computed: "z" }, { Secret: "z" }, { Title: "far too long text" }]) {
126
+ let refused = { data_object: "issues", changes: [{ id: "a", fields }] };
127
+ expect(update.confirm(refused)).toBeNull();
128
+ expect((await update.handler(refused)).error).toBeTruthy();
129
+ }
130
+ expect(dataObject.save).toHaveBeenCalledTimes(1);
131
+ view.unmount();
132
+ });
133
+
134
+ it("refuses while the open record has unsaved changes", async () => {
135
+ let assistant = fakeAssistant();
136
+ globals.ob = { chrome: { assistant } };
137
+ let dataObject = fakeDataObject([{ PrimKey: "a", Title: "Lekk", Status: 1, Secret: "x", Computed: "c" }]);
138
+ dataObject.setDirty(true);
139
+ let view = render(<Issues dataObject={dataObject} />);
140
+ let result = await assistant.tools
141
+ .get("update_records")
142
+ .handler({ data_object: "issues", changes: [{ id: "a", fields: { Title: "Ny" } }] });
143
+ expect(result.error).toContain("unsaved changes");
144
+ expect(dataObject.save).not.toHaveBeenCalled();
145
+ view.unmount();
146
+ });
147
+
148
+ it("offers no update tool when the data object cannot be updated", () => {
149
+ let assistant = fakeAssistant();
150
+ globals.ob = { chrome: { assistant } };
151
+ let view = render(
152
+ <Issues
153
+ dataObject={fakeDataObject([{ PrimKey: "a", Title: "", Status: 1, Secret: "", Computed: "" }], {
154
+ updatable: false,
155
+ })}
156
+ />,
157
+ );
158
+ expect(assistant.tools.has("read_records")).toBe(true);
159
+ expect(assistant.tools.has("update_records")).toBe(false);
160
+ view.unmount();
161
+ });
162
+ });