Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7485fa010f
|
||
|
|
2f615879ba
|
||
|
|
1b7e92897e
|
||
|
|
f4b279b95d
|
||
|
|
50845aa99b
|
No files matched your search
@@ -1,5 +1,17 @@
|
||||
# Changelog
|
||||
|
||||
## Unreleased - render_widget follows the assistant's data access; no widget is rendered until a host allows it
|
||||
|
||||
- **A widget is rendered only when the host allowed it by name.** `render_widget` asked the application to render any widget the person may see. A widget is code of the application and can show rows of any table, so it could show a model the rows of a table the assistant may not read (data access `NONE`, a table kept from AI by its metadata). The tool now applies the assistant's own rules before the application is asked: a widget that is not in `AssistantQBitConfig.withAllowedWidgetNames` is refused (the list is empty by default: no widget is renderable), and so is one in `withHiddenWidgetNames`. The README already said the list governs the tool; since the tool moved from the core tool kernel to the UI API it did not.
|
||||
- **A host says which tables a widget reads, and data access and the person's permission then decide.** New: `AssistantQBitConfig.withWidgetTables(widgetName, tableNames)`, required for every allowed widget: one that is allowed by name and has no declaration is refused (nothing says what it would show), so the tool fails closed. A declared widget is rendered only while every one of its tables may be read by the assistant (an administrator's `NONE` row, a pin in code and a table kept from AI each close the widget too) and by the signed-in person (the application is asked, as them, what it tells their screens of the table). A widget that shows nothing of any table is declared with an empty set. The refusal is one answer for every reason and does not say whether the widget exists.
|
||||
- The tool is still offered as before (its definition and the cached request prefix do not change); a call for a widget that is not allowed is a DENIED result with a log row. Not offering the tool at all while no widget is allowed is left for later: it changes the tool set of every request.
|
||||
- Tests: `RenderWidgetAccessTest` (the default is closed and the application is not asked; allowed by name only is refused; allowed and declared; hidden wins; a widget whose table is closed by a pin, read-only, or missing; a person who may not read a table the widget reads).
|
||||
|
||||
## Unreleased - Tool calls no longer wait out their time limit on a server with one or two processors
|
||||
|
||||
- **A tool call does not hold a monitor while it waits for another thread.** A tool call is a virtual thread. The first call of a turn works out what the person is offered, which asks the UI API on another virtual thread and waits for it; `ToolCallService` did that inside `synchronized(admission)`, and the other calls of the batch waited to enter the same monitor. A virtual thread that waits while it holds a monitor, or waits to enter one, keeps its carrier thread, and there are only as many carriers as processors: with two processors a batch of tool calls, and with one processor every first tool call of a turn, waited 60 seconds (`toolCallTimeoutSeconds`), after which the person was offered no write and no process tool for that turn. An admission is now guarded by a `ReentrantLock`; a virtual thread parked on it gives its carrier up. What the lock guards did not change.
|
||||
- **The build runs it with few processors.** `FewProcessorsTest` (one tool call; a batch of six with a write and a process tool among them) runs three times: with the machine's processors, and in JVMs with one and with two (`-XX:ActiveProcessorCount`, the surefire executions `one-processor` and `two-processors`). Without the fix it fails in the one-processor run after a minute per test.
|
||||
- Nothing for a host to change.
|
||||
## Unreleased - The assistant runs a process the signed-in person may run; four review findings closed
|
||||
|
||||
Builds package A4 of the actions design (`docs/actions-and-mcp.md`, section 4), with four findings of an independent review, each described by the guarantee it gives. **One behaviour change needs a host's attention before deploying: a table's own bulk edit and bulk delete become runnable through the assistant, and any other process once the host lists it (see `UPGRADE.md`).**
|
||||
|
||||
@@ -70,6 +70,7 @@ Always use the wrapper: Maven 3.10 cannot read the parent POM. The committed def
|
||||
- `ToolCallService` trusts no caller and takes nothing it can find out itself. A caller hands it a `tools.registry.ToolCall` (a `SignedInPerson`, the call's id, name and input) and nothing else: the service reads the policy fresh on every call (`PolicyService.current(true)`, narrowed for a scheduled task's conversation; never the cache), builds the tool `Context` with the gateway the runtime handed it and keeps the proposed writes itself.
|
||||
- The boundary holds at compile time for code outside the assistant's packages, not only by ArchUnit. Keep it so: `ToolCallRequest`, `ConfirmedToolCall` and `UiApiToolbox.Context` are final classes with no public constructor, made only through `of(ToolCallService.Permit, ...)`; the permit has a private constructor and the service never hands its own out. `AssistantRuntime` has no public getter for the tool registry, the UI API gateway, a toolbox or its tool families: it hands them to the collaborators it builds. Never add a public way to any of them, and never a public method on the service that runs a tool without writing its row.
|
||||
- Its public entry points: `executeAndLog(call, conversationId, hipaaRoute)` for a caller with no turn (the service makes the scope); `confirm(person, pendingActionId)` and `cancel(person, pendingActionId)`, called only by `AssistantApi` (ArchUnit); `offers(person, toolName)` and `offersAny(person, toolNames)`; `readContext(person, timeout)` (only `AssistantApi` and `RagService`, ArchUnit); `expiredIfDue(userId, action)`; `failAbandonedActions(now)` for the retention process. `execute(call, scope)`, `log(call, scope, outcome)` and `withdraw(call, scope)` are package-private, for the turn engine only.
|
||||
- An admission of `ToolCallService` is guarded by its `ReentrantLock`, never by `synchronized`: a tool call is a virtual thread, and what a person is offered is worked out by waiting for another one (`UiApiToolFamily.writableTables`, `ProcessToolFamily.runnableProcesses`). Never hold a monitor across a wait for a task of the runtime's executor: with one or two processors the task then never runs (`FewProcessorsTest`, run by the build with `-XX:ActiveProcessorCount=1` and `=2`).
|
||||
- On every call, before the tool is reached, it checks: a signed-in person, assistant access, the kill switch, that the scope's conversation and turn are that person's, the policy (unreadable refuses), the hard budget (that a spending limit is in force at all, then the limits; read on every call, never remembered per scope; one aggregate query per budget through `AssistantStore.sumUsage`, never the usage rows) and that the tool is offered to this person now. What a caller still supplies (rate limiting, per-request call limits and timeouts, classification, the HIPAA route) is listed in the service's javadoc.
|
||||
- `SignedInPerson` binds a session to the one credential forwarded to the UI API. It has no public constructor: `ofRequest(Context)` (only `AssistantSpecs`, ArchUnit; it forwards only the credential the session was resolved from) or `ofSession(qInstance, session)` (the session's own id is the credential: the authentication module resolves it, it must be the user the session names, and the person IS the session the module resolved, never the object passed in: only its time zone is carried over). Never make a person from a session that was not checked, never read access, the owner key or a permission from a session object a caller handed over, never pass a session and credentials separately, and never let the turn engine make a person.
|
||||
- The toolboxes cannot be called around the service: their entry points that run a tool are package-private, the runtime has no getter for a toolbox (each family is handed its own), and no class outside `tools/` calls into it except through the registry (ArchUnit, with a short allow-list: the runtime's wiring, the value types, and `UiApiToolbox.read`, the four read-only tools the starter prompts and the knowledge index use).
|
||||
@@ -78,6 +79,7 @@ Always use the wrapper: Maven 3.10 cannot read the parent POM. The committed def
|
||||
- A missing policy refuses; it never means "every tool".
|
||||
- Data tools run only through `UiApiToolbox` → `UiApiGateway` (spec'd `/qqq/v1` operations with the user's `sessionUUID`); never core data actions for user data. Only `navigate` and `search_help` use `AiToolKernel.execute`.
|
||||
- Data access (`DataAccessService`) and the policy only ever narrow what the UI API allows. The mode of a table or process is declared in versioned code: the default (`withDefaultTableAccess` / `withDefaultProcessAccess`, READ_WRITE) or a pin (`withTableAccess` / `withProcessAccess`). An administrator's `assistant_data_access` row narrows it and never raises it. A table whose AI exposure is NONE stays NONE, and so does every `assistant_*` table and every process of the QBit (`DataAccessService.isOwnTable`: a pin in code that no row and no host pin lifts). Rows that cannot be read and were never read mean NONE for everything, never the default.
|
||||
- `render_widget` renders only a widget the host allowed by name in code (`withAllowedWidgetNames`; none by default), not hidden, whose tables the host declared (`withWidgetTables`; no declaration is a refusal), and only while every one of those tables may be read by the assistant and by the person (asked of the UI API as them): a widget is code that can show rows of any table. The check is in `UiApiToolbox.renderWidget`, before the UI API is asked. Never render a widget on the person's permission alone.
|
||||
- READ_WRITE grants nothing: the write tools are offered to a person only when the UI API says that person may create, edit or delete records of some table (`UiApiToolFamily.writableTables`, asked as the person, once per offer, within `toolCallTimeoutSeconds`; no answer means no write tool). The person's permission for the change itself is decided by the UI API when the confirmed change runs, with its own message. Never materialise defaults as rows again: the retired "Add rows for every table" action is why `assistant-data-access-follow-user.changelog.sql` exists.
|
||||
- A write runs only after the owner confirms its pending action, with the confirming request's session, once; no policy or caller can turn confirmation off (`assistant_policy.writesRequireConfirmation` is no longer read). `ToolCallService.confirm` loads the stored action for that person, claims it, runs it and writes its row; whatever fails after the claim ends in FAILED with a row, never in RUNNING.
|
||||
- A pending action is decided once: confirming, cancelling and expiring all go through `AssistantStore.decidePendingAction` (final; `expirePendingAction` is a claim with the decision EXPIRED), which inserts the action's row into `assistant_pending_action_claim` (unique `pendingActionId`). Never decide an action with a status update alone, never expire one from a copy read earlier or a time a caller names (`ToolCallService.expiredIfDue` decides from the stored action and the runtime's clock), and never drop that unique key.
|
||||
|
||||
@@ -286,7 +286,8 @@ The nav lists the home and the main tables: **Providers**, **Conversations**, **
|
||||
| `retentionSchedulerName` | none | Runs `assistantRetention` daily on that scheduler. |
|
||||
| `ownerSecurityKeyType` | `assistant_user_id` | Key type of the owner record locks. |
|
||||
| `pricing` | Anthropic list prices, 2026-10 | USD per million tokens per model, used for cost and budgets. |
|
||||
| `allowedWidgetNames` | none | Dashboard widgets `render_widget` may render. The kernel denies every widget not on this list. This config list is the **only** way to allow a widget: QQQ widget meta-data has no supplemental hook, so there is no per-widget "assistant-safe" flag. Allow only widgets that render the same data for every user who can see them. |
|
||||
| `allowedWidgetNames` | none | Dashboard widgets `render_widget` may render. The tool refuses every widget that is not on this list, before the application is asked, so with the default (none) no widget is renderable. This list in code is the **only** way to allow a widget: QQQ widget meta-data has no supplemental hook, so there is no per-widget "assistant-safe" flag. A name here is not enough: a widget is code of the application and can show rows of any table, so it is rendered only once the tables it reads are declared with `withWidgetTables`. Allow only widgets that render the same data for every user who can see them. |
|
||||
| `withWidgetTables(widget, tables)` | none | The tables an allowed widget reads; required for every allowed widget (one without a declaration is refused). The widget is rendered through the assistant only while every one of them may be read by the assistant (data access not `NONE`: the code default, a pin, an administrator's row, a table kept from AI by its metadata) and by the signed-in person (the application is asked, as them, what it tells their screens of the table). A widget that shows nothing of any table is declared with an empty set. |
|
||||
| `hiddenWidgetNames` | none | Widgets that are never rendered, even when allowed. |
|
||||
| `customRedactionPatterns` | none | Extra regular expressions redacted from tool results and from the input kept in the tool-call log. |
|
||||
| `killSwitchPollMillis` | 2000 | How often a running turn re-checks the kill switch while it waits on the model. |
|
||||
|
||||
+16
@@ -1,5 +1,21 @@
|
||||
# Upgrading qbit-assistant
|
||||
|
||||
## render_widget renders only widgets the host allowed (Unreleased)
|
||||
|
||||
**After this upgrade the assistant renders no dashboard widget until the application names it in code.** Until now `render_widget` rendered any widget the signed-in person may see, including one that shows rows of a table the assistant may not read.
|
||||
|
||||
What a host changes, only if it wants the assistant to render widgets:
|
||||
|
||||
```java
|
||||
new AssistantQBitConfig()
|
||||
.withAllowedWidgetNames(Set.of("openOrdersByStatus")) // nothing else is renderable
|
||||
.withWidgetTables("openOrdersByStatus", Set.of("order", "customer")); // the tables its renderer reads
|
||||
```
|
||||
|
||||
- Name the tables each allowed widget reads: **both calls are needed for every widget.** A widget that is allowed by name and has no `withWidgetTables` entry is refused. A declared one is closed whenever the assistant may not read one of its tables (a `NONE` row of an administrator, a pin, a table kept from AI) and for a person who may not read one of them. For a widget that shows nothing of any table, declare an empty set: `withWidgetTables("clock", Set.of())`.
|
||||
- Allow only widgets that render the same data for every person who can see them.
|
||||
- No schema change, no permission change, no settings row.
|
||||
|
||||
## The assistant runs a process the signed-in person may run (Unreleased, UI API extension assistant 1.10.0)
|
||||
|
||||
**After this upgrade, with nothing else changed, the assistant can run two kinds of process for a person who may run them themselves, once that person confirmed the run on a card: a table's own bulk edit and its bulk delete, on a table the assistant may already change for that person.** Every other process stays closed until the application's code names it on a reviewed list. No DDL changes.
|
||||
|
||||
@@ -31,6 +31,12 @@
|
||||
<description>In-app AI assistant QBit for QQQ: conversations, turn engine, SSE routes, budgets and provider registry</description>
|
||||
<url>https://github.com/QRun-IO/qbit-assistant</url>
|
||||
|
||||
<properties>
|
||||
<!-- what JaCoCo's agent adds to; empty when coverage is skipped, so that the -->
|
||||
<!-- executions below that add a JVM option of their own still have a value -->
|
||||
<argLine></argLine>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qbits</groupId>
|
||||
@@ -152,6 +158,44 @@
|
||||
<excludedGroups>${test.excludedGroups}</excludedGroups>
|
||||
<redirectTestOutputToFile>true</redirectTestOutputToFile>
|
||||
</configuration>
|
||||
<executions>
|
||||
<!-- a server with one or two processors: tool calls are virtual threads, and a -->
|
||||
<!-- monitor held across a wait for another one leaves no carrier thread for it. -->
|
||||
<!-- FewProcessorsTest runs again in a JVM that has that few (it fails there, by -->
|
||||
<!-- waiting out a time limit, if such a wait comes back). -->
|
||||
<execution>
|
||||
<id>one-processor</id>
|
||||
<goals>
|
||||
<goal>test</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<argLine>@{argLine} -XX:ActiveProcessorCount=1</argLine>
|
||||
<includes>
|
||||
<include>**/FewProcessorsTest.java</include>
|
||||
</includes>
|
||||
<reportNameSuffix>one-processor</reportNameSuffix>
|
||||
<systemPropertyVariables>
|
||||
<assistant.fewProcessors>1</assistant.fewProcessors>
|
||||
</systemPropertyVariables>
|
||||
</configuration>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>two-processors</id>
|
||||
<goals>
|
||||
<goal>test</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<argLine>@{argLine} -XX:ActiveProcessorCount=2</argLine>
|
||||
<includes>
|
||||
<include>**/FewProcessorsTest.java</include>
|
||||
</includes>
|
||||
<reportNameSuffix>two-processors</reportNameSuffix>
|
||||
<systemPropertyVariables>
|
||||
<assistant.fewProcessors>2</assistant.fewProcessors>
|
||||
</systemPropertyVariables>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<!-- the eval fixture and harness are reused by provider-module live evals: -->
|
||||
|
||||
+50
-1
@@ -159,6 +159,7 @@ public class AssistantQBitConfig implements QBitConfig
|
||||
|
||||
private Set<String> hiddenWidgetNames = new LinkedHashSet<>();
|
||||
private Set<String> allowedWidgetNames = new LinkedHashSet<>();
|
||||
private Map<String, Set<String>> widgetTables = new LinkedHashMap<>();
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////
|
||||
// tools sent with strict: true. Empty by default: Anthropic compiles all //
|
||||
@@ -1644,7 +1645,11 @@ public class AssistantQBitConfig implements QBitConfig
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Fluent setter for allowedWidgetNames
|
||||
** Fluent setter for allowedWidgetNames: the dashboard widgets render_widget
|
||||
** may render. A widget that is not named here is refused, whoever asks
|
||||
** (the list is empty by default, so no widget is renderable until a host
|
||||
** names one). Naming a widget here is not enough: it is rendered only once
|
||||
** the tables it reads are declared too ({@link #withWidgetTables}).
|
||||
*******************************************************************************/
|
||||
public AssistantQBitConfig withAllowedWidgetNames(Set<String> allowedWidgetNames)
|
||||
{
|
||||
@@ -1654,6 +1659,50 @@ public class AssistantQBitConfig implements QBitConfig
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for widgetTables
|
||||
*******************************************************************************/
|
||||
public Map<String, Set<String>> getWidgetTables()
|
||||
{
|
||||
return (this.widgetTables);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Setter for widgetTables
|
||||
*******************************************************************************/
|
||||
public void setWidgetTables(Map<String, Set<String>> widgetTables)
|
||||
{
|
||||
this.widgetTables = widgetTables;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Declare the tables an allowed widget reads. The renderer of a widget is
|
||||
** code of the application: the assistant cannot see which tables it reads,
|
||||
** so the host says so here, for every widget it allows. An allowed widget
|
||||
** with no declaration is not rendered. A declared one is rendered through
|
||||
** the assistant only while every one of its tables may be read by the
|
||||
** assistant (data access not NONE: the code default, a pin, a row of an
|
||||
** administrator, a table kept from AI by its metadata, the tables of the
|
||||
** assistant itself) and by the signed-in person (the application is asked
|
||||
** as them). A widget that shows nothing of any table is declared with an
|
||||
** empty set, which is the host saying exactly that.
|
||||
*******************************************************************************/
|
||||
public AssistantQBitConfig withWidgetTables(String widgetName, Set<String> tableNames)
|
||||
{
|
||||
if(this.widgetTables == null)
|
||||
{
|
||||
this.widgetTables = new LinkedHashMap<>();
|
||||
}
|
||||
this.widgetTables.put(widgetName, tableNames == null ? Set.of() : new LinkedHashSet<>(tableNames));
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for customRedactionPatterns
|
||||
*******************************************************************************/
|
||||
|
||||
@@ -196,6 +196,7 @@ public class AssistantRuntime
|
||||
this.toolbox = new UiApiToolbox(qInstance, dataAccessService, exposurePolicy, new AiRedactor(settings.getCustomRedactionPatterns()),
|
||||
config.getMaxCellChars() == null ? AiToolKernelSettings.DEFAULT_MAX_CELL_CHARS : config.getMaxCellChars());
|
||||
this.toolbox.withScheduledDeliveryCheck(config.getScheduledDeliveryCheck());
|
||||
this.toolbox.withWidgetRules(() -> new UiApiToolbox.WidgetRules(config.getAllowedWidgetNames(), config.getHiddenWidgetNames(), config.getWidgetTables()));
|
||||
this.starterPrompts = new StarterPrompts(toolbox, clock);
|
||||
VectorStore vectors = config.getVectorStore() == null ? new InMemoryVectorStore() : config.getVectorStore();
|
||||
this.ragService = new RagService(this, vectors, uiApiGateway);
|
||||
|
||||
+43
-5
@@ -27,6 +27,7 @@ import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
import java.util.function.Supplier;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.kingsrook.qbits.assistant.AssistantQBitConfig;
|
||||
@@ -308,6 +309,18 @@ public class ToolCallService
|
||||
*******************************************************************************/
|
||||
private static final class Admission
|
||||
{
|
||||
///////////////////////////////////////////////////////////////////////
|
||||
// what guards an admission is a lock of java.util.concurrent, never //
|
||||
// a monitor. A call is a virtual thread, and working out what a //
|
||||
// person is offered waits for another one (the families ask the UI //
|
||||
// API on the runtime's executor). A virtual thread that waits while //
|
||||
// it holds a monitor, or waits to enter one, keeps its carrier //
|
||||
// thread; with as few carriers as processors, the thread waited for //
|
||||
// then never runs, and every call of a batch waits out its time //
|
||||
// limit. Parked on this lock a virtual thread gives its carrier up //
|
||||
///////////////////////////////////////////////////////////////////////
|
||||
private final ReentrantLock lock = new ReentrantLock();
|
||||
|
||||
private QSession session;
|
||||
private UiApiCredentials credentials;
|
||||
private Integer conversationId;
|
||||
@@ -513,7 +526,8 @@ public class ToolCallService
|
||||
|
||||
Admission admission = admission(call.person(), scope);
|
||||
ToolCallRequest request;
|
||||
synchronized(admission)
|
||||
admission.lock.lock();
|
||||
try
|
||||
{
|
||||
AiToolResult refused = refusal(call, admission, effective);
|
||||
if(refused != null)
|
||||
@@ -522,6 +536,10 @@ public class ToolCallService
|
||||
}
|
||||
request = ToolCallRequest.of(PERMIT, session, context(call.person(), admission, call.toolCallId()), call.toolCallId(), call.toolName(), call.input(), scope);
|
||||
}
|
||||
finally
|
||||
{
|
||||
admission.lock.unlock();
|
||||
}
|
||||
return (registry.find(call.toolName()).execute(request));
|
||||
}
|
||||
}
|
||||
@@ -656,7 +674,8 @@ public class ToolCallService
|
||||
*******************************************************************************/
|
||||
private Integer propose(Admission admission, String userId, String toolCallId, UiApiToolbox.ProposedWrite write) throws QException
|
||||
{
|
||||
synchronized(admission)
|
||||
admission.lock.lock();
|
||||
try
|
||||
{
|
||||
if(admission.cutShort.contains(toolCallId))
|
||||
{
|
||||
@@ -683,6 +702,10 @@ public class ToolCallService
|
||||
admission.proposed.put(toolCallId, action.getId());
|
||||
return (action.getId());
|
||||
}
|
||||
finally
|
||||
{
|
||||
admission.lock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -705,7 +728,8 @@ public class ToolCallService
|
||||
{
|
||||
AssistantSecurity.ownerKey(session, runtime.getConfig());
|
||||
Admission admission = admission(call.person(), scope);
|
||||
synchronized(admission)
|
||||
admission.lock.lock();
|
||||
try
|
||||
{
|
||||
admission.cutShort.add(call.toolCallId());
|
||||
Integer actionId = admission.proposed.get(call.toolCallId());
|
||||
@@ -714,6 +738,10 @@ public class ToolCallService
|
||||
store.withdrawPendingAction(call.person().userId(), actionId, WITHDRAWN_SUMMARY, runtime.getClock().instant());
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
admission.lock.unlock();
|
||||
}
|
||||
}
|
||||
catch(QException | RuntimeException e)
|
||||
{
|
||||
@@ -893,7 +921,8 @@ public class ToolCallService
|
||||
{
|
||||
admission = new Admission();
|
||||
}
|
||||
synchronized(admission)
|
||||
admission.lock.lock();
|
||||
try
|
||||
{
|
||||
if(!admission.bound)
|
||||
{
|
||||
@@ -902,6 +931,10 @@ public class ToolCallService
|
||||
boolean same = admission.session == person.session() && Objects.equals(admission.conversationId, scope.conversationId()) && Objects.equals(admission.turnId, scope.turnId());
|
||||
return (same ? admission : bind(new Admission(), person, scope));
|
||||
}
|
||||
finally
|
||||
{
|
||||
admission.lock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1432,11 +1465,16 @@ public class ToolCallService
|
||||
Admission admission = admission(call.person(), scope);
|
||||
boolean owned;
|
||||
String channel;
|
||||
synchronized(admission)
|
||||
admission.lock.lock();
|
||||
try
|
||||
{
|
||||
owned = admission.owned;
|
||||
channel = admission.channel;
|
||||
}
|
||||
finally
|
||||
{
|
||||
admission.lock.unlock();
|
||||
}
|
||||
String inputJson = inputRedactor.redact(JsonUtils.toJson(inputForLog(tool, call, result)), new HashSet<>());
|
||||
store.insert(new AssistantToolCall()
|
||||
.withTurnId(owned ? scope.turnId() : null)
|
||||
|
||||
+1
-1
@@ -78,7 +78,7 @@ public class UiApiToolFamily implements ToolFamily
|
||||
Map.entry(UiApiToolbox.COUNT_RECORDS, EXPOSE_THEN_READ),
|
||||
Map.entry(UiApiToolbox.GET_RECORD, READ_THEN_EXPOSE),
|
||||
Map.entry(UiApiToolbox.SEARCH_RECORDS, EXPOSE_THEN_READ),
|
||||
Map.entry(UiApiToolbox.RENDER_WIDGET, List.of(TOOL_SWITCH, SPECD_OPERATION, PERSON_PERMISSIONS)),
|
||||
Map.entry(UiApiToolbox.RENDER_WIDGET, List.of(TOOL_SWITCH, SPECD_OPERATION, DATA_ACCESS, PERSON_PERMISSIONS)),
|
||||
Map.entry(UiApiToolbox.RECORD_HISTORY, READ_THEN_EXPOSE),
|
||||
Map.entry(UiApiToolbox.CREATE_RECORD, PROPOSED_WRITE),
|
||||
Map.entry(UiApiToolbox.UPDATE_RECORD, PROPOSED_WRITE),
|
||||
|
||||
+101
-2
@@ -33,6 +33,7 @@ import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.TreeMap;
|
||||
import java.util.function.Supplier;
|
||||
import com.kingsrook.qbits.assistant.persistence.TranscriptRedactor;
|
||||
import com.kingsrook.qbits.assistant.access.DataAccessMode;
|
||||
import com.kingsrook.qbits.assistant.access.DataAccessService;
|
||||
@@ -156,6 +157,8 @@ public class UiApiToolbox
|
||||
public static final int DEFAULT_LIMIT = 20;
|
||||
|
||||
public static final String CHECK_STALE = "pending:stale";
|
||||
|
||||
static final String TABLE_META_PATH = "/metaData/table/{tableName}";
|
||||
public static final String STALE_MESSAGE = "This record changed after the change was proposed. Nothing was changed.";
|
||||
|
||||
private final QInstance qInstance;
|
||||
@@ -165,6 +168,8 @@ public class UiApiToolbox
|
||||
private final int maxCellChars;
|
||||
private final AnalysisTools analysis;
|
||||
|
||||
private Supplier<WidgetRules> widgetRules = () -> WidgetRules.NONE;
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
@@ -877,12 +882,41 @@ public class UiApiToolbox
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Which widgets render_widget may render, as the host declared it in code.
|
||||
**
|
||||
** @param allowed the widgets a host allowed; a widget not named is refused
|
||||
** @param hidden widgets a host took away again; one named here is refused
|
||||
** also when it is allowed
|
||||
** @param tables for an allowed widget, the tables it reads: it is rendered
|
||||
** only while the assistant and the person may read every one
|
||||
** of them. A widget with no entry here is not rendered
|
||||
*******************************************************************************/
|
||||
public record WidgetRules(Set<String> allowed, Set<String> hidden, Map<String, Set<String>> tables)
|
||||
{
|
||||
public static final WidgetRules NONE = new WidgetRules(Set.of(), Set.of(), Map.of());
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The widget rules of the host, read on every call. Without them no widget
|
||||
** is renderable.
|
||||
*******************************************************************************/
|
||||
public UiApiToolbox withWidgetRules(Supplier<WidgetRules> rules)
|
||||
{
|
||||
this.widgetRules = rules == null ? () -> WidgetRules.NONE : rules;
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The host's check of scheduled delivery (what is missing for a schedule to
|
||||
** run and be emailed; empty when nothing is). Null: only what the instance
|
||||
** itself shows is checked.
|
||||
*******************************************************************************/
|
||||
public UiApiToolbox withScheduledDeliveryCheck(java.util.function.Supplier<List<String>> check)
|
||||
public UiApiToolbox withScheduledDeliveryCheck(Supplier<List<String>> check)
|
||||
{
|
||||
analysis.setScheduledDeliveryCheck(check);
|
||||
return (this);
|
||||
@@ -1495,10 +1529,75 @@ public class UiApiToolbox
|
||||
|
||||
/*******************************************************************************
|
||||
** POST /widget/{widgetName}.
|
||||
**
|
||||
** The renderer of a widget is code of the application, and what it shows
|
||||
** can be rows of any table: the assistant cannot tell, and the UI API
|
||||
** decides only whether the person may see the widget. So the rules of the
|
||||
** assistant decide first, before the application is asked to render: a
|
||||
** widget is rendered only when the host allowed it by name (none is, by
|
||||
** default), did not hide it, declared the tables it reads, and every one
|
||||
** of those tables may be read by the assistant (its data access) and by
|
||||
** the person (what the application tells their own screens of the table).
|
||||
** A widget whose tables the host did not declare is refused: nothing says
|
||||
** what it would show. Everything is refused with one answer, which does
|
||||
** not say whether the widget exists.
|
||||
*******************************************************************************/
|
||||
private void renderWidget(Context context, Outcome outcome, Map<String, Object> in) throws QException
|
||||
{
|
||||
String name = requiredString(in, "name");
|
||||
String name = requiredString(in, "name");
|
||||
WidgetRules rules = widgetRules.get() == null ? WidgetRules.NONE : widgetRules.get();
|
||||
Set<String> tables = rules.tables() == null ? null : rules.tables().get(name);
|
||||
String check = null;
|
||||
if(rules.allowed() == null || !rules.allowed().contains(name))
|
||||
{
|
||||
check = "widget:notAllowed";
|
||||
}
|
||||
else if(rules.hidden() != null && rules.hidden().contains(name))
|
||||
{
|
||||
check = "widget:hidden";
|
||||
}
|
||||
else if(tables == null)
|
||||
{
|
||||
check = "widget:tablesNotDeclared";
|
||||
}
|
||||
else
|
||||
{
|
||||
for(String tableName : tables)
|
||||
{
|
||||
DataAccessService.Decision decision = dataAccess.forTable(tableName);
|
||||
if(qInstance.getTable(tableName) == null || !decision.mode().allowsRead())
|
||||
{
|
||||
check = "dataAccess:table:" + decision.mode();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
String refusal = "The widget \"" + shortText(name) + "\" is not available to the assistant.";
|
||||
if(check != null)
|
||||
{
|
||||
deny(outcome.result.withWidgetName(name), check, refusal);
|
||||
return;
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////
|
||||
// and the person: a widget that reads a table shows it to whoever //
|
||||
// may see the widget, so the application is asked, as the person, //
|
||||
// whether they may read each table it reads. No answer is a refusal //
|
||||
///////////////////////////////////////////////////////////////////////
|
||||
for(String tableName : tables)
|
||||
{
|
||||
boolean readable = false;
|
||||
if(context.gateway().isInvocable("GET", TABLE_META_PATH))
|
||||
{
|
||||
UiApiResult described = call(context, outcome, new UiApiCall("GET", TABLE_META_PATH).withPathParam("tableName", tableName));
|
||||
readable = described.isSuccess() && Boolean.TRUE.equals(asMap(described.json()).get("readPermission"));
|
||||
}
|
||||
if(!readable)
|
||||
{
|
||||
deny(outcome.result.withWidgetName(name), "uiApi:GET " + TABLE_META_PATH + ":readPermission", refusal);
|
||||
return;
|
||||
}
|
||||
}
|
||||
if(qInstance.getWidget(name) == null)
|
||||
{
|
||||
throw (new AiToolException(AiToolOutcome.NOT_FOUND, "No widget named " + name + "."));
|
||||
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.assistant.engine;
|
||||
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import com.kingsrook.qbits.assistant.model.AssistantToolCall;
|
||||
import com.kingsrook.qbits.assistant.testing.BaseAssistantTest;
|
||||
import com.kingsrook.qbits.assistant.testing.TurnRunner;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static com.kingsrook.qbits.assistant.testing.AssistantTestFixture.AUTHOR;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Tool calls on a server with one or two processors.
|
||||
**
|
||||
** A tool call is a virtual thread. The first call of a turn works out what
|
||||
** the person is offered, which asks the UI API on another virtual thread and
|
||||
** waits for it. When that wait is made while a monitor is held (and the
|
||||
** other calls of the batch wait to enter the same monitor), every waiting
|
||||
** thread keeps its carrier, there are only as many carriers as processors,
|
||||
** and the thread waited for never runs: the calls wait out their time limit
|
||||
** (60 seconds), and the person is then offered no write and no process tool
|
||||
** for that turn.
|
||||
**
|
||||
** The build runs this class three times: with the processors of the machine,
|
||||
** and again in JVMs that have one and two (the surefire executions
|
||||
** one-processor and two-processors, -XX:ActiveProcessorCount). With few
|
||||
** processors it fails, by taking a minute and by the tools it then refuses,
|
||||
** as soon as a monitor is held across such a wait again.
|
||||
*******************************************************************************/
|
||||
class FewProcessorsTest extends BaseAssistantTest
|
||||
{
|
||||
private static final long LIMIT_MILLIS = 30_000;
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The executions that say they have few processors have them.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void theJvmHasTheProcessorsItsExecutionNames()
|
||||
{
|
||||
Integer few = Integer.getInteger("assistant.fewProcessors");
|
||||
if(few != null)
|
||||
{
|
||||
assertThat(Runtime.getRuntime().availableProcessors()).isEqualTo(few);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** One tool call, the first of its turn: it is answered at once, and what
|
||||
** the person is offered was worked out (a write tool is offered to a
|
||||
** person who may change something, so the proposal is made).
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void oneToolCallIsAnsweredAtOnce() throws Exception
|
||||
{
|
||||
provider.thenToolUse("update_record", Map.of("table", "blog_post", "id", "1", "values", Map.of("title", "A new title"))).thenText("Please confirm.");
|
||||
long started = System.currentTimeMillis();
|
||||
TurnRunner.Outcome outcome = runner.run(AUTHOR, "Rename the first post");
|
||||
assertThat(outcome.end()).containsEntry("status", "COMPLETE");
|
||||
assertThat(System.currentTimeMillis() - started).as("no call waited out its time limit").isLessThan(LIMIT_MILLIS);
|
||||
assertThat(outcome.toolCalls()).singleElement().satisfies(call ->
|
||||
{
|
||||
assertThat(call.getOutcome()).as("the write tool was offered: " + call.getResultSummary()).isEqualTo("OK");
|
||||
assertThat(call.getPendingActionId()).isNotNull();
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A batch of tool calls in one reply, more of them than there are
|
||||
** processors: all are answered at once, in order, and the write and the
|
||||
** process tool among them were offered.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void aBatchOfToolCallsIsAnsweredAtOnce() throws Exception
|
||||
{
|
||||
Map<String, Object> all = Map.of("booleanOperator", "AND", "criteria", List.of());
|
||||
List<Object[]> calls = new ArrayList<>();
|
||||
calls.add(new Object[] { "count_records", Map.of("table", "blog_post", "filter", all) });
|
||||
calls.add(new Object[] { "count_records", Map.of("table", "page", "filter", all) });
|
||||
calls.add(new Object[] { "list_tables", Map.of() });
|
||||
calls.add(new Object[] { "list_processes", Map.of() });
|
||||
calls.add(new Object[] { "update_record", Map.of("table", "blog_post", "id", "1", "values", Map.of("title", "A new title")) });
|
||||
calls.add(new Object[] { "count_records", Map.of("table", "media", "filter", all) });
|
||||
provider.thenToolUses("Checking.", calls).thenText("Done.");
|
||||
|
||||
long started = System.currentTimeMillis();
|
||||
TurnRunner.Outcome outcome = runner.run(AUTHOR, "Counts, and rename the first post");
|
||||
assertThat(outcome.end()).containsEntry("status", "COMPLETE");
|
||||
assertThat(System.currentTimeMillis() - started).as("no call waited out its time limit").isLessThan(LIMIT_MILLIS);
|
||||
assertThat(outcome.toolCalls()).extracting(AssistantToolCall::getToolName).containsExactly("count_records", "count_records", "list_tables", "list_processes", "update_record", "count_records");
|
||||
assertThat(outcome.toolCalls()).as("every call ran, and the write and the process tool were offered").allSatisfy(call -> assertThat(call.getOutcome()).as(call.getToolName()).isEqualTo("OK"));
|
||||
}
|
||||
}
|
||||
+228
@@ -0,0 +1,228 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.assistant.tools;
|
||||
|
||||
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import com.kingsrook.qbits.assistant.access.DataAccessMode;
|
||||
import com.kingsrook.qbits.assistant.testing.AssistantTestFixture;
|
||||
import com.kingsrook.qbits.assistant.testing.BaseAssistantTest;
|
||||
import com.kingsrook.qbits.assistant.testing.ToolCalls;
|
||||
import com.kingsrook.qbits.assistant.tools.registry.ToolCallOutcome;
|
||||
import com.kingsrook.qqq.backend.core.actions.ai.AiToolOutcome;
|
||||
import com.kingsrook.qqq.backend.core.actions.dashboard.widgets.AbstractWidgetRenderer;
|
||||
import com.kingsrook.qqq.backend.core.exceptions.QException;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.widgets.RenderWidgetInput;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.widgets.RenderWidgetOutput;
|
||||
import com.kingsrook.qqq.backend.core.model.dashboard.widgets.RawHTML;
|
||||
import com.kingsrook.qqq.backend.core.model.dashboard.widgets.WidgetType;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.code.QCodeReference;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.dashboard.QWidgetMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.permissions.PermissionLevel;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.permissions.QPermissionRules;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static com.kingsrook.qbits.assistant.testing.AssistantTestFixture.EDITOR;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** render_widget follows the assistant's own rules, not only the person's
|
||||
** permission to see the widget. A widget is code of the application that
|
||||
** can show rows of any table, so a table the assistant may not read could be
|
||||
** read through one: the widget is rendered only when the host allowed it by
|
||||
** name, and only while the assistant may read every table the host said it
|
||||
** reads.
|
||||
**
|
||||
** The application has one widget, which anybody may see on a screen and
|
||||
** which shows a row of the blog posts.
|
||||
*******************************************************************************/
|
||||
class RenderWidgetAccessTest extends BaseAssistantTest
|
||||
{
|
||||
private static final String WIDGET = "latestPosts";
|
||||
private static final String ROW = "ROW_OF_A_TABLE_8c41";
|
||||
|
||||
private static final AtomicInteger RENDERED = new AtomicInteger();
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
protected AssistantTestFixture.InstanceCustomizer instanceCustomizer()
|
||||
{
|
||||
return (RenderWidgetAccessTest::customize);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
private static void customize(QInstance qInstance)
|
||||
{
|
||||
qInstance.addWidget(new QWidgetMetaData().withName(WIDGET).withLabel("Latest Posts").withType(WidgetType.HTML.getType()).withCodeReference(new QCodeReference(Renderer.class))
|
||||
.withPermissionRules(new QPermissionRules().withLevel(PermissionLevel.NOT_PROTECTED)));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@BeforeEach
|
||||
void reset()
|
||||
{
|
||||
RENDERED.set(0);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** No widget is renderable until the host names one and declares the
|
||||
** tables it reads: the default is closed, and a name alone opens nothing.
|
||||
** The refusal is the assistant's own, before the application is asked to
|
||||
** render, and is the same for a widget that does not exist.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void noWidgetIsRenderedUntilTheHostAllowsIt() throws Exception
|
||||
{
|
||||
ToolCallOutcome refused = call(WIDGET);
|
||||
assertThat(refused.result().getOutcome()).isEqualTo(AiToolOutcome.DENIED);
|
||||
assertThat(refused.result().getPermissionCheck()).isEqualTo("widget:notAllowed");
|
||||
assertThat(refused.result().getModelContent()).isEqualTo("The widget \"" + WIDGET + "\" is not available to the assistant.").doesNotContain(ROW);
|
||||
assertThat(refused.result().getRender()).isNull();
|
||||
assertThat(RENDERED.get()).as("the application was not asked to render it").isZero();
|
||||
assertThat(call("noSuchWidget").result().getModelContent()).as("and it does not say whether a widget exists").isEqualTo("The widget \"noSuchWidget\" is not available to the assistant.");
|
||||
|
||||
config.withAllowedWidgetNames(new LinkedHashSet<>(List.of(WIDGET)));
|
||||
ToolCallOutcome undeclared = call(WIDGET);
|
||||
assertThat(undeclared.result().getOutcome()).as("allowed by name, but nothing says which tables it reads").isEqualTo(AiToolOutcome.DENIED);
|
||||
assertThat(undeclared.result().getPermissionCheck()).isEqualTo("widget:tablesNotDeclared");
|
||||
assertThat(undeclared.result().getModelContent()).doesNotContain(ROW);
|
||||
assertThat(RENDERED.get()).as("the application was not asked to render it").isZero();
|
||||
|
||||
config.withWidgetTables(WIDGET, Set.of("blog_post"));
|
||||
ToolCallOutcome rendered = call(WIDGET);
|
||||
assertThat(rendered.result().getOutcome()).as(rendered.result().getModelContent()).isEqualTo(AiToolOutcome.OK);
|
||||
assertThat(rendered.result().getModelContent()).contains(ROW);
|
||||
assertThat(RENDERED.get()).isEqualTo(1);
|
||||
|
||||
config.withHiddenWidgetNames(new LinkedHashSet<>(List.of(WIDGET)));
|
||||
assertThat(call(WIDGET).result().getPermissionCheck()).as("a widget the host hid is refused also when it is allowed").isEqualTo("widget:hidden");
|
||||
assertThat(RENDERED.get()).isEqualTo(1);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A widget the host allowed and said reads a table is rendered only while
|
||||
** the assistant may read that table: a pin in code, a table the host named
|
||||
** that does not exist, and an administrator's row each close it, and the
|
||||
** rows of the table do not reach the model through the widget.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void aWidgetIsNotRenderedWhenTheAssistantMayNotReadATableItReads() throws Exception
|
||||
{
|
||||
config.withAllowedWidgetNames(new LinkedHashSet<>(List.of(WIDGET))).withWidgetTables(WIDGET, Set.of("blog_post", "page"));
|
||||
assertThat(call(WIDGET).result().getOutcome()).as("both tables may be read").isEqualTo(AiToolOutcome.OK);
|
||||
assertThat(RENDERED.get()).isEqualTo(1);
|
||||
|
||||
config.withTableAccess("blog_post", DataAccessMode.NONE);
|
||||
config.getRuntime().getDataAccessService().invalidate();
|
||||
ToolCallOutcome closed = call(WIDGET);
|
||||
assertThat(closed.result().getOutcome()).isEqualTo(AiToolOutcome.DENIED);
|
||||
assertThat(closed.result().getPermissionCheck()).isEqualTo("dataAccess:table:NONE");
|
||||
assertThat(closed.result().getModelContent()).isEqualTo("The widget \"" + WIDGET + "\" is not available to the assistant.").doesNotContain(ROW);
|
||||
assertThat(RENDERED.get()).as("the application was not asked to render it").isEqualTo(1);
|
||||
|
||||
config.withTableAccess("blog_post", DataAccessMode.READ);
|
||||
config.getRuntime().getDataAccessService().invalidate();
|
||||
assertThat(call(WIDGET).result().getOutcome()).as("a table the assistant may only read is read").isEqualTo(AiToolOutcome.OK);
|
||||
|
||||
config.withWidgetTables(WIDGET, Set.of("page", "noSuchTable"));
|
||||
assertThat(call(WIDGET).result().getOutcome()).as("a table that is not there is not readable").isEqualTo(AiToolOutcome.DENIED);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A widget that reads a table is not rendered for a person who may not
|
||||
** read that table, although they may see the widget on a screen and the
|
||||
** assistant may read the table: the person is the boundary.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void aWidgetIsNotRenderedForAPersonWhoMayNotReadATableItReads() throws Exception
|
||||
{
|
||||
config.withAllowedWidgetNames(new LinkedHashSet<>(List.of(WIDGET))).withWidgetTables(WIDGET, Set.of("blog_post"));
|
||||
assertThat(call(WIDGET).result().getOutcome()).as("the editor may read posts").isEqualTo(AiToolOutcome.OK);
|
||||
assertThat(RENDERED.get()).isEqualTo(1);
|
||||
|
||||
ToolCallOutcome refused = call(AssistantTestFixture.ANALYST, WIDGET);
|
||||
assertThat(refused.result().getOutcome()).as("the analyst may not").isEqualTo(AiToolOutcome.DENIED);
|
||||
assertThat(refused.result().getPermissionCheck()).isEqualTo("uiApi:GET /metaData/table/{tableName}:readPermission");
|
||||
assertThat(refused.result().getModelContent()).isEqualTo("The widget \"" + WIDGET + "\" is not available to the assistant.").doesNotContain(ROW);
|
||||
assertThat(RENDERED.get()).as("the application was not asked to render it").isEqualTo(1);
|
||||
|
||||
config.withWidgetTables(WIDGET, Set.of());
|
||||
assertThat(call(AssistantTestFixture.ANALYST, WIDGET).result().getOutcome()).as("a widget the host declared as reading no table").isEqualTo(AiToolOutcome.OK);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** One render_widget call of the fixture's editor, logged.
|
||||
*******************************************************************************/
|
||||
private ToolCallOutcome call(String widget) throws Exception
|
||||
{
|
||||
return (call(EDITOR, widget));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** One render_widget call of a person, logged.
|
||||
*******************************************************************************/
|
||||
private ToolCallOutcome call(String person, String widget) throws Exception
|
||||
{
|
||||
return (config.getRuntime().getToolCalls().executeAndLog(ToolCalls.call(config, person, UiApiToolbox.RENDER_WIDGET, Map.of("name", widget)), null, false));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The widget: it shows a row of a table.
|
||||
*******************************************************************************/
|
||||
public static class Renderer extends AbstractWidgetRenderer
|
||||
{
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public RenderWidgetOutput render(RenderWidgetInput input) throws QException
|
||||
{
|
||||
RENDERED.incrementAndGet();
|
||||
return (new RenderWidgetOutput(new RawHTML("Latest Posts", "<p>" + ROW + "</p>")));
|
||||
}
|
||||
}
|
||||
}
|
||||
+3
-2
@@ -325,9 +325,10 @@ class ToolCallArchitectureTest
|
||||
if(origin.equals(AssistantRuntime.class.getName()) || origin.startsWith(AssistantRuntime.class.getName() + "$"))
|
||||
{
|
||||
///////////////////////////////////////////////////////////////////
|
||||
// the runtime builds the toolboxes and their families //
|
||||
// the runtime builds the toolboxes and their families, and //
|
||||
// hands the record tools the host's rules for widgets //
|
||||
///////////////////////////////////////////////////////////////////
|
||||
return ("<init>".equals(name) || "withScheduledDeliveryCheck".equals(name));
|
||||
return ("<init>".equals(name) || "withScheduledDeliveryCheck".equals(name) || "withWidgetRules".equals(name));
|
||||
}
|
||||
if(owner.equals(UiApiToolbox.class.getName()))
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user