Merge custom option test fix into v2 roll-up
This commit is contained in:
99 files changed
+6433
-1221
No files matched your search
@@ -6,21 +6,21 @@ tags:
|
|||||||
|
|
||||||
Homarr has the following keyboard shortcuts:
|
Homarr has the following keyboard shortcuts:
|
||||||
|
|
||||||
| Shortcut | Description |
|
| Shortcut | Description |
|
||||||
| ---------------------------------------------- | ------------------------------------------ |
|
| ----------------------------------------------- | ------------------------------------------ |
|
||||||
| `MOD` + `K` | Opens the search bar |
|
| `MOD` + `K` | Opens the search bar |
|
||||||
| `MOD` + `J` | Toggles Dark Mode |
|
| `MOD` + `J` | Toggles Dark Mode |
|
||||||
| `MOD` + `E` | Toggles Edit Mode |
|
| `MOD` + `E` | Toggles Edit Mode |
|
||||||
| Hold `Shift` while hovering a supported widget | Opens its temporary advanced view |
|
| Hold `Shift` for 500 ms over a supported widget | Opens its temporary advanced view |
|
||||||
| `Shift` + `Enter` on a supported widget | Opens its advanced view until it is closed |
|
| `Shift` + `Enter` on a supported widget | Opens its advanced view until it is closed |
|
||||||
| `Esc` | Closes an open advanced view or board menu |
|
| `Esc` | Closes an open advanced view or board menu |
|
||||||
|
|
||||||
:::tip
|
:::tip
|
||||||
|
|
||||||
Here `MOD` refers to the modifier key, which is `Ctrl` on Windows and `Cmd` on macOS.
|
Here `MOD` refers to the modifier key, which is `Ctrl` on Windows and `Cmd` on macOS.
|
||||||
|
|
||||||
Advanced view is available outside edit mode. Widgets without a distinct advanced experience adapt to their normal
|
Advanced view is available outside edit mode. Widgets without a distinct advanced experience adapt to their normal
|
||||||
dimensions instead.
|
dimensions instead. A progress ring follows the pointer while the temporary advanced view is preparing to open.
|
||||||
|
|
||||||
:::
|
:::
|
||||||
|
|
||||||
|
|||||||
@@ -33,7 +33,9 @@ on a dashboard. By default it follows the current conversation. Widget settings
|
|||||||
conversation; the conversation picker stays hidden until **Pinned conversation** is selected.
|
conversation; the conversation picker stays hidden until **Pinned conversation** is selected.
|
||||||
The Shift+A panel is non-modal: opening it focuses its composer, but it does not capture focus from the board.
|
The Shift+A panel is non-modal: opening it focuses its composer, but it does not capture focus from the board.
|
||||||
Users can continue typing in an Assistant widget or interacting with other dashboard controls while the panel
|
Users can continue typing in an Assistant widget or interacting with other dashboard controls while the panel
|
||||||
is open.
|
is open. Every visible assistant surface keeps its own draft, attachment list, selection, and focus while sharing
|
||||||
|
the same persisted conversation. Switching conversations restores the draft that belongs to that surface and
|
||||||
|
conversation instead of copying text into another widget or the floating panel.
|
||||||
|
|
||||||
When the assistant is unavailable, its command-menu result remains visible but disabled and explains that
|
When the assistant is unavailable, its command-menu result remains visible but disabled and explains that
|
||||||
an administrator must configure and enable it.
|
an administrator must configure and enable it.
|
||||||
@@ -44,20 +46,18 @@ Homarr includes presets for OpenRouter, OpenAI, Anthropic Claude, Google Gemini,
|
|||||||
DeepSeek, Together AI, Ollama, and LM Studio. Provider icons make the presets easy to identify. A custom
|
DeepSeek, Together AI, Ollama, and LM Studio. Provider icons make the presets easy to identify. A custom
|
||||||
preset connects any other service that implements the OpenAI Chat Completions API.
|
preset connects any other service that implements the OpenAI Chat Completions API.
|
||||||
|
|
||||||
The provider list also shows **Homarr — Coming soon** as a disabled option. The future service will be a
|
The provider list also shows **Homarr — Coming soon** as a disabled option.
|
||||||
Homarr-hosted OpenRouter proxy with the same model discovery, tool-calling, and server-tool features. Keeping
|
|
||||||
it visible reserves a clear place for that service without making an unavailable backend selectable today.
|
|
||||||
|
|
||||||
The management page presents setup as three compact sections: provider and endpoint, credentials, then
|
The management page presents setup as three compact sections: provider and endpoint, credentials, then
|
||||||
model and availability. A status summary at the top shows whether the connection is ready, whether a key
|
model and availability. A status summary at the top shows whether the connection is ready, whether a key
|
||||||
is protected, which model is selected, and whether users can open the assistant.
|
is protected, and which model is selected. Redundant active-state badges are omitted when the setup is ready.
|
||||||
|
|
||||||
1. Choose a provider preset or **Custom endpoint**, then confirm the API base URL. It usually ends in `/v1`.
|
1. Choose a provider preset or **Custom endpoint**, then confirm the API base URL. It usually ends in `/v1`.
|
||||||
2. Add an API key if the service requires bearer authentication. Additional authentication or routing
|
2. Add an API key if the service requires bearer authentication. Additional authentication or routing
|
||||||
headers are available in the collapsed advanced section.
|
headers are available in the collapsed advanced section.
|
||||||
3. Save the provider connection.
|
3. Save the provider connection.
|
||||||
4. Refresh the model list and select a discovered model. Homarr displays the friendly model name but
|
4. Refresh the model list and select a discovered model. Homarr displays the friendly model name but
|
||||||
stores and sends the provider's exact model ID.
|
stores and sends the provider's exact model ID. Context-window sizes use compact labels such as `1M`.
|
||||||
5. Enable the assistant and save the configuration.
|
5. Enable the assistant and save the configuration.
|
||||||
|
|
||||||
The model discovery path defaults to `/models` and is appended to the API base URL. Leave it blank when
|
The model discovery path defaults to `/models` and is appended to the API base URL. Leave it blank when
|
||||||
@@ -121,13 +121,19 @@ Files returned by a compatible model can be downloaded directly from the message
|
|||||||
Assistant responses render GitHub-flavored Markdown, including headings, links, lists, task lists, tables,
|
Assistant responses render GitHub-flavored Markdown, including headings, links, lists, task lists, tables,
|
||||||
quotes, inline code, and fenced code blocks. Line breaks are preserved, and Homarr repairs common streamed
|
quotes, inline code, and fenced code blocks. Line breaks are preserved, and Homarr repairs common streamed
|
||||||
responses where a provider returns escaped line breaks or places a bold-label list on one line.
|
responses where a provider returns escaped line breaks or places a bold-label list on one line.
|
||||||
|
Completed fenced code blocks use language-aware syntax highlighting; a streaming block stays plain until its
|
||||||
|
content is stable. Safe same-origin links are prefetched and use client-side navigation, so opening a returned
|
||||||
|
preview, editor, board, or other Homarr item does not unload the assistant. External links keep their normal
|
||||||
|
external-browser behavior.
|
||||||
Fenced `mermaid` blocks render as diagrams in the current color scheme using Mermaid's strict security mode;
|
Fenced `mermaid` blocks render as diagrams in the current color scheme using Mermaid's strict security mode;
|
||||||
invalid diagrams fall back to their source instead of breaking the response.
|
invalid diagrams fall back to their source instead of breaking the response.
|
||||||
When Homarr's icon search returns an image URL, visual result tables render that actual icon in a compact
|
When Homarr's icon search returns an image URL, visual result tables render that actual icon in a compact
|
||||||
image column instead of substituting an emoji. Assistant-provided Markdown images accept safe relative,
|
image column instead of substituting an emoji. Assistant-provided Markdown images accept safe relative,
|
||||||
HTTP, and HTTPS sources and load without forwarding the Homarr page as the referrer.
|
HTTP, and HTTPS sources and load without forwarding the Homarr page as the referrer.
|
||||||
Images up to 1 MB and text, Markdown, CSV, HTML, XML, or JSON documents up to 350 KB can be attached by
|
Images up to 1 MB and text, Markdown, CSV, HTML, XML, or JSON documents up to 350 KB can be attached by
|
||||||
using the paperclip or dropping files onto the composer. A request can contain up to five attachments.
|
using the paperclip, dropping files onto the composer, or pasting an image with `Cmd/Ctrl + V`. Attachment
|
||||||
|
previews stay local to the composer where they were added and show upload state, file type, and a removable image
|
||||||
|
thumbnail or document tile. A request can contain up to five attachments.
|
||||||
Image understanding depends on the selected model; document text is extracted locally by Homarr and sent
|
Image understanding depends on the selected model; document text is extracted locally by Homarr and sent
|
||||||
as part of the prompt.
|
as part of the prompt.
|
||||||
|
|
||||||
@@ -143,24 +149,34 @@ their description, context size and image-input capability, plus the thinking-le
|
|||||||
stored on the conversation after a completed request. Thinking mode can be left on **Auto**, disabled, or set
|
stored on the conversation after a completed request. Thinking mode can be left on **Auto**, disabled, or set
|
||||||
from minimal through high; explicit levels are sent using the AI SDK's provider-neutral reasoning setting and
|
from minimal through high; explicit levels are sent using the AI SDK's provider-neutral reasoning setting and
|
||||||
still depend on support from the chosen model and endpoint. Reasoning text is shown live when the provider
|
still depend on support from the chosen model and endpoint. Reasoning text is shown live when the provider
|
||||||
streams it. The **Thinking** disclosure can be opened or closed without interrupting the response.
|
streams it through assistant-ui's compact chain-of-thought disclosure. The **Thinking** disclosure renders
|
||||||
|
Markdown, can be opened or closed without interrupting the response, and keeps the user's collapsed state when
|
||||||
|
another message starts. A compact dot matrix distinguishes an initial thinking pass from response streaming and
|
||||||
|
settles into waiting, success, or error states in the minimized activity bar. The state always keeps its text label,
|
||||||
|
and the animation is disabled when the operating system requests reduced motion.
|
||||||
|
|
||||||
Each completed response includes a circular context-window meter. Select it to open request details when
|
A circular context ring beside the model selector gives a quick glance at cumulative conversation usage without
|
||||||
the provider reports them: input, output, cached-input and reasoning tokens, used and remaining context,
|
expanding the composer toolbar. Its accessible label includes cumulative tokens and cost when available, while
|
||||||
time to first output, total duration, output speed, agent-step timing, and cost. OpenRouter-reported cost
|
its popover keeps the latest complete context reading as a new response starts and lists every request
|
||||||
is labeled as reported.
|
turn with its model, provider, input, output, cached-input and reasoning tokens, context use, duration, speed,
|
||||||
While the next response is still streaming, the meter keeps the last completed reading for the same model and
|
agent steps, routing details, and cost when reported. Before usage is available, the control remains a compact
|
||||||
context capacity instead of briefly showing an incorrect zero. It switches to the new request when token usage
|
ring instead of showing a redundant missing-data label. Closing and reopening the popover reads persisted
|
||||||
arrives; incompatible model capacities are never mixed.
|
conversation metadata instead of resetting the display to zero.
|
||||||
OpenRouter responses request inline usage and routing metadata. When request details are opened, Homarr also
|
|
||||||
loads the server-side generation record for each model step and briefly polls while OpenRouter finishes
|
Each assistant response places a small provider logo in the same stable action toolbar as copy, export,
|
||||||
processing it. The details separate Homarr's end-to-end timing from OpenRouter's provider latency,
|
feedback, and regenerate. Hovering the logo shows the provider, exact model, timing, throughput, and cost without
|
||||||
generation time, and provider throughput, and can include normalized and native token counts, moderation
|
adding another metadata row to the transcript. Branch navigation occupies its own adjacent group, so switching
|
||||||
latency, cache discount, fallback count, service tier, data region, BYOK status, routed provider, generation
|
between response versions never pushes the response actions off-screen.
|
||||||
identifier, exact cost, and upstream inference cost. Provider credentials remain server-side; the browser
|
|
||||||
can request only generation identifiers already stored on a conversation owned by the signed-in user and
|
OpenRouter responses request inline usage and routing metadata. Opening detailed turn data also loads the
|
||||||
signed by the Homarr server for that user and conversation. Successful generation lookups are cached
|
server-side generation record for its model steps and briefly polls while OpenRouter finishes processing it.
|
||||||
briefly so polling and multi-step requests do not repeatedly query OpenRouter for the same record.
|
The details separate Homarr's end-to-end timing from OpenRouter's provider latency, generation time, and provider
|
||||||
|
throughput, and can include normalized and native token counts, moderation latency, cache discount, fallback count,
|
||||||
|
service tier, data region, BYOK status, routed provider, generation identifier, exact cost, and upstream inference
|
||||||
|
cost. Provider credentials remain server-side; the browser can request only generation identifiers already stored
|
||||||
|
on a conversation owned by the signed-in user and signed by the Homarr server for that user and conversation.
|
||||||
|
Successful generation lookups are cached briefly so polling and multi-step requests do not repeatedly query
|
||||||
|
OpenRouter for the same record.
|
||||||
When a provider omits cost but model discovery includes prompt and completion pricing, Homarr labels the
|
When a provider omits cost but model discovery includes prompt and completion pricing, Homarr labels the
|
||||||
calculated value as estimated. Missing provider data is shown as not reported rather than inferred.
|
calculated value as estimated. Missing provider data is shown as not reported rather than inferred.
|
||||||
|
|
||||||
@@ -193,7 +209,15 @@ Custom-widget tools let an administrator list, inspect, create, and update defin
|
|||||||
form's **Design with AI** action sends a focused request into the current conversation, where the assistant
|
form's **Design with AI** action sends a focused request into the current conversation, where the assistant
|
||||||
can propose the matching mutation and use the same approval controls. Existing stored secret values are
|
can propose the matching mutation and use the same approval controls. Existing stored secret values are
|
||||||
reported only as configured/not configured and are preserved on update unless replacements are explicitly
|
reported only as configured/not configured and are preserved on update unless replacements are explicitly
|
||||||
provided.
|
provided. For Custom Widget requests, Homarr lazily adds the complete installed skill, all bundled schema,
|
||||||
|
runtime and security references, and the current JSON Schema to the trusted authoring context. This avoids an
|
||||||
|
extra provider round trip for the large `customWidget_getSkill` and `customWidget_schema` results. If the model
|
||||||
|
discovers the Custom Widget workflow mid-response, Homarr promotes the same resources before its next step and
|
||||||
|
removes the now-redundant resource calls from provider history. Multiline JSX uses `templateLines` to avoid fragile
|
||||||
|
streamed JSON escaping. The assistant validates the candidate, creates a preview, executes every returned preview query,
|
||||||
|
checks the actual HTTP status and response shape, and iterates before saving. Preview and saved-definition results
|
||||||
|
include safe Homarr paths that open in the assistant without a page reload. When placement is still a choice, the
|
||||||
|
assistant uses the structured question UI instead of ending with a prose question.
|
||||||
|
|
||||||
The shield control in the conversation header can enable automatic approvals for the current conversation.
|
The shield control in the conversation header can enable automatic approvals for the current conversation.
|
||||||
While enabled, Homarr accepts every affirmative approval step as it arrives: protected mutations are approved,
|
While enabled, Homarr accepts every affirmative approval step as it arrives: protected mutations are approved,
|
||||||
@@ -207,8 +231,9 @@ When the assistant genuinely needs missing information or a choice, it can pause
|
|||||||
question. Each proposed answer is visibly categorized as **Confirm**, **Decline**, or **Option**, so the effect
|
question. Each proposed answer is visibly categorized as **Confirm**, **Decline**, or **Option**, so the effect
|
||||||
of automatic approval is unambiguous. Users can select one of the proposed answers or choose **Other** and
|
of automatic approval is unambiguous. Users can select one of the proposed answers or choose **Other** and
|
||||||
enter their own response. While a question is unanswered, its controls stay in a dedicated area immediately
|
enter their own response. While a question is unanswered, its controls stay in a dedicated area immediately
|
||||||
above the composer instead of requiring the user to find the tool call in the transcript. The answered choice
|
above the composer instead of requiring the user to find the tool call in the transcript. The question temporarily
|
||||||
then remains in the conversation history.
|
uses the available conversation body, with its own scrolling when necessary, rather than squeezing a long option
|
||||||
|
list into a short dock beside part of the transcript. The answered choice then remains in the conversation history.
|
||||||
Submitting the answer resumes the same agent run automatically. The minimized activity bar shows the
|
Submitting the answer resumes the same agent run automatically. The minimized activity bar shows the
|
||||||
question or approval that needs attention and opens directly back to the request. While an answer, app
|
question or approval that needs attention and opens directly back to the request. While an answer, app
|
||||||
form, or mutation approval is pending, the composer preserves its draft but does not replace the pending
|
form, or mutation approval is pending, the composer preserves its draft but does not replace the pending
|
||||||
|
|||||||
@@ -38,7 +38,8 @@ Underscores and hyphen-minus are allowed.
|
|||||||
|
|
||||||
The column count defines how many fixed-width cells are available in each row.
|
The column count defines how many fixed-width cells are available in each row.
|
||||||
One cell contains a `200 × 200` logical-pixel tile.
|
One cell contains a `200 × 200` logical-pixel tile.
|
||||||
Homarr scales the whole board uniformly instead of changing widget proportions, with horizontal scrolling when further shrinking would make controls too small.
|
Homarr scales the whole board uniformly instead of changing widget proportions, and always fits it to the available width without horizontal scrolling.
|
||||||
|
The main canvas and enabled rails stay at least one viewport tall, and the canvas grows automatically while you drag or resize items near its lower edge.
|
||||||
|
|
||||||
### Public
|
### Public
|
||||||
|
|
||||||
@@ -95,6 +96,14 @@ In this section you can configure the different responsive layouts. Homarr selec
|
|||||||
|
|
||||||
Every board has two protected layouts:
|
Every board has two protected layouts:
|
||||||
|
|
||||||
|
Every `1 × 1` tile has a `200 × 200` logical-pixel content area.
|
||||||
|
The `24` logical-pixel gap between tiles is separate from that size.
|
||||||
|
A `2 × 1` tile therefore contains two fixed cell widths plus the gap between them.
|
||||||
|
Widgets see their logical size, while the board's visual scale makes the complete layout larger or smaller.
|
||||||
|
When fitting below 100%, Homarr keeps widget typography and control density at their normal readable size.
|
||||||
|
On larger canvases, the complete board grows together like browser zoom.
|
||||||
|
The complete canvas always fits the available width and never adds horizontal board scrolling.
|
||||||
|
|
||||||
- **Mobile** starts at `0px` and uses three columns on new boards.
|
- **Mobile** starts at `0px` and uses three columns on new boards.
|
||||||
- **Base** is the widest layout and starts at `768px` on new boards.
|
- **Base** is the widest layout and starts at `768px` on new boards.
|
||||||
|
|
||||||
@@ -104,9 +113,10 @@ Each layout stores independent positions and sizes. Moving or resizing a widget
|
|||||||
|
|
||||||
Use **Reset from Base** on Mobile or a custom layout to replace all of its positions and sizes with a newly generated version of Base. The layout's name, breakpoint, and column count are kept.
|
Use **Reset from Base** on Mobile or a custom layout to replace all of its positions and sizes with a newly generated version of Base. The layout's name, breakpoint, and column count are kept.
|
||||||
|
|
||||||
Every `1 × 1` tile has a `200 × 200` logical-pixel content area, with a separate `24` logical-pixel gap between tiles. Homarr scales the whole canvas to the available width without shrinking below 75%; narrower screens scroll horizontally so controls remain accessible.
|
The canvas is at least one window tall, even when it is empty.
|
||||||
|
Its left and right edges are hard drag boundaries, while its bottom edge extends automatically as a tile is dragged or resized downward.
|
||||||
The board edge is a hard drag boundary. Moving a tile outside it cancels the placement, while adding content can still create the rows it needs. New items use their widget's default size and new Containers use a useful `4 × 3` size when space allows.
|
Nested Containers keep their own resizable bounds.
|
||||||
|
New items use their widget's default size and new Containers use a useful `4 × 3` size when space allows.
|
||||||
|
|
||||||
#### Name
|
#### Name
|
||||||
|
|
||||||
@@ -118,7 +128,18 @@ The total number of columns in the layout. Changing it projects the saved positi
|
|||||||
|
|
||||||
#### Fixed rails
|
#### Fixed rails
|
||||||
|
|
||||||
Each layout can reserve a fixed left rail, a fixed right rail, or both. Set a rail width to zero to disable it, or choose one to three columns. Reserved rail columns reduce the main canvas width. Apps, widgets, and Containers in rails use the same fixed cell sizes and remain visible while the page scrolls.
|
Each responsive layout can enable a fixed left rail, a fixed right rail, or both.
|
||||||
|
Set a rail width to zero to disable it for that layout.
|
||||||
|
Choose a width from one to three columns with the three-step slider.
|
||||||
|
The preview shows how much space remains for the main canvas.
|
||||||
|
|
||||||
|
Rail columns are reserved from the layout's total column count.
|
||||||
|
For example, a 12-column layout with a two-column left rail leaves ten columns for the canvas.
|
||||||
|
Enabling or widening a rail reflows canvas items into the remaining columns.
|
||||||
|
Disabling a rail moves its contents back into the next available canvas positions.
|
||||||
|
|
||||||
|
Rails fill the available window height and remain fixed while the page scrolls.
|
||||||
|
Apps, widgets, and Containers inside them still use the same fixed `200 × 200` cells and can be rearranged in edit mode, where each rail shows its name and boundary.
|
||||||
|
|
||||||
#### Breakpoint
|
#### Breakpoint
|
||||||
|
|
||||||
|
|||||||
@@ -17,7 +17,9 @@ Install the Agent Skill from the verified Homarr repository:
|
|||||||
npx skills add https://github.com/homarr-labs/homarr --skill homarr-custom-widget
|
npx skills add https://github.com/homarr-labs/homarr --skill homarr-custom-widget
|
||||||
```
|
```
|
||||||
|
|
||||||
The portable skill gives concise authoring guidance. The Homarr MCP prompt gives connected agents a retrieval workflow: read the live schema, then fetch only the component documentation needed for the widget.
|
The portable skill gives concise authoring guidance. For connected agents, Homarr returns the complete `SKILL.md` and
|
||||||
|
all bundled skill references once in one lazy tool response. The Homarr MCP prompt then gives the agent a
|
||||||
|
retrieval workflow: read the live schema and fetch only the component documentation needed for the widget.
|
||||||
|
|
||||||
The workbench's **Copy AI prompt** action is separate. It creates a self-contained prompt below 12,000 characters for an ordinary ChatGPT or Claude conversation. It includes the lean contract, bindings, recommended components, and two polished examples. It never tells an offline model to call MCP tools.
|
The workbench's **Copy AI prompt** action is separate. It creates a self-contained prompt below 12,000 characters for an ordinary ChatGPT or Claude conversation. It includes the lean contract, bindings, recommended components, and two polished examples. It never tells an offline model to call MCP tools.
|
||||||
|
|
||||||
@@ -37,38 +39,55 @@ Repository code cannot give this attribution.
|
|||||||
|
|
||||||
The authoring-prompt tool description contains one sentence. The prompt contains the workflow instructions and resource links.
|
The authoring-prompt tool description contains one sentence. The prompt contains the workflow instructions and resource links.
|
||||||
|
|
||||||
`GET /api/custom-widgets/skill` and the MCP tool return the concise skill discovery payload:
|
`GET /api/custom-widgets/skill` and `customWidget_getSkill` return a self-contained structured skill payload:
|
||||||
|
|
||||||
```ts
|
```ts
|
||||||
{
|
{
|
||||||
name: "homarr-custom-widget";
|
name: "homarr-custom-widget";
|
||||||
version: string;
|
version: string;
|
||||||
skillMd: string;
|
skillMd: string; // Complete SKILL.md
|
||||||
|
references: Record<string, string>;
|
||||||
skillsShUrl: string;
|
skillsShUrl: string;
|
||||||
sourceUrl: string;
|
sourceUrl: string;
|
||||||
installCommand: string;
|
installCommand: string;
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
The full installed component catalog stays available through `homarr://custom-widgets/components` and per-component resources. It is deliberately not embedded in the skill or clipboard prompt.
|
The `homarr://custom-widgets/skill` MCP resource returns the same `SKILL.md` and references once as bundled Markdown.
|
||||||
|
|
||||||
|
The component catalog is a compact index of names, categories, safety levels, shared prop names, policies, and example
|
||||||
|
IDs. Per-component results contain only component-specific props and a reference to shared prop documentation. Use
|
||||||
|
`customWidget_getSharedProps` once with only the shared prop names needed across the selected components. This avoids
|
||||||
|
repeating hundreds of global props in every tool result. The catalog is deliberately not embedded in the skill or
|
||||||
|
clipboard prompt; the skill response still contains the complete authoring, schema, runtime, and security references.
|
||||||
|
|
||||||
These interfaces do not return an archive URL or archive hash.
|
These interfaces do not return an archive URL or archive hash.
|
||||||
|
|
||||||
## Create a Custom Widget with MCP
|
## Create a Custom Widget with MCP
|
||||||
|
|
||||||
1. Get the prompt, live schema, and component catalog.
|
1. Load `customWidget_getSkill`, then get the prompt and live schema.
|
||||||
2. Read the external API documentation.
|
2. Call `customWidget_getComponentCatalog`, followed by `customWidget_getComponent` for only the relevant installed
|
||||||
3. Build one definition.
|
components and `customWidget_getExample` when one catalog example matches the interaction pattern. If shared props
|
||||||
4. Validate the definition without saving it.
|
are needed, collect their catalog names and call `customWidget_getSharedProps` once for that set.
|
||||||
5. Create a preview session.
|
3. Read the external API documentation.
|
||||||
6. Test the queries and actions.
|
4. Build one definition, using `templateLines` for multiline JSX tool input.
|
||||||
7. Open the preview URL with browser tools.
|
5. Validate the definition without saving it and repair every reported issue.
|
||||||
8. Inspect the redacted journal and revise the local candidate until it is valid.
|
6. Create a preview session.
|
||||||
9. Create the widget, including any source URLs and credentials the user already supplied.
|
7. Run `customWidget_previewQuery` for every query returned by the preview and inspect its actual status and data shape.
|
||||||
10. Otherwise, ask the user to configure the saved definition with the ten-minute Homarr source-setup URL.
|
8. Test relevant actions in simulation mode.
|
||||||
11. Create a final preview with the saved definition ID so Homarr loads its stored credentials, then test it again.
|
9. Open the returned preview path with browser tools.
|
||||||
12. Update the saved definition if the final verification finds a problem.
|
10. Inspect the redacted journal and revise the local candidate until validation, data, and rendering all work.
|
||||||
13. Repeat the procedure for the next widget.
|
11. Create the widget, including any source URLs and credentials the user already supplied.
|
||||||
|
12. Open its returned management path, and use a structured question when the user must choose whether to place it on a board.
|
||||||
|
13. Otherwise, ask the user to configure the saved definition with the ten-minute Homarr source-setup URL.
|
||||||
|
14. Create a final preview with the saved definition ID so Homarr loads its stored credentials, then test it again.
|
||||||
|
15. Update the saved definition if the final verification finds a problem. `customWidget_update` also accepts
|
||||||
|
`templateLines` for multiline JSX without resetting omitted options.
|
||||||
|
16. Repeat the procedure for the next widget.
|
||||||
|
|
||||||
|
Successful validation returns a compact summary instead of echoing the full widget and template. Preview creation
|
||||||
|
returns its session, links, and query checklist without repeating the submitted definition. Keep the candidate locally
|
||||||
|
and reuse it for the next lifecycle step.
|
||||||
|
|
||||||
Each source-configuration URL applies to one definition or preview and one source. It is short-lived, single-use, and
|
Each source-configuration URL applies to one definition or preview and one source. It is short-lived, single-use, and
|
||||||
can only be opened and completed by an authenticated Homarr administrator. The administrator confirms the server URL,
|
can only be opened and completed by an authenticated Homarr administrator. The administrator confirms the server URL,
|
||||||
|
|||||||
@@ -195,21 +195,36 @@ An agent creates one `homarr-custom-widget-v2` definition at a time. Start with
|
|||||||
The API key owner must be a Homarr administrator. The same rule applies to management, import, migration, preview,
|
The API key owner must be a Homarr administrator. The same rule applies to management, import, migration, preview,
|
||||||
secrets, publication, Workshop installation, and the HTTP authoring resources.
|
secrets, publication, Workshop installation, and the HTTP authoring resources.
|
||||||
|
|
||||||
Then, read the live schema and component resources. These resources describe the installed Mantine components.
|
Load the installed skill before authoring. `customWidget_getSkill` returns the complete `SKILL.md` entrypoint and every
|
||||||
|
bundled reference in one response, so an MCP client does not need filesystem access or a second documentation fetch.
|
||||||
|
Then read the live schema and only the component resources required by the design. These resources describe the
|
||||||
|
installed Mantine components.
|
||||||
|
|
||||||
1. Call `customWidget_getAuthoringPrompt` and `customWidget_schema`.
|
1. Call `customWidget_getSkill`, `customWidget_getAuthoringPrompt`, `customWidget_schema`, and
|
||||||
2. Build one Custom Widget definition.
|
`customWidget_getComponentCatalog`.
|
||||||
3. Call `customWidget_validate` without saving the definition.
|
2. Fetch only the relevant installed component documentation with `customWidget_getComponent` and, when useful,
|
||||||
4. Call `customWidget_previewCreate`.
|
one interaction example with `customWidget_getExample`. Component results contain component-specific props; collect
|
||||||
5. Test named requests with `customWidget_previewQuery` and `customWidget_previewAction`.
|
any needed shared prop names from the compact catalog and fetch them together once with `customWidget_getSharedProps`.
|
||||||
6. Open the returned preview URL.
|
3. Build one Custom Widget definition. Use `templateLines` for generated multiline JSX to avoid a fragile JSON-escaped
|
||||||
7. Examine `customWidget_previewJournal`.
|
template string.
|
||||||
8. Revise the local candidate and create another preview session until it is ready.
|
4. Call `customWidget_validate` without saving the definition and repair every returned issue path.
|
||||||
9. Call `customWidget_create`, supplying any credentials and deployment-specific source URLs the user already provided.
|
5. Call `customWidget_previewCreate`.
|
||||||
10. If the user must enter the source URL or credentials, call `customWidget_configurationRequestUser` with the new definition ID and wait for completion.
|
6. Call `customWidget_previewQuery` for every entry in the returned `queries` list. Supply the listed invocation
|
||||||
11. Create a final preview with that definition ID so Homarr loads its stored credentials, then test it again.
|
parameters for manual queries and inspect the real HTTP status and response shape before binding template fields.
|
||||||
12. Use `customWidget_update` or `customWidget_templatePatch` for any final saved-definition corrections.
|
7. Test relevant actions with `customWidget_previewAction` in simulation mode.
|
||||||
13. Repeat this procedure for the next Custom Widget.
|
8. Open the returned `previewPath` or `previewUrl`.
|
||||||
|
9. Examine `customWidget_previewJournal`.
|
||||||
|
10. Revise the local candidate and create another preview session until validation, query data, actions, and rendering
|
||||||
|
are ready.
|
||||||
|
11. Call `customWidget_create`, supplying any credentials and deployment-specific source URLs the user already provided.
|
||||||
|
12. Open the returned `managementPath` to review the exact saved definition.
|
||||||
|
13. If the user must enter the source URL or credentials, call `customWidget_configurationRequestUser` with the new definition ID and wait for completion.
|
||||||
|
14. Create a final preview with that definition ID so Homarr loads its stored credentials, then test it again.
|
||||||
|
15. Use `customWidget_update` or `customWidget_templatePatch` for any final saved-definition corrections.
|
||||||
|
16. Repeat this procedure for the next Custom Widget.
|
||||||
|
|
||||||
|
Validation and preview creation return compact lifecycle metadata. They do not echo the submitted widget or duplicate
|
||||||
|
its template as both a string and line array; the agent should retain and reuse its local candidate.
|
||||||
|
|
||||||
The agent receives the configuration-request status. The agent does not receive plaintext credentials. A preview-scoped setup URL configures only that temporary preview; use a definition-scoped URL when the values must persist.
|
The agent receives the configuration-request status. The agent does not receive plaintext credentials. A preview-scoped setup URL configures only that temporary preview; use a definition-scoped URL when the values must persist.
|
||||||
|
|
||||||
@@ -245,6 +260,10 @@ The Custom Widget tools are:
|
|||||||
- `customWidget_workshopGet`
|
- `customWidget_workshopGet`
|
||||||
- `customWidget_workshopInstall`
|
- `customWidget_workshopInstall`
|
||||||
- `customWidget_getAuthoringPrompt`
|
- `customWidget_getAuthoringPrompt`
|
||||||
|
- `customWidget_getComponentCatalog`
|
||||||
|
- `customWidget_getComponent`
|
||||||
|
- `customWidget_getSharedProps`
|
||||||
|
- `customWidget_getExample`
|
||||||
- `customWidget_getSkill`
|
- `customWidget_getSkill`
|
||||||
|
|
||||||
Custom Widget permissions are not assignable group capabilities. Administrator status is required for the complete
|
Custom Widget permissions are not assignable group capabilities. Administrator status is required for the complete
|
||||||
|
|||||||
@@ -41,17 +41,19 @@ active conversation silently: select **Open conversation** inside the widget bef
|
|||||||
### Conversation features
|
### Conversation features
|
||||||
|
|
||||||
- Create, switch, rename, and delete conversations.
|
- Create, switch, rename, and delete conversations.
|
||||||
- Send text and supported file or image attachments.
|
- Send text and supported file or image attachments by picker, drag and drop, or image paste.
|
||||||
- Mention permitted apps, integrations, boards, widgets, and tools with `@`.
|
- Mention permitted apps, integrations, boards, widgets, and tools with `@`.
|
||||||
- Use `/` shortcuts for common dashboard tasks.
|
- Use `/` shortcuts for common dashboard tasks.
|
||||||
- Review tool calls, approve mutations, and answer structured assistant questions inline.
|
- Review tool calls, approve mutations, and answer structured assistant questions inline.
|
||||||
- Answer pending structured questions from the dock above the composer without scrolling through the conversation.
|
- Answer pending structured questions from the dock above the composer without scrolling through the conversation.
|
||||||
- Enable conversation-scoped automatic approvals from the shield control to approve protected mutations, use presented form details, and choose answers categorized as affirmative without individual clicks.
|
- Enable conversation-scoped automatic approvals from the shield control to approve protected mutations, use presented form details, and choose answers categorized as affirmative without individual clicks.
|
||||||
- Edit user messages and copy, regenerate, branch, quote, export, or rate responses.
|
- Edit user messages and copy, regenerate, branch, quote, export, or rate responses.
|
||||||
- Inspect Markdown, sources, generated files, tool results, reasoning, token use, context-window use, timing,
|
- Inspect syntax-highlighted Markdown, sources, generated files, tool results, streaming chain-of-thought,
|
||||||
speed, provider routing, and cost.
|
cumulative conversation usage, per-turn token and context use, timing, speed, provider routing, and cost.
|
||||||
- Change the model and reasoning effort for the active conversation.
|
- Change the model and reasoning effort for the active conversation.
|
||||||
- Refresh the current board from the conversation header. Approved mutations also refresh visible board data automatically.
|
- Refresh the current board from the conversation header. Approved mutations also refresh visible board data automatically.
|
||||||
|
|
||||||
The expanded assistant and board widget use the same persisted thread runtime. A response continues in the
|
The expanded assistant and board widget use the same persisted thread runtime. A response continues in the
|
||||||
background when the widget leaves the viewport or the expanded panel is minimized.
|
background when the widget leaves the viewport or the expanded panel is minimized. Each visible surface keeps an
|
||||||
|
independent draft, attachments, selection, and focus, so typing in a board widget cannot move or overwrite the
|
||||||
|
floating panel composer.
|
||||||
@@ -4,8 +4,6 @@ description: "Stats of your containers"
|
|||||||
hide_title: true
|
hide_title: true
|
||||||
---
|
---
|
||||||
|
|
||||||
import { WidgetInteractionGuide } from "@site/src/components/widgets/interactions";
|
|
||||||
|
|
||||||
import { WidgetHeader } from "@site/src/components/widgets/header";
|
import { WidgetHeader } from "@site/src/components/widgets/header";
|
||||||
import { AddingWidget } from "@site/src/components/widgets/adding";
|
import { AddingWidget } from "@site/src/components/widgets/adding";
|
||||||
import { WidgetConfig } from "@site/src/components/widgets/configuration";
|
import { WidgetConfig } from "@site/src/components/widgets/configuration";
|
||||||
@@ -44,8 +42,6 @@ import dockerTable from "./img/table.png";
|
|||||||
|
|
||||||
Hover a column header to reveal its grab handle, then drag it to reorder the table or drag the header's edge to resize it. The layout is saved automatically for each widget instance and restored after a reload. These controls are disabled while the board is in edit mode.
|
Hover a column header to reveal its grab handle, then drag it to reorder the table or drag the header's edge to resize it. The layout is saved automatically for each widget instance and restored after a reload. These controls are disabled while the board is in edit mode.
|
||||||
|
|
||||||
Advanced mode exposes every available column regardless of the compact-mode column selection.
|
|
||||||
|
|
||||||
Each container row has an action menu, accessible via the three-dot icon or by right-clicking the row, with the following options:
|
Each container row has an action menu, accessible via the three-dot icon or by right-clicking the row, with the following options:
|
||||||
|
|
||||||
- **View logs** - opens a dedicated terminal page streaming the container's logs
|
- **View logs** - opens a dedicated terminal page streaming the container's logs
|
||||||
@@ -53,8 +49,6 @@ Each container row has an action menu, accessible via the three-dot icon or by r
|
|||||||
- **Remove** - permanently remove the container after a second confirmation click
|
- **Remove** - permanently remove the container after a second confirmation click
|
||||||
- **Add to Homarr** - create a bookmark app from the container
|
- **Add to Homarr** - create a bookmark app from the container
|
||||||
|
|
||||||
<WidgetInteractionGuide />
|
|
||||||
|
|
||||||
### Adding the widget
|
### Adding the widget
|
||||||
|
|
||||||
<AddingWidget />
|
<AddingWidget />
|
||||||
|
|||||||
@@ -107,6 +107,7 @@
|
|||||||
"react": "catalog:",
|
"react": "catalog:",
|
||||||
"react-dom": "catalog:",
|
"react-dom": "catalog:",
|
||||||
"react-error-boundary": "catalog:",
|
"react-error-boundary": "catalog:",
|
||||||
|
"react-shiki": "catalog:",
|
||||||
"react-simple-code-editor": "catalog:",
|
"react-simple-code-editor": "catalog:",
|
||||||
"remark-breaks": "catalog:",
|
"remark-breaks": "catalog:",
|
||||||
"remark-directive": "catalog:",
|
"remark-directive": "catalog:",
|
||||||
|
|||||||
@@ -9,14 +9,48 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.gutter {
|
.gutter {
|
||||||
position: relative;
|
--board-gutter-sticky-top: calc((var(--app-shell-header-offset, 0px) + 1rem) * var(--board-canvas-inverse-scale, 1));
|
||||||
top: 0;
|
--board-gutter-viewport-height: calc(
|
||||||
|
(100dvh - var(--app-shell-header-offset, 0px) - 1rem) * var(--board-canvas-inverse-scale, 1)
|
||||||
|
);
|
||||||
|
|
||||||
|
position: sticky;
|
||||||
|
top: var(--board-gutter-sticky-top);
|
||||||
align-self: start;
|
align-self: start;
|
||||||
|
box-sizing: border-box;
|
||||||
|
height: var(--board-gutter-viewport-height);
|
||||||
padding-top: 24px;
|
padding-top: 24px;
|
||||||
margin-top: -24px;
|
margin-top: -24px;
|
||||||
max-height: calc(100dvh - var(--app-shell-header-offset, 0px) - var(--mantine-spacing-md));
|
overflow-x: hidden;
|
||||||
overflow-y: auto;
|
overflow-y: auto;
|
||||||
overscroll-behavior: contain;
|
overscroll-behavior: contain;
|
||||||
scrollbar-gutter: stable;
|
scrollbar-gutter: stable;
|
||||||
transform: translateY(var(--board-gutter-sticky-offset, 0px));
|
}
|
||||||
|
|
||||||
|
.gutter[data-board-editing="true"] {
|
||||||
|
outline: 1px dashed var(--mantine-color-default-border);
|
||||||
|
outline-offset: -1px;
|
||||||
|
border-radius: var(--mantine-radius-md);
|
||||||
|
}
|
||||||
|
|
||||||
|
.gutter[data-board-editing="true"]::before {
|
||||||
|
position: sticky;
|
||||||
|
top: 0;
|
||||||
|
inset-inline-start: 0;
|
||||||
|
z-index: 2;
|
||||||
|
display: block;
|
||||||
|
width: fit-content;
|
||||||
|
height: 24px;
|
||||||
|
padding-inline: var(--mantine-spacing-xs);
|
||||||
|
margin-top: -24px;
|
||||||
|
overflow: hidden;
|
||||||
|
font-size: var(--mantine-font-size-xs);
|
||||||
|
line-height: 24px;
|
||||||
|
color: var(--mantine-color-dimmed);
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
pointer-events: none;
|
||||||
|
content: attr(aria-label);
|
||||||
|
background: color-mix(in srgb, var(--mantine-color-body) 88%, transparent);
|
||||||
|
border-radius: var(--mantine-radius-sm);
|
||||||
}
|
}
|
||||||
@@ -1,9 +1,9 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useEffect, useState } from "react";
|
|
||||||
import { Box, Paper, Stack, Text } from "@mantine/core";
|
import { Box, Paper, Stack, Text } from "@mantine/core";
|
||||||
|
|
||||||
import { useCurrentLayout, useInitialViewportWidth, useLayoutOverride, useRequiredBoard } from "@homarr/boards/context";
|
import { useCurrentLayout, useInitialViewportWidth, useLayoutOverride, useRequiredBoard } from "@homarr/boards/context";
|
||||||
|
import { useEditMode } from "@homarr/boards/edit-mode";
|
||||||
import { useScopedI18n } from "@homarr/translation/client";
|
import { useScopedI18n } from "@homarr/translation/client";
|
||||||
|
|
||||||
import { getRepresentativeLayoutWidth } from "../_layout-utils";
|
import { getRepresentativeLayoutWidth } from "../_layout-utils";
|
||||||
@@ -25,68 +25,14 @@ import classes from "./_client.module.css";
|
|||||||
|
|
||||||
const APP_SHELL_INLINE_PADDING = 32;
|
const APP_SHELL_INLINE_PADDING = 32;
|
||||||
|
|
||||||
const useFixedBoardGutters = () => {
|
|
||||||
const [columns, setColumns] = useState<HTMLDivElement | null>(null);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (!columns) return;
|
|
||||||
|
|
||||||
let frame = 0;
|
|
||||||
const update = () => {
|
|
||||||
frame = 0;
|
|
||||||
const columnsRect = columns.getBoundingClientRect();
|
|
||||||
const headerBottom = document.querySelector("[data-app-shell-header]")?.getBoundingClientRect().bottom ?? 0;
|
|
||||||
const stickyTop = Math.max(0, headerBottom + 16);
|
|
||||||
|
|
||||||
for (const gutter of columns.querySelectorAll<HTMLElement>("[data-board-gutter]")) {
|
|
||||||
const rect = gutter.getBoundingClientRect();
|
|
||||||
if (gutter.offsetWidth <= 0) continue;
|
|
||||||
|
|
||||||
const effectiveScale = rect.width / gutter.offsetWidth;
|
|
||||||
if (!Number.isFinite(effectiveScale) || effectiveScale <= 0) continue;
|
|
||||||
|
|
||||||
const previousOffset = Number(gutter.dataset.stickyOffset ?? 0);
|
|
||||||
const uncorrectedTop = rect.top - previousOffset * effectiveScale;
|
|
||||||
const maximumTop = columnsRect.bottom - rect.height;
|
|
||||||
const targetTop = Math.min(stickyTop, maximumTop);
|
|
||||||
const nextOffset = Math.max(0, targetTop - uncorrectedTop) / effectiveScale;
|
|
||||||
|
|
||||||
gutter.dataset.stickyOffset = String(nextOffset);
|
|
||||||
gutter.style.setProperty("--board-gutter-sticky-offset", `${nextOffset}px`);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
const scheduleUpdate = () => {
|
|
||||||
if (frame !== 0) return;
|
|
||||||
frame = window.requestAnimationFrame(update);
|
|
||||||
};
|
|
||||||
|
|
||||||
const resizeObserver = new ResizeObserver(scheduleUpdate);
|
|
||||||
resizeObserver.observe(columns);
|
|
||||||
document.addEventListener("scroll", scheduleUpdate, { capture: true, passive: true });
|
|
||||||
window.addEventListener("scroll", scheduleUpdate, { passive: true });
|
|
||||||
window.addEventListener("resize", scheduleUpdate, { passive: true });
|
|
||||||
scheduleUpdate();
|
|
||||||
|
|
||||||
return () => {
|
|
||||||
window.cancelAnimationFrame(frame);
|
|
||||||
resizeObserver.disconnect();
|
|
||||||
document.removeEventListener("scroll", scheduleUpdate, { capture: true });
|
|
||||||
window.removeEventListener("scroll", scheduleUpdate);
|
|
||||||
window.removeEventListener("resize", scheduleUpdate);
|
|
||||||
};
|
|
||||||
}, [columns]);
|
|
||||||
|
|
||||||
return setColumns;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const ClientBoard = () => {
|
export const ClientBoard = () => {
|
||||||
const board = useRequiredBoard();
|
const board = useRequiredBoard();
|
||||||
const t = useScopedI18n("board.landmark");
|
const t = useScopedI18n("board.landmark");
|
||||||
const tPreview = useScopedI18n("board.setting.section.layout.preview");
|
const tPreview = useScopedI18n("board.setting.section.layout.preview");
|
||||||
|
const [isEditMode] = useEditMode();
|
||||||
const currentLayoutId = useCurrentLayout();
|
const currentLayoutId = useCurrentLayout();
|
||||||
const initialViewportWidth = useInitialViewportWidth();
|
const initialViewportWidth = useInitialViewportWidth();
|
||||||
const layoutOverrideId = useLayoutOverride();
|
const layoutOverrideId = useLayoutOverride();
|
||||||
const columnsRef = useFixedBoardGutters();
|
|
||||||
const currentLayout = board.layouts.find((layout) => layout.id === currentLayoutId) ?? board.layouts.at(0);
|
const currentLayout = board.layouts.find((layout) => layout.id === currentLayoutId) ?? board.layouts.at(0);
|
||||||
if (!currentLayout) throw new Error("Expected the board to contain a layout");
|
if (!currentLayout) throw new Error("Expected the board to contain a layout");
|
||||||
|
|
||||||
@@ -128,16 +74,13 @@ export const ClientBoard = () => {
|
|||||||
>
|
>
|
||||||
<BoardGridEditorBoundary key={currentLayoutId}>
|
<BoardGridEditorBoundary key={currentLayoutId}>
|
||||||
<BoardGridPortalRenderer />
|
<BoardGridPortalRenderer />
|
||||||
<div
|
<div className={classes.columns} style={{ gridTemplateColumns, paddingTop: LOGICAL_GRID_GAP }}>
|
||||||
ref={columnsRef}
|
|
||||||
className={classes.columns}
|
|
||||||
style={{ gridTemplateColumns, paddingTop: LOGICAL_GRID_GAP }}
|
|
||||||
>
|
|
||||||
{leftColumnCount > 0 && leftSection && (
|
{leftColumnCount > 0 && leftSection && (
|
||||||
<aside
|
<aside
|
||||||
className={`${classes.lane} ${classes.gutter}`}
|
className={`${classes.lane} ${classes.gutter}`}
|
||||||
aria-label={t("leftRail")}
|
aria-label={t("leftRail")}
|
||||||
data-board-gutter="left"
|
data-board-gutter="left"
|
||||||
|
data-board-editing={isEditMode ? "true" : undefined}
|
||||||
>
|
>
|
||||||
<BoardEmptySection
|
<BoardEmptySection
|
||||||
key={`${currentLayoutId}-${leftSection.id}`}
|
key={`${currentLayoutId}-${leftSection.id}`}
|
||||||
@@ -163,6 +106,7 @@ export const ClientBoard = () => {
|
|||||||
className={`${classes.lane} ${classes.gutter}`}
|
className={`${classes.lane} ${classes.gutter}`}
|
||||||
aria-label={t("rightRail")}
|
aria-label={t("rightRail")}
|
||||||
data-board-gutter="right"
|
data-board-gutter="right"
|
||||||
|
data-board-editing={isEditMode ? "true" : undefined}
|
||||||
>
|
>
|
||||||
<BoardEmptySection
|
<BoardEmptySection
|
||||||
key={`${currentLayoutId}-${rightSection.id}`}
|
key={`${currentLayoutId}-${rightSection.id}`}
|
||||||
|
|||||||
+8
-1
@@ -1,6 +1,6 @@
|
|||||||
import { describe, expect, it } from "vitest";
|
import { describe, expect, it } from "vitest";
|
||||||
|
|
||||||
import { getAssistantConnectionState } from "./assistant-configuration-state";
|
import { formatAssistantContextWindow, getAssistantConnectionState } from "./assistant-configuration-state";
|
||||||
|
|
||||||
describe("getAssistantConnectionState", () => {
|
describe("getAssistantConnectionState", () => {
|
||||||
it("marks a saved required-key provider as ready", () => {
|
it("marks a saved required-key provider as ready", () => {
|
||||||
@@ -63,3 +63,10 @@ describe("getAssistantConnectionState", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe("formatAssistantContextWindow", () => {
|
||||||
|
it("uses Homarr's compact number format for large context windows", () => {
|
||||||
|
expect(formatAssistantContextWindow(1_048_576)).toBe("1M");
|
||||||
|
expect(formatAssistantContextWindow(131_072)).toBe("131k");
|
||||||
|
});
|
||||||
|
});
|
||||||
+4
@@ -1,3 +1,5 @@
|
|||||||
|
import { formatNumber } from "@homarr/common";
|
||||||
|
|
||||||
interface AssistantConnectionStateInput {
|
interface AssistantConnectionStateInput {
|
||||||
connectionConfigured: boolean;
|
connectionConfigured: boolean;
|
||||||
destinationChanged: boolean;
|
destinationChanged: boolean;
|
||||||
@@ -21,3 +23,5 @@ export const getAssistantConnectionState = ({
|
|||||||
connectionReady: !connectionPending,
|
connectionReady: !connectionPending,
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const formatAssistantContextWindow = (tokens: number) => formatNumber(tokens, 0);
|
||||||
+20
-29
@@ -57,7 +57,7 @@ import { showErrorNotification, showSuccessNotification } from "@homarr/notifica
|
|||||||
import { useScopedI18n } from "@homarr/translation/client";
|
import { useScopedI18n } from "@homarr/translation/client";
|
||||||
|
|
||||||
import classes from "./assistant-configuration.module.css";
|
import classes from "./assistant-configuration.module.css";
|
||||||
import { getAssistantConnectionState } from "./assistant-configuration-state";
|
import { formatAssistantContextWindow, getAssistantConnectionState } from "./assistant-configuration-state";
|
||||||
|
|
||||||
type HeaderEntry = { id: number; name: string; value: string };
|
type HeaderEntry = { id: number; name: string; value: string };
|
||||||
type CredentialFlow = "idle" | "replace" | "remove";
|
type CredentialFlow = "idle" | "replace" | "remove";
|
||||||
@@ -438,9 +438,11 @@ export const AssistantConfiguration = () => {
|
|||||||
{t("overview.keyProtected")}
|
{t("overview.keyProtected")}
|
||||||
</Badge>
|
</Badge>
|
||||||
)}
|
)}
|
||||||
<Badge variant="filled" color={configuration?.enabled ? "green" : "gray"}>
|
{configuration?.enabled === false && (
|
||||||
{configuration?.enabled ? t("overview.available") : t("overview.disabled")}
|
<Badge variant="filled" color="gray">
|
||||||
</Badge>
|
{t("overview.disabled")}
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
</Group>
|
</Group>
|
||||||
</Group>
|
</Group>
|
||||||
</Paper>
|
</Paper>
|
||||||
@@ -473,7 +475,7 @@ export const AssistantConfiguration = () => {
|
|||||||
allowDeselect={false}
|
allowDeselect={false}
|
||||||
leftSection={<ProviderIcon providerId={provider} />}
|
leftSection={<ProviderIcon providerId={provider} />}
|
||||||
renderOption={({ option }) => (
|
renderOption={({ option }) => (
|
||||||
<Group gap="sm" wrap="nowrap" align={option.value === "homarr" ? "flex-start" : "center"} w="100%">
|
<Group gap="sm" wrap="nowrap" align="center" w="100%">
|
||||||
<ProviderIcon providerId={option.value as AssistantProviderOption} />
|
<ProviderIcon providerId={option.value as AssistantProviderOption} />
|
||||||
<Box flex={1} miw={0}>
|
<Box flex={1} miw={0}>
|
||||||
<Group gap="xs" wrap="nowrap" justify="space-between">
|
<Group gap="xs" wrap="nowrap" justify="space-between">
|
||||||
@@ -486,11 +488,6 @@ export const AssistantConfiguration = () => {
|
|||||||
</Badge>
|
</Badge>
|
||||||
)}
|
)}
|
||||||
</Group>
|
</Group>
|
||||||
{option.value === "homarr" && (
|
|
||||||
<Text size="xs" c="dimmed" lineClamp={2} maw="46ch">
|
|
||||||
{t("provider.options.homarr.description")}
|
|
||||||
</Text>
|
|
||||||
)}
|
|
||||||
</Box>
|
</Box>
|
||||||
</Group>
|
</Group>
|
||||||
)}
|
)}
|
||||||
@@ -511,12 +508,6 @@ export const AssistantConfiguration = () => {
|
|||||||
placeholder="/models"
|
placeholder="/models"
|
||||||
/>
|
/>
|
||||||
</Stack>
|
</Stack>
|
||||||
|
|
||||||
{destinationChanged && (
|
|
||||||
<Alert icon={<IconAlertTriangle size={18} />} color="yellow" title={t("destinationChanged.title")}>
|
|
||||||
{t("destinationChanged.description")}
|
|
||||||
</Alert>
|
|
||||||
)}
|
|
||||||
</ConfigurationSection>
|
</ConfigurationSection>
|
||||||
|
|
||||||
<ConfigurationSection
|
<ConfigurationSection
|
||||||
@@ -524,13 +515,11 @@ export const AssistantConfiguration = () => {
|
|||||||
title={t("credentials.title")}
|
title={t("credentials.title")}
|
||||||
description={t("credentials.description")}
|
description={t("credentials.description")}
|
||||||
status={
|
status={
|
||||||
<Badge variant="light" color={hasStoredApiKey ? "green" : preset.requiresApiKey ? "yellow" : "gray"}>
|
hasStoredApiKey ? undefined : (
|
||||||
{hasStoredApiKey
|
<Badge variant="light" color={preset.requiresApiKey ? "yellow" : "gray"}>
|
||||||
? t("apiKey.configuredBadge")
|
{preset.requiresApiKey ? t("credentials.required") : t("credentials.optional")}
|
||||||
: preset.requiresApiKey
|
</Badge>
|
||||||
? t("credentials.required")
|
)
|
||||||
: t("credentials.optional")}
|
|
||||||
</Badge>
|
|
||||||
}
|
}
|
||||||
actions={
|
actions={
|
||||||
<Group justify="space-between">
|
<Group justify="space-between">
|
||||||
@@ -787,14 +776,14 @@ export const AssistantConfiguration = () => {
|
|||||||
title={t("model.title")}
|
title={t("model.title")}
|
||||||
description={t("model.description")}
|
description={t("model.description")}
|
||||||
status={
|
status={
|
||||||
configuration?.modelId ? (
|
!configuration?.modelId ? (
|
||||||
<Badge variant="light" color={configuration.enabled ? "green" : "gray"}>
|
|
||||||
{configuration.enabled ? t("overview.available") : t("overview.disabled")}
|
|
||||||
</Badge>
|
|
||||||
) : (
|
|
||||||
<Badge variant="light" color="gray">
|
<Badge variant="light" color="gray">
|
||||||
{t("overview.noModel")}
|
{t("overview.noModel")}
|
||||||
</Badge>
|
</Badge>
|
||||||
|
) : configuration.enabled ? undefined : (
|
||||||
|
<Badge variant="light" color="gray">
|
||||||
|
{t("overview.disabled")}
|
||||||
|
</Badge>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
actions={
|
actions={
|
||||||
@@ -873,7 +862,9 @@ export const AssistantConfiguration = () => {
|
|||||||
</Box>
|
</Box>
|
||||||
<Group className={classes.selectedModelBadges} gap="xs" justify="flex-end">
|
<Group className={classes.selectedModelBadges} gap="xs" justify="flex-end">
|
||||||
{selectedModel.contextLength && (
|
{selectedModel.contextLength && (
|
||||||
<Badge variant="light">{t("model.context", { count: selectedModel.contextLength })}</Badge>
|
<Badge variant="light">
|
||||||
|
{t("model.context", { count: formatAssistantContextWindow(selectedModel.contextLength) })}
|
||||||
|
</Badge>
|
||||||
)}
|
)}
|
||||||
<Badge
|
<Badge
|
||||||
variant="light"
|
variant="light"
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import { assistantExecutionPolicy } from "./assistant-execution-policy";
|
|||||||
describe("assistantExecutionPolicy", () => {
|
describe("assistantExecutionPolicy", () => {
|
||||||
test("allows a sizeable batch of tool calls to finish in one request", () => {
|
test("allows a sizeable batch of tool calls to finish in one request", () => {
|
||||||
expect(assistantExecutionPolicy.maxSteps).toBeGreaterThanOrEqual(32);
|
expect(assistantExecutionPolicy.maxSteps).toBeGreaterThanOrEqual(32);
|
||||||
expect(assistantExecutionPolicy.maxOutputTokens).toBeGreaterThanOrEqual(8_192);
|
expect(assistantExecutionPolicy.maxOutputTokens).toBeGreaterThanOrEqual(65_536);
|
||||||
expect(assistantExecutionPolicy.totalTimeoutMs).toBeGreaterThan(assistantExecutionPolicy.stepTimeoutMs);
|
expect(assistantExecutionPolicy.totalTimeoutMs).toBeGreaterThan(assistantExecutionPolicy.stepTimeoutMs);
|
||||||
expect(assistantExecutionPolicy.toolTimeoutMs).toBeGreaterThanOrEqual(60_000);
|
expect(assistantExecutionPolicy.toolTimeoutMs).toBeGreaterThanOrEqual(60_000);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
export const assistantExecutionPolicy = {
|
export const assistantExecutionPolicy = {
|
||||||
maxSteps: 32,
|
maxSteps: 32,
|
||||||
maxOutputTokens: 8_192,
|
maxOutputTokens: 65_536,
|
||||||
totalTimeoutMs: 240_000,
|
totalTimeoutMs: 240_000,
|
||||||
stepTimeoutMs: 60_000,
|
stepTimeoutMs: 60_000,
|
||||||
toolTimeoutMs: 60_000,
|
toolTimeoutMs: 60_000,
|
||||||
|
|||||||
@@ -3,6 +3,21 @@ import { describe, expect, test } from "vitest";
|
|||||||
import { getAssistantStreamErrorMessage } from "./assistant-stream-error";
|
import { getAssistantStreamErrorMessage } from "./assistant-stream-error";
|
||||||
|
|
||||||
describe("assistant stream errors", () => {
|
describe("assistant stream errors", () => {
|
||||||
|
test("explains a provider-interrupted input stream without blaming tool input", () => {
|
||||||
|
expect(getAssistantStreamErrorMessage(new Error("Error in input stream"))).toBe(
|
||||||
|
"The model provider interrupted the streamed response before the assistant could finish. Try again.",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("explains malformed tool input without implying the action ran", () => {
|
||||||
|
expect(getAssistantStreamErrorMessage(new Error("AI_InvalidToolInputError"))).toBe(
|
||||||
|
"The model produced invalid tool input, so Homarr did not run the action. Try again.",
|
||||||
|
);
|
||||||
|
expect(getAssistantStreamErrorMessage(new Error("Invalid input for tool customWidget_previewCreate"))).toBe(
|
||||||
|
"The model produced incomplete Custom Widget input, so Homarr did not run the action. Try again; multiline JSX will be sent as templateLines.",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
test("explains invalid provider model identifiers", () => {
|
test("explains invalid provider model identifiers", () => {
|
||||||
expect(
|
expect(
|
||||||
getAssistantStreamErrorMessage({
|
getAssistantStreamErrorMessage({
|
||||||
@@ -31,4 +46,12 @@ describe("assistant stream errors", () => {
|
|||||||
"The model endpoint took too long to respond. Try again.",
|
"The model endpoint took too long to respond. Try again.",
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test.each([
|
||||||
|
[401, "The provider rejected the configured credentials. Ask an administrator to update the API key."],
|
||||||
|
[429, "The model endpoint is rate limited. Wait a moment and try again."],
|
||||||
|
[503, "The model provider is temporarily unavailable. Try again later."],
|
||||||
|
])("prefers actionable status %s over a generic input-stream phrase", (statusCode, expected) => {
|
||||||
|
expect(getAssistantStreamErrorMessage({ statusCode, responseBody: "Error in input stream" })).toBe(expected);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
@@ -35,9 +35,6 @@ export const getAssistantStreamErrorMessage = (error: unknown) => {
|
|||||||
) {
|
) {
|
||||||
return "The provider rejected the selected model. Ask an administrator to select a valid model ID.";
|
return "The provider rejected the selected model. Ask an administrator to select a valid model ID.";
|
||||||
}
|
}
|
||||||
if (statusCode === 400) {
|
|
||||||
return "The provider rejected the request. The selected model may not support the requested input or tools.";
|
|
||||||
}
|
|
||||||
if (statusCode === 401 || statusCode === 403) {
|
if (statusCode === 401 || statusCode === 403) {
|
||||||
return "The provider rejected the configured credentials. Ask an administrator to update the API key.";
|
return "The provider rejected the configured credentials. Ask an administrator to update the API key.";
|
||||||
}
|
}
|
||||||
@@ -56,6 +53,17 @@ export const getAssistantStreamErrorMessage = (error: unknown) => {
|
|||||||
if (statusCode !== undefined && statusCode >= 500) {
|
if (statusCode !== undefined && statusCode >= 500) {
|
||||||
return "The model provider is temporarily unavailable. Try again later.";
|
return "The model provider is temporarily unavailable. Try again later.";
|
||||||
}
|
}
|
||||||
|
if (/AI_InvalidToolInputError|Invalid input for tool/iu.test(message)) {
|
||||||
|
return /customWidget_|custom[\s-]+widget/iu.test(message)
|
||||||
|
? "The model produced incomplete Custom Widget input, so Homarr did not run the action. Try again; multiline JSX will be sent as templateLines."
|
||||||
|
: "The model produced invalid tool input, so Homarr did not run the action. Try again.";
|
||||||
|
}
|
||||||
|
if (statusCode === 400) {
|
||||||
|
return "The provider rejected the request. The selected model may not support the requested input or tools.";
|
||||||
|
}
|
||||||
|
if (/\bError in input stream\b/iu.test(message)) {
|
||||||
|
return "The model provider interrupted the streamed response before the assistant could finish. Try again.";
|
||||||
|
}
|
||||||
|
|
||||||
return "The model endpoint stopped the response. Try again, or ask an administrator to verify its URL, model, and credentials.";
|
return "The model endpoint stopped the response. Try again, or ask an administrator to verify its URL, model, and credentials.";
|
||||||
};
|
};
|
||||||
@@ -27,4 +27,77 @@ describe("getSafeAssistantToolError", () => {
|
|||||||
"The Homarr tool could not complete this request.",
|
"The Homarr tool could not complete this request.",
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("preserves safe custom-widget validation paths and messages", () => {
|
||||||
|
const cause = Object.assign(new Error("validation failed"), {
|
||||||
|
issues: [
|
||||||
|
{ path: ["requests", "fixtures", "path"], message: "Required" },
|
||||||
|
{ path: ["template"], message: "Use Image instead of img (line 8, column 3)" },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
const error = new TRPCError({ code: "BAD_REQUEST", cause });
|
||||||
|
|
||||||
|
expect(getSafeAssistantToolError(error, { toolName: "customWidget_create" })).toBe(
|
||||||
|
"The custom widget input was invalid: requests.fixtures.path: Required; template: Use Image instead of img (line 8, column 3)",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("turns joined templateLines parser failures into actionable assistant and MCP text", () => {
|
||||||
|
const cause = Object.assign(new Error("validation failed"), {
|
||||||
|
issues: [{ path: ["template"], message: "Element 'img' is not supported; use Image instead" }],
|
||||||
|
});
|
||||||
|
const error = new TRPCError({
|
||||||
|
code: "BAD_REQUEST",
|
||||||
|
message: "The custom widget authoring input is invalid",
|
||||||
|
cause,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(getSafeAssistantToolError(error, { toolName: "customWidget_previewCreate" })).toBe(
|
||||||
|
"The custom widget input was invalid: template: Element 'img' is not supported; use Image instead",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("does not expose custom-widget credentials in validation details", () => {
|
||||||
|
const error = new TRPCError({
|
||||||
|
code: "BAD_REQUEST",
|
||||||
|
message: "headers.Authorization: Bearer sk-secret-123456 at https://private.example/api",
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = getSafeAssistantToolError(error, { toolName: "customWidget_validate" });
|
||||||
|
expect(result).toContain("[REDACTED]");
|
||||||
|
expect(result).toContain("[URL]");
|
||||||
|
expect(result).not.toContain("sk-secret-123456");
|
||||||
|
expect(result).not.toContain("private.example");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("keeps non-custom-widget bad requests generic", () => {
|
||||||
|
expect(
|
||||||
|
getSafeAssistantToolError(new TRPCError({ code: "BAD_REQUEST", message: "sensitive validation" }), {
|
||||||
|
toolName: "integration_create",
|
||||||
|
}),
|
||||||
|
).toBe("The tool input was not valid.");
|
||||||
|
});
|
||||||
|
|
||||||
|
test.each([
|
||||||
|
["BAD_GATEWAY", "data source could not complete", "External request failed for https://private.example/api"],
|
||||||
|
["PAYLOAD_TOO_LARGE", "exceeded a safety limit", "Response exceeds the 1 MiB limit"],
|
||||||
|
["CONFLICT", "changed while this request was running", "Preview session changed; retry"],
|
||||||
|
] as const)("keeps custom-widget %s preview failures actionable and redacted", (code, expected, message) => {
|
||||||
|
const error = new TRPCError({ code, message });
|
||||||
|
|
||||||
|
const result = getSafeAssistantToolError(error, { toolName: "customWidget_previewQuery" });
|
||||||
|
|
||||||
|
expect(result).toContain(expected);
|
||||||
|
expect(result).not.toContain("private.example");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("keeps unrelated gateway, payload, and conflict failures generic", () => {
|
||||||
|
for (const code of ["BAD_GATEWAY", "PAYLOAD_TOO_LARGE", "CONFLICT"] as const) {
|
||||||
|
expect(
|
||||||
|
getSafeAssistantToolError(new TRPCError({ code, message: "private upstream detail" }), {
|
||||||
|
toolName: "integration_create",
|
||||||
|
}),
|
||||||
|
).toBe("The Homarr tool could not complete this request.");
|
||||||
|
}
|
||||||
|
});
|
||||||
});
|
});
|
||||||
@@ -11,8 +11,48 @@ const getErrorChain = (error: unknown) => {
|
|||||||
return chain;
|
return chain;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const getSafeAssistantToolError = (error: unknown) => {
|
const sanitizeValidationText = (value: string) =>
|
||||||
|
value
|
||||||
|
.replace(/https?:\/\/\S+/giu, "[URL]")
|
||||||
|
.replace(/\b(Bearer|Basic)\s+\S+/giu, "$1 [REDACTED]")
|
||||||
|
.replace(/\b(api[_ -]?key|authorization|password|token)\s*[:=]\s*\S+/giu, "$1=[REDACTED]")
|
||||||
|
.replace(/\s+/gu, " ")
|
||||||
|
.trim()
|
||||||
|
.slice(0, 240);
|
||||||
|
|
||||||
|
const getCustomWidgetValidationDetails = (chain: Record<string, unknown>[]) => {
|
||||||
|
const details = chain
|
||||||
|
.flatMap((candidate) => (Array.isArray(candidate.issues) ? candidate.issues : []))
|
||||||
|
.flatMap((issue) => {
|
||||||
|
const record = asErrorRecord(issue);
|
||||||
|
if (!record || typeof record.message !== "string") return [];
|
||||||
|
const path = Array.isArray(record.path)
|
||||||
|
? record.path
|
||||||
|
.filter((segment): segment is string | number => typeof segment === "string" || typeof segment === "number")
|
||||||
|
.map(String)
|
||||||
|
.join(".")
|
||||||
|
: "";
|
||||||
|
const message = sanitizeValidationText(record.message);
|
||||||
|
return message ? [`${path || "widget"}: ${message}`] : [];
|
||||||
|
})
|
||||||
|
.slice(0, 6);
|
||||||
|
if (details.length > 0) return details.join("; ");
|
||||||
|
|
||||||
|
const safeMessage = chain
|
||||||
|
.map((candidate) => (typeof candidate.message === "string" ? sanitizeValidationText(candidate.message) : ""))
|
||||||
|
.find(
|
||||||
|
(message) =>
|
||||||
|
message.length > 0 &&
|
||||||
|
!["BAD_REQUEST", "Invalid input", "Invalid request parameters"].includes(message) &&
|
||||||
|
!message.startsWith("[") &&
|
||||||
|
!message.startsWith("{"),
|
||||||
|
);
|
||||||
|
return safeMessage;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getSafeAssistantToolError = (error: unknown, options?: { toolName?: string }) => {
|
||||||
const chain = getErrorChain(error);
|
const chain = getErrorChain(error);
|
||||||
|
const isCustomWidgetTool = options?.toolName?.startsWith("customWidget_") === true;
|
||||||
if (
|
if (
|
||||||
chain.some(
|
chain.some(
|
||||||
(candidate) =>
|
(candidate) =>
|
||||||
@@ -31,7 +71,35 @@ export const getSafeAssistantToolError = (error: unknown) => {
|
|||||||
case "NOT_FOUND":
|
case "NOT_FOUND":
|
||||||
return "The requested resource was not found or is not compatible with this tool.";
|
return "The requested resource was not found or is not compatible with this tool.";
|
||||||
case "BAD_REQUEST":
|
case "BAD_REQUEST":
|
||||||
|
if (isCustomWidgetTool) {
|
||||||
|
const details = getCustomWidgetValidationDetails(chain);
|
||||||
|
if (details) return `The custom widget input was invalid: ${details}`;
|
||||||
|
}
|
||||||
return "The tool input was not valid.";
|
return "The tool input was not valid.";
|
||||||
|
case "BAD_GATEWAY":
|
||||||
|
if (isCustomWidgetTool) {
|
||||||
|
const details = getCustomWidgetValidationDetails(chain);
|
||||||
|
return details
|
||||||
|
? `The custom widget data source could not complete the preview request: ${details}`
|
||||||
|
: "The custom widget data source could not complete the preview request.";
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case "PAYLOAD_TOO_LARGE":
|
||||||
|
if (isCustomWidgetTool) {
|
||||||
|
const details = getCustomWidgetValidationDetails(chain);
|
||||||
|
return details
|
||||||
|
? `The custom widget preview exceeded a safety limit: ${details}`
|
||||||
|
: "The custom widget preview exceeded a response or request size safety limit.";
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case "CONFLICT":
|
||||||
|
if (isCustomWidgetTool) {
|
||||||
|
const details = getCustomWidgetValidationDetails(chain);
|
||||||
|
return details
|
||||||
|
? `The custom widget preview changed while this request was running: ${details}`
|
||||||
|
: "The custom widget preview changed while this request was running. Retry the preview step.";
|
||||||
|
}
|
||||||
|
break;
|
||||||
case "PRECONDITION_FAILED":
|
case "PRECONDITION_FAILED":
|
||||||
return "The requested resource is not ready for this operation. Check its configuration and try again.";
|
return "The requested resource is not ready for this operation. Check its configuration and try again.";
|
||||||
case "TOO_MANY_REQUESTS":
|
case "TOO_MANY_REQUESTS":
|
||||||
|
|||||||
@@ -0,0 +1,47 @@
|
|||||||
|
import { describe, expect, test } from "vitest";
|
||||||
|
|
||||||
|
import { repairCustomWidgetToolInput } from "./assistant-tool-input-repair";
|
||||||
|
|
||||||
|
describe("repairCustomWidgetToolInput", () => {
|
||||||
|
test("repairs literal newlines generated inside a multiline Custom JSX template", () => {
|
||||||
|
const input = `{"definition":{"template":"<Stack>
|
||||||
|
<Text>{data.fixtures?.length} fixtures</Text>
|
||||||
|
</Stack>"}}`;
|
||||||
|
const repaired = repairCustomWidgetToolInput({ toolName: "customWidget_previewCreate", input });
|
||||||
|
|
||||||
|
expect(repaired).not.toBeNull();
|
||||||
|
expect(JSON.parse(repaired?.input ?? "")).toEqual({
|
||||||
|
definition: { template: "<Stack>\n <Text>{data.fixtures?.length} fixtures</Text>\n</Stack>" },
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test("repairs every JSON-forbidden control character inside a Custom Widget string", () => {
|
||||||
|
const repaired = repairCustomWidgetToolInput({
|
||||||
|
toolName: "customWidget_validate",
|
||||||
|
input: '{"value":"before\u0000\b\fafter"}',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(JSON.parse(repaired?.input ?? "")).toEqual({ value: "before\u0000\b\fafter" });
|
||||||
|
});
|
||||||
|
|
||||||
|
test("does not alter unrelated tools or guess at truncated JSON", () => {
|
||||||
|
expect(repairCustomWidgetToolInput({ toolName: "app_create", input: '{"name":"Wiki\npedia"}' })).toBeNull();
|
||||||
|
expect(
|
||||||
|
repairCustomWidgetToolInput({ toolName: "customWidget_create", input: '{"template":"<Text>broken' }),
|
||||||
|
).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
test.each([
|
||||||
|
"customWidget_getSkill",
|
||||||
|
"customWidget_schema",
|
||||||
|
"customWidget_getAuthoringPrompt",
|
||||||
|
"customWidget_getComponentCatalog",
|
||||||
|
"customWidget_list",
|
||||||
|
])("normalizes malformed or provider-specific no-input arguments for %s", (toolName) => {
|
||||||
|
expect(repairCustomWidgetToolInput({ toolName, input: "null" })?.input).toBe("{}");
|
||||||
|
expect(repairCustomWidgetToolInput({ toolName, input: "[]" })?.input).toBe("{}");
|
||||||
|
expect(repairCustomWidgetToolInput({ toolName, input: '{"unexpected":true}' })?.input).toBe("{}");
|
||||||
|
expect(repairCustomWidgetToolInput({ toolName, input: '"' })?.input).toBe("{}");
|
||||||
|
expect(repairCustomWidgetToolInput({ toolName, input: "{}" })).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
interface AssistantToolCallInput {
|
||||||
|
toolName: string;
|
||||||
|
input: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const customWidgetNoInputToolNames = new Set([
|
||||||
|
"customWidget_schema",
|
||||||
|
"customWidget_getAuthoringPrompt",
|
||||||
|
"customWidget_getSkill",
|
||||||
|
"customWidget_getComponentCatalog",
|
||||||
|
"customWidget_list",
|
||||||
|
]);
|
||||||
|
|
||||||
|
const escapeControlCharactersInsideJsonStrings = (value: string) => {
|
||||||
|
let result = "";
|
||||||
|
let insideString = false;
|
||||||
|
let escaped = false;
|
||||||
|
for (const character of value) {
|
||||||
|
if (!insideString) {
|
||||||
|
result += character;
|
||||||
|
if (character === '"') insideString = true;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (escaped) {
|
||||||
|
result += character;
|
||||||
|
escaped = false;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (character === "\\") {
|
||||||
|
result += character;
|
||||||
|
escaped = true;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (character === '"') {
|
||||||
|
result += character;
|
||||||
|
insideString = false;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
switch (character) {
|
||||||
|
case "\n":
|
||||||
|
result += "\\n";
|
||||||
|
break;
|
||||||
|
case "\r":
|
||||||
|
result += "\\r";
|
||||||
|
break;
|
||||||
|
case "\t":
|
||||||
|
result += "\\t";
|
||||||
|
break;
|
||||||
|
case "\b":
|
||||||
|
result += "\\b";
|
||||||
|
break;
|
||||||
|
case "\f":
|
||||||
|
result += "\\f";
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
result +=
|
||||||
|
character.charCodeAt(0) < 0x20 ? `\\u${character.charCodeAt(0).toString(16).padStart(4, "0")}` : character;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const repairCustomWidgetToolInput = <T extends AssistantToolCallInput>(toolCall: T): T | null => {
|
||||||
|
if (!toolCall.toolName.startsWith("customWidget_")) return null;
|
||||||
|
if (customWidgetNoInputToolNames.has(toolCall.toolName)) {
|
||||||
|
try {
|
||||||
|
const input = JSON.parse(toolCall.input) as unknown;
|
||||||
|
if (typeof input === "object" && input !== null && !Array.isArray(input) && Object.keys(input).length === 0) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// These read-only resource tools accept no input, so malformed provider arguments are
|
||||||
|
// unambiguous and can be replaced without guessing at user data.
|
||||||
|
}
|
||||||
|
return { ...toolCall, input: "{}" };
|
||||||
|
}
|
||||||
|
const repairedInput = escapeControlCharactersInsideJsonStrings(toolCall.input);
|
||||||
|
if (repairedInput === toolCall.input) return null;
|
||||||
|
try {
|
||||||
|
JSON.parse(repairedInput);
|
||||||
|
return { ...toolCall, input: repairedInput };
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -1,7 +1,12 @@
|
|||||||
import { describe, expect, test } from "vitest";
|
import { describe, expect, test } from "vitest";
|
||||||
import type { UIMessage } from "ai";
|
import type { UIMessage } from "ai";
|
||||||
|
|
||||||
import { getForcedAssistantToolName, withAssistantToolPolicy } from "./assistant-tool-policy";
|
import {
|
||||||
|
customWidgetAssistantInstructions,
|
||||||
|
getForcedAssistantToolName,
|
||||||
|
getRequiredAssistantToolNames,
|
||||||
|
withAssistantToolPolicy,
|
||||||
|
} from "./assistant-tool-policy";
|
||||||
|
|
||||||
const assistantMessage = (...parts: UIMessage["parts"]): UIMessage => ({
|
const assistantMessage = (...parts: UIMessage["parts"]): UIMessage => ({
|
||||||
id: "assistant-message",
|
id: "assistant-message",
|
||||||
@@ -23,6 +28,29 @@ describe("withAssistantToolPolicy", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe("customWidgetAssistantInstructions", () => {
|
||||||
|
test("requires the complete skill and real preview-query data before creation", () => {
|
||||||
|
expect(customWidgetAssistantInstructions).toContain("when they are preloaded below");
|
||||||
|
expect(customWidgetAssistantInstructions).toContain("do not call customWidget_getSkill or customWidget_schema");
|
||||||
|
expect(customWidgetAssistantInstructions).toContain("first call customWidget_getSkill");
|
||||||
|
expect(customWidgetAssistantInstructions).toContain("customWidget_schema");
|
||||||
|
expect(customWidgetAssistantInstructions).toContain("customWidget_getComponentCatalog");
|
||||||
|
expect(customWidgetAssistantInstructions).toContain("customWidget_getComponent");
|
||||||
|
expect(customWidgetAssistantInstructions).toContain("customWidget_getSharedProps once");
|
||||||
|
expect(customWidgetAssistantInstructions).toContain("customWidget_getExample");
|
||||||
|
expect(customWidgetAssistantInstructions).toContain("templateLines");
|
||||||
|
expect(customWidgetAssistantInstructions).toContain("customWidget_previewQuery for every query");
|
||||||
|
expect(customWidgetAssistantInstructions).toContain("Call customWidget_create only after");
|
||||||
|
expect(customWidgetAssistantInstructions).toContain("managementPath");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("routes meaningful follow-up choices through ask_user instead of prose", () => {
|
||||||
|
expect(customWidgetAssistantInstructions).toContain("call ask_user with explicit choices");
|
||||||
|
expect(customWidgetAssistantInstructions).toContain("Never end a custom-widget response with a prose question");
|
||||||
|
expect(customWidgetAssistantInstructions).toContain("purely rhetorical questions do not require ask_user");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe("getForcedAssistantToolName", () => {
|
describe("getForcedAssistantToolName", () => {
|
||||||
test("continues directly from the reviewed app form to app creation", () => {
|
test("continues directly from the reviewed app form to app creation", () => {
|
||||||
expect(
|
expect(
|
||||||
@@ -152,3 +180,137 @@ describe("getForcedAssistantToolName", () => {
|
|||||||
).toBeUndefined();
|
).toBeUndefined();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe("getRequiredAssistantToolNames", () => {
|
||||||
|
test("requires a structured placement decision after custom widget creation", () => {
|
||||||
|
expect(
|
||||||
|
getRequiredAssistantToolNames([
|
||||||
|
assistantMessage({
|
||||||
|
type: "dynamic-tool",
|
||||||
|
toolName: "customWidget_create",
|
||||||
|
toolCallId: "create-widget-1",
|
||||||
|
input: { name: "PSG fixtures" },
|
||||||
|
state: "output-available",
|
||||||
|
output: {
|
||||||
|
id: "widget-1",
|
||||||
|
managementPath: "/manage/custom-widgets/edit/widget-1",
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
]),
|
||||||
|
).toEqual(["configure_widget", "ask_user"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("does not force a follow-up after failed custom widget creation", () => {
|
||||||
|
expect(
|
||||||
|
getRequiredAssistantToolNames([
|
||||||
|
assistantMessage({
|
||||||
|
type: "dynamic-tool",
|
||||||
|
toolName: "customWidget_create",
|
||||||
|
toolCallId: "create-widget-1",
|
||||||
|
input: { name: "PSG fixtures" },
|
||||||
|
state: "output-available",
|
||||||
|
output: { error: "The custom widget input was invalid." },
|
||||||
|
}),
|
||||||
|
]),
|
||||||
|
).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("requires the structured follow-up immediately after creation in the same agent run", () => {
|
||||||
|
const completedSteps = [
|
||||||
|
{
|
||||||
|
toolResults: [
|
||||||
|
{
|
||||||
|
toolName: "customWidget_previewQuery",
|
||||||
|
output: { status: 200, data: { events: [] } },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
toolResults: [
|
||||||
|
{
|
||||||
|
toolName: "customWidget_create",
|
||||||
|
output: {
|
||||||
|
id: "widget-1",
|
||||||
|
managementPath: "/manage/custom-widgets/edit/widget-1",
|
||||||
|
nextAction: {
|
||||||
|
type: "place-custom-widget",
|
||||||
|
widgetKind: "customApi",
|
||||||
|
options: { definitionId: "widget-1" },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
expect(getRequiredAssistantToolNames([], completedSteps)).toEqual(["configure_widget", "ask_user"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("requires the structured follow-up after an approved creation executes before step zero", () => {
|
||||||
|
const responseMessages = [
|
||||||
|
{
|
||||||
|
role: "tool",
|
||||||
|
content: [
|
||||||
|
{
|
||||||
|
type: "tool-result",
|
||||||
|
toolCallId: "create-widget-1",
|
||||||
|
toolName: "customWidget_create",
|
||||||
|
output: {
|
||||||
|
type: "json",
|
||||||
|
value: {
|
||||||
|
id: "widget-1",
|
||||||
|
managementPath: "/manage/custom-widgets/edit/widget-1",
|
||||||
|
nextAction: {
|
||||||
|
type: "place-custom-widget",
|
||||||
|
widgetKind: "customApi",
|
||||||
|
options: { definitionId: "widget-1" },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
expect(getRequiredAssistantToolNames([], [], responseMessages)).toEqual(["configure_widget", "ask_user"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("does not keep forcing the creation follow-up after a later step has completed", () => {
|
||||||
|
const completedSteps = [
|
||||||
|
{
|
||||||
|
toolResults: [
|
||||||
|
{
|
||||||
|
toolName: "customWidget_create",
|
||||||
|
output: {
|
||||||
|
id: "widget-1",
|
||||||
|
managementPath: "/manage/custom-widgets/edit/widget-1",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
toolResults: [{ toolName: "board_all", output: { boards: [] } }],
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
expect(getRequiredAssistantToolNames([], completedSteps)).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("does not require a follow-up for an in-request creation error", () => {
|
||||||
|
expect(
|
||||||
|
getRequiredAssistantToolNames(
|
||||||
|
[],
|
||||||
|
[
|
||||||
|
{
|
||||||
|
toolResults: [
|
||||||
|
{
|
||||||
|
toolName: "customWidget_create",
|
||||||
|
output: { error: "The custom widget input was invalid." },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
),
|
||||||
|
).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -4,6 +4,16 @@ import type { UIMessage } from "ai";
|
|||||||
const mutationApprovalInstruction =
|
const mutationApprovalInstruction =
|
||||||
"This action is protected by Homarr's native approval UI. When the user's request and the required inputs are clear, call this tool immediately. The tool call only requests approval; it does not execute until the user selects Approve and run. Never ask for confirmation in prose before calling it.";
|
"This action is protected by Homarr's native approval UI. When the user's request and the required inputs are clear, call this tool immediately. The tool call only requests approval; it does not execute until the user selects Approve and run. Never ask for confirmation in prose before calling it.";
|
||||||
|
|
||||||
|
export const customWidgetAssistantInstructions = `
|
||||||
|
|
||||||
|
Custom Widget authoring rules:
|
||||||
|
- For every request to create, repair, validate, preview, or explain a Custom JSX widget, use the complete installed skill and JSON Schema from the trusted Custom Widget authoring context when they are preloaded below; do not call customWidget_getSkill or customWidget_schema in that case. When they are not preloaded, first call customWidget_getSkill, whose response contains the complete installed skill and all references, then call customWidget_schema. Follow those resources as authoritative. Next call the compact customWidget_getComponentCatalog for the installed release. Fetch only the relevant named component documentation with customWidget_getComponent and, when its interaction pattern applies, one named example with customWidget_getExample before authoring. Component results contain only component-specific props; if the design needs shared props such as spacing or color, collect their names from the catalog and call customWidget_getSharedProps once with only those names.
|
||||||
|
- Use templateLines for multiline JSX tool input. Do not send a heavily escaped multiline template string when templateLines is accepted.
|
||||||
|
- Never skip the authoring lifecycle: customWidget_validate, repair all issues, customWidget_previewCreate, then customWidget_previewQuery for every query listed by the preview. Inspect the real status and returned data shape, correct request paths and template bindings, and repeat validation and preview after changes. Call customWidget_create only after the definition and its preview queries succeed.
|
||||||
|
- A preview session is not evidence that its API queries work. Never claim live data works until customWidget_previewQuery returned it. Use the returned previewPath when the user should inspect the rendered result.
|
||||||
|
- After creating a widget, include the returned managementPath as a Markdown link so the user can open and edit the exact widget in Homarr.
|
||||||
|
- If the user must choose what happens next, such as whether to add the created widget to a board or leave it unplaced, call ask_user with explicit choices. Never end a custom-widget response with a prose question that expects a typed answer. Open-ended conversation and purely rhetorical questions do not require ask_user; state optional next steps declaratively instead of asking about them.`;
|
||||||
|
|
||||||
export const withAssistantToolPolicy = (description: string | undefined, requiresApproval: boolean) => {
|
export const withAssistantToolPolicy = (description: string | undefined, requiresApproval: boolean) => {
|
||||||
if (!requiresApproval) return description;
|
if (!requiresApproval) return description;
|
||||||
return description ? `${description}\n\n${mutationApprovalInstruction}` : mutationApprovalInstruction;
|
return description ? `${description}\n\n${mutationApprovalInstruction}` : mutationApprovalInstruction;
|
||||||
@@ -35,3 +45,106 @@ export const getForcedAssistantToolName = (messages: UIMessage[]) => {
|
|||||||
? nextToolByHumanTool[toolName as keyof typeof nextToolByHumanTool]
|
? nextToolByHumanTool[toolName as keyof typeof nextToolByHumanTool]
|
||||||
: undefined;
|
: undefined;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
type AssistantToolExecutionStep = {
|
||||||
|
toolResults: readonly {
|
||||||
|
toolName: string;
|
||||||
|
output: unknown;
|
||||||
|
}[];
|
||||||
|
};
|
||||||
|
|
||||||
|
type AssistantToolResponseMessage = {
|
||||||
|
role: string;
|
||||||
|
content: unknown;
|
||||||
|
};
|
||||||
|
|
||||||
|
const isSuccessfulCustomWidgetCreateOutput = (output: unknown) =>
|
||||||
|
typeof output === "object" &&
|
||||||
|
output !== null &&
|
||||||
|
"id" in output &&
|
||||||
|
typeof output.id === "string" &&
|
||||||
|
output.id.length > 0 &&
|
||||||
|
"managementPath" in output &&
|
||||||
|
typeof output.managementPath === "string" &&
|
||||||
|
output.managementPath.length > 0 &&
|
||||||
|
(!("error" in output) || output.error === undefined);
|
||||||
|
|
||||||
|
const getCustomWidgetCreateOutputFromResponseMessages = (responseMessages: readonly AssistantToolResponseMessage[]) => {
|
||||||
|
for (const message of responseMessages.toReversed()) {
|
||||||
|
if (message.role !== "tool" || !Array.isArray(message.content)) continue;
|
||||||
|
for (const part of message.content.toReversed()) {
|
||||||
|
if (
|
||||||
|
typeof part !== "object" ||
|
||||||
|
part === null ||
|
||||||
|
!("type" in part) ||
|
||||||
|
part.type !== "tool-result" ||
|
||||||
|
!("toolName" in part) ||
|
||||||
|
part.toolName !== "customWidget_create" ||
|
||||||
|
!("output" in part)
|
||||||
|
) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const output = part.output;
|
||||||
|
if (
|
||||||
|
typeof output === "object" &&
|
||||||
|
output !== null &&
|
||||||
|
"type" in output &&
|
||||||
|
output.type === "json" &&
|
||||||
|
"value" in output
|
||||||
|
) {
|
||||||
|
return output.value;
|
||||||
|
}
|
||||||
|
return output;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return undefined;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getRequiredAssistantToolNames = (
|
||||||
|
messages: UIMessage[],
|
||||||
|
completedSteps: readonly AssistantToolExecutionStep[] = [],
|
||||||
|
responseMessages: readonly AssistantToolResponseMessage[] = [],
|
||||||
|
) => {
|
||||||
|
// prepareStep receives every completed server-side step in the current stream. Prefer its most
|
||||||
|
// recent result so a customWidget_create performed mid-run is handled before the model can fall
|
||||||
|
// back to a prose question. Once another step has completed, the creation is no longer the
|
||||||
|
// immediately preceding action and must not keep forcing the same follow-up.
|
||||||
|
if (completedSteps.length > 0) {
|
||||||
|
const latestCreateResult = completedSteps
|
||||||
|
.at(-1)
|
||||||
|
?.toolResults.toReversed()
|
||||||
|
.find((result) => result.toolName === "customWidget_create");
|
||||||
|
return latestCreateResult && isSuccessfulCustomWidgetCreateOutput(latestCreateResult.output)
|
||||||
|
? (["configure_widget", "ask_user"] as const)
|
||||||
|
: [];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Approval-gated tools execute immediately before the first model step of the follow-up request.
|
||||||
|
// AI SDK exposes those fresh outputs through responseMessages, not completedSteps or the incoming
|
||||||
|
// UI history, so inspect them before falling back to the persisted UI part.
|
||||||
|
const responseCreateOutput = getCustomWidgetCreateOutputFromResponseMessages(responseMessages);
|
||||||
|
if (responseCreateOutput !== undefined) {
|
||||||
|
return isSuccessfulCustomWidgetCreateOutput(responseCreateOutput)
|
||||||
|
? (["configure_widget", "ask_user"] as const)
|
||||||
|
: [];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Approval-gated tools finish in a later HTTP request. At step zero their result is already in
|
||||||
|
// the incoming UI history when the client has already received it.
|
||||||
|
const latestMessage = messages.at(-1);
|
||||||
|
if (latestMessage?.role !== "assistant") return [];
|
||||||
|
const latestToolPart = latestMessage.parts.toReversed().find((part) => isToolUIPart(part));
|
||||||
|
if (
|
||||||
|
latestToolPart === undefined ||
|
||||||
|
latestToolPart.state !== "output-available" ||
|
||||||
|
getToolName(latestToolPart) !== "customWidget_create"
|
||||||
|
) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
if (!isSuccessfulCustomWidgetCreateOutput(latestToolPart.output)) return [];
|
||||||
|
|
||||||
|
// A successful definition creation always has one structured follow-up: place the widget when
|
||||||
|
// a target is already known, or ask whether it should remain unplaced. Requiring one of these
|
||||||
|
// tools prevents the model from falling back to a prose "Want me to add it?" question.
|
||||||
|
return ["configure_widget", "ask_user"] as const;
|
||||||
|
};
|
||||||
@@ -0,0 +1,265 @@
|
|||||||
|
import { convertToModelMessages } from "ai";
|
||||||
|
import type { UIMessage } from "ai";
|
||||||
|
import { describe, expect, test } from "vitest";
|
||||||
|
|
||||||
|
import { getCustomWidgetSkill, getCustomWidgetSkillContent } from "@homarr/custom-widgets/authoring-resources";
|
||||||
|
import { getCustomWidgetJsonSchema } from "@homarr/custom-widgets/core";
|
||||||
|
|
||||||
|
import {
|
||||||
|
createCustomWidgetDynamicContextController,
|
||||||
|
getCustomWidgetAuthoringContext,
|
||||||
|
isCustomWidgetAuthoringToolName,
|
||||||
|
needsCustomWidgetAuthoringContext,
|
||||||
|
preloadedCustomWidgetToolNames,
|
||||||
|
prunePreloadedCustomWidgetModelMessages,
|
||||||
|
} from "./custom-widget-authoring-context";
|
||||||
|
|
||||||
|
const userMessage = (text: string): UIMessage => ({
|
||||||
|
id: crypto.randomUUID(),
|
||||||
|
role: "user",
|
||||||
|
parts: [{ type: "text", text }],
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("needsCustomWidgetAuthoringContext", () => {
|
||||||
|
test.each([
|
||||||
|
"Create a custom widget for these fixtures",
|
||||||
|
"Create custom widgets for these services",
|
||||||
|
"Repair this custom-widget",
|
||||||
|
"Validate this Custom JSX definition",
|
||||||
|
'Fix this {"$schema":"homarr-custom-widget-v2"}',
|
||||||
|
])("detects explicit authoring intent: %s", (text) => {
|
||||||
|
expect(needsCustomWidgetAuthoringContext([userMessage(text)])).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("continues loading authoring context after a Custom Widget tool call", () => {
|
||||||
|
const messages: UIMessage[] = [
|
||||||
|
userMessage("Continue"),
|
||||||
|
{
|
||||||
|
id: "assistant-1",
|
||||||
|
role: "assistant",
|
||||||
|
parts: [
|
||||||
|
{
|
||||||
|
type: "dynamic-tool",
|
||||||
|
toolName: "customWidget_previewCreate",
|
||||||
|
toolCallId: "preview-1",
|
||||||
|
state: "output-available",
|
||||||
|
input: { name: "Fixtures" },
|
||||||
|
output: { previewId: "preview-1" },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
expect(needsCustomWidgetAuthoringContext(messages)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("keeps context for a user follow-up immediately after a Custom Widget tool call", () => {
|
||||||
|
const messages: UIMessage[] = [
|
||||||
|
{
|
||||||
|
id: "assistant-1",
|
||||||
|
role: "assistant",
|
||||||
|
parts: [
|
||||||
|
{
|
||||||
|
type: "dynamic-tool",
|
||||||
|
toolName: "customWidget_previewCreate",
|
||||||
|
toolCallId: "preview-1",
|
||||||
|
state: "output-available",
|
||||||
|
input: { name: "Fixtures" },
|
||||||
|
output: { previewId: "preview-1" },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
userMessage("Make the colors more compact"),
|
||||||
|
];
|
||||||
|
|
||||||
|
expect(needsCustomWidgetAuthoringContext(messages)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("does not keep loading context because of stale Custom Widget history", () => {
|
||||||
|
const messages: UIMessage[] = [
|
||||||
|
userMessage("Explain custom widgets"),
|
||||||
|
{
|
||||||
|
id: "assistant-1",
|
||||||
|
role: "assistant",
|
||||||
|
parts: [{ type: "text", text: "Custom Widgets render safe JSX." }],
|
||||||
|
},
|
||||||
|
userMessage("How healthy is my media server?"),
|
||||||
|
];
|
||||||
|
|
||||||
|
expect(needsCustomWidgetAuthoringContext(messages)).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("ignores malformed unknown message parts", () => {
|
||||||
|
const malformedMessage = {
|
||||||
|
id: "malformed",
|
||||||
|
role: "user",
|
||||||
|
parts: [null, {}, { type: 1 }, { type: "text", text: null }],
|
||||||
|
} as unknown as UIMessage;
|
||||||
|
|
||||||
|
expect(needsCustomWidgetAuthoringContext([malformedMessage])).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("does not load authoring context for ordinary widget requests or assistant prose", () => {
|
||||||
|
const messages: UIMessage[] = [
|
||||||
|
userMessage("Add my media server widget to the home board"),
|
||||||
|
{
|
||||||
|
id: "assistant-1",
|
||||||
|
role: "assistant",
|
||||||
|
parts: [{ type: "text", text: "I could also build a custom widget." }],
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
expect(needsCustomWidgetAuthoringContext(messages)).toBe(false);
|
||||||
|
expect(getCustomWidgetAuthoringContext(messages, true)).toEqual({ systemContext: "", omittedToolNames: [] });
|
||||||
|
expect(Buffer.byteLength(getCustomWidgetAuthoringContext(messages, true).systemContext, "utf8")).toBe(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("getCustomWidgetAuthoringContext", () => {
|
||||||
|
test("does not expose administrator-only authoring resources to non-admins", () => {
|
||||||
|
expect(getCustomWidgetAuthoringContext([userMessage("Create a custom widget")], false)).toEqual({
|
||||||
|
systemContext: "",
|
||||||
|
omittedToolNames: [],
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test("preloads the complete installed skill and every exact bundled reference", () => {
|
||||||
|
const context = getCustomWidgetAuthoringContext([userMessage("Create a custom widget")], true);
|
||||||
|
const skill = getCustomWidgetSkill();
|
||||||
|
|
||||||
|
expect(context.systemContext).toContain(`## Installed skill: ${skill.name} ${skill.version}`);
|
||||||
|
expect(context.systemContext).toContain(skill.skillMd.trim());
|
||||||
|
expect(context.systemContext).toContain(getCustomWidgetSkillContent());
|
||||||
|
for (const [file, content] of Object.entries(skill.references)) {
|
||||||
|
expect(context.systemContext).toContain(`# Bundled file: ${file}`);
|
||||||
|
expect(context.systemContext).toContain(content.trim());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("preloads a valid current JSON Schema and omits only the redundant resource tools", () => {
|
||||||
|
const context = getCustomWidgetAuthoringContext([userMessage("Validate my custom widget")], true);
|
||||||
|
const schemaBlock = context.systemContext.match(
|
||||||
|
/## Current Custom Widget JSON Schema\n\n```json\n(?<schema>[\s\S]+)\n```$/u,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(schemaBlock?.groups?.schema).toBeDefined();
|
||||||
|
const schema = JSON.parse(schemaBlock?.groups?.schema ?? "null") as Record<string, unknown>;
|
||||||
|
expect(schema).toMatchObject({
|
||||||
|
$schema: expect.any(String),
|
||||||
|
title: "Homarr Custom JSX v2 widget",
|
||||||
|
type: "object",
|
||||||
|
});
|
||||||
|
expect(schema).toEqual(getCustomWidgetJsonSchema());
|
||||||
|
expect(JSON.stringify(schema)).toContain("homarr-custom-widget-v2");
|
||||||
|
expect(context.omittedToolNames).toEqual(preloadedCustomWidgetToolNames);
|
||||||
|
expect(context.systemContext).toContain(
|
||||||
|
"customWidget_getSkill and customWidget_schema are already preloaded below",
|
||||||
|
);
|
||||||
|
expect(context.systemContext).toContain("intentionally omitted from the available tools");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("keeps the complete trusted context within a bounded request budget", () => {
|
||||||
|
const context = getCustomWidgetAuthoringContext([userMessage("Create a custom widget")], true);
|
||||||
|
|
||||||
|
expect(Buffer.byteLength(context.systemContext, "utf8")).toBeLessThan(100_000);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("createCustomWidgetDynamicContextController", () => {
|
||||||
|
test("activates only for authoring tools, not lightweight management or Workshop inspection", () => {
|
||||||
|
expect(isCustomWidgetAuthoringToolName("customWidget_getComponentCatalog")).toBe(true);
|
||||||
|
expect(isCustomWidgetAuthoringToolName("customWidget_validate")).toBe(true);
|
||||||
|
expect(isCustomWidgetAuthoringToolName("customWidget_previewCreate")).toBe(true);
|
||||||
|
expect(isCustomWidgetAuthoringToolName("customWidget_list")).toBe(false);
|
||||||
|
expect(isCustomWidgetAuthoringToolName("customWidget_get")).toBe(false);
|
||||||
|
expect(isCustomWidgetAuthoringToolName("customWidget_workshopSearch")).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("does not promote protected resources after a non-admin tool attempt", () => {
|
||||||
|
const prepareContext = createCustomWidgetDynamicContextController({
|
||||||
|
isAdmin: false,
|
||||||
|
baseInstructions: "Base instructions",
|
||||||
|
availableToolNames: ["customWidget_getSkill", "customWidget_schema"],
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(
|
||||||
|
prepareContext({
|
||||||
|
instructions: "Base instructions",
|
||||||
|
messages: [],
|
||||||
|
steps: [{ toolCalls: [{ toolName: "customWidget_getSkill" }] }],
|
||||||
|
}),
|
||||||
|
).toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("prunePreloadedCustomWidgetModelMessages", () => {
|
||||||
|
test("removes only preloaded resource call-result pairs and preserves the rest of the turn", async () => {
|
||||||
|
const messages: UIMessage[] = [
|
||||||
|
userMessage("Create a custom widget"),
|
||||||
|
{
|
||||||
|
id: "assistant-1",
|
||||||
|
role: "assistant",
|
||||||
|
parts: [
|
||||||
|
{
|
||||||
|
type: "dynamic-tool",
|
||||||
|
toolName: "customWidget_getSkill",
|
||||||
|
toolCallId: "skill-1",
|
||||||
|
state: "output-available",
|
||||||
|
input: {},
|
||||||
|
output: { name: "homarr-custom-widget" },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: "dynamic-tool",
|
||||||
|
toolName: "customWidget_schema",
|
||||||
|
toolCallId: "schema-1",
|
||||||
|
state: "output-available",
|
||||||
|
input: {},
|
||||||
|
output: { type: "object" },
|
||||||
|
},
|
||||||
|
{ type: "text", text: "I loaded the authoring resources." },
|
||||||
|
{
|
||||||
|
type: "dynamic-tool",
|
||||||
|
toolName: "customWidget_previewCreate",
|
||||||
|
toolCallId: "preview-1",
|
||||||
|
state: "output-available",
|
||||||
|
input: { widget: { name: "Fixtures" } },
|
||||||
|
output: { previewId: "preview-1" },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
const modelMessages = await convertToModelMessages(messages);
|
||||||
|
const result = prunePreloadedCustomWidgetModelMessages(modelMessages);
|
||||||
|
const serialized = JSON.stringify(result);
|
||||||
|
|
||||||
|
expect(serialized).not.toContain("customWidget_getSkill");
|
||||||
|
expect(serialized).not.toContain("customWidget_schema");
|
||||||
|
expect(serialized).toContain("customWidget_previewCreate");
|
||||||
|
expect(serialized).toContain("I loaded the authoring resources.");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("removes empty assistant and tool messages left by resource-only history", async () => {
|
||||||
|
const modelMessages = await convertToModelMessages([
|
||||||
|
userMessage("Create a custom widget"),
|
||||||
|
{
|
||||||
|
id: "assistant-1",
|
||||||
|
role: "assistant",
|
||||||
|
parts: [
|
||||||
|
{
|
||||||
|
type: "dynamic-tool",
|
||||||
|
toolName: "customWidget_getSkill",
|
||||||
|
toolCallId: "skill-1",
|
||||||
|
state: "output-available",
|
||||||
|
input: {},
|
||||||
|
output: { name: "homarr-custom-widget" },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
|
||||||
|
expect(prunePreloadedCustomWidgetModelMessages(modelMessages)).toEqual([
|
||||||
|
{ role: "user", content: [{ type: "text", text: "Create a custom widget" }] },
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,176 @@
|
|||||||
|
import { pruneMessages } from "ai";
|
||||||
|
import type { Instructions, ModelMessage, UIMessage } from "ai";
|
||||||
|
|
||||||
|
import { getCustomWidgetSkill, getCustomWidgetSkillContent } from "@homarr/custom-widgets/authoring-resources";
|
||||||
|
import { getCustomWidgetJsonSchema } from "@homarr/custom-widgets/core";
|
||||||
|
|
||||||
|
export const preloadedCustomWidgetToolNames = ["customWidget_getSkill", "customWidget_schema"] as const;
|
||||||
|
const preloadedCustomWidgetToolNameSet = new Set<string>(preloadedCustomWidgetToolNames);
|
||||||
|
const customWidgetAuthoringToolNameSet = new Set([
|
||||||
|
...preloadedCustomWidgetToolNames,
|
||||||
|
"customWidget_getAuthoringPrompt",
|
||||||
|
"customWidget_getComponentCatalog",
|
||||||
|
"customWidget_getComponent",
|
||||||
|
"customWidget_getSharedProps",
|
||||||
|
"customWidget_getExample",
|
||||||
|
"customWidget_validate",
|
||||||
|
"customWidget_previewCreate",
|
||||||
|
"customWidget_previewQuery",
|
||||||
|
"customWidget_previewAction",
|
||||||
|
"customWidget_previewJournal",
|
||||||
|
"customWidget_create",
|
||||||
|
"customWidget_update",
|
||||||
|
"customWidget_templatePatch",
|
||||||
|
"customWidget_legacyMigrationPrompt",
|
||||||
|
"customWidget_migrateLegacy",
|
||||||
|
]);
|
||||||
|
|
||||||
|
export const isPreloadedCustomWidgetToolName = (toolName: string) => preloadedCustomWidgetToolNameSet.has(toolName);
|
||||||
|
export const isCustomWidgetAuthoringToolName = (toolName: string) => customWidgetAuthoringToolNameSet.has(toolName);
|
||||||
|
|
||||||
|
export type CustomWidgetAuthoringContext = {
|
||||||
|
systemContext: string;
|
||||||
|
omittedToolNames: readonly (typeof preloadedCustomWidgetToolNames)[number][];
|
||||||
|
};
|
||||||
|
|
||||||
|
const emptyCustomWidgetAuthoringContext: CustomWidgetAuthoringContext = {
|
||||||
|
systemContext: "",
|
||||||
|
omittedToolNames: [],
|
||||||
|
};
|
||||||
|
|
||||||
|
const customWidgetIntentPattern =
|
||||||
|
/(?:\bcustom[\s-]+widgets?\b|\bcustom\s+jsx\b|\bhomarr-custom-widget-v\d+\b|\bcustomWidget_[A-Za-z\d_]+\b)/iu;
|
||||||
|
|
||||||
|
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
||||||
|
typeof value === "object" && value !== null && !Array.isArray(value);
|
||||||
|
|
||||||
|
const hasCustomWidgetToolPart = (message: UIMessage) =>
|
||||||
|
message.parts.some((part) => {
|
||||||
|
if (!isRecord(part) || typeof part.type !== "string") return false;
|
||||||
|
const toolName =
|
||||||
|
part.type === "dynamic-tool" && typeof part.toolName === "string"
|
||||||
|
? part.toolName
|
||||||
|
: part.type.startsWith("tool-")
|
||||||
|
? part.type.slice("tool-".length)
|
||||||
|
: undefined;
|
||||||
|
return toolName?.startsWith("customWidget_") === true;
|
||||||
|
});
|
||||||
|
|
||||||
|
const hasExplicitCustomWidgetIntent = (message: UIMessage) =>
|
||||||
|
message.role === "user" &&
|
||||||
|
message.parts.some(
|
||||||
|
(part) =>
|
||||||
|
isRecord(part) &&
|
||||||
|
part.type === "text" &&
|
||||||
|
typeof part.text === "string" &&
|
||||||
|
customWidgetIntentPattern.test(part.text),
|
||||||
|
);
|
||||||
|
|
||||||
|
export const needsCustomWidgetAuthoringContext = (messages: UIMessage[]) => {
|
||||||
|
const latestMessage = messages.at(-1);
|
||||||
|
if (!latestMessage) return false;
|
||||||
|
if (hasExplicitCustomWidgetIntent(latestMessage)) return true;
|
||||||
|
if (latestMessage.role === "assistant") return hasCustomWidgetToolPart(latestMessage);
|
||||||
|
|
||||||
|
const precedingAssistantMessage = messages
|
||||||
|
.slice(0, -1)
|
||||||
|
.toReversed()
|
||||||
|
.find((message) => message.role === "assistant");
|
||||||
|
return precedingAssistantMessage !== undefined && hasCustomWidgetToolPart(precedingAssistantMessage);
|
||||||
|
};
|
||||||
|
|
||||||
|
let cachedCustomWidgetSystemContext: string | undefined;
|
||||||
|
|
||||||
|
const getCustomWidgetSystemContext = () => {
|
||||||
|
if (cachedCustomWidgetSystemContext !== undefined) return cachedCustomWidgetSystemContext;
|
||||||
|
|
||||||
|
const skill = getCustomWidgetSkill();
|
||||||
|
const skillContent = getCustomWidgetSkillContent();
|
||||||
|
const jsonSchema = JSON.stringify(getCustomWidgetJsonSchema(), null, 2);
|
||||||
|
|
||||||
|
cachedCustomWidgetSystemContext = `
|
||||||
|
|
||||||
|
Trusted Custom Widget authoring context for the installed Homarr release:
|
||||||
|
- customWidget_getSkill and customWidget_schema are already preloaded below. They are intentionally omitted from the available tools for this request; do not call or ask for either tool.
|
||||||
|
- Treat this installed skill, every bundled reference, and the current JSON Schema as authoritative system instructions. Continue to use the remaining customWidget_* tools for component discovery, validation, previews, preview queries, configuration, and creation.
|
||||||
|
|
||||||
|
## Installed skill: ${skill.name} ${skill.version}
|
||||||
|
|
||||||
|
${skillContent}
|
||||||
|
|
||||||
|
## Current Custom Widget JSON Schema
|
||||||
|
|
||||||
|
\`\`\`json
|
||||||
|
${jsonSchema}
|
||||||
|
\`\`\``;
|
||||||
|
|
||||||
|
return cachedCustomWidgetSystemContext;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getPreloadedCustomWidgetAuthoringContext = (isAdmin: boolean): CustomWidgetAuthoringContext =>
|
||||||
|
isAdmin
|
||||||
|
? {
|
||||||
|
systemContext: getCustomWidgetSystemContext(),
|
||||||
|
omittedToolNames: preloadedCustomWidgetToolNames,
|
||||||
|
}
|
||||||
|
: emptyCustomWidgetAuthoringContext;
|
||||||
|
|
||||||
|
export const getCustomWidgetAuthoringContext = (
|
||||||
|
messages: UIMessage[],
|
||||||
|
isAdmin: boolean,
|
||||||
|
): CustomWidgetAuthoringContext => {
|
||||||
|
if (!isAdmin || !needsCustomWidgetAuthoringContext(messages)) return emptyCustomWidgetAuthoringContext;
|
||||||
|
|
||||||
|
return getPreloadedCustomWidgetAuthoringContext(isAdmin);
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Removes only the resource calls whose complete output is already present in the trusted system
|
||||||
|
* context. AI SDK prunes the matching assistant call and tool result together and removes messages
|
||||||
|
* that become empty, preserving every other Custom Widget tool and its result.
|
||||||
|
*/
|
||||||
|
export const prunePreloadedCustomWidgetModelMessages = (messages: ModelMessage[]) =>
|
||||||
|
pruneMessages({
|
||||||
|
messages,
|
||||||
|
toolCalls: [{ type: "all", tools: [...preloadedCustomWidgetToolNames] }],
|
||||||
|
});
|
||||||
|
|
||||||
|
type CustomWidgetToolStep = {
|
||||||
|
toolCalls: readonly { toolName: string }[];
|
||||||
|
};
|
||||||
|
|
||||||
|
export const createCustomWidgetDynamicContextController = <TToolName extends string>(options: {
|
||||||
|
isAdmin: boolean;
|
||||||
|
baseInstructions: string;
|
||||||
|
availableToolNames: readonly TToolName[];
|
||||||
|
}) => {
|
||||||
|
const activeToolNames = options.availableToolNames.filter((toolName) => !isPreloadedCustomWidgetToolName(toolName));
|
||||||
|
let contextIsActive = false;
|
||||||
|
let contextWasInjected = false;
|
||||||
|
|
||||||
|
return (step: {
|
||||||
|
instructions: Instructions | undefined;
|
||||||
|
messages: ModelMessage[];
|
||||||
|
steps: readonly CustomWidgetToolStep[];
|
||||||
|
}) => {
|
||||||
|
const authoringToolWasCalled = step.steps.some((result) =>
|
||||||
|
result.toolCalls.some((toolCall) => isCustomWidgetAuthoringToolName(toolCall.toolName)),
|
||||||
|
);
|
||||||
|
if (options.isAdmin && authoringToolWasCalled) contextIsActive = true;
|
||||||
|
if (!contextIsActive) return undefined;
|
||||||
|
|
||||||
|
const context = getPreloadedCustomWidgetAuthoringContext(options.isAdmin);
|
||||||
|
const shouldInjectContext = !contextWasInjected;
|
||||||
|
if (shouldInjectContext) contextWasInjected = true;
|
||||||
|
|
||||||
|
return {
|
||||||
|
...(shouldInjectContext
|
||||||
|
? {
|
||||||
|
instructions: `${typeof step.instructions === "string" ? step.instructions : options.baseInstructions}${context.systemContext}`,
|
||||||
|
}
|
||||||
|
: {}),
|
||||||
|
messages: prunePreloadedCustomWidgetModelMessages(step.messages),
|
||||||
|
activeTools: activeToolNames,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
@@ -0,0 +1,229 @@
|
|||||||
|
import { describe, expect, it, vi } from "vitest";
|
||||||
|
import { jsonSchema, simulateReadableStream, stepCountIs, streamText, tool } from "ai";
|
||||||
|
import { MockLanguageModelV4 } from "ai/test";
|
||||||
|
import { parse, stringify } from "superjson";
|
||||||
|
|
||||||
|
import { getCustomWidgetSkill } from "@homarr/custom-widgets/authoring-resources";
|
||||||
|
import { getCustomWidgetJsonSchema } from "@homarr/custom-widgets/core";
|
||||||
|
|
||||||
|
import { createCustomWidgetDynamicContextController } from "./custom-widget-authoring-context";
|
||||||
|
import { repairCustomWidgetToolInput } from "./assistant-tool-input-repair";
|
||||||
|
|
||||||
|
const usage = {
|
||||||
|
inputTokens: { total: 10, noCache: 10, cacheRead: 0, cacheWrite: 0 },
|
||||||
|
outputTokens: { total: 5, text: 5, reasoning: 0 },
|
||||||
|
};
|
||||||
|
|
||||||
|
const finish = (unified: "stop" | "tool-calls") => ({
|
||||||
|
type: "finish" as const,
|
||||||
|
finishReason: { unified, raw: unified },
|
||||||
|
usage,
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("Custom Widget assistant tool loop", () => {
|
||||||
|
it("feeds the complete skill and schema into the next streamed model step", async () => {
|
||||||
|
const streamErrors = vi.fn();
|
||||||
|
const model = new MockLanguageModelV4({
|
||||||
|
doStream: [
|
||||||
|
{
|
||||||
|
stream: simulateReadableStream({
|
||||||
|
chunks: [
|
||||||
|
{ type: "stream-start" as const, warnings: [] },
|
||||||
|
{
|
||||||
|
type: "tool-call" as const,
|
||||||
|
toolCallId: "skill-call",
|
||||||
|
toolName: "customWidget_getSkill",
|
||||||
|
input: "{}",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: "tool-call" as const,
|
||||||
|
toolCallId: "schema-call",
|
||||||
|
toolName: "customWidget_schema",
|
||||||
|
input: "{}",
|
||||||
|
},
|
||||||
|
finish("tool-calls"),
|
||||||
|
],
|
||||||
|
chunkDelayInMs: null,
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
stream: simulateReadableStream({
|
||||||
|
chunks: [
|
||||||
|
{ type: "stream-start" as const, warnings: [] },
|
||||||
|
{ type: "text-start" as const, id: "answer" },
|
||||||
|
{ type: "text-delta" as const, id: "answer", delta: "Custom Widget resources loaded." },
|
||||||
|
{ type: "text-end" as const, id: "answer" },
|
||||||
|
finish("stop"),
|
||||||
|
],
|
||||||
|
chunkDelayInMs: null,
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
const noInputSchema = jsonSchema({ type: "object", properties: {}, additionalProperties: false });
|
||||||
|
const result = streamText({
|
||||||
|
model,
|
||||||
|
prompt: "Create a Custom Widget.",
|
||||||
|
tools: {
|
||||||
|
customWidget_getSkill: tool({
|
||||||
|
inputSchema: noInputSchema,
|
||||||
|
execute: () => parse(stringify(getCustomWidgetSkill())),
|
||||||
|
}),
|
||||||
|
customWidget_schema: tool({
|
||||||
|
inputSchema: noInputSchema,
|
||||||
|
execute: () => parse(stringify(getCustomWidgetJsonSchema())),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
stopWhen: stepCountIs(2),
|
||||||
|
onError: streamErrors,
|
||||||
|
});
|
||||||
|
|
||||||
|
await expect(result.text).resolves.toBe("Custom Widget resources loaded.");
|
||||||
|
expect(streamErrors).not.toHaveBeenCalled();
|
||||||
|
expect(model.doStreamCalls).toHaveLength(2);
|
||||||
|
|
||||||
|
const nextStepPrompt = model.doStreamCalls[1]?.prompt;
|
||||||
|
expect(() => JSON.stringify(nextStepPrompt)).not.toThrow();
|
||||||
|
const serializedPrompt = JSON.stringify(nextStepPrompt);
|
||||||
|
expect(serializedPrompt).toContain('"name":"homarr-custom-widget"');
|
||||||
|
expect(serializedPrompt).toContain('"references/schema.md"');
|
||||||
|
expect(serializedPrompt).toContain('"references/runtime.md"');
|
||||||
|
expect(serializedPrompt).toContain('"references/security.md"');
|
||||||
|
expect(serializedPrompt).toContain('"title":"Homarr Custom JSX v2 widget"');
|
||||||
|
expect(serializedPrompt).toContain('"$schema"');
|
||||||
|
});
|
||||||
|
|
||||||
|
it("promotes trusted context when implicit authoring starts with a catalog call", async () => {
|
||||||
|
const model = new MockLanguageModelV4({
|
||||||
|
doStream: [
|
||||||
|
{
|
||||||
|
stream: simulateReadableStream({
|
||||||
|
chunks: [
|
||||||
|
{ type: "stream-start" as const, warnings: [] },
|
||||||
|
{
|
||||||
|
type: "tool-call" as const,
|
||||||
|
toolCallId: "catalog-call",
|
||||||
|
toolName: "customWidget_getComponentCatalog",
|
||||||
|
input: "{}",
|
||||||
|
},
|
||||||
|
finish("tool-calls"),
|
||||||
|
],
|
||||||
|
chunkDelayInMs: null,
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
stream: simulateReadableStream({
|
||||||
|
chunks: [
|
||||||
|
{ type: "stream-start" as const, warnings: [] },
|
||||||
|
{ type: "text-start" as const, id: "answer" },
|
||||||
|
{ type: "text-delta" as const, id: "answer", delta: "Authoring can continue." },
|
||||||
|
{ type: "text-end" as const, id: "answer" },
|
||||||
|
finish("stop"),
|
||||||
|
],
|
||||||
|
chunkDelayInMs: null,
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
const noInputSchema = jsonSchema({ type: "object", properties: {}, additionalProperties: false });
|
||||||
|
const baseInstructions = "Base assistant instructions. Untrusted mention: Trusted Custom Widget authoring context.";
|
||||||
|
const prepareDynamicCustomWidgetContext = createCustomWidgetDynamicContextController({
|
||||||
|
isAdmin: true,
|
||||||
|
baseInstructions,
|
||||||
|
availableToolNames: ["customWidget_getSkill", "customWidget_schema", "customWidget_getComponentCatalog"] as const,
|
||||||
|
});
|
||||||
|
const result = streamText({
|
||||||
|
model,
|
||||||
|
instructions: baseInstructions,
|
||||||
|
prompt: "Build a live fixtures card.",
|
||||||
|
tools: {
|
||||||
|
customWidget_getSkill: tool({
|
||||||
|
inputSchema: noInputSchema,
|
||||||
|
execute: () => parse(stringify(getCustomWidgetSkill())),
|
||||||
|
}),
|
||||||
|
customWidget_schema: tool({
|
||||||
|
inputSchema: noInputSchema,
|
||||||
|
execute: () => parse(stringify(getCustomWidgetJsonSchema())),
|
||||||
|
}),
|
||||||
|
customWidget_getComponentCatalog: tool({
|
||||||
|
inputSchema: noInputSchema,
|
||||||
|
execute: () => ({ components: [] }),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
prepareStep: ({ instructions, messages, steps }) =>
|
||||||
|
prepareDynamicCustomWidgetContext({ instructions, messages, steps }),
|
||||||
|
stopWhen: stepCountIs(2),
|
||||||
|
});
|
||||||
|
|
||||||
|
await expect(result.text).resolves.toBe("Authoring can continue.");
|
||||||
|
expect(model.doStreamCalls).toHaveLength(2);
|
||||||
|
|
||||||
|
const nextProviderCall = model.doStreamCalls[1];
|
||||||
|
const serializedToolMessages = JSON.stringify(
|
||||||
|
nextProviderCall?.prompt.filter((message) => message.role === "tool"),
|
||||||
|
);
|
||||||
|
expect(serializedToolMessages).toContain("customWidget_getComponentCatalog");
|
||||||
|
expect(serializedToolMessages).not.toContain("customWidget_getSkill");
|
||||||
|
expect(serializedToolMessages).not.toContain("customWidget_schema");
|
||||||
|
const systemContent = nextProviderCall?.prompt.find((message) => message.role === "system")?.content;
|
||||||
|
expect(systemContent).toEqual(expect.any(String));
|
||||||
|
expect(systemContent).toContain("# Bundled file: references/schema.md");
|
||||||
|
expect(systemContent).toContain('"title": "Homarr Custom JSX v2 widget"');
|
||||||
|
expect(nextProviderCall?.tools?.map((entry) => entry.name)).toEqual(["customWidget_getComponentCatalog"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("repairs malformed no-input provider arguments and executes the resource tool", async () => {
|
||||||
|
const execute = vi.fn((_input: unknown) => ({ name: "homarr-custom-widget" }));
|
||||||
|
const model = new MockLanguageModelV4({
|
||||||
|
doStream: [
|
||||||
|
{
|
||||||
|
stream: simulateReadableStream({
|
||||||
|
chunks: [
|
||||||
|
{ type: "stream-start" as const, warnings: [] },
|
||||||
|
{
|
||||||
|
type: "tool-call" as const,
|
||||||
|
toolCallId: "skill-call",
|
||||||
|
toolName: "customWidget_getSkill",
|
||||||
|
input: "{",
|
||||||
|
},
|
||||||
|
finish("tool-calls"),
|
||||||
|
],
|
||||||
|
chunkDelayInMs: null,
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
stream: simulateReadableStream({
|
||||||
|
chunks: [
|
||||||
|
{ type: "stream-start" as const, warnings: [] },
|
||||||
|
{ type: "text-start" as const, id: "answer" },
|
||||||
|
{ type: "text-delta" as const, id: "answer", delta: "Repaired." },
|
||||||
|
{ type: "text-end" as const, id: "answer" },
|
||||||
|
finish("stop"),
|
||||||
|
],
|
||||||
|
chunkDelayInMs: null,
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = streamText({
|
||||||
|
model,
|
||||||
|
prompt: "Load the skill.",
|
||||||
|
tools: {
|
||||||
|
customWidget_getSkill: tool({
|
||||||
|
inputSchema: jsonSchema({ type: "object", properties: {}, additionalProperties: false }),
|
||||||
|
execute,
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
experimental_repairToolCall: ({ toolCall }) => Promise.resolve(repairCustomWidgetToolInput(toolCall)),
|
||||||
|
stopWhen: stepCountIs(2),
|
||||||
|
});
|
||||||
|
|
||||||
|
await expect(result.text).resolves.toBe("Repaired.");
|
||||||
|
expect(execute).toHaveBeenCalledTimes(1);
|
||||||
|
expect(execute.mock.calls[0]?.[0]).toEqual({});
|
||||||
|
expect(model.doStreamCalls[1]?.prompt.some((message) => message.role === "tool")).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -56,10 +56,26 @@ import { toProviderOptionsKey } from "./assistant-provider-options";
|
|||||||
import { assistantExecutionPolicy } from "./assistant-execution-policy";
|
import { assistantExecutionPolicy } from "./assistant-execution-policy";
|
||||||
import { getAssistantStreamErrorMessage } from "./assistant-stream-error";
|
import { getAssistantStreamErrorMessage } from "./assistant-stream-error";
|
||||||
import { getSafeAssistantToolError } from "./assistant-tool-error";
|
import { getSafeAssistantToolError } from "./assistant-tool-error";
|
||||||
import { getForcedAssistantToolName, withAssistantToolPolicy } from "./assistant-tool-policy";
|
import { repairCustomWidgetToolInput } from "./assistant-tool-input-repair";
|
||||||
|
import {
|
||||||
|
createCustomWidgetDynamicContextController,
|
||||||
|
getCustomWidgetAuthoringContext,
|
||||||
|
prunePreloadedCustomWidgetModelMessages,
|
||||||
|
} from "./custom-widget-authoring-context";
|
||||||
|
import {
|
||||||
|
customWidgetAssistantInstructions,
|
||||||
|
getForcedAssistantToolName,
|
||||||
|
getRequiredAssistantToolNames,
|
||||||
|
withAssistantToolPolicy,
|
||||||
|
} from "./assistant-tool-policy";
|
||||||
|
|
||||||
export const maxDuration = 300;
|
export const maxDuration = 300;
|
||||||
|
|
||||||
|
// Five 1 MB image attachments expand to roughly 6.7 MB as base64 before the surrounding message
|
||||||
|
// history and JSON envelope are added. Keep the transport ceiling above the composer contract while
|
||||||
|
// retaining a bounded request size for this authenticated endpoint.
|
||||||
|
const assistantRequestMaxBytes = 12_000_000;
|
||||||
|
|
||||||
const logger = createLogger({ module: "assistant" });
|
const logger = createLogger({ module: "assistant" });
|
||||||
const getToolApprovalSecret = () =>
|
const getToolApprovalSecret = () =>
|
||||||
Buffer.from(
|
Buffer.from(
|
||||||
@@ -117,7 +133,7 @@ Homarr concepts:
|
|||||||
|
|
||||||
Action rules:
|
Action rules:
|
||||||
- Prefer read-only tools before actions.
|
- Prefer read-only tools before actions.
|
||||||
- When required information is missing or the user must choose between meaningful alternatives, call ask_user. Do not ask the question only in prose. Offer distinct choices, categorize agreement or proceeding as affirmative, refusal as negative, and unrelated selections as alternative, then leave the freeform Other answer enabled. A confirmation question must have exactly one affirmative option.
|
- Whenever you need an answer from the user before choosing the next action, call ask_user. Never end a prose response with a question that expects the user to type a reply. Offer distinct choices, categorize agreement or proceeding as affirmative, refusal as negative, and unrelated selections as alternative, then leave the freeform Other answer enabled. A confirmation question must have exactly one affirmative option. Purely rhetorical questions and open-ended conversation that does not block an action may remain prose, but optional next steps should be stated declaratively instead of phrased as a question.
|
||||||
- Mutating Homarr tools already pause for native user approval. Calling a mutation only proposes the action; it cannot execute until the user selects Approve and run. Once the requested change is sufficiently specified, call the mutation immediately so the approval UI appears.
|
- Mutating Homarr tools already pause for native user approval. Calling a mutation only proposes the action; it cannot execute until the user selects Approve and run. Once the requested change is sufficiently specified, call the mutation immediately so the approval UI appears.
|
||||||
- A prose response such as "Please confirm if you would like me to proceed", "Would you like me to proceed?", or a parameter summary that asks for confirmation is incorrect. Never ask for a second textual confirmation before an approval-gated tool call.
|
- A prose response such as "Please confirm if you would like me to proceed", "Would you like me to proceed?", or a parameter summary that asks for confirmation is incorrect. Never ask for a second textual confirmation before an approval-gated tool call.
|
||||||
- Do not retry a denied action.
|
- Do not retry a denied action.
|
||||||
@@ -332,8 +348,9 @@ const getProcedureTypeMap = () => {
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const waitForDemoChunkAsync = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
|
||||||
|
|
||||||
const createDemoAssistantResponse = (request: z.infer<typeof requestSchema>) => {
|
const createDemoAssistantResponse = (request: z.infer<typeof requestSchema>) => {
|
||||||
const delay = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
|
|
||||||
const text =
|
const text =
|
||||||
"This is the Homarr demo assistant. It is running in preview/mock mode, so it responds with a canned answer instead of calling a real language model. In a real deployment, an administrator configures a provider and a model for full conversations.";
|
"This is the Homarr demo assistant. It is running in preview/mock mode, so it responds with a canned answer instead of calling a real language model. In a real deployment, an administrator configures a provider and a model for full conversations.";
|
||||||
const responseId = crypto.randomUUID();
|
const responseId = crypto.randomUUID();
|
||||||
@@ -347,7 +364,7 @@ const createDemoAssistantResponse = (request: z.infer<typeof requestSchema>) =>
|
|||||||
writer.write({ type: "text-start", id: partId });
|
writer.write({ type: "text-start", id: partId });
|
||||||
for (const chunk of chunkTexts) {
|
for (const chunk of chunkTexts) {
|
||||||
writer.write({ type: "text-delta", id: partId, delta: chunk });
|
writer.write({ type: "text-delta", id: partId, delta: chunk });
|
||||||
await delay(18);
|
await waitForDemoChunkAsync(18);
|
||||||
}
|
}
|
||||||
writer.write({ type: "text-end", id: partId });
|
writer.write({ type: "text-end", id: partId });
|
||||||
writer.write({ type: "finish", finishReason: "stop" });
|
writer.write({ type: "finish", finishReason: "stop" });
|
||||||
@@ -359,7 +376,7 @@ const createDemoAssistantResponse = (request: z.infer<typeof requestSchema>) =>
|
|||||||
|
|
||||||
export async function POST(request: Request) {
|
export async function POST(request: Request) {
|
||||||
const contentLength = Number(request.headers.get("content-length") ?? 0);
|
const contentLength = Number(request.headers.get("content-length") ?? 0);
|
||||||
if (contentLength > 2_000_000) {
|
if (contentLength > assistantRequestMaxBytes) {
|
||||||
return Response.json({ error: "The assistant request is too large." }, { status: 413 });
|
return Response.json({ error: "The assistant request is too large." }, { status: 413 });
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -369,7 +386,7 @@ export async function POST(request: Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const requestBody = await request.text();
|
const requestBody = await request.text();
|
||||||
if (requestBody.length > 2_000_000) {
|
if (requestBody.length > assistantRequestMaxBytes) {
|
||||||
return Response.json({ error: "The assistant request is too large." }, { status: 413 });
|
return Response.json({ error: "The assistant request is too large." }, { status: 413 });
|
||||||
}
|
}
|
||||||
const parsed = requestSchema.safeParse(
|
const parsed = requestSchema.safeParse(
|
||||||
@@ -390,6 +407,7 @@ export async function POST(request: Request) {
|
|||||||
{ status: 413 },
|
{ status: 413 },
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
const incomingMessages = parsed.data.messages as UIMessage[];
|
||||||
|
|
||||||
const configuration = await db.query.assistantConfigurations.findFirst({
|
const configuration = await db.query.assistantConfigurations.findFirst({
|
||||||
where: eq(assistantConfigurations.id, "default"),
|
where: eq(assistantConfigurations.id, "default"),
|
||||||
@@ -458,9 +476,12 @@ export async function POST(request: Request) {
|
|||||||
) {
|
) {
|
||||||
return Response.json({ error: "The selected model does not support image input." }, { status: 400 });
|
return Response.json({ error: "The selected model does not support image input." }, { status: 400 });
|
||||||
}
|
}
|
||||||
|
const canAuthorCustomWidgets = session.user.permissions.includes("admin");
|
||||||
|
const customWidgetAuthoringContext = getCustomWidgetAuthoringContext(incomingMessages, canAuthorCustomWidgets);
|
||||||
const caller = mcpRouter.createCaller(context);
|
const caller = mcpRouter.createCaller(context);
|
||||||
const procedureTypes = getProcedureTypeMap();
|
const procedureTypes = getProcedureTypeMap();
|
||||||
const mcpTools = extractMcpTools();
|
const omittedCustomWidgetTools = new Set<string>(customWidgetAuthoringContext.omittedToolNames);
|
||||||
|
const mcpTools = extractMcpTools().filter((mcpTool) => !omittedCustomWidgetTools.has(mcpTool.name));
|
||||||
|
|
||||||
const homarrTools = Object.fromEntries(
|
const homarrTools = Object.fromEntries(
|
||||||
mcpTools.map((mcpTool) => {
|
mcpTools.map((mcpTool) => {
|
||||||
@@ -493,7 +514,7 @@ export async function POST(request: Request) {
|
|||||||
toolName: mcpTool.name,
|
toolName: mcpTool.name,
|
||||||
error: error instanceof Error ? error.message : String(error),
|
error: error instanceof Error ? error.message : String(error),
|
||||||
});
|
});
|
||||||
return { error: getSafeAssistantToolError(error) };
|
return { error: getSafeAssistantToolError(error, { toolName: mcpTool.name }) };
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
@@ -524,7 +545,7 @@ export async function POST(request: Request) {
|
|||||||
}),
|
}),
|
||||||
) satisfies ToolSet;
|
) satisfies ToolSet;
|
||||||
const availableTools = { ...homarrTools, ...frontendTools };
|
const availableTools = { ...homarrTools, ...frontendTools };
|
||||||
const forcedToolName = getForcedAssistantToolName(parsed.data.messages as UIMessage[]);
|
const forcedToolName = getForcedAssistantToolName(incomingMessages);
|
||||||
const openRouterServerToolsEnabled =
|
const openRouterServerToolsEnabled =
|
||||||
configuration.webSearchEnabled && assistantProviderCanUseOpenRouterServerTools(configuration.provider);
|
configuration.webSearchEnabled && assistantProviderCanUseOpenRouterServerTools(configuration.provider);
|
||||||
|
|
||||||
@@ -560,17 +581,39 @@ export async function POST(request: Request) {
|
|||||||
let hasReportedCost = false;
|
let hasReportedCost = false;
|
||||||
let upstreamCost = 0;
|
let upstreamCost = 0;
|
||||||
let hasUpstreamCost = false;
|
let hasUpstreamCost = false;
|
||||||
|
const initialModelMessages = await convertToModelMessages(prepareMessagesForModel(incomingMessages));
|
||||||
|
const modelMessages =
|
||||||
|
customWidgetAuthoringContext.systemContext.length > 0
|
||||||
|
? prunePreloadedCustomWidgetModelMessages(initialModelMessages)
|
||||||
|
: initialModelMessages;
|
||||||
|
const baseInstructions = `${assistantInstructions}${customWidgetAssistantInstructions}${openRouterServerToolsEnabled ? webSearchInstructions : ""}${mentionContext}${customWidgetAuthoringContext.systemContext}`;
|
||||||
|
const prepareDynamicCustomWidgetContext = createCustomWidgetDynamicContextController({
|
||||||
|
isAdmin: canAuthorCustomWidgets,
|
||||||
|
baseInstructions,
|
||||||
|
availableToolNames: Object.keys(availableTools),
|
||||||
|
});
|
||||||
const result = streamText({
|
const result = streamText({
|
||||||
model: provider(modelId),
|
model: provider(modelId),
|
||||||
instructions: `${assistantInstructions}${openRouterServerToolsEnabled ? webSearchInstructions : ""}${mentionContext}`,
|
instructions: baseInstructions,
|
||||||
messages: await convertToModelMessages(prepareMessagesForModel(parsed.data.messages as UIMessage[])),
|
messages: modelMessages,
|
||||||
tools: availableTools,
|
tools: availableTools,
|
||||||
prepareStep: ({ stepNumber }) => {
|
prepareStep: ({ instructions, messages, stepNumber, steps, responseMessages }) => {
|
||||||
if (stepNumber !== 0 || forcedToolName === undefined || !(forcedToolName in availableTools)) return undefined;
|
const dynamicStepOverrides = prepareDynamicCustomWidgetContext({ instructions, messages, steps });
|
||||||
return {
|
const stepOverrides = dynamicStepOverrides ?? {};
|
||||||
activeTools: [forcedToolName],
|
if (stepNumber === 0 && forcedToolName !== undefined && forcedToolName in availableTools) {
|
||||||
toolChoice: { type: "tool", toolName: forcedToolName },
|
return {
|
||||||
};
|
...stepOverrides,
|
||||||
|
activeTools: [forcedToolName],
|
||||||
|
toolChoice: { type: "tool", toolName: forcedToolName },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const requiredToolNames = getRequiredAssistantToolNames(incomingMessages, steps, responseMessages).filter(
|
||||||
|
(toolName) => toolName in availableTools,
|
||||||
|
);
|
||||||
|
if (requiredToolNames.length > 0) {
|
||||||
|
return { ...stepOverrides, activeTools: requiredToolNames, toolChoice: "required" };
|
||||||
|
}
|
||||||
|
return dynamicStepOverrides;
|
||||||
},
|
},
|
||||||
stopWhen: stepCountIs(assistantExecutionPolicy.maxSteps),
|
stopWhen: stepCountIs(assistantExecutionPolicy.maxSteps),
|
||||||
abortSignal: request.signal,
|
abortSignal: request.signal,
|
||||||
@@ -581,6 +624,7 @@ export async function POST(request: Request) {
|
|||||||
},
|
},
|
||||||
maxOutputTokens: assistantExecutionPolicy.maxOutputTokens,
|
maxOutputTokens: assistantExecutionPolicy.maxOutputTokens,
|
||||||
maxRetries: 2,
|
maxRetries: 2,
|
||||||
|
experimental_repairToolCall: ({ toolCall }) => Promise.resolve(repairCustomWidgetToolInput(toolCall)),
|
||||||
reasoning: parsed.data.reasoning === "auto" ? undefined : parsed.data.reasoning,
|
reasoning: parsed.data.reasoning === "auto" ? undefined : parsed.data.reasoning,
|
||||||
providerOptions:
|
providerOptions:
|
||||||
configuration.provider === "openrouter" || openRouterServerToolsEnabled
|
configuration.provider === "openrouter" || openRouterServerToolsEnabled
|
||||||
|
|||||||
@@ -101,7 +101,7 @@ async function callMcp(method: string, params: Record<string, unknown> = {}, id
|
|||||||
const data = response.headers.get("content-type")?.includes("text/event-stream")
|
const data = response.headers.get("content-type")?.includes("text/event-stream")
|
||||||
? text
|
? text
|
||||||
.split("\n")
|
.split("\n")
|
||||||
.find((line) => line.startsWith("data: "))
|
.find((line: string) => line.startsWith("data: "))
|
||||||
?.slice("data: ".length)
|
?.slice("data: ".length)
|
||||||
: text;
|
: text;
|
||||||
if (!data) throw new Error(`MCP response did not contain JSON-RPC data: ${text}`);
|
if (!data) throw new Error(`MCP response did not contain JSON-RPC data: ${text}`);
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import type { NextRequest } from "next/server";
|
import type { NextRequest } from "next/server";
|
||||||
import { userAgent } from "next/server";
|
import { userAgent } from "next/server";
|
||||||
import { ResourceTemplate, type McpServer } from "@modelcontextprotocol/server";
|
import type { McpServer } from "@modelcontextprotocol/server";
|
||||||
|
import { ResourceTemplate } from "@modelcontextprotocol/server";
|
||||||
import { z } from "zod/v4";
|
import { z } from "zod/v4";
|
||||||
|
|
||||||
import type { McpTool } from "@homarr/api/mcp";
|
import type { McpTool } from "@homarr/api/mcp";
|
||||||
@@ -20,6 +21,7 @@ import { customJsxExamples, getCustomWidgetJsonSchema } from "@homarr/custom-wid
|
|||||||
import { db } from "@homarr/db";
|
import { db } from "@homarr/db";
|
||||||
|
|
||||||
import { getPackageVersion } from "~/versions/package-reader";
|
import { getPackageVersion } from "~/versions/package-reader";
|
||||||
|
import { getSafeAssistantToolError } from "../assistant/chat/assistant-tool-error";
|
||||||
import { extractMcpTools } from "./_extract-tools";
|
import { extractMcpTools } from "./_extract-tools";
|
||||||
import { createMcpProtocolHandler } from "./_protocol";
|
import { createMcpProtocolHandler } from "./_protocol";
|
||||||
|
|
||||||
@@ -203,7 +205,8 @@ const SAFE_ERROR_MESSAGES: Record<string, string> = {
|
|||||||
PRECONDITION_FAILED: "A precondition for this operation was not met",
|
PRECONDITION_FAILED: "A precondition for this operation was not met",
|
||||||
};
|
};
|
||||||
|
|
||||||
function sanitizeErrorMessage(error: unknown): string {
|
function sanitizeErrorMessage(error: unknown, toolName: string): string {
|
||||||
|
if (toolName.startsWith("customWidget_")) return getSafeAssistantToolError(error, { toolName });
|
||||||
if (error instanceof Error && "code" in error) {
|
if (error instanceof Error && "code" in error) {
|
||||||
const trpcCode = (error as Error & { code: string }).code;
|
const trpcCode = (error as Error & { code: string }).code;
|
||||||
const safeMessage = SAFE_ERROR_MESSAGES[trpcCode];
|
const safeMessage = SAFE_ERROR_MESSAGES[trpcCode];
|
||||||
|
|||||||
@@ -99,6 +99,30 @@ describe("MCP v2 protocol", () => {
|
|||||||
expect(response.result.content).toEqual([{ type: "text", text: '{"message":"hello"}' }]);
|
expect(response.result.content).toEqual([{ type: "text", text: '{"message":"hello"}' }]);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("passes the tool name to safe error formatting", async () => {
|
||||||
|
const formatToolError = vi.fn((_error: unknown, toolName: string) => `${toolName} input was invalid`);
|
||||||
|
const handler = createMcpProtocolHandler({
|
||||||
|
caller: {
|
||||||
|
echo: vi.fn(async () => {
|
||||||
|
throw new Error("private details");
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
tools: [echoTool],
|
||||||
|
version: "1.0.0",
|
||||||
|
instructions: "Test server",
|
||||||
|
formatToolError,
|
||||||
|
});
|
||||||
|
const response = await parseResponse(
|
||||||
|
await handler.fetch(createRequest("tools/call", { name: "echo", arguments: { message: "hello" } }, "echo")),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(formatToolError).toHaveBeenCalledWith(expect.any(Error), "echo");
|
||||||
|
expect(response.result).toMatchObject({
|
||||||
|
isError: true,
|
||||||
|
content: [{ type: "text", text: '{"error":"echo input was invalid"}' }],
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
test("keeps stateless compatibility with 2025 Streamable HTTP clients", async () => {
|
test("keeps stateless compatibility with 2025 Streamable HTTP clients", async () => {
|
||||||
const { handler } = createTestHandler();
|
const { handler } = createTestHandler();
|
||||||
const request = new Request("http://homarr.test/api/mcp", {
|
const request = new Request("http://homarr.test/api/mcp", {
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ interface CreateMcpProtocolHandlerOptions {
|
|||||||
version: string;
|
version: string;
|
||||||
instructions: string;
|
instructions: string;
|
||||||
configureServer?: (server: McpServer) => void;
|
configureServer?: (server: McpServer) => void;
|
||||||
formatToolError: (error: unknown) => string;
|
formatToolError: (error: unknown, toolName: string) => string;
|
||||||
onToolError?: (toolName: string, error: unknown) => void;
|
onToolError?: (toolName: string, error: unknown) => void;
|
||||||
onProtocolError?: (error: Error) => void;
|
onProtocolError?: (error: Error) => void;
|
||||||
}
|
}
|
||||||
@@ -70,7 +70,9 @@ export const createMcpProtocolHandler = ({
|
|||||||
} catch (error) {
|
} catch (error) {
|
||||||
onToolError?.(tool.name, error);
|
onToolError?.(tool.name, error);
|
||||||
return {
|
return {
|
||||||
content: [{ type: "text" as const, text: JSON.stringify({ error: formatToolError(error) }) }],
|
content: [
|
||||||
|
{ type: "text" as const, text: JSON.stringify({ error: formatToolError(error, tool.name) }) },
|
||||||
|
],
|
||||||
isError: true,
|
isError: true,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,46 @@
|
|||||||
|
import { describe, expect, test } from "vitest";
|
||||||
|
|
||||||
|
import { getAssistantActivityState, getRunningAssistantPartType } from "./assistant-activity-state";
|
||||||
|
|
||||||
|
describe("getAssistantActivityState", () => {
|
||||||
|
test("does not treat output from the previous completed response as current streaming", () => {
|
||||||
|
expect(getRunningAssistantPartType("complete", "text")).toBeUndefined();
|
||||||
|
expect(getRunningAssistantPartType("running", "text")).toBe("text");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("distinguishes thinking from a response that is already streaming", () => {
|
||||||
|
expect(
|
||||||
|
getAssistantActivityState({ isRunning: true, latestPartType: undefined, needsApproval: false, failed: false }),
|
||||||
|
).toBe("thinking");
|
||||||
|
expect(
|
||||||
|
getAssistantActivityState({ isRunning: true, latestPartType: "reasoning", needsApproval: false, failed: false }),
|
||||||
|
).toBe("thinking");
|
||||||
|
expect(
|
||||||
|
getAssistantActivityState({ isRunning: true, latestPartType: "text", needsApproval: false, failed: false }),
|
||||||
|
).toBe("streaming");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("shows a waiting pattern while a tool is running", () => {
|
||||||
|
expect(
|
||||||
|
getAssistantActivityState({ isRunning: true, latestPartType: "tool-call", needsApproval: false, failed: false }),
|
||||||
|
).toBe("waiting");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("maps settled states to waiting, failure, and success glyphs", () => {
|
||||||
|
expect(
|
||||||
|
getAssistantActivityState({ isRunning: false, latestPartType: "text", needsApproval: true, failed: false }),
|
||||||
|
).toBe("waiting");
|
||||||
|
expect(
|
||||||
|
getAssistantActivityState({ isRunning: false, latestPartType: "text", needsApproval: false, failed: true }),
|
||||||
|
).toBe("error");
|
||||||
|
expect(
|
||||||
|
getAssistantActivityState({ isRunning: false, latestPartType: "text", needsApproval: false, failed: false }),
|
||||||
|
).toBe("success");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("keeps a required action visible even if the last run also failed", () => {
|
||||||
|
expect(
|
||||||
|
getAssistantActivityState({ isRunning: false, latestPartType: "text", needsApproval: true, failed: true }),
|
||||||
|
).toBe("waiting");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import type { AssistantDotMatrixState } from "./assistant-dot-matrix";
|
||||||
|
|
||||||
|
interface AssistantActivityStateInput {
|
||||||
|
isRunning: boolean;
|
||||||
|
latestPartType: string | undefined;
|
||||||
|
needsApproval: boolean;
|
||||||
|
failed: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const getRunningAssistantPartType = (
|
||||||
|
messageStatusType: string | undefined,
|
||||||
|
latestPartType: string | undefined,
|
||||||
|
) => (messageStatusType === "running" ? latestPartType : undefined);
|
||||||
|
|
||||||
|
export const getAssistantActivityState = ({
|
||||||
|
isRunning,
|
||||||
|
latestPartType,
|
||||||
|
needsApproval,
|
||||||
|
failed,
|
||||||
|
}: AssistantActivityStateInput): AssistantDotMatrixState => {
|
||||||
|
if (isRunning) {
|
||||||
|
if (latestPartType === "tool-call") return "waiting";
|
||||||
|
if (latestPartType === undefined || latestPartType === "reasoning") return "thinking";
|
||||||
|
return "streaming";
|
||||||
|
}
|
||||||
|
if (needsApproval) return "waiting";
|
||||||
|
if (failed) return "error";
|
||||||
|
return "success";
|
||||||
|
};
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
import type { UIMessage } from "ai";
|
||||||
|
import { describe, expect, test } from "vitest";
|
||||||
|
|
||||||
|
import { prepareAssistantMessagesForTransport, prepareAssistantRequestBody } from "./assistant-attachment-payload";
|
||||||
|
|
||||||
|
const routeRequestBudget = 12_000_000;
|
||||||
|
// A valid padded base64 payload that decodes to exactly the composer's 1,000,000-byte image limit.
|
||||||
|
const oneMegabyteBase64 = `${"A".repeat(1_333_334)}==`;
|
||||||
|
|
||||||
|
const createAttachmentTurn = (id: string, payloadMarker: string): UIMessage => ({
|
||||||
|
id,
|
||||||
|
role: "user",
|
||||||
|
parts: [
|
||||||
|
{ type: "text", text: `Review attachments from ${id}` },
|
||||||
|
...Array.from({ length: 5 }, (_, index) => ({
|
||||||
|
type: "file" as const,
|
||||||
|
filename: `${id}-${index}.png`,
|
||||||
|
mediaType: "image/png",
|
||||||
|
url: `data:image/png;base64,${payloadMarker}${oneMegabyteBase64.slice(payloadMarker.length)}`,
|
||||||
|
})),
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("assistant attachment payload", () => {
|
||||||
|
test("keeps five current attachments but removes historical bytes before a second heavy turn", () => {
|
||||||
|
const firstMarker = "FIRSTPAYLOAD";
|
||||||
|
const secondMarker = "SECONDPAYLOAD";
|
||||||
|
const messages: UIMessage[] = [
|
||||||
|
createAttachmentTurn("user-1", firstMarker),
|
||||||
|
{ id: "assistant-1", role: "assistant", parts: [{ type: "text", text: "I reviewed the first set." }] },
|
||||||
|
createAttachmentTurn("user-2", secondMarker),
|
||||||
|
];
|
||||||
|
|
||||||
|
const preparedMessages = prepareAssistantMessagesForTransport(messages);
|
||||||
|
const body = JSON.stringify({ id: "thread-1", messages: preparedMessages });
|
||||||
|
|
||||||
|
expect(new TextEncoder().encode(body).byteLength).toBeLessThan(routeRequestBudget);
|
||||||
|
expect(body).not.toContain(firstMarker);
|
||||||
|
expect(body.match(/data:image\/png;base64,/gu)).toHaveLength(5);
|
||||||
|
expect(body).toContain(secondMarker);
|
||||||
|
expect(preparedMessages[0]?.parts).toContainEqual(
|
||||||
|
expect.objectContaining({ type: "text", text: expect.stringContaining('"filename":"user-1-0.png"') }),
|
||||||
|
);
|
||||||
|
expect(messages[0]?.parts.filter((part) => part.type === "file")).toHaveLength(5);
|
||||||
|
expect(JSON.stringify(messages[0])).toContain(firstMarker);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("prunes the serialized transport envelope without changing its initialized thread id", () => {
|
||||||
|
const originalBody = JSON.stringify({
|
||||||
|
id: "remote-thread-id",
|
||||||
|
reasoning: "auto",
|
||||||
|
messages: [
|
||||||
|
createAttachmentTurn("user-1", "OLDINLINEBYTES"),
|
||||||
|
{ id: "assistant-1", role: "assistant", parts: [{ type: "text", text: "Done" }] },
|
||||||
|
{ id: "user-2", role: "user", parts: [{ type: "text", text: "Follow up" }] },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
const prepared = prepareAssistantRequestBody(originalBody);
|
||||||
|
|
||||||
|
expect(typeof prepared).toBe("string");
|
||||||
|
expect(prepared).not.toContain("OLDINLINEBYTES");
|
||||||
|
expect(JSON.parse(prepared as string)).toMatchObject({ id: "remote-thread-id", reasoning: "auto" });
|
||||||
|
});
|
||||||
|
|
||||||
|
test("keeps the active user turn available during an automatic assistant continuation", () => {
|
||||||
|
const messages: UIMessage[] = [
|
||||||
|
createAttachmentTurn("user-1", "ORIGINALTURNBYTES"),
|
||||||
|
{ id: "assistant-1", role: "assistant", parts: [{ type: "text", text: "Calling a tool" }] },
|
||||||
|
];
|
||||||
|
|
||||||
|
const prepared = prepareAssistantMessagesForTransport(messages);
|
||||||
|
|
||||||
|
expect(JSON.stringify(prepared)).toContain("ORIGINALTURNBYTES");
|
||||||
|
expect(prepared[0]?.parts.filter((part) => part.type === "file")).toHaveLength(5);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("preserves hosted and provider-referenced files in historical messages", () => {
|
||||||
|
const hostedPart = {
|
||||||
|
type: "file" as const,
|
||||||
|
filename: "report.pdf",
|
||||||
|
mediaType: "application/pdf",
|
||||||
|
url: "https://files.example.test/report.pdf",
|
||||||
|
};
|
||||||
|
const providerPart = {
|
||||||
|
type: "file" as const,
|
||||||
|
filename: "provider-report.pdf",
|
||||||
|
mediaType: "application/pdf",
|
||||||
|
url: "",
|
||||||
|
providerReference: { openai: "file-1" },
|
||||||
|
};
|
||||||
|
const messages: UIMessage[] = [
|
||||||
|
{ id: "user-1", role: "user", parts: [hostedPart, providerPart] },
|
||||||
|
{ id: "assistant-1", role: "assistant", parts: [{ type: "text", text: "Done" }] },
|
||||||
|
{ id: "user-2", role: "user", parts: [{ type: "text", text: "Follow up" }] },
|
||||||
|
];
|
||||||
|
|
||||||
|
const prepared = prepareAssistantMessagesForTransport(messages);
|
||||||
|
|
||||||
|
expect(prepared[0]?.parts).toEqual([hostedPart, providerPart]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
import type { UIMessage } from "ai";
|
||||||
|
|
||||||
|
const inlineAttachmentUrlPattern = /^data:[^,]+;base64,/u;
|
||||||
|
|
||||||
|
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
||||||
|
typeof value === "object" && value !== null && !Array.isArray(value);
|
||||||
|
|
||||||
|
const isFilePart = (value: unknown): value is Record<string, unknown> & { type: "file" } =>
|
||||||
|
isRecord(value) && value.type === "file";
|
||||||
|
|
||||||
|
const isUIMessage = (value: unknown): value is UIMessage =>
|
||||||
|
isRecord(value) &&
|
||||||
|
typeof value.id === "string" &&
|
||||||
|
(value.role === "user" || value.role === "assistant" || value.role === "system") &&
|
||||||
|
Array.isArray(value.parts);
|
||||||
|
|
||||||
|
const replaceControlCharacters = (value: string) =>
|
||||||
|
[...value]
|
||||||
|
.map((character) => {
|
||||||
|
const codePoint = character.codePointAt(0);
|
||||||
|
return codePoint !== undefined && (codePoint <= 0x1f || codePoint === 0x7f) ? " " : character;
|
||||||
|
})
|
||||||
|
.join("");
|
||||||
|
|
||||||
|
const getAttachmentMetadataPart = (part: Record<string, unknown>) => {
|
||||||
|
const filename =
|
||||||
|
typeof part.filename === "string" && part.filename.trim().length > 0
|
||||||
|
? replaceControlCharacters(part.filename).trim().slice(0, 160)
|
||||||
|
: "attachment";
|
||||||
|
const mediaType = typeof part.mediaType === "string" ? part.mediaType.slice(0, 100) : "application/octet-stream";
|
||||||
|
|
||||||
|
return {
|
||||||
|
type: "text" as const,
|
||||||
|
text: `[Historical attachment; binary omitted after its original turn: ${JSON.stringify({ filename, mediaType })}]`,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Keep inline bytes only for the most recent user message. The provider receives those bytes on
|
||||||
|
* the attachment's original turn; replaying every prior data URL on later turns wastes the route's
|
||||||
|
* bounded request budget and can make two otherwise valid five-image turns fail with HTTP 413.
|
||||||
|
*/
|
||||||
|
export const prepareAssistantMessagesForTransport = <TMessage extends UIMessage>(
|
||||||
|
messages: readonly TMessage[],
|
||||||
|
): TMessage[] => {
|
||||||
|
const currentAttachmentMessageIndex = messages.findLastIndex((message) => message.role === "user");
|
||||||
|
|
||||||
|
return messages.map((message, messageIndex) => {
|
||||||
|
let changed = false;
|
||||||
|
const parts: UIMessage["parts"] = [];
|
||||||
|
for (const part of message.parts) {
|
||||||
|
if (!isFilePart(part)) {
|
||||||
|
parts.push(part);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const url = typeof part.url === "string" ? part.url : "";
|
||||||
|
if (!inlineAttachmentUrlPattern.test(url) || messageIndex === currentAttachmentMessageIndex) {
|
||||||
|
parts.push(part);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
changed = true;
|
||||||
|
parts.push(getAttachmentMetadataPart(part));
|
||||||
|
}
|
||||||
|
|
||||||
|
return changed ? ({ ...message, parts } as TMessage) : message;
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* AssistantChatTransport has already initialized the remote thread id when its fetch middleware is
|
||||||
|
* called. Prune the serialized envelope here so changing the message body cannot accidentally
|
||||||
|
* replace that remote id with assistant-ui's pre-initialization local id.
|
||||||
|
*/
|
||||||
|
export const prepareAssistantRequestBody = (body: BodyInit | null | undefined): BodyInit | null | undefined => {
|
||||||
|
if (typeof body !== "string") return body;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(body) as unknown;
|
||||||
|
if (!isRecord(parsed) || !Array.isArray(parsed.messages)) return body;
|
||||||
|
if (!parsed.messages.every(isUIMessage)) return body;
|
||||||
|
return JSON.stringify({ ...parsed, messages: prepareAssistantMessagesForTransport(parsed.messages) });
|
||||||
|
} catch {
|
||||||
|
return body;
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
@property --assistant-dot-matrix-hi {
|
||||||
|
syntax: "<number>";
|
||||||
|
inherits: false;
|
||||||
|
initial-value: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
@property --assistant-dot-matrix-lo {
|
||||||
|
syntax: "<number>";
|
||||||
|
inherits: false;
|
||||||
|
initial-value: 0.15;
|
||||||
|
}
|
||||||
|
|
||||||
|
.root {
|
||||||
|
display: inline-block;
|
||||||
|
width: 1rem;
|
||||||
|
height: 1rem;
|
||||||
|
flex: 0 0 auto;
|
||||||
|
color: currentColor;
|
||||||
|
}
|
||||||
|
|
||||||
|
.root[data-state="idle"],
|
||||||
|
.root[data-state="paused"],
|
||||||
|
.root[data-state="stopped"],
|
||||||
|
.root[data-state="offline"] {
|
||||||
|
color: var(--mantine-color-dimmed);
|
||||||
|
}
|
||||||
|
|
||||||
|
.root[data-state="recording"],
|
||||||
|
.root[data-state="error"] {
|
||||||
|
color: var(--mantine-color-red-filled);
|
||||||
|
}
|
||||||
|
|
||||||
|
.root[data-state="success"] {
|
||||||
|
color: var(--mantine-color-green-filled);
|
||||||
|
}
|
||||||
|
|
||||||
|
.root[data-state="warning"] {
|
||||||
|
color: var(--mantine-color-yellow-filled);
|
||||||
|
}
|
||||||
|
|
||||||
|
.root[data-state="info"] {
|
||||||
|
color: var(--mantine-color-blue-filled);
|
||||||
|
}
|
||||||
|
|
||||||
|
.grid {
|
||||||
|
display: block;
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.dot {
|
||||||
|
transition-duration: 300ms;
|
||||||
|
transition-property: --assistant-dot-matrix-hi, --assistant-dot-matrix-lo, opacity;
|
||||||
|
animation-name: assistant-dot-matrix-blink;
|
||||||
|
animation-timing-function: ease-in-out;
|
||||||
|
animation-iteration-count: infinite;
|
||||||
|
}
|
||||||
|
|
||||||
|
.visuallyHidden {
|
||||||
|
position: absolute;
|
||||||
|
width: 1px;
|
||||||
|
height: 1px;
|
||||||
|
overflow: hidden;
|
||||||
|
padding: 0;
|
||||||
|
border: 0;
|
||||||
|
margin: -1px;
|
||||||
|
clip: rect(0, 0, 0, 0);
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes assistant-dot-matrix-blink {
|
||||||
|
0%,
|
||||||
|
100% {
|
||||||
|
opacity: var(--assistant-dot-matrix-hi, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
50% {
|
||||||
|
opacity: var(--assistant-dot-matrix-lo, 0.15);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-reduced-motion: reduce) {
|
||||||
|
.dot {
|
||||||
|
transition-duration: 0ms;
|
||||||
|
animation-name: none;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
// @vitest-environment jsdom
|
||||||
|
|
||||||
|
import { act, createElement } from "react";
|
||||||
|
import { createRoot } from "react-dom/client";
|
||||||
|
import { afterEach, beforeEach, describe, expect, test } from "vitest";
|
||||||
|
|
||||||
|
import { AssistantDotMatrix, assistantDotMatrixStates } from "./assistant-dot-matrix";
|
||||||
|
|
||||||
|
describe("AssistantDotMatrix", () => {
|
||||||
|
let host: HTMLDivElement;
|
||||||
|
let root: ReturnType<typeof createRoot>;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
host = document.createElement("div");
|
||||||
|
document.body.append(host);
|
||||||
|
root = createRoot(host);
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(async () => {
|
||||||
|
await act(async () => root.unmount());
|
||||||
|
host.remove();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("renders an accessible deterministic 5 by 5 loading matrix", async () => {
|
||||||
|
await act(async () => root.render(createElement(AssistantDotMatrix, { label: "Loading response" })));
|
||||||
|
|
||||||
|
const matrix = host.querySelector<HTMLElement>("[data-slot='assistant-dot-matrix']");
|
||||||
|
expect(matrix?.dataset.state).toBe("loading");
|
||||||
|
expect(matrix?.tagName).toBe("OUTPUT");
|
||||||
|
expect(matrix?.textContent).toBe("Loading response");
|
||||||
|
expect(matrix?.querySelector("svg")?.getAttribute("aria-hidden")).toBe("true");
|
||||||
|
expect(matrix?.querySelectorAll("[data-slot='assistant-dot-matrix-dot']")).toHaveLength(25);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("switches from the thinking wave to the streaming wave without changing its structure", async () => {
|
||||||
|
await act(async () => root.render(createElement(AssistantDotMatrix, { state: "thinking", label: "Thinking" })));
|
||||||
|
const matrix = host.querySelector<HTMLElement>("[data-slot='assistant-dot-matrix']");
|
||||||
|
const firstDot = matrix?.querySelector<SVGCircleElement>("[data-slot='assistant-dot-matrix-dot']");
|
||||||
|
expect(matrix?.dataset.state).toBe("thinking");
|
||||||
|
expect(firstDot?.style.animationDuration).toBe("1.2s");
|
||||||
|
|
||||||
|
await act(async () =>
|
||||||
|
root.render(createElement(AssistantDotMatrix, { state: "streaming", label: "Writing response" })),
|
||||||
|
);
|
||||||
|
const updatedMatrix = host.querySelector<HTMLElement>("[data-slot='assistant-dot-matrix']");
|
||||||
|
const updatedFirstDot = updatedMatrix?.querySelector<SVGCircleElement>("[data-slot='assistant-dot-matrix-dot']");
|
||||||
|
expect(updatedMatrix).toBe(matrix);
|
||||||
|
expect(updatedMatrix?.dataset.state).toBe("streaming");
|
||||||
|
expect(updatedMatrix?.textContent).toBe("Writing response");
|
||||||
|
expect(updatedFirstDot?.style.animationDuration).toBe("0.9s");
|
||||||
|
expect(updatedMatrix?.querySelectorAll("[data-slot='assistant-dot-matrix-dot']")).toHaveLength(25);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("supports every documented assistant-ui matrix state", async () => {
|
||||||
|
expect(assistantDotMatrixStates).toEqual([
|
||||||
|
"idle",
|
||||||
|
"loading",
|
||||||
|
"thinking",
|
||||||
|
"streaming",
|
||||||
|
"searching",
|
||||||
|
"syncing",
|
||||||
|
"connecting",
|
||||||
|
"waiting",
|
||||||
|
"uploading",
|
||||||
|
"downloading",
|
||||||
|
"listening",
|
||||||
|
"speaking",
|
||||||
|
"recording",
|
||||||
|
"success",
|
||||||
|
"error",
|
||||||
|
"warning",
|
||||||
|
"info",
|
||||||
|
"paused",
|
||||||
|
"stopped",
|
||||||
|
"offline",
|
||||||
|
]);
|
||||||
|
|
||||||
|
for (const state of assistantDotMatrixStates) {
|
||||||
|
await act(async () => root.render(createElement(AssistantDotMatrix, { state })));
|
||||||
|
expect(host.querySelector("[data-slot='assistant-dot-matrix']")?.getAttribute("data-state")).toBe(state);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,234 @@
|
|||||||
|
import type { ComponentProps, CSSProperties } from "react";
|
||||||
|
|
||||||
|
import classes from "./assistant-dot-matrix.module.css";
|
||||||
|
|
||||||
|
const gridSize = 5;
|
||||||
|
const center = (gridSize - 1) / 2;
|
||||||
|
const dotIndexes = Array.from({ length: gridSize * gridSize }, (_, index) => index);
|
||||||
|
|
||||||
|
const hash = (value: number, salt: number, range: number) => {
|
||||||
|
let mixed = (Math.imul(value, 374761393) + Math.imul(salt, 668265263)) >>> 0;
|
||||||
|
mixed = Math.imul(mixed ^ (mixed >>> 13), 1274126177) >>> 0;
|
||||||
|
return ((mixed ^ (mixed >>> 16)) % range) / 1000;
|
||||||
|
};
|
||||||
|
|
||||||
|
const glyph = (dots: [number, number][]) => new Set(dots.map(([row, column]) => row * gridSize + column));
|
||||||
|
|
||||||
|
const check = glyph([
|
||||||
|
[1, 4],
|
||||||
|
[2, 3],
|
||||||
|
[3, 0],
|
||||||
|
[3, 2],
|
||||||
|
[4, 1],
|
||||||
|
]);
|
||||||
|
const cross = glyph([
|
||||||
|
[0, 0],
|
||||||
|
[0, 4],
|
||||||
|
[1, 1],
|
||||||
|
[1, 3],
|
||||||
|
[2, 2],
|
||||||
|
[3, 1],
|
||||||
|
[3, 3],
|
||||||
|
[4, 0],
|
||||||
|
[4, 4],
|
||||||
|
]);
|
||||||
|
const bang = glyph([
|
||||||
|
[0, 2],
|
||||||
|
[1, 2],
|
||||||
|
[2, 2],
|
||||||
|
[4, 2],
|
||||||
|
]);
|
||||||
|
const info = glyph([
|
||||||
|
[0, 2],
|
||||||
|
[2, 2],
|
||||||
|
[3, 2],
|
||||||
|
[4, 2],
|
||||||
|
]);
|
||||||
|
const pause = glyph([
|
||||||
|
[1, 1],
|
||||||
|
[2, 1],
|
||||||
|
[3, 1],
|
||||||
|
[1, 3],
|
||||||
|
[2, 3],
|
||||||
|
[3, 3],
|
||||||
|
]);
|
||||||
|
const stop = glyph([
|
||||||
|
[1, 1],
|
||||||
|
[1, 2],
|
||||||
|
[1, 3],
|
||||||
|
[2, 1],
|
||||||
|
[2, 2],
|
||||||
|
[2, 3],
|
||||||
|
[3, 1],
|
||||||
|
[3, 2],
|
||||||
|
[3, 3],
|
||||||
|
]);
|
||||||
|
const record = glyph([
|
||||||
|
[1, 2],
|
||||||
|
[2, 1],
|
||||||
|
[2, 2],
|
||||||
|
[2, 3],
|
||||||
|
[3, 2],
|
||||||
|
]);
|
||||||
|
const ellipsis = glyph([
|
||||||
|
[2, 0],
|
||||||
|
[2, 2],
|
||||||
|
[2, 4],
|
||||||
|
]);
|
||||||
|
|
||||||
|
interface Blink {
|
||||||
|
duration: number;
|
||||||
|
delay: number;
|
||||||
|
lo: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface StateConfig {
|
||||||
|
glyph?: Set<number>;
|
||||||
|
base?: number;
|
||||||
|
dim?: number;
|
||||||
|
blink?: (index: number, row: number, column: number) => Blink;
|
||||||
|
}
|
||||||
|
|
||||||
|
const states = {
|
||||||
|
idle: { base: 0.3 },
|
||||||
|
loading: {
|
||||||
|
blink: (index) => ({
|
||||||
|
duration: 0.9 + hash(index, 2, 700),
|
||||||
|
delay: -hash(index, 1, 1200),
|
||||||
|
lo: 0.15,
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
thinking: {
|
||||||
|
blink: (_index, row, column) => ({
|
||||||
|
duration: 1.2,
|
||||||
|
delay: -(row + column) * 0.09,
|
||||||
|
lo: 0.2,
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
streaming: {
|
||||||
|
blink: (_index, row, column) => ({
|
||||||
|
duration: 0.9,
|
||||||
|
delay: -(row * 0.12 + hash(column, 3, 900)),
|
||||||
|
lo: 0.15,
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
searching: {
|
||||||
|
blink: (_index, _row, column) => ({ duration: 1.1, delay: -column * 0.12, lo: 0.2 }),
|
||||||
|
},
|
||||||
|
syncing: {
|
||||||
|
blink: (_index, row, column) => {
|
||||||
|
const turn = (Math.atan2(row - center, column - center) + Math.PI) / (2 * Math.PI);
|
||||||
|
return { duration: 1.3, delay: -turn * 1.3, lo: 0.2 };
|
||||||
|
},
|
||||||
|
},
|
||||||
|
connecting: {
|
||||||
|
blink: (_index, row, column) => ({
|
||||||
|
duration: 1.4,
|
||||||
|
delay: -Math.max(Math.abs(row - center), Math.abs(column - center)) * 0.18,
|
||||||
|
lo: 0.15,
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
waiting: {
|
||||||
|
glyph: ellipsis,
|
||||||
|
blink: (_index, _row, column) => ({
|
||||||
|
duration: 1.2,
|
||||||
|
delay: -column * 0.09,
|
||||||
|
lo: 0.2,
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
uploading: {
|
||||||
|
blink: (_index, row) => ({
|
||||||
|
duration: 1,
|
||||||
|
delay: -(gridSize - 1 - row) * 0.12,
|
||||||
|
lo: 0.2,
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
downloading: {
|
||||||
|
blink: (_index, row) => ({ duration: 1, delay: -row * 0.12, lo: 0.2 }),
|
||||||
|
},
|
||||||
|
listening: {
|
||||||
|
blink: (_index, _row, column) => ({
|
||||||
|
duration: 0.7 + hash(column, 4, 500),
|
||||||
|
delay: -hash(column, 5, 900),
|
||||||
|
lo: 0.25,
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
speaking: {
|
||||||
|
blink: (_index, _row, column) => ({
|
||||||
|
duration: 0.4 + hash(column, 6, 350),
|
||||||
|
delay: -hash(column, 7, 700),
|
||||||
|
lo: 0.2,
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
recording: {
|
||||||
|
glyph: record,
|
||||||
|
dim: 0.12,
|
||||||
|
blink: () => ({ duration: 1.4, delay: 0, lo: 0.3 }),
|
||||||
|
},
|
||||||
|
success: { glyph: check },
|
||||||
|
error: {
|
||||||
|
glyph: cross,
|
||||||
|
blink: () => ({ duration: 1.1, delay: 0, lo: 0.4 }),
|
||||||
|
},
|
||||||
|
warning: {
|
||||||
|
glyph: bang,
|
||||||
|
blink: () => ({ duration: 1.6, delay: 0, lo: 0.45 }),
|
||||||
|
},
|
||||||
|
info: { glyph: info },
|
||||||
|
paused: { glyph: pause },
|
||||||
|
stopped: { glyph: stop },
|
||||||
|
offline: { base: 0.15 },
|
||||||
|
} satisfies Record<string, StateConfig>;
|
||||||
|
|
||||||
|
export type AssistantDotMatrixState = keyof typeof states;
|
||||||
|
|
||||||
|
export const assistantDotMatrixStates = Object.keys(states) as readonly AssistantDotMatrixState[];
|
||||||
|
|
||||||
|
interface AssistantDotMatrixProps extends Omit<ComponentProps<"output">, "children"> {
|
||||||
|
state?: AssistantDotMatrixState;
|
||||||
|
label?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const AssistantDotMatrix = ({ className, state = "loading", label, ...props }: AssistantDotMatrixProps) => {
|
||||||
|
const config: StateConfig = states[state];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<output
|
||||||
|
data-slot="assistant-dot-matrix"
|
||||||
|
data-state={state}
|
||||||
|
className={[classes.root, className].filter(Boolean).join(" ")}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<span className={classes.visuallyHidden}>{label ?? state}</span>
|
||||||
|
<svg aria-hidden viewBox="0 0 20 20" fill="currentColor" className={classes.grid}>
|
||||||
|
{dotIndexes.map((index) => {
|
||||||
|
const row = Math.floor(index / gridSize);
|
||||||
|
const column = index % gridSize;
|
||||||
|
const on = !config.glyph || config.glyph.has(index);
|
||||||
|
const hi = on ? (config.base ?? 1) : (config.dim ?? 0.15);
|
||||||
|
const blink = on ? config.blink?.(index, row, column) : undefined;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<circle
|
||||||
|
key={index}
|
||||||
|
data-slot="assistant-dot-matrix-dot"
|
||||||
|
cx={2 + column * 4}
|
||||||
|
cy={2 + row * 4}
|
||||||
|
r={1.3}
|
||||||
|
className={classes.dot}
|
||||||
|
style={
|
||||||
|
{
|
||||||
|
opacity: hi,
|
||||||
|
animationDuration: `${blink?.duration ?? 1}s`,
|
||||||
|
animationDelay: `${blink?.delay ?? 0}s`,
|
||||||
|
"--assistant-dot-matrix-hi": hi,
|
||||||
|
"--assistant-dot-matrix-lo": blink?.lo ?? hi,
|
||||||
|
} as CSSProperties
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</svg>
|
||||||
|
</output>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import { describe, expect, test } from "vitest";
|
import { describe, expect, test } from "vitest";
|
||||||
|
|
||||||
import { getSafeAssistantMarkdownImageSource } from "./assistant-markdown-image";
|
import { getSafeAssistantAttachmentImageSource, getSafeAssistantMarkdownImageSource } from "./assistant-markdown-image";
|
||||||
|
|
||||||
describe("getSafeAssistantMarkdownImageSource", () => {
|
describe("getSafeAssistantMarkdownImageSource", () => {
|
||||||
test("allows Homarr-relative and ordinary remote images", () => {
|
test("allows Homarr-relative and ordinary remote images", () => {
|
||||||
@@ -17,3 +17,25 @@ describe("getSafeAssistantMarkdownImageSource", () => {
|
|||||||
expect(getSafeAssistantMarkdownImageSource("https://user:secret@example.com/icon.svg")).toBeNull();
|
expect(getSafeAssistantMarkdownImageSource("https://user:secret@example.com/icon.svg")).toBeNull();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe("getSafeAssistantAttachmentImageSource", () => {
|
||||||
|
test("allows persisted raster image data and same-origin image URLs", () => {
|
||||||
|
expect(getSafeAssistantAttachmentImageSource("data:image/png;base64,iVBORw0KGgo=", "https://homarr.local")).toBe(
|
||||||
|
"data:image/png;base64,iVBORw0KGgo=",
|
||||||
|
);
|
||||||
|
expect(getSafeAssistantAttachmentImageSource("/api/assistant/file/one", "https://homarr.local")).toBe(
|
||||||
|
"/api/assistant/file/one",
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
getSafeAssistantAttachmentImageSource("https://homarr.local/api/assistant/file/one", "https://homarr.local"),
|
||||||
|
).toBe("https://homarr.local/api/assistant/file/one");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("rejects active image formats, unsafe schemes, and cross-origin URLs", () => {
|
||||||
|
expect(
|
||||||
|
getSafeAssistantAttachmentImageSource("data:image/svg+xml;base64,PHN2Zy8+", "https://homarr.local"),
|
||||||
|
).toBeNull();
|
||||||
|
expect(getSafeAssistantAttachmentImageSource("javascript:alert(1)", "https://homarr.local")).toBeNull();
|
||||||
|
expect(getSafeAssistantAttachmentImageSource("https://example.com/private.png", "https://homarr.local")).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,11 +1,33 @@
|
|||||||
|
import { getSafeAssistantHttpUrl } from "./assistant-url";
|
||||||
|
|
||||||
export const getSafeAssistantMarkdownImageSource = (source: string | Blob | undefined) => {
|
export const getSafeAssistantMarkdownImageSource = (source: string | Blob | undefined) => {
|
||||||
if (typeof source !== "string" || !source) return null;
|
if (typeof source !== "string" || !source) return null;
|
||||||
if (source.startsWith("/") && !source.startsWith("//")) return source;
|
if (source.startsWith("/") && !source.startsWith("//")) return source;
|
||||||
|
|
||||||
|
return getSafeAssistantHttpUrl(source);
|
||||||
|
};
|
||||||
|
|
||||||
|
const safeAttachmentDataUrl =
|
||||||
|
/^data:image\/(?:gif|jpeg|png|webp);base64,(?:[a-z\d+/]{4})*(?:[a-z\d+/]{2}==|[a-z\d+/]{3}=)?$/iu;
|
||||||
|
|
||||||
|
export const getSafeAssistantAttachmentImageSource = (source: unknown, currentOrigin?: string) => {
|
||||||
|
if (typeof source !== "string" || !source) return null;
|
||||||
|
if (safeAttachmentDataUrl.test(source)) return source;
|
||||||
|
if (source.startsWith("/") && !source.startsWith("//")) return source;
|
||||||
|
if (!currentOrigin) return null;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const url = new URL(source);
|
const sourceUrl = new URL(source);
|
||||||
if ((url.protocol !== "http:" && url.protocol !== "https:") || url.username || url.password) return null;
|
const originUrl = new URL(currentOrigin);
|
||||||
return url.toString();
|
if (
|
||||||
|
sourceUrl.origin !== originUrl.origin ||
|
||||||
|
(sourceUrl.protocol !== "http:" && sourceUrl.protocol !== "https:") ||
|
||||||
|
sourceUrl.username ||
|
||||||
|
sourceUrl.password
|
||||||
|
) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return sourceUrl.toString();
|
||||||
} catch {
|
} catch {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,11 +1,42 @@
|
|||||||
import { describe, expect, test } from "vitest";
|
import { describe, expect, test } from "vitest";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
|
getAssistantConversationUsage,
|
||||||
getAssistantTelemetry,
|
getAssistantTelemetry,
|
||||||
getAssistantUsage,
|
getAssistantUsage,
|
||||||
resolveAssistantContextWindowTelemetry,
|
resolveAssistantContextWindowTelemetry,
|
||||||
} from "./assistant-message-metadata";
|
} from "./assistant-message-metadata";
|
||||||
|
|
||||||
|
const createUsageMetadata = ({
|
||||||
|
requestId,
|
||||||
|
inputTokens,
|
||||||
|
outputTokens,
|
||||||
|
cost,
|
||||||
|
contextUsed,
|
||||||
|
}: {
|
||||||
|
requestId: string;
|
||||||
|
inputTokens: number;
|
||||||
|
outputTokens: number;
|
||||||
|
cost: number;
|
||||||
|
contextUsed?: number;
|
||||||
|
}) => ({
|
||||||
|
usage: { inputTokens, outputTokens, totalTokens: inputTokens + outputTokens },
|
||||||
|
custom: {
|
||||||
|
telemetry: {
|
||||||
|
requestId,
|
||||||
|
provider: "openrouter",
|
||||||
|
modelId: "example/model",
|
||||||
|
startedAt: "2026-08-04T10:00:00.000Z",
|
||||||
|
completedAt: "2026-08-04T10:00:01.000Z",
|
||||||
|
durationMs: 1000,
|
||||||
|
cost,
|
||||||
|
contextLength: 128_000,
|
||||||
|
...(contextUsed === undefined ? {} : { contextUsed }),
|
||||||
|
steps: [],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
describe("getAssistantTelemetry", () => {
|
describe("getAssistantTelemetry", () => {
|
||||||
test("extracts persisted request telemetry", () => {
|
test("extracts persisted request telemetry", () => {
|
||||||
expect(
|
expect(
|
||||||
@@ -171,3 +202,63 @@ describe("resolveAssistantContextWindowTelemetry", () => {
|
|||||||
).toBeNull();
|
).toBeNull();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe("getAssistantConversationUsage", () => {
|
||||||
|
test("aggregates unique request usage and keeps the latest reported context reading", () => {
|
||||||
|
const first = createUsageMetadata({
|
||||||
|
requestId: "first",
|
||||||
|
inputTokens: 100,
|
||||||
|
outputTokens: 25,
|
||||||
|
cost: 0.001,
|
||||||
|
contextUsed: 125,
|
||||||
|
});
|
||||||
|
const second = createUsageMetadata({ requestId: "second", inputTokens: 200, outputTokens: 50, cost: 0.002 });
|
||||||
|
|
||||||
|
expect(getAssistantConversationUsage([first, second, second, undefined])).toMatchObject({
|
||||||
|
inputTokens: 300,
|
||||||
|
outputTokens: 75,
|
||||||
|
totalTokens: 375,
|
||||||
|
cost: 0.003,
|
||||||
|
contextUsed: 125,
|
||||||
|
contextLength: 128_000,
|
||||||
|
turns: [{ requestId: "first" }, { requestId: "second" }],
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test("falls back to step metrics when top-level usage is unavailable", () => {
|
||||||
|
const result = getAssistantConversationUsage([
|
||||||
|
{
|
||||||
|
custom: {
|
||||||
|
telemetry: {
|
||||||
|
requestId: "step-only",
|
||||||
|
provider: "openrouter",
|
||||||
|
modelId: "example/model",
|
||||||
|
startedAt: "2026-08-04T10:00:00.000Z",
|
||||||
|
steps: [
|
||||||
|
{
|
||||||
|
index: 1,
|
||||||
|
durationMs: 100,
|
||||||
|
modelDurationMs: 100,
|
||||||
|
toolDurationMs: 0,
|
||||||
|
inputTokens: 80,
|
||||||
|
outputTokens: 20,
|
||||||
|
cachedInputTokens: 10,
|
||||||
|
reasoningTokens: 5,
|
||||||
|
cost: 0.0004,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
|
||||||
|
expect(result).toMatchObject({
|
||||||
|
inputTokens: 80,
|
||||||
|
outputTokens: 20,
|
||||||
|
totalTokens: 100,
|
||||||
|
cachedInputTokens: 10,
|
||||||
|
reasoningTokens: 5,
|
||||||
|
cost: 0.0004,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -92,6 +92,36 @@ export type AssistantContextWindowTelemetry = {
|
|||||||
source: "current" | "previous";
|
source: "current" | "previous";
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export type AssistantConversationTurnUsage = {
|
||||||
|
requestId: string;
|
||||||
|
provider: string;
|
||||||
|
modelId: string;
|
||||||
|
startedAt: string;
|
||||||
|
inputTokens?: number;
|
||||||
|
outputTokens?: number;
|
||||||
|
totalTokens?: number;
|
||||||
|
cachedInputTokens?: number;
|
||||||
|
reasoningTokens?: number;
|
||||||
|
cost?: number;
|
||||||
|
durationMs?: number;
|
||||||
|
contextUsed?: number;
|
||||||
|
contextLength?: number;
|
||||||
|
usage: AssistantUsage;
|
||||||
|
telemetry: AssistantRequestTelemetry;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type AssistantConversationUsage = {
|
||||||
|
turns: AssistantConversationTurnUsage[];
|
||||||
|
inputTokens: number;
|
||||||
|
outputTokens: number;
|
||||||
|
totalTokens: number;
|
||||||
|
cachedInputTokens: number;
|
||||||
|
reasoningTokens: number;
|
||||||
|
cost: number;
|
||||||
|
contextUsed?: number;
|
||||||
|
contextLength?: number;
|
||||||
|
};
|
||||||
|
|
||||||
const getFiniteNonNegativeNumber = (value: unknown) =>
|
const getFiniteNonNegativeNumber = (value: unknown) =>
|
||||||
typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined;
|
typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined;
|
||||||
|
|
||||||
@@ -306,6 +336,82 @@ export const getAssistantTelemetry = (metadata: unknown): AssistantRequestTeleme
|
|||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const sumReportedStepMetric = (
|
||||||
|
steps: AssistantRequestStep[],
|
||||||
|
getValue: (step: AssistantRequestStep) => number | undefined,
|
||||||
|
) => {
|
||||||
|
const values = steps.flatMap((step) => {
|
||||||
|
const value = getValue(step);
|
||||||
|
return value === undefined ? [] : [value];
|
||||||
|
});
|
||||||
|
return values.length > 0 ? values.reduce((sum, value) => sum + value, 0) : undefined;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Produces a stable conversation-level usage snapshot from persisted message metadata.
|
||||||
|
*
|
||||||
|
* A newly-created or streaming message can temporarily have no usage metadata. Keeping
|
||||||
|
* the latest complete context reading from earlier turns avoids flashing the composer
|
||||||
|
* meter back to zero while the next request starts or when its popover is reopened.
|
||||||
|
*/
|
||||||
|
export const getAssistantConversationUsage = (messageMetadata: unknown[]): AssistantConversationUsage => {
|
||||||
|
const turnsByRequestId = new Map<string, AssistantConversationTurnUsage>();
|
||||||
|
|
||||||
|
for (const metadata of messageMetadata) {
|
||||||
|
const telemetry = getAssistantTelemetry(metadata);
|
||||||
|
if (!telemetry) continue;
|
||||||
|
|
||||||
|
const usage = getAssistantUsage(metadata);
|
||||||
|
const inputTokens = usage?.inputTokens ?? sumReportedStepMetric(telemetry.steps, (step) => step.inputTokens);
|
||||||
|
const outputTokens = usage?.outputTokens ?? sumReportedStepMetric(telemetry.steps, (step) => step.outputTokens);
|
||||||
|
const totalTokens =
|
||||||
|
usage?.totalTokens ??
|
||||||
|
(inputTokens !== undefined || outputTokens !== undefined ? (inputTokens ?? 0) + (outputTokens ?? 0) : undefined);
|
||||||
|
const cachedInputTokens =
|
||||||
|
usage?.cachedInputTokens ?? sumReportedStepMetric(telemetry.steps, (step) => step.cachedInputTokens);
|
||||||
|
const reasoningTokens =
|
||||||
|
usage?.reasoningTokens ?? sumReportedStepMetric(telemetry.steps, (step) => step.reasoningTokens);
|
||||||
|
const cost = telemetry.cost ?? sumReportedStepMetric(telemetry.steps, (step) => step.cost);
|
||||||
|
|
||||||
|
turnsByRequestId.set(telemetry.requestId, {
|
||||||
|
requestId: telemetry.requestId,
|
||||||
|
provider: telemetry.provider,
|
||||||
|
modelId: telemetry.modelId,
|
||||||
|
startedAt: telemetry.startedAt,
|
||||||
|
...(inputTokens !== undefined ? { inputTokens } : {}),
|
||||||
|
...(outputTokens !== undefined ? { outputTokens } : {}),
|
||||||
|
...(totalTokens !== undefined ? { totalTokens } : {}),
|
||||||
|
...(cachedInputTokens !== undefined ? { cachedInputTokens } : {}),
|
||||||
|
...(reasoningTokens !== undefined ? { reasoningTokens } : {}),
|
||||||
|
...(cost !== undefined ? { cost } : {}),
|
||||||
|
...(telemetry.durationMs !== undefined ? { durationMs: telemetry.durationMs } : {}),
|
||||||
|
...(telemetry.contextUsed !== undefined ? { contextUsed: telemetry.contextUsed } : {}),
|
||||||
|
...(telemetry.contextLength !== undefined ? { contextLength: telemetry.contextLength } : {}),
|
||||||
|
usage: usage ?? {},
|
||||||
|
telemetry,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const turns = [...turnsByRequestId.values()];
|
||||||
|
const latestContextTurn = turns.findLast(
|
||||||
|
(turn) => turn.contextUsed !== undefined && turn.contextLength !== undefined,
|
||||||
|
);
|
||||||
|
const sum = (getValue: (turn: AssistantConversationTurnUsage) => number | undefined) =>
|
||||||
|
turns.reduce((total, turn) => total + (getValue(turn) ?? 0), 0);
|
||||||
|
|
||||||
|
return {
|
||||||
|
turns,
|
||||||
|
inputTokens: sum((turn) => turn.inputTokens),
|
||||||
|
outputTokens: sum((turn) => turn.outputTokens),
|
||||||
|
totalTokens: sum((turn) => turn.totalTokens),
|
||||||
|
cachedInputTokens: sum((turn) => turn.cachedInputTokens),
|
||||||
|
reasoningTokens: sum((turn) => turn.reasoningTokens),
|
||||||
|
cost: sum((turn) => turn.cost),
|
||||||
|
...(latestContextTurn?.contextUsed !== undefined ? { contextUsed: latestContextTurn.contextUsed } : {}),
|
||||||
|
...(latestContextTurn?.contextLength !== undefined ? { contextLength: latestContextTurn.contextLength } : {}),
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
export const resolveAssistantContextWindowTelemetry = (
|
export const resolveAssistantContextWindowTelemetry = (
|
||||||
current: AssistantRequestTelemetry,
|
current: AssistantRequestTelemetry,
|
||||||
previousMetadata: unknown[],
|
previousMetadata: unknown[],
|
||||||
|
|||||||
@@ -205,7 +205,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.composerWrap {
|
.composerWrap {
|
||||||
padding: 0.45rem;
|
padding: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.composer {
|
.composer {
|
||||||
@@ -225,6 +225,15 @@
|
|||||||
.suggestions {
|
.suggestions {
|
||||||
grid-template-columns: 1fr;
|
grid-template-columns: 1fr;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.humanToolOption {
|
||||||
|
grid-template-columns: max-content minmax(0, 1fr);
|
||||||
|
}
|
||||||
|
|
||||||
|
.humanToolOptionBadge {
|
||||||
|
grid-column: 2;
|
||||||
|
justify-self: start;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@container assistant-widget (max-width: 22rem) {
|
@container assistant-widget (max-width: 22rem) {
|
||||||
@@ -251,6 +260,15 @@
|
|||||||
.runtimeSelectorEffort {
|
.runtimeSelectorEffort {
|
||||||
display: none;
|
display: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.composerContext {
|
||||||
|
width: 1.9rem;
|
||||||
|
padding-inline: 0.15rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.composerContext > :last-child {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@container assistant-widget (max-width: 18rem) {
|
@container assistant-widget (max-width: 18rem) {
|
||||||
@@ -334,6 +352,12 @@
|
|||||||
max-width: 100%;
|
max-width: 100%;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.messagePending {
|
||||||
|
width: max-content;
|
||||||
|
min-height: 1.75rem;
|
||||||
|
padding-inline: 0.1rem;
|
||||||
|
}
|
||||||
|
|
||||||
.messageText {
|
.messageText {
|
||||||
line-height: 1.6;
|
line-height: 1.6;
|
||||||
overflow-wrap: anywhere;
|
overflow-wrap: anywhere;
|
||||||
@@ -493,6 +517,33 @@
|
|||||||
font-size: var(--mantine-font-size-xs);
|
font-size: var(--mantine-font-size-xs);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.syntaxHighlighter {
|
||||||
|
max-width: 100%;
|
||||||
|
margin-block: 0.75rem;
|
||||||
|
overflow: hidden;
|
||||||
|
border: 1px solid var(--mantine-color-default-border);
|
||||||
|
border-radius: var(--mantine-radius-md);
|
||||||
|
background: var(--mantine-color-default);
|
||||||
|
}
|
||||||
|
|
||||||
|
.syntaxHighlighter :global(pre) {
|
||||||
|
max-width: 100%;
|
||||||
|
margin: 0;
|
||||||
|
overflow: auto;
|
||||||
|
padding: 0.75rem;
|
||||||
|
border: 0;
|
||||||
|
border-radius: 0;
|
||||||
|
background: transparent !important;
|
||||||
|
line-height: 1.5;
|
||||||
|
}
|
||||||
|
|
||||||
|
.syntaxHighlighter :global(code) {
|
||||||
|
padding: 0;
|
||||||
|
background: transparent;
|
||||||
|
font-family: var(--mantine-font-family-monospace);
|
||||||
|
font-size: var(--mantine-font-size-xs);
|
||||||
|
}
|
||||||
|
|
||||||
.messageMarkdown hr {
|
.messageMarkdown hr {
|
||||||
margin-block: 1rem;
|
margin-block: 1rem;
|
||||||
border: 0;
|
border: 0;
|
||||||
@@ -638,19 +689,25 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.pendingQuestionDock {
|
.pendingQuestionDock {
|
||||||
flex: 0 1 auto;
|
min-height: 0;
|
||||||
max-height: min(22rem, 50cqh);
|
flex: 1 1 auto;
|
||||||
overflow-y: auto;
|
overflow-y: auto;
|
||||||
overscroll-behavior: contain;
|
overscroll-behavior: contain;
|
||||||
padding: 0.65rem 0.75rem 0.35rem;
|
padding: 0.75rem;
|
||||||
border-top: 1px solid var(--mantine-color-default-border);
|
|
||||||
background: var(--mantine-color-body);
|
background: var(--mantine-color-body);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.thread[data-pending-question] .viewport {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
.pendingQuestionTarget {
|
.pendingQuestionTarget {
|
||||||
|
display: flex;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
|
min-height: 100%;
|
||||||
max-width: 44rem;
|
max-width: 44rem;
|
||||||
margin-inline: auto;
|
margin-inline: auto;
|
||||||
|
align-items: safe center;
|
||||||
}
|
}
|
||||||
|
|
||||||
.pendingQuestionTarget .humanTool {
|
.pendingQuestionTarget .humanTool {
|
||||||
@@ -723,6 +780,11 @@
|
|||||||
white-space: nowrap;
|
white-space: nowrap;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.humanToolOptionBadge {
|
||||||
|
min-width: max-content;
|
||||||
|
max-width: none;
|
||||||
|
}
|
||||||
|
|
||||||
.humanToolOptionText {
|
.humanToolOptionText {
|
||||||
min-width: 0;
|
min-width: 0;
|
||||||
}
|
}
|
||||||
@@ -770,6 +832,10 @@
|
|||||||
white-space: pre-wrap;
|
white-space: pre-wrap;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.toolResultNavigation {
|
||||||
|
padding-top: 0.125rem;
|
||||||
|
}
|
||||||
|
|
||||||
.toolResultProperties {
|
.toolResultProperties {
|
||||||
display: grid;
|
display: grid;
|
||||||
grid-template-columns: repeat(auto-fit, minmax(7.5rem, 1fr));
|
grid-template-columns: repeat(auto-fit, minmax(7.5rem, 1fr));
|
||||||
@@ -849,9 +915,10 @@
|
|||||||
|
|
||||||
.reasoning {
|
.reasoning {
|
||||||
margin-block: 0.45rem;
|
margin-block: 0.45rem;
|
||||||
padding: 0.45rem 0.6rem;
|
overflow: hidden;
|
||||||
|
border: 1px solid var(--mantine-color-default-border);
|
||||||
border-radius: var(--mantine-radius-md);
|
border-radius: var(--mantine-radius-md);
|
||||||
background: var(--mantine-color-default);
|
background: color-mix(in srgb, var(--mantine-color-default) 72%, transparent);
|
||||||
}
|
}
|
||||||
|
|
||||||
.reasoningToggle {
|
.reasoningToggle {
|
||||||
@@ -859,10 +926,14 @@
|
|||||||
width: 100%;
|
width: 100%;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
justify-content: space-between;
|
justify-content: space-between;
|
||||||
border-radius: var(--mantine-radius-sm);
|
padding: 0.4rem 0.55rem;
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.reasoningToggle:hover {
|
||||||
|
background: var(--mantine-color-default-hover);
|
||||||
|
}
|
||||||
|
|
||||||
.reasoningToggle:focus-visible {
|
.reasoningToggle:focus-visible {
|
||||||
outline: 2px solid var(--mantine-primary-color-filled);
|
outline: 2px solid var(--mantine-primary-color-filled);
|
||||||
outline-offset: 2px;
|
outline-offset: 2px;
|
||||||
@@ -877,11 +948,17 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.reasoningContent {
|
.reasoningContent {
|
||||||
padding-top: 0.45rem;
|
padding: 0.45rem 0.55rem 0.55rem;
|
||||||
|
border-top: 1px solid var(--mantine-color-default-border);
|
||||||
}
|
}
|
||||||
|
|
||||||
.reasoningText {
|
.reasoningText {
|
||||||
white-space: pre-wrap;
|
color: var(--mantine-color-dimmed);
|
||||||
|
font-size: var(--mantine-font-size-sm);
|
||||||
|
}
|
||||||
|
|
||||||
|
.reasoningParts {
|
||||||
|
min-width: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.source {
|
.source {
|
||||||
@@ -941,30 +1018,57 @@
|
|||||||
|
|
||||||
.attachment {
|
.attachment {
|
||||||
display: inline-flex;
|
display: inline-flex;
|
||||||
|
min-width: min(11rem, 100%);
|
||||||
align-items: center;
|
align-items: center;
|
||||||
gap: 0.35rem;
|
gap: 0.5rem;
|
||||||
margin: 0 0.35rem 0.35rem 0;
|
margin: 0 0.35rem 0.35rem 0;
|
||||||
|
padding: 0.3rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
.attachmentThumb {
|
.attachmentImage,
|
||||||
|
.attachmentFileIcon {
|
||||||
display: grid;
|
display: grid;
|
||||||
width: 1.7rem;
|
width: 2.5rem;
|
||||||
height: 1.7rem;
|
height: 2.5rem;
|
||||||
|
flex: 0 0 auto;
|
||||||
place-items: center;
|
place-items: center;
|
||||||
border-radius: var(--mantine-radius-sm);
|
border-radius: var(--mantine-radius-sm);
|
||||||
color: var(--mantine-color-dimmed);
|
color: var(--mantine-color-dimmed);
|
||||||
background: var(--mantine-color-body);
|
background: var(--mantine-color-body);
|
||||||
font-size: 0.62rem;
|
}
|
||||||
font-weight: 700;
|
|
||||||
|
.attachmentImage {
|
||||||
|
object-fit: cover;
|
||||||
|
}
|
||||||
|
|
||||||
|
.attachmentCopy {
|
||||||
|
min-width: 0;
|
||||||
|
flex: 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
.attachmentName {
|
.attachmentName {
|
||||||
max-width: 12rem;
|
max-width: 13rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.attachmentType {
|
||||||
|
max-width: 13rem;
|
||||||
|
color: light-dark(var(--mantine-color-gray-7), var(--mantine-color-gray-4));
|
||||||
}
|
}
|
||||||
|
|
||||||
.messageActions {
|
.messageActions {
|
||||||
|
display: flex;
|
||||||
|
min-width: 0;
|
||||||
min-height: 1.75rem;
|
min-height: 1.75rem;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.2rem;
|
||||||
margin-top: 0.3rem;
|
margin-top: 0.3rem;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.messageActionBar {
|
||||||
|
min-width: 0;
|
||||||
|
max-width: 100%;
|
||||||
|
flex: 0 1 auto;
|
||||||
}
|
}
|
||||||
|
|
||||||
.userActions {
|
.userActions {
|
||||||
@@ -973,11 +1077,41 @@
|
|||||||
|
|
||||||
.branchPicker {
|
.branchPicker {
|
||||||
display: flex;
|
display: flex;
|
||||||
|
width: max-content;
|
||||||
min-height: 1.75rem;
|
min-height: 1.75rem;
|
||||||
|
flex: 0 0 auto;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
gap: 0.1rem;
|
gap: 0.1rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.providerAction,
|
||||||
|
.conversationTurnProvider {
|
||||||
|
display: grid;
|
||||||
|
flex: 0 0 auto;
|
||||||
|
place-items: center;
|
||||||
|
color: var(--mantine-color-dimmed);
|
||||||
|
}
|
||||||
|
|
||||||
|
.providerAction {
|
||||||
|
width: 1.75rem;
|
||||||
|
height: 1.75rem;
|
||||||
|
border-radius: var(--mantine-radius-sm);
|
||||||
|
}
|
||||||
|
|
||||||
|
.providerAction:hover {
|
||||||
|
background: var(--mantine-color-default-hover);
|
||||||
|
}
|
||||||
|
|
||||||
|
.providerAction:focus-visible {
|
||||||
|
outline: 2px solid var(--mantine-primary-color-filled);
|
||||||
|
outline-offset: 1px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.providerIcon {
|
||||||
|
display: block;
|
||||||
|
object-fit: contain;
|
||||||
|
}
|
||||||
|
|
||||||
.editComposer {
|
.editComposer {
|
||||||
margin-block: 0.9rem;
|
margin-block: 0.9rem;
|
||||||
padding: 0.65rem;
|
padding: 0.65rem;
|
||||||
@@ -997,75 +1131,6 @@
|
|||||||
font: inherit;
|
font: inherit;
|
||||||
}
|
}
|
||||||
|
|
||||||
.telemetry {
|
|
||||||
margin-top: 0.45rem;
|
|
||||||
padding-inline: 0.15rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.telemetryFacts {
|
|
||||||
flex: 1 1 auto;
|
|
||||||
min-width: 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.modelBadge {
|
|
||||||
max-width: min(100%, 14rem);
|
|
||||||
}
|
|
||||||
|
|
||||||
.contextMeter {
|
|
||||||
display: grid;
|
|
||||||
width: 2.75rem;
|
|
||||||
height: 2.75rem;
|
|
||||||
flex: 0 0 auto;
|
|
||||||
place-items: center;
|
|
||||||
border-radius: 50%;
|
|
||||||
color: var(--mantine-color-text);
|
|
||||||
transition:
|
|
||||||
background-color 160ms ease,
|
|
||||||
transform 160ms ease;
|
|
||||||
}
|
|
||||||
|
|
||||||
.contextMeter:hover {
|
|
||||||
background: var(--mantine-color-default-hover);
|
|
||||||
}
|
|
||||||
|
|
||||||
.contextMeter:active {
|
|
||||||
transform: scale(0.96);
|
|
||||||
}
|
|
||||||
|
|
||||||
.contextMeter:focus-visible {
|
|
||||||
outline: 2px solid var(--mantine-primary-color-filled);
|
|
||||||
outline-offset: 2px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.contextMeterLabel {
|
|
||||||
font-size: 0.55rem;
|
|
||||||
line-height: 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
.telemetryPopover {
|
|
||||||
max-height: min(32rem, calc(100dvh - 2rem));
|
|
||||||
overflow-y: auto;
|
|
||||||
}
|
|
||||||
|
|
||||||
.contextStats {
|
|
||||||
display: grid;
|
|
||||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
|
||||||
gap: 0.5rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.contextStats > div {
|
|
||||||
min-width: 0;
|
|
||||||
padding: 0.45rem 0.5rem;
|
|
||||||
border-radius: var(--mantine-radius-sm);
|
|
||||||
background: var(--mantine-color-body);
|
|
||||||
}
|
|
||||||
|
|
||||||
.contextStats :global(.mantine-Text-root) {
|
|
||||||
overflow: hidden;
|
|
||||||
text-overflow: ellipsis;
|
|
||||||
white-space: nowrap;
|
|
||||||
}
|
|
||||||
|
|
||||||
.usageGrid {
|
.usageGrid {
|
||||||
display: grid;
|
display: grid;
|
||||||
grid-template-columns: repeat(auto-fit, minmax(7rem, 1fr));
|
grid-template-columns: repeat(auto-fit, minmax(7rem, 1fr));
|
||||||
@@ -1086,9 +1151,71 @@
|
|||||||
white-space: nowrap;
|
white-space: nowrap;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.composerContext {
|
||||||
|
display: flex;
|
||||||
|
width: 1.75rem;
|
||||||
|
height: 1.75rem;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
padding: 0;
|
||||||
|
border: 1px solid var(--mantine-color-default-border);
|
||||||
|
border-radius: 50%;
|
||||||
|
color: var(--mantine-color-text);
|
||||||
|
background: var(--mantine-color-body);
|
||||||
|
}
|
||||||
|
|
||||||
|
.composerContext:hover {
|
||||||
|
background: var(--mantine-color-default-hover);
|
||||||
|
}
|
||||||
|
|
||||||
|
.composerContext:focus-visible {
|
||||||
|
outline: 2px solid var(--mantine-primary-color-filled);
|
||||||
|
outline-offset: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.conversationContextPopover {
|
||||||
|
max-height: min(34rem, calc(100dvh - 1rem));
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.conversationUsageSummary {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||||
|
gap: 0.4rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.conversationUsageSummary > div {
|
||||||
|
min-width: 0;
|
||||||
|
padding: 0.45rem 0.5rem;
|
||||||
|
border-radius: var(--mantine-radius-sm);
|
||||||
|
background: var(--mantine-color-default);
|
||||||
|
}
|
||||||
|
|
||||||
|
.conversationTurn {
|
||||||
|
min-width: 0;
|
||||||
|
padding: 0.5rem 0.55rem;
|
||||||
|
border: 1px solid var(--mantine-color-default-border);
|
||||||
|
border-radius: var(--mantine-radius-sm);
|
||||||
|
}
|
||||||
|
|
||||||
|
.conversationTurnTrigger {
|
||||||
|
width: 100%;
|
||||||
|
text-align: start;
|
||||||
|
}
|
||||||
|
|
||||||
|
.conversationTurnTrigger:focus-visible {
|
||||||
|
outline: 2px solid var(--mantine-primary-color-filled);
|
||||||
|
outline-offset: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.conversationTurnProvider {
|
||||||
|
width: 1.5rem;
|
||||||
|
height: 1.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
.composerWrap {
|
.composerWrap {
|
||||||
flex: 0 0 auto;
|
flex: 0 0 auto;
|
||||||
padding: 0.65rem 0.75rem 0.75rem;
|
padding: 0;
|
||||||
border-top: 1px solid var(--mantine-color-default-border);
|
border-top: 1px solid var(--mantine-color-default-border);
|
||||||
background: var(--mantine-color-body);
|
background: var(--mantine-color-body);
|
||||||
}
|
}
|
||||||
@@ -1097,20 +1224,22 @@
|
|||||||
position: relative;
|
position: relative;
|
||||||
display: flex;
|
display: flex;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
max-width: 44rem;
|
max-width: none;
|
||||||
margin-inline: auto;
|
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
align-items: stretch;
|
align-items: stretch;
|
||||||
gap: 0.5rem;
|
gap: 0.5rem;
|
||||||
padding: 0.4rem;
|
padding: 0.45rem 0.75rem 0.55rem;
|
||||||
border: 1px solid var(--mantine-color-default-border);
|
border: 0;
|
||||||
border-radius: var(--mantine-radius-lg);
|
border-radius: 0;
|
||||||
background: var(--mantine-color-default);
|
background: var(--mantine-color-body);
|
||||||
|
}
|
||||||
|
|
||||||
|
.composer:has(.composerInput:focus-within) {
|
||||||
|
box-shadow: inset 0 0 0 2px var(--mantine-color-red-filled);
|
||||||
}
|
}
|
||||||
|
|
||||||
.composerDropzone[data-dragging] .composer {
|
.composerDropzone[data-dragging] .composer {
|
||||||
border-color: var(--mantine-primary-color-filled);
|
box-shadow: inset 0 0 0 2px var(--mantine-primary-color-filled);
|
||||||
box-shadow: 0 0 0 2px var(--mantine-primary-color-light);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.composerQuote {
|
.composerQuote {
|
||||||
@@ -1147,10 +1276,6 @@
|
|||||||
width: 100%;
|
width: 100%;
|
||||||
}
|
}
|
||||||
|
|
||||||
.composer:focus-within {
|
|
||||||
border-color: var(--mantine-primary-color-filled);
|
|
||||||
}
|
|
||||||
|
|
||||||
.composerInput {
|
.composerInput {
|
||||||
position: relative;
|
position: relative;
|
||||||
min-height: 2.25rem;
|
min-height: 2.25rem;
|
||||||
@@ -1180,7 +1305,7 @@
|
|||||||
.composerInput :global(.aui-lexical-placeholder) {
|
.composerInput :global(.aui-lexical-placeholder) {
|
||||||
position: absolute;
|
position: absolute;
|
||||||
inset: 0.35rem 0.45rem auto;
|
inset: 0.35rem 0.45rem auto;
|
||||||
color: var(--mantine-color-dimmed);
|
color: light-dark(var(--mantine-color-gray-7), var(--mantine-color-gray-5));
|
||||||
line-height: 1.5;
|
line-height: 1.5;
|
||||||
pointer-events: none;
|
pointer-events: none;
|
||||||
}
|
}
|
||||||
@@ -1194,6 +1319,11 @@
|
|||||||
padding-inline: 0.2rem;
|
padding-inline: 0.2rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.composerControls {
|
||||||
|
min-width: 0;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
.runtimeSelectorTrigger {
|
.runtimeSelectorTrigger {
|
||||||
width: fit-content;
|
width: fit-content;
|
||||||
min-width: 0;
|
min-width: 0;
|
||||||
@@ -1246,7 +1376,7 @@
|
|||||||
|
|
||||||
.modelOption {
|
.modelOption {
|
||||||
margin-inline: 0.25rem;
|
margin-inline: 0.25rem;
|
||||||
padding: 0.32rem 0.45rem;
|
padding: 0.32rem 0.45rem 0.32rem 0.3rem;
|
||||||
border-radius: var(--mantine-radius-sm);
|
border-radius: var(--mantine-radius-sm);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1254,7 +1384,16 @@
|
|||||||
.modelOption[data-combobox-active] {
|
.modelOption[data-combobox-active] {
|
||||||
color: var(--mantine-color-text);
|
color: var(--mantine-color-text);
|
||||||
background: var(--mantine-color-default-hover);
|
background: var(--mantine-color-default-hover);
|
||||||
box-shadow: inset 2px 0 0 var(--mantine-primary-color-filled);
|
}
|
||||||
|
|
||||||
|
.modelOptionDivider {
|
||||||
|
height: 2rem;
|
||||||
|
align-self: center;
|
||||||
|
border-color: transparent;
|
||||||
|
}
|
||||||
|
|
||||||
|
.modelOptionDivider[data-active] {
|
||||||
|
border-color: var(--mantine-primary-color-filled);
|
||||||
}
|
}
|
||||||
|
|
||||||
.modelOptionText {
|
.modelOptionText {
|
||||||
@@ -1337,6 +1476,10 @@
|
|||||||
text-align: center;
|
text-align: center;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.emptyDescription {
|
||||||
|
color: light-dark(var(--mantine-color-gray-7), var(--mantine-color-gray-5));
|
||||||
|
}
|
||||||
|
|
||||||
.suggestions {
|
.suggestions {
|
||||||
display: grid;
|
display: grid;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
@@ -1411,7 +1554,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.composerWrap {
|
.composerWrap {
|
||||||
padding: 0.5rem;
|
padding: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.composer {
|
.composer {
|
||||||
@@ -1482,6 +1625,19 @@
|
|||||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.conversationUsageSummary {
|
||||||
|
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||||
|
}
|
||||||
|
|
||||||
|
.humanToolOption {
|
||||||
|
grid-template-columns: max-content minmax(0, 1fr);
|
||||||
|
}
|
||||||
|
|
||||||
|
.humanToolOptionBadge {
|
||||||
|
grid-column: 2;
|
||||||
|
justify-self: start;
|
||||||
|
}
|
||||||
|
|
||||||
.approvalActions {
|
.approvalActions {
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
}
|
}
|
||||||
@@ -1492,6 +1648,10 @@
|
|||||||
padding: 0.8rem;
|
padding: 0.8rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.pendingQuestionDock {
|
||||||
|
padding: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
.boardSettingsActions,
|
.boardSettingsActions,
|
||||||
.boardSettingsSubmitGroup {
|
.boardSettingsSubmitGroup {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
@@ -1506,7 +1666,6 @@
|
|||||||
@media (prefers-reduced-motion: reduce) {
|
@media (prefers-reduced-motion: reduce) {
|
||||||
.activityBar,
|
.activityBar,
|
||||||
.floatingPanel,
|
.floatingPanel,
|
||||||
.contextMeter,
|
|
||||||
.disclosureIcon,
|
.disclosureIcon,
|
||||||
.reasoningChevron {
|
.reasoningChevron {
|
||||||
animation: none;
|
animation: none;
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
@@ -28,13 +28,19 @@ import { AssistantWidgetRendererProvider } from "@homarr/widgets";
|
|||||||
import { AssistantContext, AssistantPreferencesContext, useAssistantPreferences } from "./assistant-context";
|
import { AssistantContext, AssistantPreferencesContext, useAssistantPreferences } from "./assistant-context";
|
||||||
import { shouldAutomaticallyContinueAssistant } from "./assistant-auto-submit";
|
import { shouldAutomaticallyContinueAssistant } from "./assistant-auto-submit";
|
||||||
import { AssistantAutoApprovalProvider } from "./assistant-auto-approval";
|
import { AssistantAutoApprovalProvider } from "./assistant-auto-approval";
|
||||||
|
import { getRunningAssistantPartType } from "./assistant-activity-state";
|
||||||
|
import { prepareAssistantRequestBody } from "./assistant-attachment-payload";
|
||||||
import { createAssistantBrowserToolExecutors } from "./assistant-browser-tool-executors";
|
import { createAssistantBrowserToolExecutors } from "./assistant-browser-tool-executors";
|
||||||
import { AssistantAskUserTool, AssistantConfigureAppTool } from "./assistant-human-tools";
|
import { AssistantAskUserTool, AssistantConfigureAppTool } from "./assistant-human-tools";
|
||||||
import { AssistantPanel } from "./assistant-panel";
|
import { AssistantPanel } from "./assistant-panel";
|
||||||
import { getPendingAssistantAction } from "./assistant-pending-action";
|
import { getPendingAssistantAction } from "./assistant-pending-action";
|
||||||
import type { AssistantReasoningMode, AssistantRuntimeModelOption } from "./assistant-preferences";
|
import type { AssistantReasoningMode, AssistantRuntimeModelOption } from "./assistant-preferences";
|
||||||
import { resolveAssistantPreferenceModelId, resolveAssistantThreadPreferenceModelId } from "./assistant-preferences";
|
import { resolveAssistantPreferenceModelId, resolveAssistantThreadPreferenceModelId } from "./assistant-preferences";
|
||||||
import { AssistantRuntimeProviderWithTools } from "./assistant-runtime-provider";
|
import {
|
||||||
|
AssistantComposerSurfaceProvider,
|
||||||
|
AssistantRunFocusPreserver,
|
||||||
|
AssistantRuntimeProviderWithTools,
|
||||||
|
} from "./assistant-runtime-provider";
|
||||||
import { sendAssistantPrompt as sendPromptThroughRuntime } from "./assistant-send";
|
import { sendAssistantPrompt as sendPromptThroughRuntime } from "./assistant-send";
|
||||||
import { createAssistantPromptInteraction } from "./assistant-spotlight";
|
import { createAssistantPromptInteraction } from "./assistant-spotlight";
|
||||||
import { browserToolContracts } from "./assistant-tool-contracts";
|
import { browserToolContracts } from "./assistant-tool-contracts";
|
||||||
@@ -69,14 +75,9 @@ const fileToDataUrlAsync = (file: File) =>
|
|||||||
});
|
});
|
||||||
|
|
||||||
const createAssistantAttachmentAdapter = (allowImages: boolean): AttachmentAdapter => {
|
const createAssistantAttachmentAdapter = (allowImages: boolean): AttachmentAdapter => {
|
||||||
const pendingAttachmentIds = new Set<string>();
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
accept: [...(allowImages ? assistantImageAttachmentTypes : []), ...assistantDocumentAttachmentTypes].join(","),
|
accept: [...(allowImages ? assistantImageAttachmentTypes : []), ...assistantDocumentAttachmentTypes].join(","),
|
||||||
async add({ file }) {
|
async add({ file }) {
|
||||||
if (pendingAttachmentIds.size >= 5) {
|
|
||||||
throw new Error("A message can include up to 5 attachments.");
|
|
||||||
}
|
|
||||||
const isImage = file.type.startsWith("image/");
|
const isImage = file.type.startsWith("image/");
|
||||||
if (isImage && !allowImages) {
|
if (isImage && !allowImages) {
|
||||||
throw new Error("The selected model does not support image input.");
|
throw new Error("The selected model does not support image input.");
|
||||||
@@ -93,7 +94,6 @@ const createAssistantAttachmentAdapter = (allowImages: boolean): AttachmentAdapt
|
|||||||
throw new Error(isImage ? "Images must be smaller than 1 MB." : "Documents must be smaller than 350 KB.");
|
throw new Error(isImage ? "Images must be smaller than 1 MB." : "Documents must be smaller than 350 KB.");
|
||||||
}
|
}
|
||||||
const id = createId();
|
const id = createId();
|
||||||
pendingAttachmentIds.add(id);
|
|
||||||
return {
|
return {
|
||||||
id,
|
id,
|
||||||
type: isImage ? "image" : "document",
|
type: isImage ? "image" : "document",
|
||||||
@@ -104,26 +104,20 @@ const createAssistantAttachmentAdapter = (allowImages: boolean): AttachmentAdapt
|
|||||||
};
|
};
|
||||||
},
|
},
|
||||||
async send(attachment) {
|
async send(attachment) {
|
||||||
try {
|
return {
|
||||||
return {
|
...attachment,
|
||||||
...attachment,
|
status: { type: "complete" },
|
||||||
status: { type: "complete" },
|
content: [
|
||||||
content: [
|
{
|
||||||
{
|
type: "file",
|
||||||
type: "file",
|
filename: attachment.name,
|
||||||
filename: attachment.name,
|
mimeType: attachment.contentType ?? "application/octet-stream",
|
||||||
mimeType: attachment.contentType ?? "application/octet-stream",
|
data: await fileToDataUrlAsync(attachment.file),
|
||||||
data: await fileToDataUrlAsync(attachment.file),
|
},
|
||||||
},
|
],
|
||||||
],
|
};
|
||||||
};
|
|
||||||
} finally {
|
|
||||||
pendingAttachmentIds.delete(attachment.id);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
async remove(attachment) {
|
|
||||||
pendingAttachmentIds.delete(attachment.id);
|
|
||||||
},
|
},
|
||||||
|
async remove() {},
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -334,6 +328,7 @@ const AssistantThreadRuntime = () => {
|
|||||||
new AssistantChatTransport({
|
new AssistantChatTransport({
|
||||||
api: "/api/assistant/chat",
|
api: "/api/assistant/chat",
|
||||||
body: preferences.getRequestBody,
|
body: preferences.getRequestBody,
|
||||||
|
fetch: (input, init) => globalThis.fetch(input, { ...init, body: prepareAssistantRequestBody(init?.body) }),
|
||||||
}),
|
}),
|
||||||
[preferences.getRequestBody],
|
[preferences.getRequestBody],
|
||||||
);
|
);
|
||||||
@@ -460,6 +455,7 @@ const AssistantRuntime = ({ children }: PropsWithChildren) => {
|
|||||||
return (
|
return (
|
||||||
<AssistantRuntimeProviderWithTools runtime={runtime} toolkit={toolkit}>
|
<AssistantRuntimeProviderWithTools runtime={runtime} toolkit={toolkit}>
|
||||||
<AssistantRuntimeEvents />
|
<AssistantRuntimeEvents />
|
||||||
|
<AssistantRunFocusPreserver />
|
||||||
<AssistantPreferenceSync />
|
<AssistantPreferenceSync />
|
||||||
{children}
|
{children}
|
||||||
</AssistantRuntimeProviderWithTools>
|
</AssistantRuntimeProviderWithTools>
|
||||||
@@ -541,6 +537,10 @@ const EnabledAssistantProvider = ({ children }: PropsWithChildren) => {
|
|||||||
const latestAssistantText = getMessageText(latestAssistantMessage);
|
const latestAssistantText = getMessageText(latestAssistantMessage);
|
||||||
const latestUserText = getMessageText(latestUserMessage);
|
const latestUserText = getMessageText(latestUserMessage);
|
||||||
const latestStatus = latestAssistantMessage?.role === "assistant" ? latestAssistantMessage.status : undefined;
|
const latestStatus = latestAssistantMessage?.role === "assistant" ? latestAssistantMessage.status : undefined;
|
||||||
|
const latestAssistantPartType = getRunningAssistantPartType(
|
||||||
|
latestStatus?.type,
|
||||||
|
latestAssistantMessage?.content.at(-1)?.type,
|
||||||
|
);
|
||||||
const pendingAction = getPendingAssistantAction(latestAssistantMessage);
|
const pendingAction = getPendingAssistantAction(latestAssistantMessage);
|
||||||
const assistantIsRunning = isRunning || queuedPrompt !== null;
|
const assistantIsRunning = isRunning || queuedPrompt !== null;
|
||||||
const notificationKey = getNotificationKey(latestAssistantMessage);
|
const notificationKey = getNotificationKey(latestAssistantMessage);
|
||||||
@@ -690,30 +690,33 @@ const EnabledAssistantProvider = ({ children }: PropsWithChildren) => {
|
|||||||
<AssistantAutoApprovalProvider conversationId={conversationId}>
|
<AssistantAutoApprovalProvider conversationId={conversationId}>
|
||||||
<AssistantContext.Provider value={value}>
|
<AssistantContext.Provider value={value}>
|
||||||
<AssistantWidgetRendererProvider renderer={AssistantBoardWidget}>{children}</AssistantWidgetRendererProvider>
|
<AssistantWidgetRendererProvider renderer={AssistantBoardWidget}>{children}</AssistantWidgetRendererProvider>
|
||||||
<AssistantPanel
|
<AssistantComposerSurfaceProvider surfaceId="floating-panel">
|
||||||
opened={opened}
|
<AssistantPanel
|
||||||
onOpen={open}
|
opened={opened}
|
||||||
onClose={close}
|
onOpen={open}
|
||||||
onDismissActivity={() => {
|
onClose={close}
|
||||||
markRead();
|
onDismissActivity={() => {
|
||||||
setActivityDismissed(true);
|
markRead();
|
||||||
}}
|
setActivityDismissed(true);
|
||||||
activityDismissed={activityDismissed}
|
}}
|
||||||
isRunning={assistantIsRunning}
|
activityDismissed={activityDismissed}
|
||||||
unreadCount={unreadCount}
|
isRunning={assistantIsRunning}
|
||||||
latestAssistantText={latestAssistantText}
|
unreadCount={unreadCount}
|
||||||
latestUserText={queuedPrompt ?? latestUserText}
|
latestAssistantText={latestAssistantText}
|
||||||
latestStatus={latestStatus}
|
latestAssistantPartType={latestAssistantPartType}
|
||||||
pendingAction={pendingAction}
|
latestUserText={queuedPrompt ?? latestUserText}
|
||||||
modelId={preferences.modelId}
|
latestStatus={latestStatus}
|
||||||
models={preferences.models}
|
pendingAction={pendingAction}
|
||||||
modelOptionsLoading={preferences.isLoading}
|
modelId={preferences.modelId}
|
||||||
reasoning={preferences.reasoning}
|
models={preferences.models}
|
||||||
isRefreshing={isRefreshing}
|
modelOptionsLoading={preferences.isLoading}
|
||||||
onRefresh={refreshCurrentView}
|
reasoning={preferences.reasoning}
|
||||||
onModelChange={selectModel}
|
isRefreshing={isRefreshing}
|
||||||
onReasoningChange={preferences.setReasoning}
|
onRefresh={refreshCurrentView}
|
||||||
/>
|
onModelChange={selectModel}
|
||||||
|
onReasoningChange={preferences.setReasoning}
|
||||||
|
/>
|
||||||
|
</AssistantComposerSurfaceProvider>
|
||||||
</AssistantContext.Provider>
|
</AssistantContext.Provider>
|
||||||
</AssistantAutoApprovalProvider>
|
</AssistantAutoApprovalProvider>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -0,0 +1,144 @@
|
|||||||
|
// @vitest-environment jsdom
|
||||||
|
|
||||||
|
import { act, createElement, useEffect } from "react";
|
||||||
|
import { createRoot } from "react-dom/client";
|
||||||
|
import type { AssistantClient, ChatModelAdapter, ThreadMessageLike } from "@assistant-ui/react";
|
||||||
|
import {
|
||||||
|
AssistantRuntimeProvider,
|
||||||
|
ChainOfThoughtPrimitive,
|
||||||
|
MessagePrimitive,
|
||||||
|
ThreadPrimitive,
|
||||||
|
useAui,
|
||||||
|
useLocalRuntime,
|
||||||
|
} from "@assistant-ui/react";
|
||||||
|
import { afterEach, describe, expect, test } from "vitest";
|
||||||
|
|
||||||
|
import { useAssistantReasoningState } from "./assistant-reasoning-state";
|
||||||
|
|
||||||
|
(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
|
||||||
|
|
||||||
|
const flushEffects = () => new Promise((resolve) => setTimeout(resolve, 0));
|
||||||
|
const containers: HTMLDivElement[] = [];
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
for (const container of containers.splice(0)) container.remove();
|
||||||
|
});
|
||||||
|
|
||||||
|
const ReasoningPart = ({ text }: { text: string }) => <span data-testid="reasoning-part">{text}</span>;
|
||||||
|
const ToolPart = ({ toolName }: { toolName: string }) => <span data-testid="tool-part">{toolName}</span>;
|
||||||
|
|
||||||
|
const TestChainOfThought = ({ preferredCollapsed = true }: { preferredCollapsed?: boolean }) => {
|
||||||
|
const { chainStatus, collapsed } = useAssistantReasoningState(preferredCollapsed);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ChainOfThoughtPrimitive.Root
|
||||||
|
data-testid="chain-of-thought"
|
||||||
|
data-status={chainStatus.type}
|
||||||
|
data-collapsed={String(collapsed)}
|
||||||
|
>
|
||||||
|
<ChainOfThoughtPrimitive.Parts components={{ Reasoning: ReasoningPart, tools: { Fallback: ToolPart } }} />
|
||||||
|
</ChainOfThoughtPrimitive.Root>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const TestMessage = () => (
|
||||||
|
<MessagePrimitive.Root>
|
||||||
|
<MessagePrimitive.Parts components={{ ChainOfThought: TestChainOfThought }} />
|
||||||
|
</MessagePrimitive.Root>
|
||||||
|
);
|
||||||
|
|
||||||
|
const RuntimeProbe = ({ onReady }: { onReady: (aui: AssistantClient) => void }) => {
|
||||||
|
const aui = useAui();
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
onReady(aui);
|
||||||
|
}, [aui, onReady]);
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const renderAssistant = async (adapter: ChatModelAdapter, initialMessages: ThreadMessageLike[] = []) => {
|
||||||
|
const container = document.createElement("div");
|
||||||
|
containers.push(container);
|
||||||
|
document.body.append(container);
|
||||||
|
const root = createRoot(container);
|
||||||
|
let client: AssistantClient | undefined;
|
||||||
|
|
||||||
|
const TestAssistant = () => {
|
||||||
|
const runtime = useLocalRuntime(adapter, { initialMessages });
|
||||||
|
return (
|
||||||
|
<AssistantRuntimeProvider runtime={runtime}>
|
||||||
|
<RuntimeProbe
|
||||||
|
onReady={(aui) => {
|
||||||
|
client = aui;
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<ThreadPrimitive.Messages components={{ Message: TestMessage }} />
|
||||||
|
</AssistantRuntimeProvider>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
root.render(createElement(TestAssistant));
|
||||||
|
await flushEffects();
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!client) throw new Error("The assistant runtime was not registered");
|
||||||
|
return { client, container, root };
|
||||||
|
};
|
||||||
|
|
||||||
|
describe("useAssistantReasoningState", () => {
|
||||||
|
test("mounts and renders streamed reasoning without updating the chain resource before mount", async () => {
|
||||||
|
const adapter: ChatModelAdapter = {
|
||||||
|
async *run() {
|
||||||
|
yield { content: [{ type: "reasoning", text: "Inspecting the dashboard" }] };
|
||||||
|
await flushEffects();
|
||||||
|
yield {
|
||||||
|
content: [
|
||||||
|
{ type: "reasoning", text: "Inspecting the dashboard" },
|
||||||
|
{ type: "text", text: "Done" },
|
||||||
|
],
|
||||||
|
};
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const { client, container, root } = await renderAssistant(adapter);
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
client.composer().setText("Inspect my dashboard");
|
||||||
|
client.composer().send();
|
||||||
|
await flushEffects();
|
||||||
|
await flushEffects();
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(container.querySelector('[data-testid="reasoning-part"]')?.textContent).toBe("Inspecting the dashboard");
|
||||||
|
expect(container.querySelector('[data-testid="chain-of-thought"]')?.getAttribute("data-status")).toBe("complete");
|
||||||
|
|
||||||
|
await act(async () => root.unmount());
|
||||||
|
});
|
||||||
|
|
||||||
|
test("opens a pending tool call even when completed reasoning is normally collapsed", async () => {
|
||||||
|
const pendingToolMessage: ThreadMessageLike = {
|
||||||
|
role: "assistant",
|
||||||
|
content: [
|
||||||
|
{ type: "reasoning", text: "I need approval" },
|
||||||
|
{
|
||||||
|
type: "tool-call",
|
||||||
|
toolCallId: "approval-1",
|
||||||
|
toolName: "app_create",
|
||||||
|
args: { name: "Wikipedia" },
|
||||||
|
argsText: JSON.stringify({ name: "Wikipedia" }),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
status: { type: "requires-action", reason: "tool-calls" },
|
||||||
|
};
|
||||||
|
const { container, root } = await renderAssistant({ async *run() {} }, [pendingToolMessage]);
|
||||||
|
await act(async () => flushEffects());
|
||||||
|
|
||||||
|
expect(container.querySelector('[data-testid="tool-part"]')?.textContent).toBe("app_create");
|
||||||
|
expect(container.querySelector('[data-testid="chain-of-thought"]')?.getAttribute("data-status")).toBe(
|
||||||
|
"requires-action",
|
||||||
|
);
|
||||||
|
expect(container.querySelector('[data-testid="chain-of-thought"]')?.getAttribute("data-collapsed")).toBe("false");
|
||||||
|
|
||||||
|
await act(async () => root.unmount());
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useEffect } from "react";
|
||||||
|
import { useAui, useAuiState } from "@assistant-ui/react";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Keeps the per-message chain of thought aligned with the conversation preference.
|
||||||
|
*
|
||||||
|
* assistant-ui commits its chain resource in a passive effect. Updating it from a
|
||||||
|
* layout effect races that commit and throws `Resource updated before mount` when
|
||||||
|
* reasoning or tool parts first appear. Keep all programmatic chain updates in
|
||||||
|
* passive effects so the resource is mounted before it receives an update.
|
||||||
|
*/
|
||||||
|
export const useAssistantReasoningState = (preferredCollapsed: boolean) => {
|
||||||
|
const aui = useAui();
|
||||||
|
const chainStatus = useAuiState((state) => state.chainOfThought.status);
|
||||||
|
const collapsed = useAuiState((state) => state.chainOfThought.collapsed);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
aui.chainOfThought().setCollapsed(preferredCollapsed);
|
||||||
|
}, [aui, preferredCollapsed]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (chainStatus.type !== "requires-action") return;
|
||||||
|
aui.chainOfThought().setCollapsed(false);
|
||||||
|
}, [aui, chainStatus.type]);
|
||||||
|
|
||||||
|
return { chainStatus, collapsed };
|
||||||
|
};
|
||||||
@@ -1,17 +1,63 @@
|
|||||||
// @vitest-environment jsdom
|
// @vitest-environment jsdom
|
||||||
|
|
||||||
import { act, createElement } from "react";
|
import type { ComponentProps } from "react";
|
||||||
|
import { act, createElement, useEffect } from "react";
|
||||||
import { createRoot } from "react-dom/client";
|
import { createRoot } from "react-dom/client";
|
||||||
import type { ChatModelAdapter, ThreadMessageLike } from "@assistant-ui/react";
|
import type {
|
||||||
import { defineToolkit, MessagePrimitive, ThreadPrimitive, useLocalRuntime } from "@assistant-ui/react";
|
AssistantClient,
|
||||||
import { afterEach, describe, expect, test } from "vitest";
|
AssistantRuntime,
|
||||||
|
AttachmentAdapter,
|
||||||
|
ChatModelAdapter,
|
||||||
|
ThreadMessageLike,
|
||||||
|
} from "@assistant-ui/react";
|
||||||
|
import {
|
||||||
|
defineToolkit,
|
||||||
|
INTERNAL,
|
||||||
|
MessagePrimitive,
|
||||||
|
ThreadPrimitive,
|
||||||
|
useAui,
|
||||||
|
useLocalRuntime,
|
||||||
|
} from "@assistant-ui/react";
|
||||||
|
import { LexicalComposerInput } from "@assistant-ui/react-lexical";
|
||||||
|
import { afterEach, describe, expect, test, vi } from "vitest";
|
||||||
import { z } from "zod/v4";
|
import { z } from "zod/v4";
|
||||||
|
|
||||||
import { AssistantRuntimeProviderWithTools } from "./assistant-runtime-provider";
|
import { showErrorNotification } from "@homarr/notifications";
|
||||||
|
|
||||||
|
import {
|
||||||
|
AssistantComposerSurfaceProvider,
|
||||||
|
AssistantRunFocusPreserver,
|
||||||
|
AssistantRuntimeProviderWithTools,
|
||||||
|
assistantSurfaceComposerCacheLimit,
|
||||||
|
} from "./assistant-runtime-provider";
|
||||||
|
|
||||||
|
vi.mock("@homarr/notifications", () => ({ showErrorNotification: vi.fn() }));
|
||||||
|
vi.mock("@homarr/translation/client", () => ({ useScopedI18n: () => (key: string) => key }));
|
||||||
|
|
||||||
(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
|
(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
|
||||||
|
|
||||||
const noOpAdapter: ChatModelAdapter = { async *run() {} };
|
const noOpAdapter: ChatModelAdapter = { async *run() {} };
|
||||||
|
const createAttachmentAdapter = (accept: string): AttachmentAdapter => ({
|
||||||
|
accept,
|
||||||
|
async add({ file }) {
|
||||||
|
return {
|
||||||
|
id: `${file.name}-${file.size}`,
|
||||||
|
type: file.type.startsWith("image/") ? "image" : "document",
|
||||||
|
name: file.name,
|
||||||
|
contentType: file.type,
|
||||||
|
file,
|
||||||
|
status: { type: "requires-action", reason: "composer-send" },
|
||||||
|
};
|
||||||
|
},
|
||||||
|
async send(attachment) {
|
||||||
|
return {
|
||||||
|
...attachment,
|
||||||
|
status: { type: "complete" },
|
||||||
|
content: [{ type: "text", text: attachment.name }],
|
||||||
|
};
|
||||||
|
},
|
||||||
|
async remove() {},
|
||||||
|
});
|
||||||
const toolkit = defineToolkit({
|
const toolkit = defineToolkit({
|
||||||
ask_user: {
|
ask_user: {
|
||||||
type: "human",
|
type: "human",
|
||||||
@@ -54,6 +100,104 @@ const TestAssistant = () => {
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
interface SurfaceProbeProps {
|
||||||
|
id: string;
|
||||||
|
onReady: (id: string, aui: AssistantClient) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
const SurfaceProbe = ({ id, onReady }: SurfaceProbeProps) => {
|
||||||
|
const aui = useAui();
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
onReady(id, aui);
|
||||||
|
}, [aui, id, onReady]);
|
||||||
|
|
||||||
|
return createElement(LexicalComposerInput, {
|
||||||
|
"data-assistant-composer-input": true,
|
||||||
|
"data-testid": `input-${id}`,
|
||||||
|
} as ComponentProps<typeof LexicalComposerInput>);
|
||||||
|
};
|
||||||
|
|
||||||
|
const SurfaceTestAssistant = ({
|
||||||
|
onReady,
|
||||||
|
onRuntimeReady,
|
||||||
|
allowImages = true,
|
||||||
|
}: {
|
||||||
|
onReady: SurfaceProbeProps["onReady"];
|
||||||
|
onRuntimeReady: (runtime: AssistantRuntime) => void;
|
||||||
|
allowImages?: boolean;
|
||||||
|
}) => {
|
||||||
|
const runtime = useLocalRuntime(noOpAdapter, {
|
||||||
|
adapters: { attachments: createAttachmentAdapter(allowImages ? "image/png,text/plain" : "text/plain") },
|
||||||
|
});
|
||||||
|
useEffect(() => onRuntimeReady(runtime), [onRuntimeReady, runtime]);
|
||||||
|
return createElement(
|
||||||
|
AssistantRuntimeProviderWithTools,
|
||||||
|
{ runtime, toolkit },
|
||||||
|
createElement(AssistantRunFocusPreserver),
|
||||||
|
createElement(
|
||||||
|
AssistantComposerSurfaceProvider,
|
||||||
|
{ surfaceId: "surface-a" },
|
||||||
|
createElement(SurfaceProbe, { id: "a", onReady }),
|
||||||
|
),
|
||||||
|
createElement(
|
||||||
|
AssistantComposerSurfaceProvider,
|
||||||
|
{ surfaceId: "surface-b" },
|
||||||
|
createElement(SurfaceProbe, { id: "b", onReady }),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const renderSurfaceTestAssistant = async ({ allowImages = true }: { allowImages?: boolean } = {}) => {
|
||||||
|
const container = document.createElement("div");
|
||||||
|
containers.push(container);
|
||||||
|
document.body.append(container);
|
||||||
|
const root = createRoot(container);
|
||||||
|
const clients = new Map<string, AssistantClient>();
|
||||||
|
let sharedRuntime: AssistantRuntime | undefined;
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
root.render(
|
||||||
|
createElement(SurfaceTestAssistant, {
|
||||||
|
allowImages,
|
||||||
|
onReady: (id, aui) => clients.set(id, aui),
|
||||||
|
onRuntimeReady: (runtime) => {
|
||||||
|
sharedRuntime = runtime;
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||||
|
});
|
||||||
|
|
||||||
|
const a = clients.get("a");
|
||||||
|
const b = clients.get("b");
|
||||||
|
if (!a || !b || !sharedRuntime) throw new Error("The assistant runtime and both surfaces must be registered");
|
||||||
|
|
||||||
|
return {
|
||||||
|
container,
|
||||||
|
root,
|
||||||
|
a,
|
||||||
|
b,
|
||||||
|
sharedRuntime,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
const getRequiredComposerInput = (container: HTMLElement, testId: string) => {
|
||||||
|
const wrapper = container.querySelector<HTMLElement>(`[data-testid="${testId}"]`);
|
||||||
|
const target = wrapper?.querySelector<HTMLElement>('[contenteditable="true"]');
|
||||||
|
if (!target) throw new Error(`Missing composer input ${testId}`);
|
||||||
|
return target;
|
||||||
|
};
|
||||||
|
|
||||||
|
const getUserMessageText = (aui: AssistantClient) =>
|
||||||
|
aui
|
||||||
|
.thread()
|
||||||
|
.getState()
|
||||||
|
.messages.filter((message) => message.role === "user")
|
||||||
|
.flatMap((message) => message.content)
|
||||||
|
.filter((part) => part.type === "text")
|
||||||
|
.map((part) => part.text);
|
||||||
|
|
||||||
const containers: HTMLDivElement[] = [];
|
const containers: HTMLDivElement[] = [];
|
||||||
|
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
@@ -77,4 +221,293 @@ describe("AssistantRuntimeProviderWithTools", () => {
|
|||||||
|
|
||||||
await act(async () => root.unmount());
|
await act(async () => root.unmount());
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("keeps drafts and attachments independent while both surfaces share one thread", async () => {
|
||||||
|
const { container, root, a, b } = await renderSurfaceTestAssistant();
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
a.composer().setText("Draft in the board widget");
|
||||||
|
b.composer().setText("Draft in the floating panel");
|
||||||
|
});
|
||||||
|
await act(async () => new Promise((resolve) => setTimeout(resolve, 0)));
|
||||||
|
await act(async () => {
|
||||||
|
await a.composer().addAttachment({
|
||||||
|
id: "board-file",
|
||||||
|
name: "board.txt",
|
||||||
|
contentType: "text/plain",
|
||||||
|
content: [{ type: "text", text: "board attachment" }],
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(a.composer().getState().text).toBe("Draft in the board widget");
|
||||||
|
expect(b.composer().getState().text).toBe("Draft in the floating panel");
|
||||||
|
expect(
|
||||||
|
a
|
||||||
|
.composer()
|
||||||
|
.getState()
|
||||||
|
.attachments.map((attachment) => attachment.name),
|
||||||
|
).toEqual(["board.txt"]);
|
||||||
|
expect(b.composer().getState().attachments).toHaveLength(0);
|
||||||
|
expect(a.thread().getState().messages).toEqual(b.thread().getState().messages);
|
||||||
|
expect(getRequiredComposerInput(container, "input-a").textContent).toBe("Draft in the board widget");
|
||||||
|
expect(getRequiredComposerInput(container, "input-b").textContent).toBe("Draft in the floating panel");
|
||||||
|
|
||||||
|
await act(async () => root.unmount());
|
||||||
|
});
|
||||||
|
|
||||||
|
test("sends either local composer into the same shared conversation without clearing the other draft", async () => {
|
||||||
|
const { root, a, b } = await renderSurfaceTestAssistant();
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
a.composer().setText("Message from the widget");
|
||||||
|
b.composer().setText("Message from the panel");
|
||||||
|
a.composer().send();
|
||||||
|
});
|
||||||
|
await act(async () => new Promise((resolve) => setTimeout(resolve, 0)));
|
||||||
|
|
||||||
|
expect(getUserMessageText(a)).toContain("Message from the widget");
|
||||||
|
expect(getUserMessageText(b)).toContain("Message from the widget");
|
||||||
|
expect(a.composer().getState().text).toBe("");
|
||||||
|
expect(b.composer().getState().text).toBe("Message from the panel");
|
||||||
|
|
||||||
|
act(() => b.composer().send());
|
||||||
|
await act(async () => new Promise((resolve) => setTimeout(resolve, 0)));
|
||||||
|
expect(getUserMessageText(a)).toContain("Message from the panel");
|
||||||
|
expect(getUserMessageText(b)).toContain("Message from the panel");
|
||||||
|
|
||||||
|
await act(async () => root.unmount());
|
||||||
|
});
|
||||||
|
|
||||||
|
test("keeps each surface draft scoped to the selected conversation", async () => {
|
||||||
|
const { root, a, b } = await renderSurfaceTestAssistant();
|
||||||
|
act(() => {
|
||||||
|
a.composer().setText("Initialize the first conversation");
|
||||||
|
a.composer().send();
|
||||||
|
});
|
||||||
|
await act(async () => new Promise((resolve) => setTimeout(resolve, 0)));
|
||||||
|
const firstThreadId = a.threads().getState().mainThreadId;
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
a.composer().setText("First thread / widget");
|
||||||
|
b.composer().setText("First thread / panel");
|
||||||
|
});
|
||||||
|
await act(async () => a.threads().switchToNewThread());
|
||||||
|
|
||||||
|
expect(a.threads().getState().mainThreadId).not.toBe(firstThreadId);
|
||||||
|
expect(a.composer().getState().text).toBe("");
|
||||||
|
expect(b.composer().getState().text).toBe("");
|
||||||
|
act(() => a.composer().setText("Second thread / widget"));
|
||||||
|
|
||||||
|
await act(async () => a.threads().switchToThread(firstThreadId));
|
||||||
|
expect(a.composer().getState().text).toBe("First thread / widget");
|
||||||
|
expect(b.composer().getState().text).toBe("First thread / panel");
|
||||||
|
|
||||||
|
await act(async () => root.unmount());
|
||||||
|
});
|
||||||
|
|
||||||
|
test("restores focus after the Lexical run-start behavior tries to focus every surface", async () => {
|
||||||
|
const outsideInput = document.createElement("input");
|
||||||
|
document.body.append(outsideInput);
|
||||||
|
const { root, a } = await renderSurfaceTestAssistant();
|
||||||
|
outsideInput.focus();
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
a.composer().setText("Run without stealing focus");
|
||||||
|
a.composer().send();
|
||||||
|
});
|
||||||
|
await act(async () => {
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(document.activeElement).toBe(outsideInput);
|
||||||
|
outsideInput.remove();
|
||||||
|
await act(async () => root.unmount());
|
||||||
|
});
|
||||||
|
|
||||||
|
test("adds pasted images only to the active surface composer", async () => {
|
||||||
|
const { container, root, a, b } = await renderSurfaceTestAssistant();
|
||||||
|
const target = getRequiredComposerInput(container, "input-a");
|
||||||
|
const paste = new Event("paste", { bubbles: true, cancelable: true });
|
||||||
|
Object.defineProperty(paste, "clipboardData", {
|
||||||
|
value: { files: [new File(["image"], "dashboard.png", { type: "image/png" })] },
|
||||||
|
});
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
target.dispatchEvent(paste);
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(paste.defaultPrevented).toBe(true);
|
||||||
|
expect(
|
||||||
|
a
|
||||||
|
.composer()
|
||||||
|
.getState()
|
||||||
|
.attachments.map((attachment) => attachment.name),
|
||||||
|
).toEqual(["dashboard.png"]);
|
||||||
|
expect(b.composer().getState().attachments).toHaveLength(0);
|
||||||
|
await act(async () => root.unmount());
|
||||||
|
});
|
||||||
|
|
||||||
|
test("rejects a pasted image with an actionable message when the selected model is text-only", async () => {
|
||||||
|
vi.mocked(showErrorNotification).mockClear();
|
||||||
|
const { container, root, a } = await renderSurfaceTestAssistant({ allowImages: false });
|
||||||
|
const target = getRequiredComposerInput(container, "input-a");
|
||||||
|
const paste = new Event("paste", { bubbles: true, cancelable: true });
|
||||||
|
Object.defineProperty(paste, "clipboardData", {
|
||||||
|
value: { files: [new File(["image"], "dashboard.png", { type: "image/png" })] },
|
||||||
|
});
|
||||||
|
|
||||||
|
await act(async () => target.dispatchEvent(paste));
|
||||||
|
|
||||||
|
expect(a.composer().getState().attachments).toHaveLength(0);
|
||||||
|
expect(showErrorNotification).toHaveBeenCalledWith({
|
||||||
|
title: "attachments.errorTitle",
|
||||||
|
message: "attachments.imageUnsupported",
|
||||||
|
});
|
||||||
|
await act(async () => root.unmount());
|
||||||
|
});
|
||||||
|
|
||||||
|
test("does not capture file paste from a non-composer textarea", async () => {
|
||||||
|
const { container, root, a } = await renderSurfaceTestAssistant();
|
||||||
|
const textarea = document.createElement("textarea");
|
||||||
|
container.querySelector('[data-testid="input-a"]')?.parentElement?.append(textarea);
|
||||||
|
const paste = new Event("paste", { bubbles: true, cancelable: true });
|
||||||
|
Object.defineProperty(paste, "clipboardData", {
|
||||||
|
value: { files: [new File(["image"], "dashboard.png", { type: "image/png" })] },
|
||||||
|
});
|
||||||
|
|
||||||
|
await act(async () => textarea.dispatchEvent(paste));
|
||||||
|
|
||||||
|
expect(paste.defaultPrevented).toBe(false);
|
||||||
|
expect(a.composer().getState().attachments).toHaveLength(0);
|
||||||
|
await act(async () => root.unmount());
|
||||||
|
});
|
||||||
|
|
||||||
|
test("enforces the attachment limit independently for each surface", async () => {
|
||||||
|
vi.mocked(showErrorNotification).mockClear();
|
||||||
|
const { root, a, b } = await renderSurfaceTestAssistant();
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
await Promise.all(
|
||||||
|
Array.from({ length: 5 }, (_, index) =>
|
||||||
|
a.composer().addAttachment(new File([`a-${index}`], `a-${index}.txt`, { type: "text/plain" })),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
await Promise.all(
|
||||||
|
Array.from({ length: 5 }, (_, index) =>
|
||||||
|
b.composer().addAttachment(new File([`b-${index}`], `b-${index}.txt`, { type: "text/plain" })),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(a.composer().getState().attachments).toHaveLength(5);
|
||||||
|
expect(b.composer().getState().attachments).toHaveLength(5);
|
||||||
|
await expect(a.composer().addAttachment(new File(["six"], "a-six.txt", { type: "text/plain" }))).rejects.toThrow(
|
||||||
|
"A message can include up to 5 attachments.",
|
||||||
|
);
|
||||||
|
expect(b.composer().getState().attachments).toHaveLength(5);
|
||||||
|
|
||||||
|
await act(async () => root.unmount());
|
||||||
|
});
|
||||||
|
|
||||||
|
test("disposes scoped composer subscriptions when its surfaces unmount", async () => {
|
||||||
|
const originalConnect = INTERNAL.DefaultThreadComposerRuntimeCore.prototype.connect;
|
||||||
|
let activeConnections = 0;
|
||||||
|
const connectSpy = vi
|
||||||
|
.spyOn(INTERNAL.DefaultThreadComposerRuntimeCore.prototype, "connect")
|
||||||
|
.mockImplementation(function (this: InstanceType<typeof INTERNAL.DefaultThreadComposerRuntimeCore>) {
|
||||||
|
const unsubscribe = originalConnect.call(this);
|
||||||
|
activeConnections += 1;
|
||||||
|
let connected = true;
|
||||||
|
return () => {
|
||||||
|
if (!connected) return;
|
||||||
|
connected = false;
|
||||||
|
activeConnections -= 1;
|
||||||
|
unsubscribe();
|
||||||
|
};
|
||||||
|
});
|
||||||
|
const { root } = await renderSurfaceTestAssistant();
|
||||||
|
const mountedConnections = activeConnections;
|
||||||
|
expect(mountedConnections).toBeGreaterThanOrEqual(3);
|
||||||
|
|
||||||
|
await act(async () => root.unmount());
|
||||||
|
|
||||||
|
expect(activeConnections).toBeLessThan(mountedConnections);
|
||||||
|
expect(mountedConnections - activeConnections).toBe(2);
|
||||||
|
connectSpy.mockRestore();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("recreates scoped composers when the shared conversation core is replaced", async () => {
|
||||||
|
const originalConnect = INTERNAL.DefaultThreadComposerRuntimeCore.prototype.connect;
|
||||||
|
let connectCalls = 0;
|
||||||
|
let disconnectCalls = 0;
|
||||||
|
const connectSpy = vi
|
||||||
|
.spyOn(INTERNAL.DefaultThreadComposerRuntimeCore.prototype, "connect")
|
||||||
|
.mockImplementation(function (this: InstanceType<typeof INTERNAL.DefaultThreadComposerRuntimeCore>) {
|
||||||
|
connectCalls += 1;
|
||||||
|
const unsubscribe = originalConnect.call(this);
|
||||||
|
let connected = true;
|
||||||
|
return () => {
|
||||||
|
if (!connected) return;
|
||||||
|
connected = false;
|
||||||
|
disconnectCalls += 1;
|
||||||
|
unsubscribe();
|
||||||
|
};
|
||||||
|
});
|
||||||
|
const { root, a, b, sharedRuntime } = await renderSurfaceTestAssistant();
|
||||||
|
const mountedConnectCalls = connectCalls;
|
||||||
|
act(() => {
|
||||||
|
a.composer().setText("Draft on the first board core");
|
||||||
|
b.composer().setText("Draft on the first panel core");
|
||||||
|
});
|
||||||
|
|
||||||
|
const sharedThread = sharedRuntime.thread as InstanceType<typeof INTERNAL.ThreadRuntimeImpl>;
|
||||||
|
// oxlint-disable-next-line no-underscore-dangle -- replacing the bound core reproduces assistant-ui's outer runtime swap.
|
||||||
|
const binding = sharedThread.__internal_threadBinding;
|
||||||
|
const originalGetState = binding.getState;
|
||||||
|
const originalCore = originalGetState();
|
||||||
|
const replacementCore = new Proxy(originalCore, {
|
||||||
|
get(target, property) {
|
||||||
|
const value = Reflect.get(target, property, target) as unknown;
|
||||||
|
return typeof value === "function" ? value.bind(target) : value;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
binding.getState = () => replacementCore;
|
||||||
|
|
||||||
|
act(() => originalCore.reset());
|
||||||
|
await act(async () => new Promise((resolve) => setTimeout(resolve, 0)));
|
||||||
|
|
||||||
|
expect(connectCalls - mountedConnectCalls).toBeGreaterThanOrEqual(2);
|
||||||
|
expect(disconnectCalls).toBeGreaterThanOrEqual(2);
|
||||||
|
expect(a.composer().getState().text).toBe("Draft on the first board core");
|
||||||
|
expect(b.composer().getState().text).toBe("Draft on the first panel core");
|
||||||
|
|
||||||
|
await act(async () => root.unmount());
|
||||||
|
binding.getState = originalGetState;
|
||||||
|
connectSpy.mockRestore();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("evicts the least recently used inactive conversation draft", async () => {
|
||||||
|
const { root, a } = await renderSurfaceTestAssistant();
|
||||||
|
act(() => {
|
||||||
|
a.composer().setText("Initialize the oldest conversation");
|
||||||
|
a.composer().send();
|
||||||
|
});
|
||||||
|
await act(async () => new Promise((resolve) => setTimeout(resolve, 0)));
|
||||||
|
const oldestThreadId = a.threads().getState().mainThreadId;
|
||||||
|
act(() => a.composer().setText("Draft that should eventually be evicted"));
|
||||||
|
|
||||||
|
for (let index = 0; index < assistantSurfaceComposerCacheLimit; index += 1) {
|
||||||
|
await act(async () => a.threads().switchToNewThread());
|
||||||
|
act(() => {
|
||||||
|
a.composer().setText(`Initialize conversation ${index}`);
|
||||||
|
a.composer().send();
|
||||||
|
});
|
||||||
|
await act(async () => new Promise((resolve) => setTimeout(resolve, 0)));
|
||||||
|
}
|
||||||
|
|
||||||
|
await act(async () => a.threads().switchToThread(oldestThreadId));
|
||||||
|
expect(a.composer().getState().text).toBe("");
|
||||||
|
await act(async () => root.unmount());
|
||||||
|
});
|
||||||
});
|
});
|
||||||
@@ -1,8 +1,12 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import type { PropsWithChildren } from "react";
|
import type { ClipboardEvent, PropsWithChildren } from "react";
|
||||||
import type { AssistantRuntime, Toolkit } from "@assistant-ui/react";
|
import { createContext, useContext, useEffect, useId, useLayoutEffect, useMemo, useRef } from "react";
|
||||||
import { AssistantRuntimeProvider, Tools, useAui } from "@assistant-ui/react";
|
import type { AssistantRuntime, AttachmentAdapter, ThreadListRuntime, Toolkit } from "@assistant-ui/react";
|
||||||
|
import { AssistantRuntimeProvider, INTERNAL, Tools, useAui, useAuiEvent } from "@assistant-ui/react";
|
||||||
|
|
||||||
|
import { showErrorNotification } from "@homarr/notifications";
|
||||||
|
import { useScopedI18n } from "@homarr/translation/client";
|
||||||
|
|
||||||
interface AssistantRuntimeProviderWithToolsProps extends PropsWithChildren {
|
interface AssistantRuntimeProviderWithToolsProps extends PropsWithChildren {
|
||||||
runtime: AssistantRuntime;
|
runtime: AssistantRuntime;
|
||||||
@@ -21,3 +25,501 @@ export const AssistantRuntimeProviderWithTools = ({
|
|||||||
</AssistantRuntimeProvider>
|
</AssistantRuntimeProvider>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
type ThreadCore = INTERNAL.ThreadRuntimeCore;
|
||||||
|
type ThreadCoreWithAdapters = ConstructorParameters<typeof INTERNAL.DefaultThreadComposerRuntimeCore>[0];
|
||||||
|
type ComposerConnectionDisposer = () => void;
|
||||||
|
|
||||||
|
export const assistantSurfaceComposerCacheLimit = 12;
|
||||||
|
const assistantSurfaceAttachmentLimit = 5;
|
||||||
|
const composerConnectionDisposers = new WeakMap<object, ComposerConnectionDisposer>();
|
||||||
|
|
||||||
|
class AssistantSurfaceComposerRuntimeCore extends INTERNAL.DefaultThreadComposerRuntimeCore {
|
||||||
|
public override connect() {
|
||||||
|
const dispose = super.connect();
|
||||||
|
composerConnectionDisposers.set(this, dispose);
|
||||||
|
return dispose;
|
||||||
|
}
|
||||||
|
|
||||||
|
public dispose() {
|
||||||
|
composerConnectionDisposers.get(this)?.();
|
||||||
|
composerConnectionDisposers.delete(this);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
interface AssistantSurfaceRuntime extends AssistantRuntime {
|
||||||
|
dispose(): void;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface AssistantSurfaceComposerEntry {
|
||||||
|
composer: AssistantSurfaceComposerRuntimeCore;
|
||||||
|
source: ThreadCore;
|
||||||
|
}
|
||||||
|
|
||||||
|
const getThreadAdapters = (threadCore: ThreadCore) => (threadCore as ThreadCoreWithAdapters).adapters;
|
||||||
|
|
||||||
|
const bindRuntimeValue = (target: object, property: PropertyKey, cache: WeakMap<object, Map<PropertyKey, unknown>>) => {
|
||||||
|
const value = Reflect.get(target, property, target) as unknown;
|
||||||
|
if (typeof value !== "function") return value;
|
||||||
|
|
||||||
|
let targetCache = cache.get(target);
|
||||||
|
if (!targetCache) {
|
||||||
|
targetCache = new Map();
|
||||||
|
cache.set(target, targetCache);
|
||||||
|
}
|
||||||
|
const cached = targetCache.get(property);
|
||||||
|
if (cached) return cached;
|
||||||
|
const bound = value.bind(target) as unknown;
|
||||||
|
targetCache.set(property, bound);
|
||||||
|
return bound;
|
||||||
|
};
|
||||||
|
|
||||||
|
const createSurfaceAttachmentAdapter = (threadCore: ThreadCore): AttachmentAdapter => {
|
||||||
|
const pendingAttachmentIds = new Set<string>();
|
||||||
|
let pendingAdds = 0;
|
||||||
|
const getAdapter = () => {
|
||||||
|
const adapter = getThreadAdapters(threadCore)?.attachments;
|
||||||
|
if (!adapter) throw new Error("Attachments are not supported");
|
||||||
|
return adapter;
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
get accept() {
|
||||||
|
return getThreadAdapters(threadCore)?.attachments?.accept ?? "";
|
||||||
|
},
|
||||||
|
add({ file }) {
|
||||||
|
if (pendingAttachmentIds.size + pendingAdds >= assistantSurfaceAttachmentLimit) {
|
||||||
|
throw new Error(`A message can include up to ${assistantSurfaceAttachmentLimit} attachments.`);
|
||||||
|
}
|
||||||
|
|
||||||
|
pendingAdds += 1;
|
||||||
|
let result: ReturnType<AttachmentAdapter["add"]>;
|
||||||
|
try {
|
||||||
|
result = getAdapter().add({ file });
|
||||||
|
} catch (error) {
|
||||||
|
pendingAdds -= 1;
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Symbol.asyncIterator in result) {
|
||||||
|
return (async function* () {
|
||||||
|
let reservationPending = true;
|
||||||
|
try {
|
||||||
|
for await (const attachment of result) {
|
||||||
|
if (reservationPending) {
|
||||||
|
reservationPending = false;
|
||||||
|
pendingAdds -= 1;
|
||||||
|
}
|
||||||
|
pendingAttachmentIds.add(attachment.id);
|
||||||
|
yield attachment;
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
if (reservationPending) pendingAdds -= 1;
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
}
|
||||||
|
|
||||||
|
return result.then(
|
||||||
|
(attachment) => {
|
||||||
|
pendingAdds -= 1;
|
||||||
|
pendingAttachmentIds.add(attachment.id);
|
||||||
|
return attachment;
|
||||||
|
},
|
||||||
|
(error: unknown) => {
|
||||||
|
pendingAdds -= 1;
|
||||||
|
throw error;
|
||||||
|
},
|
||||||
|
);
|
||||||
|
},
|
||||||
|
async remove(attachment) {
|
||||||
|
try {
|
||||||
|
await getAdapter().remove(attachment);
|
||||||
|
} finally {
|
||||||
|
pendingAttachmentIds.delete(attachment.id);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
async send(attachment) {
|
||||||
|
try {
|
||||||
|
return await getAdapter().send(attachment);
|
||||||
|
} finally {
|
||||||
|
pendingAttachmentIds.delete(attachment.id);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
const createSurfaceComposerHost = (
|
||||||
|
threadCore: ThreadCore,
|
||||||
|
boundRuntimeValues: WeakMap<object, Map<PropertyKey, unknown>>,
|
||||||
|
) => {
|
||||||
|
const attachments = createSurfaceAttachmentAdapter(threadCore);
|
||||||
|
const adapters = {
|
||||||
|
get attachments() {
|
||||||
|
return getThreadAdapters(threadCore)?.attachments ? attachments : undefined;
|
||||||
|
},
|
||||||
|
get dictation() {
|
||||||
|
return getThreadAdapters(threadCore)?.dictation;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
return new Proxy(threadCore as ThreadCoreWithAdapters, {
|
||||||
|
get(target, property) {
|
||||||
|
if (property === "adapters") return adapters;
|
||||||
|
return bindRuntimeValue(target, property, boundRuntimeValues);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* assistant-ui intentionally stores the thread composer on the thread runtime. That is the right
|
||||||
|
* default for a single chat surface, but Homarr can render the same conversation in the floating
|
||||||
|
* panel and in one or more board widgets at the same time. A second runtime-bound Lexical input
|
||||||
|
* would otherwise mirror the first input's draft, attachments and selection.
|
||||||
|
*
|
||||||
|
* This adapter keeps the thread runtime itself shared and replaces only its composer core. The
|
||||||
|
* local composer still delegates send/cancel to the shared thread, so messages, runs, tools,
|
||||||
|
* branches and history remain one conversation. Composers are cached per conversation id because
|
||||||
|
* some assistant-ui runtimes reuse the same underlying core while switching conversations.
|
||||||
|
*/
|
||||||
|
export const createAssistantSurfaceRuntime = (runtime: AssistantRuntime): AssistantSurfaceRuntime => {
|
||||||
|
const sharedThread = runtime.thread as InstanceType<typeof INTERNAL.ThreadRuntimeImpl>;
|
||||||
|
// oxlint-disable-next-line no-underscore-dangle -- assistant-ui exposes the binding only through its internal adapter API.
|
||||||
|
const sharedBinding = sharedThread.__internal_threadBinding;
|
||||||
|
const composerByConversation = new Map<string, AssistantSurfaceComposerEntry>();
|
||||||
|
const surfaceCoreByConversation = new Map<string, { source: ThreadCore; surface: ThreadCore }>();
|
||||||
|
const activeConversationCounts = new Map<string, number>();
|
||||||
|
const boundRuntimeValues = new WeakMap<object, Map<PropertyKey, unknown>>();
|
||||||
|
|
||||||
|
const disposeComposer = (conversationId: string, entry: AssistantSurfaceComposerEntry) => {
|
||||||
|
const reset = entry.composer.reset();
|
||||||
|
entry.composer.dispose();
|
||||||
|
composerByConversation.delete(conversationId);
|
||||||
|
surfaceCoreByConversation.delete(conversationId);
|
||||||
|
void reset.catch(() => {});
|
||||||
|
};
|
||||||
|
|
||||||
|
const evictInactiveComposers = () => {
|
||||||
|
while (composerByConversation.size > assistantSurfaceComposerCacheLimit) {
|
||||||
|
let candidate: [string, AssistantSurfaceComposerEntry] | undefined;
|
||||||
|
for (const entry of composerByConversation) {
|
||||||
|
if (!activeConversationCounts.has(entry[0])) {
|
||||||
|
candidate = entry;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!candidate) return;
|
||||||
|
disposeComposer(candidate[0], candidate[1]);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const retainConversation = (conversationId: string) => {
|
||||||
|
activeConversationCounts.set(conversationId, (activeConversationCounts.get(conversationId) ?? 0) + 1);
|
||||||
|
};
|
||||||
|
|
||||||
|
const releaseConversation = (conversationId: string) => {
|
||||||
|
const count = activeConversationCounts.get(conversationId);
|
||||||
|
if (count === undefined) return;
|
||||||
|
if (count <= 1) activeConversationCounts.delete(conversationId);
|
||||||
|
else activeConversationCounts.set(conversationId, count - 1);
|
||||||
|
evictInactiveComposers();
|
||||||
|
};
|
||||||
|
|
||||||
|
const getComposer = (conversationId: string, threadCore: ThreadCore) => {
|
||||||
|
const existing = composerByConversation.get(conversationId);
|
||||||
|
if (existing?.source === threadCore) {
|
||||||
|
composerByConversation.delete(conversationId);
|
||||||
|
composerByConversation.set(conversationId, existing);
|
||||||
|
return existing.composer;
|
||||||
|
}
|
||||||
|
const draft = existing
|
||||||
|
? {
|
||||||
|
attachments: existing.composer.attachments,
|
||||||
|
quote: existing.composer.quote,
|
||||||
|
role: existing.composer.role,
|
||||||
|
runConfig: existing.composer.runConfig,
|
||||||
|
text: existing.composer.text,
|
||||||
|
}
|
||||||
|
: undefined;
|
||||||
|
if (existing) disposeComposer(conversationId, existing);
|
||||||
|
|
||||||
|
const host = createSurfaceComposerHost(threadCore, boundRuntimeValues);
|
||||||
|
const composer = new AssistantSurfaceComposerRuntimeCore(host);
|
||||||
|
composerByConversation.set(conversationId, { composer, source: threadCore });
|
||||||
|
if (draft) {
|
||||||
|
composer.setText(draft.text);
|
||||||
|
composer.setRole(draft.role);
|
||||||
|
composer.setRunConfig(draft.runConfig);
|
||||||
|
composer.setQuote(draft.quote);
|
||||||
|
for (const attachment of draft.attachments) {
|
||||||
|
if (attachment.status.type === "complete" && attachment.content) {
|
||||||
|
void composer
|
||||||
|
.addAttachment({
|
||||||
|
id: attachment.id,
|
||||||
|
type: attachment.type,
|
||||||
|
name: attachment.name,
|
||||||
|
contentType: attachment.contentType,
|
||||||
|
content: attachment.content,
|
||||||
|
})
|
||||||
|
.catch(() => {});
|
||||||
|
} else if (attachment.file) {
|
||||||
|
void composer.addAttachment(attachment.file).catch(() => {});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
evictInactiveComposers();
|
||||||
|
return composer;
|
||||||
|
};
|
||||||
|
|
||||||
|
const getSurfaceCore = (conversationId: string, threadCore: ThreadCore) => {
|
||||||
|
const existing = surfaceCoreByConversation.get(conversationId);
|
||||||
|
if (existing?.source === threadCore) return existing.surface;
|
||||||
|
|
||||||
|
const composer = getComposer(conversationId, threadCore);
|
||||||
|
const surfaceCore = new Proxy(threadCore, {
|
||||||
|
get(target, property) {
|
||||||
|
if (property === "composer") return composer;
|
||||||
|
return bindRuntimeValue(target, property, boundRuntimeValues);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
surfaceCoreByConversation.set(conversationId, { source: threadCore, surface: surfaceCore });
|
||||||
|
return surfaceCore;
|
||||||
|
};
|
||||||
|
|
||||||
|
const getConversationId = () => runtime.threads.mainItem.getState().id;
|
||||||
|
|
||||||
|
const surfaceBinding: INTERNAL.ThreadRuntimeCoreBinding = {
|
||||||
|
path: sharedBinding.path,
|
||||||
|
getState: () => getSurfaceCore(getConversationId(), sharedBinding.getState()),
|
||||||
|
outerSubscribe: (callback) => sharedBinding.outerSubscribe(callback),
|
||||||
|
subscribe(callback) {
|
||||||
|
let activeCore = sharedBinding.getState();
|
||||||
|
let activeConversationId = getConversationId();
|
||||||
|
retainConversation(activeConversationId);
|
||||||
|
let unsubscribeComposer = getComposer(activeConversationId, activeCore).subscribe(callback);
|
||||||
|
const handleSharedUpdate = () => {
|
||||||
|
const nextCore = sharedBinding.getState();
|
||||||
|
const nextConversationId = getConversationId();
|
||||||
|
if (nextCore !== activeCore || nextConversationId !== activeConversationId) {
|
||||||
|
unsubscribeComposer();
|
||||||
|
releaseConversation(activeConversationId);
|
||||||
|
activeCore = nextCore;
|
||||||
|
activeConversationId = nextConversationId;
|
||||||
|
retainConversation(activeConversationId);
|
||||||
|
unsubscribeComposer = getComposer(activeConversationId, activeCore).subscribe(callback);
|
||||||
|
}
|
||||||
|
callback();
|
||||||
|
};
|
||||||
|
const unsubscribeThread = sharedBinding.subscribe(handleSharedUpdate);
|
||||||
|
const unsubscribeThreadItem = runtime.threads.mainItem.subscribe(handleSharedUpdate);
|
||||||
|
return () => {
|
||||||
|
unsubscribeComposer();
|
||||||
|
releaseConversation(activeConversationId);
|
||||||
|
unsubscribeThread();
|
||||||
|
unsubscribeThreadItem();
|
||||||
|
};
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const sharedMainItem = runtime.threads.mainItem;
|
||||||
|
const mainItemBinding: INTERNAL.ThreadListItemRuntimeBinding = {
|
||||||
|
path: sharedMainItem.path,
|
||||||
|
getState: () => sharedMainItem.getState(),
|
||||||
|
subscribe: (callback) => sharedMainItem.subscribe(callback),
|
||||||
|
};
|
||||||
|
const surfaceThread = new INTERNAL.ThreadRuntimeImpl(surfaceBinding, mainItemBinding);
|
||||||
|
const sharedThreads = runtime.threads;
|
||||||
|
const getSurfaceThreadById = (threadId: string) => {
|
||||||
|
const requestedItem = sharedThreads.getItemById(threadId).getState();
|
||||||
|
if (requestedItem.id === sharedMainItem.getState().id) return surfaceThread;
|
||||||
|
// Homarr renders only the selected conversation. Preserve the upstream behavior for inactive
|
||||||
|
// thread inspection without manufacturing another composer outside this surface's LRU cache.
|
||||||
|
return sharedThreads.getById(threadId);
|
||||||
|
};
|
||||||
|
const surfaceThreads: ThreadListRuntime = {
|
||||||
|
main: surfaceThread,
|
||||||
|
mainItem: sharedMainItem,
|
||||||
|
getState: () => sharedThreads.getState(),
|
||||||
|
subscribe: (callback) => sharedThreads.subscribe(callback),
|
||||||
|
getById: getSurfaceThreadById,
|
||||||
|
getItemById: (threadId) => sharedThreads.getItemById(threadId),
|
||||||
|
getItemByIndex: (index) => sharedThreads.getItemByIndex(index),
|
||||||
|
getArchivedItemByIndex: (index) => sharedThreads.getArchivedItemByIndex(index),
|
||||||
|
switchToThread: (threadId, options) => sharedThreads.switchToThread(threadId, options),
|
||||||
|
switchToNewThread: () => sharedThreads.switchToNewThread(),
|
||||||
|
getLoadThreadsPromise: () => sharedThreads.getLoadThreadsPromise(),
|
||||||
|
reload: () => sharedThreads.reload(),
|
||||||
|
loadMore: () => sharedThreads.loadMore(),
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
threads: surfaceThreads,
|
||||||
|
thread: surfaceThread,
|
||||||
|
// The root runtime already owns the inherited model-context client. Re-registering that same
|
||||||
|
// provider for every surface would make one unmount remove it from the shared runtime's Set.
|
||||||
|
registerModelContextProvider: () => () => {},
|
||||||
|
dispose() {
|
||||||
|
activeConversationCounts.clear();
|
||||||
|
for (const [conversationId, entry] of composerByConversation) disposeComposer(conversationId, entry);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
interface AssistantComposerSurfaceValue {
|
||||||
|
id: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const AssistantComposerSurfaceContext = createContext<AssistantComposerSurfaceValue | null>(null);
|
||||||
|
|
||||||
|
export const useAssistantComposerSurface = () => {
|
||||||
|
const value = useContext(AssistantComposerSurfaceContext);
|
||||||
|
if (!value) throw new Error("useAssistantComposerSurface must be used within AssistantComposerSurfaceProvider");
|
||||||
|
return value;
|
||||||
|
};
|
||||||
|
|
||||||
|
const surfaceElements = new Map<string, HTMLElement>();
|
||||||
|
|
||||||
|
const getSurfaceIdForElement = (element: Element | null) => {
|
||||||
|
if (!element) return null;
|
||||||
|
for (const [surfaceId, surfaceElement] of surfaceElements) {
|
||||||
|
if (surfaceElement.contains(element)) return surfaceId;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const getClipboardAttachmentName = (file: File, index: number) => {
|
||||||
|
if (file.name.trim().length > 0) return file.name;
|
||||||
|
const extension = file.type.split("/")[1]?.replace("jpeg", "jpg") ?? "bin";
|
||||||
|
return `pasted-file-${index + 1}.${extension}`;
|
||||||
|
};
|
||||||
|
|
||||||
|
const AssistantComposerSurfaceEvents = () => {
|
||||||
|
const t = useScopedI18n("common.assistant");
|
||||||
|
useAuiEvent("composer.attachmentAddError", ({ message }) => {
|
||||||
|
showErrorNotification({ title: t("attachments.errorTitle"), message });
|
||||||
|
});
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const AssistantComposerSurfaceBoundary = ({ children, surfaceId }: PropsWithChildren<{ surfaceId: string }>) => {
|
||||||
|
const t = useScopedI18n("common.assistant");
|
||||||
|
const aui = useAui();
|
||||||
|
const elementRef = useRef<HTMLDivElement>(null);
|
||||||
|
const contextValue = useMemo(() => ({ id: surfaceId }), [surfaceId]);
|
||||||
|
|
||||||
|
useLayoutEffect(() => {
|
||||||
|
const element = elementRef.current;
|
||||||
|
if (!element) return undefined;
|
||||||
|
surfaceElements.set(surfaceId, element);
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
if (surfaceElements.get(surfaceId) === element) surfaceElements.delete(surfaceId);
|
||||||
|
};
|
||||||
|
}, [surfaceId]);
|
||||||
|
|
||||||
|
const handlePasteCapture = (event: ClipboardEvent<HTMLDivElement>) => {
|
||||||
|
const target = event.target;
|
||||||
|
if (!(target instanceof HTMLElement) || !target.closest("[data-assistant-composer-input]")) return;
|
||||||
|
const files = Array.from(event.clipboardData.files);
|
||||||
|
if (files.length === 0) return;
|
||||||
|
|
||||||
|
event.preventDefault();
|
||||||
|
const composer = aui.composer();
|
||||||
|
const acceptedTypes = new Set(
|
||||||
|
composer
|
||||||
|
.getState()
|
||||||
|
.attachmentAccept.split(",")
|
||||||
|
.map((type) => type.trim())
|
||||||
|
.filter(Boolean),
|
||||||
|
);
|
||||||
|
|
||||||
|
files.forEach((file, index) => {
|
||||||
|
if (
|
||||||
|
file.type.startsWith("image/") &&
|
||||||
|
!acceptedTypes.has("*") &&
|
||||||
|
!acceptedTypes.has(file.type) &&
|
||||||
|
!acceptedTypes.has("image/*")
|
||||||
|
) {
|
||||||
|
showErrorNotification({
|
||||||
|
title: t("attachments.errorTitle"),
|
||||||
|
message: t("attachments.imageUnsupported"),
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const attachment =
|
||||||
|
file.name.trim().length > 0
|
||||||
|
? file
|
||||||
|
: new File([file], getClipboardAttachmentName(file, index), {
|
||||||
|
type: file.type,
|
||||||
|
lastModified: file.lastModified,
|
||||||
|
});
|
||||||
|
void composer.addAttachment(attachment).catch(() => {
|
||||||
|
// The scoped composer event above presents the adapter's actionable error message.
|
||||||
|
});
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<AssistantComposerSurfaceContext.Provider value={contextValue}>
|
||||||
|
<div ref={elementRef} style={{ display: "contents" }} onPasteCapture={handlePasteCapture}>
|
||||||
|
<AssistantComposerSurfaceEvents />
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
</AssistantComposerSurfaceContext.Provider>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The current react-lexical FocusPlugin focuses every mounted composer when a run starts. Mount
|
||||||
|
* this once above all surfaces so programmatic focus returns to the element/surface the user was
|
||||||
|
* actually interacting with after those listeners have run.
|
||||||
|
*/
|
||||||
|
export const AssistantRunFocusPreserver = () => {
|
||||||
|
useAuiEvent("thread.runStart", () => {
|
||||||
|
const focusedBeforeRun = document.activeElement instanceof HTMLElement ? document.activeElement : null;
|
||||||
|
const surfaceIdBeforeRun = getSurfaceIdForElement(focusedBeforeRun);
|
||||||
|
|
||||||
|
const restoreFocus = () => {
|
||||||
|
const surfaceIdAfterRun = getSurfaceIdForElement(document.activeElement);
|
||||||
|
if (!surfaceIdAfterRun || surfaceIdAfterRun === surfaceIdBeforeRun) return;
|
||||||
|
|
||||||
|
if (focusedBeforeRun?.isConnected) focusedBeforeRun.focus({ preventScroll: true });
|
||||||
|
if (
|
||||||
|
getSurfaceIdForElement(document.activeElement) !== surfaceIdBeforeRun &&
|
||||||
|
document.activeElement instanceof HTMLElement
|
||||||
|
) {
|
||||||
|
document.activeElement.blur();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
queueMicrotask(() => queueMicrotask(restoreFocus));
|
||||||
|
requestAnimationFrame(restoreFocus);
|
||||||
|
});
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
|
||||||
|
interface AssistantComposerSurfaceProviderProps extends PropsWithChildren {
|
||||||
|
surfaceId: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gives one rendered assistant surface a local composer while preserving the shared conversation.
|
||||||
|
* Every component below this boundary can keep using the normal assistant-ui primitives and hooks.
|
||||||
|
*/
|
||||||
|
export const AssistantComposerSurfaceProvider = ({ children, surfaceId }: AssistantComposerSurfaceProviderProps) => {
|
||||||
|
const parentAui = useAui();
|
||||||
|
const instanceId = useId();
|
||||||
|
const resolvedSurfaceId = `${surfaceId}:${instanceId}`;
|
||||||
|
// oxlint-disable-next-line no-underscore-dangle -- required to derive a scoped runtime without cloning the shared thread.
|
||||||
|
const sharedRuntime = parentAui.threads().__internal_getAssistantRuntime?.();
|
||||||
|
const surfaceRuntime = useMemo(() => {
|
||||||
|
if (!sharedRuntime) throw new Error("Assistant runtime is not available for this composer surface");
|
||||||
|
return createAssistantSurfaceRuntime(sharedRuntime);
|
||||||
|
}, [sharedRuntime]);
|
||||||
|
useEffect(() => () => surfaceRuntime.dispose(), [surfaceRuntime]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<AssistantRuntimeProvider aui={parentAui} runtime={surfaceRuntime}>
|
||||||
|
<AssistantComposerSurfaceBoundary surfaceId={resolvedSurfaceId}>{children}</AssistantComposerSurfaceBoundary>
|
||||||
|
</AssistantRuntimeProvider>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
import { describe, expect, test } from "vitest";
|
||||||
|
|
||||||
|
import { getSafeAssistantHttpUrl } from "./assistant-url";
|
||||||
|
|
||||||
|
describe("getSafeAssistantHttpUrl", () => {
|
||||||
|
test("allows ordinary HTTP and HTTPS source URLs", () => {
|
||||||
|
expect(getSafeAssistantHttpUrl("https://example.com/source?q=homarr")).toBe("https://example.com/source?q=homarr");
|
||||||
|
expect(getSafeAssistantHttpUrl("http://example.com/source")).toBe("http://example.com/source");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("rejects unsafe protocols, relative URLs, and embedded credentials", () => {
|
||||||
|
expect(getSafeAssistantHttpUrl("javascript:alert(1)")).toBeNull();
|
||||||
|
expect(getSafeAssistantHttpUrl("data:text/html;base64,PGgxPkJhZDwvaDE+")).toBeNull();
|
||||||
|
expect(getSafeAssistantHttpUrl("/manage/custom-widgets")).toBeNull();
|
||||||
|
expect(getSafeAssistantHttpUrl("https://user:secret@example.com/source")).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
export const getSafeAssistantHttpUrl = (source: unknown) => {
|
||||||
|
if (typeof source !== "string" || !source) return null;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const url = new URL(source);
|
||||||
|
if ((url.protocol !== "http:" && url.protocol !== "https:") || url.username || url.password) return null;
|
||||||
|
return url.toString();
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -13,6 +13,7 @@ import classes from "./assistant-panel.module.css";
|
|||||||
import { AssistantConversationSurface } from "./assistant-panel";
|
import { AssistantConversationSurface } from "./assistant-panel";
|
||||||
import { getPendingAssistantAction } from "./assistant-pending-action";
|
import { getPendingAssistantAction } from "./assistant-pending-action";
|
||||||
import { useAssistantPreferences, useHomarrAssistant } from "./assistant-context";
|
import { useAssistantPreferences, useHomarrAssistant } from "./assistant-context";
|
||||||
|
import { AssistantComposerSurfaceProvider } from "./assistant-runtime-provider";
|
||||||
|
|
||||||
export const AssistantBoardWidget = (props: WidgetComponentProps<"assistant">) => {
|
export const AssistantBoardWidget = (props: WidgetComponentProps<"assistant">) => {
|
||||||
const assistant = useHomarrAssistant();
|
const assistant = useHomarrAssistant();
|
||||||
@@ -21,7 +22,11 @@ export const AssistantBoardWidget = (props: WidgetComponentProps<"assistant">) =
|
|||||||
return <UnavailableAssistantWidget description={assistant.unavailableDescription} />;
|
return <UnavailableAssistantWidget description={assistant.unavailableDescription} />;
|
||||||
}
|
}
|
||||||
|
|
||||||
return <EnabledAssistantBoardWidget {...props} />;
|
return (
|
||||||
|
<AssistantComposerSurfaceProvider surfaceId={`board-widget-${props.itemId ?? "preview"}`}>
|
||||||
|
<EnabledAssistantBoardWidget {...props} />
|
||||||
|
</AssistantComposerSurfaceProvider>
|
||||||
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
const EnabledAssistantBoardWidget = ({ options, width, height, isEditMode }: WidgetComponentProps<"assistant">) => {
|
const EnabledAssistantBoardWidget = ({ options, width, height, isEditMode }: WidgetComponentProps<"assistant">) => {
|
||||||
|
|||||||
@@ -16,9 +16,15 @@
|
|||||||
box-shadow: var(--mantine-shadow-md);
|
box-shadow: var(--mantine-shadow-md);
|
||||||
overscroll-behavior: contain;
|
overscroll-behavior: contain;
|
||||||
animation: focus-surface-in 180ms cubic-bezier(0.16, 1, 0.3, 1);
|
animation: focus-surface-in 180ms cubic-bezier(0.16, 1, 0.3, 1);
|
||||||
|
animation-fill-mode: backwards;
|
||||||
|
animation-play-state: paused;
|
||||||
transform-origin: top left;
|
transform-origin: top left;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.surfaceReady {
|
||||||
|
animation-play-state: running;
|
||||||
|
}
|
||||||
|
|
||||||
.manualSurface {
|
.manualSurface {
|
||||||
position: fixed;
|
position: fixed;
|
||||||
max-width: none;
|
max-width: none;
|
||||||
@@ -82,6 +88,58 @@
|
|||||||
pointer-events: auto;
|
pointer-events: auto;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.holdIndicator {
|
||||||
|
position: fixed;
|
||||||
|
top: 0;
|
||||||
|
left: 0;
|
||||||
|
z-index: var(--mantine-z-index-modal);
|
||||||
|
display: grid;
|
||||||
|
width: 36px;
|
||||||
|
height: 36px;
|
||||||
|
color: var(--mantine-color-text);
|
||||||
|
pointer-events: none;
|
||||||
|
transform: translate3d(var(--advanced-focus-pointer-x), var(--advanced-focus-pointer-y), 0) translate(-50%, -50%);
|
||||||
|
place-items: center;
|
||||||
|
will-change: transform;
|
||||||
|
}
|
||||||
|
|
||||||
|
.holdIndicatorRing {
|
||||||
|
position: absolute;
|
||||||
|
inset: 0;
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
overflow: visible;
|
||||||
|
filter: drop-shadow(0 1px 3px rgb(0 0 0 / 35%));
|
||||||
|
transform: rotate(-90deg);
|
||||||
|
}
|
||||||
|
|
||||||
|
.holdIndicatorTrack,
|
||||||
|
.holdIndicatorProgress {
|
||||||
|
stroke-width: 3;
|
||||||
|
}
|
||||||
|
|
||||||
|
.holdIndicatorTrack {
|
||||||
|
fill: color-mix(in srgb, var(--mantine-color-body) 82%, transparent);
|
||||||
|
stroke: color-mix(in srgb, var(--mantine-color-dimmed) 45%, transparent);
|
||||||
|
}
|
||||||
|
|
||||||
|
.holdIndicatorProgress {
|
||||||
|
fill: none;
|
||||||
|
stroke: var(--mantine-primary-color-filled);
|
||||||
|
stroke-linecap: round;
|
||||||
|
stroke-dasharray: 1;
|
||||||
|
stroke-dashoffset: 1;
|
||||||
|
animation: advanced-focus-hold-progress 500ms linear forwards;
|
||||||
|
}
|
||||||
|
|
||||||
|
.holdIndicatorLabel {
|
||||||
|
position: relative;
|
||||||
|
font-size: 15px;
|
||||||
|
font-weight: 700;
|
||||||
|
line-height: 1;
|
||||||
|
text-shadow: 0 1px 2px rgb(0 0 0 / 25%);
|
||||||
|
}
|
||||||
|
|
||||||
@keyframes focus-backdrop-in {
|
@keyframes focus-backdrop-in {
|
||||||
from {
|
from {
|
||||||
opacity: 0;
|
opacity: 0;
|
||||||
@@ -110,12 +168,23 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@keyframes advanced-focus-hold-progress {
|
||||||
|
to {
|
||||||
|
stroke-dashoffset: 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@media (prefers-reduced-motion: reduce) {
|
@media (prefers-reduced-motion: reduce) {
|
||||||
.backdrop,
|
.backdrop,
|
||||||
.surface,
|
.surface,
|
||||||
.manualSurface {
|
.manualSurface {
|
||||||
animation: none;
|
animation: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.holdIndicatorProgress {
|
||||||
|
stroke-dashoffset: 0;
|
||||||
|
animation: none;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@media (forced-colors: active) {
|
@media (forced-colors: active) {
|
||||||
@@ -123,4 +192,21 @@
|
|||||||
background: Canvas;
|
background: Canvas;
|
||||||
opacity: 0.4;
|
opacity: 0.4;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.holdIndicatorTrack {
|
||||||
|
fill: Canvas;
|
||||||
|
}
|
||||||
|
|
||||||
|
.holdIndicatorTrack {
|
||||||
|
stroke: GrayText;
|
||||||
|
}
|
||||||
|
|
||||||
|
.holdIndicatorProgress {
|
||||||
|
stroke: Highlight;
|
||||||
|
}
|
||||||
|
|
||||||
|
.holdIndicatorLabel {
|
||||||
|
color: CanvasText;
|
||||||
|
text-shadow: none;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,195 @@
|
|||||||
|
// @vitest-environment jsdom
|
||||||
|
|
||||||
|
import { act, createElement } from "react";
|
||||||
|
import { createRoot } from "react-dom/client";
|
||||||
|
import { MantineProvider } from "@mantine/core";
|
||||||
|
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
|
||||||
|
|
||||||
|
import { EditModeProvider } from "@homarr/boards/edit-mode";
|
||||||
|
|
||||||
|
import { BoardAdvancedFocusProvider, useAdvancedFocus } from "./context";
|
||||||
|
|
||||||
|
const sourceRect = {
|
||||||
|
left: 20,
|
||||||
|
top: 30,
|
||||||
|
right: 220,
|
||||||
|
bottom: 150,
|
||||||
|
width: 200,
|
||||||
|
height: 120,
|
||||||
|
x: 20,
|
||||||
|
y: 30,
|
||||||
|
toJSON: () => undefined,
|
||||||
|
};
|
||||||
|
|
||||||
|
describe("BoardAdvancedFocusProvider preview interaction", () => {
|
||||||
|
let host: HTMLDivElement;
|
||||||
|
let root: ReturnType<typeof createRoot>;
|
||||||
|
let focus: ReturnType<typeof useAdvancedFocus>;
|
||||||
|
|
||||||
|
const Harness = () => {
|
||||||
|
focus = useAdvancedFocus();
|
||||||
|
return createElement(
|
||||||
|
"div",
|
||||||
|
null,
|
||||||
|
createElement("div", { "data-testid": "source" }),
|
||||||
|
createElement("div", { "data-advanced-focus-surface": true, "data-testid": "surface" }),
|
||||||
|
createElement(
|
||||||
|
"div",
|
||||||
|
{ "data-portal": true },
|
||||||
|
createElement("button", { role: "menuitem", "data-testid": "portalled-menu-item" }),
|
||||||
|
),
|
||||||
|
createElement("div", { "data-testid": "outside" }),
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
vi.useFakeTimers();
|
||||||
|
vi.stubGlobal(
|
||||||
|
"matchMedia",
|
||||||
|
vi.fn().mockImplementation((query: string) => ({
|
||||||
|
matches: false,
|
||||||
|
media: query,
|
||||||
|
onchange: null,
|
||||||
|
addEventListener: vi.fn(),
|
||||||
|
removeEventListener: vi.fn(),
|
||||||
|
addListener: vi.fn(),
|
||||||
|
removeListener: vi.fn(),
|
||||||
|
dispatchEvent: vi.fn(),
|
||||||
|
})),
|
||||||
|
);
|
||||||
|
Object.defineProperty(document, "elementsFromPoint", {
|
||||||
|
configurable: true,
|
||||||
|
value: vi.fn(() => []),
|
||||||
|
});
|
||||||
|
host = document.createElement("div");
|
||||||
|
document.body.append(host);
|
||||||
|
root = createRoot(host);
|
||||||
|
|
||||||
|
await act(async () =>
|
||||||
|
root.render(
|
||||||
|
createElement(
|
||||||
|
MantineProvider,
|
||||||
|
null,
|
||||||
|
createElement(
|
||||||
|
EditModeProvider,
|
||||||
|
null,
|
||||||
|
createElement(BoardAdvancedFocusProvider, null, createElement(Harness)),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
const source = host.querySelector<HTMLElement>("[data-testid='source']");
|
||||||
|
if (!source) throw new Error("Expected source fixture");
|
||||||
|
vi.spyOn(source, "getBoundingClientRect").mockReturnValue(sourceRect);
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(async () => {
|
||||||
|
await act(async () => root.unmount());
|
||||||
|
host.remove();
|
||||||
|
document.querySelectorAll("[data-portal]").forEach((portal) => portal.remove());
|
||||||
|
vi.useRealTimers();
|
||||||
|
vi.unstubAllGlobals();
|
||||||
|
});
|
||||||
|
|
||||||
|
const startPreview = async () => {
|
||||||
|
const source = host.querySelector<HTMLElement>("[data-testid='source']");
|
||||||
|
if (!source) throw new Error("Expected source fixture");
|
||||||
|
await act(async () => {
|
||||||
|
window.dispatchEvent(new MouseEvent("pointermove", { clientX: 48, clientY: 52 }));
|
||||||
|
focus.hover("widget-1", source);
|
||||||
|
window.dispatchEvent(new KeyboardEvent("keydown", { key: "Shift" }));
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
test("shows pointer-following hold feedback for the full 500 ms delay", async () => {
|
||||||
|
await startPreview();
|
||||||
|
|
||||||
|
const indicator = document.querySelector<HTMLElement>("[data-advanced-focus-hold-indicator]");
|
||||||
|
expect(indicator?.style.getPropertyValue("--advanced-focus-pointer-x")).toBe("48px");
|
||||||
|
expect(indicator?.style.getPropertyValue("--advanced-focus-pointer-y")).toBe("52px");
|
||||||
|
expect(focus.active).toBeNull();
|
||||||
|
|
||||||
|
await act(async () => vi.advanceTimersByTime(499));
|
||||||
|
expect(focus.active).toBeNull();
|
||||||
|
expect(document.querySelector("[data-advanced-focus-hold-indicator]")).not.toBeNull();
|
||||||
|
|
||||||
|
await act(async () => vi.advanceTimersByTime(1));
|
||||||
|
expect(focus.active?.itemId).toBe("widget-1");
|
||||||
|
expect(focus.active?.activation).toBe("preview");
|
||||||
|
expect(document.querySelector("[data-advanced-focus-hold-indicator]")).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("does not show hold feedback when Shift is pressed without a hovered source", async () => {
|
||||||
|
await act(async () => window.dispatchEvent(new KeyboardEvent("keydown", { key: "Shift" })));
|
||||||
|
expect(document.querySelector("[data-advanced-focus-hold-indicator]")).toBeNull();
|
||||||
|
|
||||||
|
await act(async () => vi.advanceTimersByTime(500));
|
||||||
|
expect(focus.active).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("cancels the hold feedback and activation when Shift is released early", async () => {
|
||||||
|
await startPreview();
|
||||||
|
|
||||||
|
await act(async () => vi.advanceTimersByTime(250));
|
||||||
|
await act(async () => window.dispatchEvent(new KeyboardEvent("keyup", { key: "Shift" })));
|
||||||
|
expect(document.querySelector("[data-advanced-focus-hold-indicator]")).toBeNull();
|
||||||
|
|
||||||
|
await act(async () => vi.advanceTimersByTime(250));
|
||||||
|
expect(focus.active).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("cancels the hold feedback and activation when the source is left early", async () => {
|
||||||
|
await startPreview();
|
||||||
|
|
||||||
|
await act(async () => vi.advanceTimersByTime(250));
|
||||||
|
await act(async () => focus.leave("widget-1"));
|
||||||
|
expect(document.querySelector("[data-advanced-focus-hold-indicator]")).toBeNull();
|
||||||
|
|
||||||
|
await act(async () => vi.advanceTimersByTime(250));
|
||||||
|
expect(focus.active).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("keeps the preview open across the source-to-portal gap and closes after leaving both", async () => {
|
||||||
|
await startPreview();
|
||||||
|
await act(async () => vi.advanceTimersByTime(500));
|
||||||
|
|
||||||
|
await act(async () => focus.leave("widget-1"));
|
||||||
|
await act(async () => vi.advanceTimersByTime(40));
|
||||||
|
const surface = host.querySelector<HTMLElement>("[data-testid='surface']");
|
||||||
|
if (!surface) throw new Error("Expected surface fixture");
|
||||||
|
await act(async () =>
|
||||||
|
surface.dispatchEvent(new MouseEvent("pointerover", { bubbles: true, clientX: 300, clientY: 200 })),
|
||||||
|
);
|
||||||
|
await act(async () => vi.advanceTimersByTime(80));
|
||||||
|
expect(focus.active?.phase).toBe("visible");
|
||||||
|
|
||||||
|
const outside = host.querySelector<HTMLElement>("[data-testid='outside']");
|
||||||
|
if (!outside) throw new Error("Expected outside fixture");
|
||||||
|
await act(async () =>
|
||||||
|
outside.dispatchEvent(new MouseEvent("pointermove", { bubbles: true, clientX: 500, clientY: 500 })),
|
||||||
|
);
|
||||||
|
await act(async () => vi.advanceTimersByTime(79));
|
||||||
|
expect(focus.active?.phase).toBe("visible");
|
||||||
|
await act(async () => vi.advanceTimersByTime(1));
|
||||||
|
expect(focus.active?.phase).toBe("closing");
|
||||||
|
await act(async () => vi.advanceTimersByTime(180));
|
||||||
|
expect(focus.active).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("keeps the preview open while a widget-owned portalled popup is hovered", async () => {
|
||||||
|
await startPreview();
|
||||||
|
await act(async () => vi.advanceTimersByTime(500));
|
||||||
|
|
||||||
|
await act(async () => focus.leave("widget-1"));
|
||||||
|
await act(async () => vi.advanceTimersByTime(40));
|
||||||
|
const menuItem = host.querySelector<HTMLElement>("[data-testid='portalled-menu-item']");
|
||||||
|
if (!menuItem) throw new Error("Expected portalled menu fixture");
|
||||||
|
await act(async () =>
|
||||||
|
menuItem.dispatchEvent(new MouseEvent("pointerover", { bubbles: true, clientX: 320, clientY: 210 })),
|
||||||
|
);
|
||||||
|
await act(async () => vi.advanceTimersByTime(80));
|
||||||
|
|
||||||
|
expect(focus.active?.phase).toBe("visible");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import type { PropsWithChildren } from "react";
|
import type { CSSProperties, PropsWithChildren } from "react";
|
||||||
import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
|
import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
|
||||||
import { Overlay, Portal } from "@mantine/core";
|
import { Overlay, Portal } from "@mantine/core";
|
||||||
import { useIsomorphicEffect } from "@mantine/hooks";
|
import { useIsomorphicEffect } from "@mantine/hooks";
|
||||||
@@ -36,10 +36,9 @@ interface AdvancedFocusContextValue {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const AdvancedFocusContext = createContext<AdvancedFocusContextValue | null>(null);
|
const AdvancedFocusContext = createContext<AdvancedFocusContextValue | null>(null);
|
||||||
const HOVER_DELAY_MS = 150;
|
const HOVER_DELAY_MS = 500;
|
||||||
|
const POINTER_TRANSITION_GRACE_MS = 80;
|
||||||
const CLOSE_DURATION_MS = 180;
|
const CLOSE_DURATION_MS = 180;
|
||||||
const interactiveSelector =
|
|
||||||
"a[href], button, input, textarea, select, [contenteditable='true'], [role='button'], [role='link'], [role='menuitem'], [role='option']";
|
|
||||||
|
|
||||||
const isEditableTarget = (target: EventTarget | null) =>
|
const isEditableTarget = (target: EventTarget | null) =>
|
||||||
target instanceof HTMLElement &&
|
target instanceof HTMLElement &&
|
||||||
@@ -48,16 +47,28 @@ const isEditableTarget = (target: EventTarget | null) =>
|
|||||||
export const BoardAdvancedFocusProvider = ({ children }: PropsWithChildren) => {
|
export const BoardAdvancedFocusProvider = ({ children }: PropsWithChildren) => {
|
||||||
const [isEditMode] = useEditMode();
|
const [isEditMode] = useEditMode();
|
||||||
const [active, setActive] = useState<ActiveFocus | null>(null);
|
const [active, setActive] = useState<ActiveFocus | null>(null);
|
||||||
|
const [isHoldPending, setIsHoldPending] = useState(false);
|
||||||
const activeRef = useRef<ActiveFocus | null>(null);
|
const activeRef = useRef<ActiveFocus | null>(null);
|
||||||
const hoveredRef = useRef<{ itemId: string; source: HTMLElement } | null>(null);
|
const hoveredRef = useRef<{ itemId: string; source: HTMLElement } | null>(null);
|
||||||
const shiftHeldRef = useRef(false);
|
const shiftHeldRef = useRef(false);
|
||||||
const hoverTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
const hoverTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||||
|
const previewLeaveTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||||
const closeTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
const closeTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||||
|
const holdIndicatorRef = useRef<HTMLDivElement | null>(null);
|
||||||
|
const pointerPositionRef = useRef({ x: -100, y: -100 });
|
||||||
|
const pointerFrameRef = useRef<number | null>(null);
|
||||||
|
|
||||||
const cancelHoverTimer = useCallback(() => {
|
const cancelHoverTimer = useCallback(() => {
|
||||||
if (hoverTimerRef.current === null) return;
|
if (hoverTimerRef.current === null) return;
|
||||||
clearTimeout(hoverTimerRef.current);
|
clearTimeout(hoverTimerRef.current);
|
||||||
hoverTimerRef.current = null;
|
hoverTimerRef.current = null;
|
||||||
|
setIsHoldPending(false);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const cancelPreviewLeaveTimer = useCallback(() => {
|
||||||
|
if (previewLeaveTimerRef.current === null) return;
|
||||||
|
clearTimeout(previewLeaveTimerRef.current);
|
||||||
|
previewLeaveTimerRef.current = null;
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const updateActive = useCallback((next: ActiveFocus | null) => {
|
const updateActive = useCallback((next: ActiveFocus | null) => {
|
||||||
@@ -75,6 +86,7 @@ export const BoardAdvancedFocusProvider = ({ children }: PropsWithChildren) => {
|
|||||||
(itemId: string, source: HTMLElement, options: OpenAdvancedFocusOptions = {}) => {
|
(itemId: string, source: HTMLElement, options: OpenAdvancedFocusOptions = {}) => {
|
||||||
if (isEditMode) return;
|
if (isEditMode) return;
|
||||||
cancelHoverTimer();
|
cancelHoverTimer();
|
||||||
|
cancelPreviewLeaveTimer();
|
||||||
cancelCloseTimer();
|
cancelCloseTimer();
|
||||||
const rect = source.getBoundingClientRect();
|
const rect = source.getBoundingClientRect();
|
||||||
updateActive({
|
updateActive({
|
||||||
@@ -87,12 +99,13 @@ export const BoardAdvancedFocusProvider = ({ children }: PropsWithChildren) => {
|
|||||||
phase: "visible",
|
phase: "visible",
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
[cancelCloseTimer, cancelHoverTimer, isEditMode, updateActive],
|
[cancelCloseTimer, cancelHoverTimer, cancelPreviewLeaveTimer, isEditMode, updateActive],
|
||||||
);
|
);
|
||||||
|
|
||||||
const close = useCallback(
|
const close = useCallback(
|
||||||
(restoreFocus = true) => {
|
(restoreFocus = true) => {
|
||||||
cancelHoverTimer();
|
cancelHoverTimer();
|
||||||
|
cancelPreviewLeaveTimer();
|
||||||
const current = activeRef.current;
|
const current = activeRef.current;
|
||||||
if (!current || current.phase === "closing") return;
|
if (!current || current.phase === "closing") return;
|
||||||
updateActive({ ...current, phase: "closing" });
|
updateActive({ ...current, phase: "closing" });
|
||||||
@@ -103,22 +116,43 @@ export const BoardAdvancedFocusProvider = ({ children }: PropsWithChildren) => {
|
|||||||
if (restoreFocus && current.source.isConnected) requestAnimationFrame(() => current.source.focus());
|
if (restoreFocus && current.source.isConnected) requestAnimationFrame(() => current.source.focus());
|
||||||
}, closeDuration);
|
}, closeDuration);
|
||||||
},
|
},
|
||||||
[cancelHoverTimer, updateActive],
|
[cancelHoverTimer, cancelPreviewLeaveTimer, updateActive],
|
||||||
|
);
|
||||||
|
|
||||||
|
const schedulePreviewClose = useCallback(
|
||||||
|
(itemId: string) => {
|
||||||
|
if (previewLeaveTimerRef.current !== null) return;
|
||||||
|
previewLeaveTimerRef.current = setTimeout(() => {
|
||||||
|
previewLeaveTimerRef.current = null;
|
||||||
|
const current = activeRef.current;
|
||||||
|
if (current?.activation !== "preview" || current.itemId !== itemId) return;
|
||||||
|
if (hoveredRef.current?.itemId === itemId) hoveredRef.current = null;
|
||||||
|
close(current.restorePreviewFocus);
|
||||||
|
}, POINTER_TRANSITION_GRACE_MS);
|
||||||
|
},
|
||||||
|
[close],
|
||||||
);
|
);
|
||||||
|
|
||||||
const startHoverTimer = useCallback(() => {
|
const startHoverTimer = useCallback(() => {
|
||||||
cancelHoverTimer();
|
cancelHoverTimer();
|
||||||
const hovered = hoveredRef.current;
|
const hovered = hoveredRef.current;
|
||||||
if (!hovered || !shiftHeldRef.current || activeRef.current) return;
|
if (!hovered || !shiftHeldRef.current || activeRef.current) return;
|
||||||
hoverTimerRef.current = setTimeout(
|
if (pointerPositionRef.current.x < 0 || pointerPositionRef.current.y < 0) {
|
||||||
() => open(hovered.itemId, hovered.source, { activation: "preview" }),
|
const rect = hovered.source.getBoundingClientRect();
|
||||||
HOVER_DELAY_MS,
|
pointerPositionRef.current = { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 };
|
||||||
);
|
}
|
||||||
|
setIsHoldPending(true);
|
||||||
|
hoverTimerRef.current = setTimeout(() => {
|
||||||
|
hoverTimerRef.current = null;
|
||||||
|
setIsHoldPending(false);
|
||||||
|
open(hovered.itemId, hovered.source, { activation: "preview" });
|
||||||
|
}, HOVER_DELAY_MS);
|
||||||
}, [cancelHoverTimer, open]);
|
}, [cancelHoverTimer, open]);
|
||||||
|
|
||||||
const hover = useCallback(
|
const hover = useCallback(
|
||||||
(itemId: string, source: HTMLElement) => {
|
(itemId: string, source: HTMLElement) => {
|
||||||
hoveredRef.current = { itemId, source };
|
hoveredRef.current = { itemId, source };
|
||||||
|
cancelPreviewLeaveTimer();
|
||||||
const current = activeRef.current;
|
const current = activeRef.current;
|
||||||
if (current?.activation === "preview" && current.itemId !== itemId) {
|
if (current?.activation === "preview" && current.itemId !== itemId) {
|
||||||
cancelCloseTimer();
|
cancelCloseTimer();
|
||||||
@@ -127,18 +161,38 @@ export const BoardAdvancedFocusProvider = ({ children }: PropsWithChildren) => {
|
|||||||
}
|
}
|
||||||
startHoverTimer();
|
startHoverTimer();
|
||||||
},
|
},
|
||||||
[cancelCloseTimer, startHoverTimer, updateActive],
|
[cancelCloseTimer, cancelPreviewLeaveTimer, startHoverTimer, updateActive],
|
||||||
);
|
);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const handlePointerMove = (event: PointerEvent) => {
|
const handlePointerMove = (event: PointerEvent) => {
|
||||||
|
pointerPositionRef.current = { x: event.clientX, y: event.clientY };
|
||||||
|
if (holdIndicatorRef.current && pointerFrameRef.current === null) {
|
||||||
|
pointerFrameRef.current = requestAnimationFrame(() => {
|
||||||
|
pointerFrameRef.current = null;
|
||||||
|
const indicator = holdIndicatorRef.current;
|
||||||
|
if (!indicator) return;
|
||||||
|
indicator.style.setProperty("--advanced-focus-pointer-x", `${pointerPositionRef.current.x}px`);
|
||||||
|
indicator.style.setProperty("--advanced-focus-pointer-y", `${pointerPositionRef.current.y}px`);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
const current = activeRef.current;
|
const current = activeRef.current;
|
||||||
if (!shiftHeldRef.current || current?.activation !== "preview") return;
|
if (!shiftHeldRef.current || current?.activation !== "preview") return;
|
||||||
if (
|
if (event.target instanceof Element && event.target.closest("[data-advanced-focus-surface], [data-portal]")) {
|
||||||
event.target instanceof Element &&
|
cancelPreviewLeaveTimer();
|
||||||
event.target.closest(interactiveSelector)?.closest("[data-advanced-focus-surface]")
|
|
||||||
)
|
|
||||||
return;
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const isInsideSourceRect =
|
||||||
|
event.clientX >= current.sourceRect.left &&
|
||||||
|
event.clientX <= current.sourceRect.left + current.sourceRect.width &&
|
||||||
|
event.clientY >= current.sourceRect.top &&
|
||||||
|
event.clientY <= current.sourceRect.top + current.sourceRect.height;
|
||||||
|
if (isInsideSourceRect) {
|
||||||
|
cancelPreviewLeaveTimer();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const underlyingSource = document
|
const underlyingSource = document
|
||||||
.elementsFromPoint(event.clientX, event.clientY)
|
.elementsFromPoint(event.clientX, event.clientY)
|
||||||
@@ -151,7 +205,10 @@ export const BoardAdvancedFocusProvider = ({ children }: PropsWithChildren) => {
|
|||||||
)
|
)
|
||||||
.find((source) => source !== null && source !== current.source);
|
.find((source) => source !== null && source !== current.source);
|
||||||
const itemId = underlyingSource?.dataset.itemId;
|
const itemId = underlyingSource?.dataset.itemId;
|
||||||
if (!underlyingSource || !itemId) return;
|
if (!underlyingSource || !itemId) {
|
||||||
|
schedulePreviewClose(current.itemId);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (underlyingSource.hasAttribute("aria-keyshortcuts")) {
|
if (underlyingSource.hasAttribute("aria-keyshortcuts")) {
|
||||||
hover(itemId, underlyingSource);
|
hover(itemId, underlyingSource);
|
||||||
@@ -160,31 +217,38 @@ export const BoardAdvancedFocusProvider = ({ children }: PropsWithChildren) => {
|
|||||||
|
|
||||||
hoveredRef.current = null;
|
hoveredRef.current = null;
|
||||||
cancelHoverTimer();
|
cancelHoverTimer();
|
||||||
cancelCloseTimer();
|
schedulePreviewClose(current.itemId);
|
||||||
updateActive(null);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
window.addEventListener("pointermove", handlePointerMove, { capture: true });
|
window.addEventListener("pointermove", handlePointerMove, { capture: true });
|
||||||
return () => window.removeEventListener("pointermove", handlePointerMove, { capture: true });
|
window.addEventListener("pointerover", handlePointerMove, { capture: true });
|
||||||
}, [cancelCloseTimer, cancelHoverTimer, hover, updateActive]);
|
return () => {
|
||||||
|
window.removeEventListener("pointermove", handlePointerMove, { capture: true });
|
||||||
|
window.removeEventListener("pointerover", handlePointerMove, { capture: true });
|
||||||
|
if (pointerFrameRef.current !== null) cancelAnimationFrame(pointerFrameRef.current);
|
||||||
|
};
|
||||||
|
}, [cancelHoverTimer, cancelPreviewLeaveTimer, hover, schedulePreviewClose]);
|
||||||
|
|
||||||
const leave = useCallback(
|
const leave = useCallback(
|
||||||
(itemId: string) => {
|
(itemId: string) => {
|
||||||
if (hoveredRef.current?.itemId !== itemId) return;
|
if (hoveredRef.current?.itemId !== itemId) return;
|
||||||
hoveredRef.current = null;
|
hoveredRef.current = null;
|
||||||
cancelHoverTimer();
|
cancelHoverTimer();
|
||||||
|
if (activeRef.current?.activation === "preview" && activeRef.current.itemId === itemId)
|
||||||
|
schedulePreviewClose(itemId);
|
||||||
},
|
},
|
||||||
[cancelHoverTimer],
|
[cancelHoverTimer, schedulePreviewClose],
|
||||||
);
|
);
|
||||||
|
|
||||||
const dismiss = useCallback(
|
const dismiss = useCallback(
|
||||||
(itemId: string) => {
|
(itemId: string) => {
|
||||||
if (activeRef.current?.itemId !== itemId) return;
|
if (activeRef.current?.itemId !== itemId) return;
|
||||||
cancelHoverTimer();
|
cancelHoverTimer();
|
||||||
|
cancelPreviewLeaveTimer();
|
||||||
cancelCloseTimer();
|
cancelCloseTimer();
|
||||||
updateActive(null);
|
updateActive(null);
|
||||||
},
|
},
|
||||||
[cancelCloseTimer, cancelHoverTimer, updateActive],
|
[cancelCloseTimer, cancelHoverTimer, cancelPreviewLeaveTimer, updateActive],
|
||||||
);
|
);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -223,9 +287,10 @@ export const BoardAdvancedFocusProvider = ({ children }: PropsWithChildren) => {
|
|||||||
window.removeEventListener("keyup", handleKeyUp);
|
window.removeEventListener("keyup", handleKeyUp);
|
||||||
window.removeEventListener("blur", handleBlur);
|
window.removeEventListener("blur", handleBlur);
|
||||||
cancelHoverTimer();
|
cancelHoverTimer();
|
||||||
|
cancelPreviewLeaveTimer();
|
||||||
cancelCloseTimer();
|
cancelCloseTimer();
|
||||||
};
|
};
|
||||||
}, [cancelCloseTimer, cancelHoverTimer, close, isEditMode, startHoverTimer]);
|
}, [cancelCloseTimer, cancelHoverTimer, cancelPreviewLeaveTimer, close, isEditMode, startHoverTimer]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (isEditMode && activeRef.current) close(false);
|
if (isEditMode && activeRef.current) close(false);
|
||||||
@@ -252,6 +317,28 @@ export const BoardAdvancedFocusProvider = ({ children }: PropsWithChildren) => {
|
|||||||
return (
|
return (
|
||||||
<AdvancedFocusContext.Provider value={value}>
|
<AdvancedFocusContext.Provider value={value}>
|
||||||
{children}
|
{children}
|
||||||
|
{isHoldPending && (
|
||||||
|
<Portal>
|
||||||
|
<div
|
||||||
|
ref={holdIndicatorRef}
|
||||||
|
data-advanced-focus-hold-indicator
|
||||||
|
className={classes.holdIndicator}
|
||||||
|
style={
|
||||||
|
{
|
||||||
|
"--advanced-focus-pointer-x": `${pointerPositionRef.current.x}px`,
|
||||||
|
"--advanced-focus-pointer-y": `${pointerPositionRef.current.y}px`,
|
||||||
|
} as CSSProperties
|
||||||
|
}
|
||||||
|
aria-hidden
|
||||||
|
>
|
||||||
|
<svg className={classes.holdIndicatorRing} viewBox="0 0 36 36">
|
||||||
|
<circle className={classes.holdIndicatorTrack} cx="18" cy="18" r="15" pathLength="1" />
|
||||||
|
<circle className={classes.holdIndicatorProgress} cx="18" cy="18" r="15" pathLength="1" />
|
||||||
|
</svg>
|
||||||
|
<span className={classes.holdIndicatorLabel}>⇧</span>
|
||||||
|
</div>
|
||||||
|
</Portal>
|
||||||
|
)}
|
||||||
{active?.activation === "preview" && (
|
{active?.activation === "preview" && (
|
||||||
<Portal>
|
<Portal>
|
||||||
<Overlay
|
<Overlay
|
||||||
|
|||||||
@@ -0,0 +1,62 @@
|
|||||||
|
// @vitest-environment jsdom
|
||||||
|
|
||||||
|
import { afterEach, describe, expect, test, vi } from "vitest";
|
||||||
|
|
||||||
|
import { startAdvancedFocusEntrance } from "./entrance";
|
||||||
|
|
||||||
|
describe("startAdvancedFocusEntrance", () => {
|
||||||
|
afterEach(() => {
|
||||||
|
document.body.replaceChildren();
|
||||||
|
vi.unstubAllGlobals();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("moves the persistent portal before releasing its source-frame animation", () => {
|
||||||
|
let releaseFrame: FrameRequestCallback | undefined;
|
||||||
|
vi.stubGlobal(
|
||||||
|
"requestAnimationFrame",
|
||||||
|
vi.fn((callback: FrameRequestCallback) => {
|
||||||
|
releaseFrame = callback;
|
||||||
|
return 7;
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
const compactHost = document.createElement("div");
|
||||||
|
const previewHost = document.createElement("div");
|
||||||
|
const portalTarget = document.createElement("div");
|
||||||
|
const surface = document.createElement("div");
|
||||||
|
surface.classList.add("surface-ready");
|
||||||
|
portalTarget.append(surface);
|
||||||
|
compactHost.append(portalTarget);
|
||||||
|
document.body.append(compactHost, previewHost);
|
||||||
|
|
||||||
|
expect(startAdvancedFocusEntrance(portalTarget, previewHost, surface, "surface-ready")).toBe(7);
|
||||||
|
expect(portalTarget.parentElement).toBe(previewHost);
|
||||||
|
expect(surface.classList.contains("surface-ready")).toBe(false);
|
||||||
|
|
||||||
|
releaseFrame?.(0);
|
||||||
|
expect(surface.classList.contains("surface-ready")).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("does not release a detached surface", () => {
|
||||||
|
let releaseFrame: FrameRequestCallback | undefined;
|
||||||
|
vi.stubGlobal(
|
||||||
|
"requestAnimationFrame",
|
||||||
|
vi.fn((callback: FrameRequestCallback) => {
|
||||||
|
releaseFrame = callback;
|
||||||
|
return 8;
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
const previewHost = document.createElement("div");
|
||||||
|
const portalTarget = document.createElement("div");
|
||||||
|
const surface = document.createElement("div");
|
||||||
|
portalTarget.append(surface);
|
||||||
|
document.body.append(previewHost);
|
||||||
|
|
||||||
|
startAdvancedFocusEntrance(portalTarget, previewHost, surface, "surface-ready");
|
||||||
|
portalTarget.remove();
|
||||||
|
releaseFrame?.(0);
|
||||||
|
|
||||||
|
expect(surface.classList.contains("surface-ready")).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
export const startAdvancedFocusEntrance = (
|
||||||
|
portalTarget: HTMLElement,
|
||||||
|
host: HTMLElement,
|
||||||
|
surface: HTMLElement,
|
||||||
|
readyClass: string,
|
||||||
|
) => {
|
||||||
|
host.append(portalTarget);
|
||||||
|
surface.classList.remove(readyClass);
|
||||||
|
|
||||||
|
return requestAnimationFrame(() => {
|
||||||
|
if (surface.isConnected) surface.classList.add(readyClass);
|
||||||
|
});
|
||||||
|
};
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import type { ComponentType, CSSProperties, KeyboardEvent, MutableRefObject } from "react";
|
import type { ComponentType, CSSProperties, KeyboardEvent, MutableRefObject } from "react";
|
||||||
import { Suspense, use, useEffect, useRef, useState } from "react";
|
import { memo, Suspense, use, useCallback, useEffect, useRef, useState } from "react";
|
||||||
import { createPortal } from "react-dom";
|
import { createPortal } from "react-dom";
|
||||||
import dynamic from "next/dynamic";
|
import dynamic from "next/dynamic";
|
||||||
import type { CardProps } from "@mantine/core";
|
import type { CardProps } from "@mantine/core";
|
||||||
@@ -27,6 +27,7 @@ import { loadWidgetResources, reduceWidgetOptionsWithDefinition } from "@homarr/
|
|||||||
import type { SectionItem } from "~/app/[locale]/boards/_types";
|
import type { SectionItem } from "~/app/[locale]/boards/_types";
|
||||||
import advancedFocusClasses from "../advanced-focus/advanced-focus.module.css";
|
import advancedFocusClasses from "../advanced-focus/advanced-focus.module.css";
|
||||||
import { useAdvancedFocus } from "../advanced-focus/context";
|
import { useAdvancedFocus } from "../advanced-focus/context";
|
||||||
|
import { startAdvancedFocusEntrance } from "../advanced-focus/entrance";
|
||||||
import { getAdvancedFocusClosePosition, getAdvancedFocusRect } from "../advanced-focus/geometry";
|
import { getAdvancedFocusClosePosition, getAdvancedFocusRect } from "../advanced-focus/geometry";
|
||||||
import { AdvancedFocusManualSurface } from "../advanced-focus/manual-surface";
|
import { AdvancedFocusManualSurface } from "../advanced-focus/manual-surface";
|
||||||
import { redirectShiftWheel } from "../advanced-focus/wheel";
|
import { redirectShiftWheel } from "../advanced-focus/wheel";
|
||||||
@@ -153,6 +154,7 @@ const LoadedBoardItemContent = ({
|
|||||||
const { definition, Component } = use(loadWidgetResources(item.kind));
|
const { definition, Component } = use(loadWidgetResources(item.kind));
|
||||||
const sourceRef = useRef<HTMLDivElement>(null);
|
const sourceRef = useRef<HTMLDivElement>(null);
|
||||||
const cardRef = useRef<HTMLDivElement>(null);
|
const cardRef = useRef<HTMLDivElement>(null);
|
||||||
|
const previewEntranceFrameRef = useRef<number | null>(null);
|
||||||
const { width: viewportWidth, height: viewportHeight } = useViewportSize();
|
const { width: viewportWidth, height: viewportHeight } = useViewportSize();
|
||||||
const board = useRequiredBoard();
|
const board = useRequiredBoard();
|
||||||
const t = useI18n();
|
const t = useI18n();
|
||||||
@@ -213,14 +215,52 @@ const LoadedBoardItemContent = ({
|
|||||||
return () => surface.removeEventListener("wheel", handleWheel, { capture: true });
|
return () => surface.removeEventListener("wheel", handleWheel, { capture: true });
|
||||||
}, [isAdvanced, isManual, manualSurface]);
|
}, [isAdvanced, isManual, manualSurface]);
|
||||||
|
|
||||||
const mountPortalTarget = (node: HTMLDivElement | null, activation: "compact" | "preview" | "manual") => {
|
const cancelPreviewEntrance = useCallback(() => {
|
||||||
if (!node || !surfacePortalTarget) return;
|
if (previewEntranceFrameRef.current === null) return;
|
||||||
const shouldMount =
|
cancelAnimationFrame(previewEntranceFrameRef.current);
|
||||||
(activation === "compact" && !isAdvanced) ||
|
previewEntranceFrameRef.current = null;
|
||||||
(activation === "preview" && isPreview) ||
|
}, []);
|
||||||
(activation === "manual" && isManual);
|
|
||||||
if (shouldMount) node.append(surfacePortalTarget);
|
const mountCompactHost = useCallback(
|
||||||
};
|
(host: HTMLDivElement | null) => {
|
||||||
|
if (!host || !surfacePortalTarget || isAdvanced) return;
|
||||||
|
cancelPreviewEntrance();
|
||||||
|
host.append(surfacePortalTarget);
|
||||||
|
},
|
||||||
|
[cancelPreviewEntrance, isAdvanced, surfacePortalTarget],
|
||||||
|
);
|
||||||
|
|
||||||
|
const mountPreviewHost = useCallback(
|
||||||
|
(host: HTMLDivElement | null) => {
|
||||||
|
if (!host || !surfacePortalTarget || !isPreview) {
|
||||||
|
if (!host) cancelPreviewEntrance();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (activeFocus?.phase !== "visible") {
|
||||||
|
host.append(surfacePortalTarget);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const card = cardRef.current;
|
||||||
|
const readyClass = advancedFocusClasses.surfaceReady;
|
||||||
|
if (!card || !readyClass) return;
|
||||||
|
|
||||||
|
cancelPreviewEntrance();
|
||||||
|
previewEntranceFrameRef.current = startAdvancedFocusEntrance(surfacePortalTarget, host, card, readyClass);
|
||||||
|
},
|
||||||
|
[activeFocus?.phase, cancelPreviewEntrance, isPreview, surfacePortalTarget],
|
||||||
|
);
|
||||||
|
|
||||||
|
const mountManualHost = useCallback(
|
||||||
|
(host: HTMLDivElement | null) => {
|
||||||
|
if (!host || !surfacePortalTarget || !isManual) return;
|
||||||
|
cancelPreviewEntrance();
|
||||||
|
host.append(surfacePortalTarget);
|
||||||
|
},
|
||||||
|
[cancelPreviewEntrance, isManual, surfacePortalTarget],
|
||||||
|
);
|
||||||
|
|
||||||
|
useEffect(() => cancelPreviewEntrance, [cancelPreviewEntrance]);
|
||||||
|
|
||||||
const previewStyle =
|
const previewStyle =
|
||||||
isPreview && advancedRect && activeFocus
|
isPreview && advancedRect && activeFocus
|
||||||
@@ -331,16 +371,13 @@ const LoadedBoardItemContent = ({
|
|||||||
}}
|
}}
|
||||||
className={combineClasses(isAdvanced && advancedFocusClasses.sourcePlaceholder)}
|
className={combineClasses(isAdvanced && advancedFocusClasses.sourcePlaceholder)}
|
||||||
>
|
>
|
||||||
<div ref={(node) => mountPortalTarget(node, "compact")} className={advancedFocusClasses.surfaceHost}>
|
<div ref={mountCompactHost} className={advancedFocusClasses.surfaceHost}>
|
||||||
{!supportsAdvancedFocus && widgetCard}
|
{!supportsAdvancedFocus && widgetCard}
|
||||||
</div>
|
</div>
|
||||||
{surfacePortalTarget && createPortal(widgetCard, surfacePortalTarget)}
|
{surfacePortalTarget && createPortal(widgetCard, surfacePortalTarget)}
|
||||||
{isPreview && (
|
{isPreview && (
|
||||||
<Portal reuseTargetNode={false}>
|
<Portal reuseTargetNode={false}>
|
||||||
<div
|
<div ref={mountPreviewHost} className={advancedFocusClasses.surfaceHostAdvanced} />
|
||||||
ref={(node) => mountPortalTarget(node, "preview")}
|
|
||||||
className={advancedFocusClasses.surfaceHostAdvanced}
|
|
||||||
/>
|
|
||||||
</Portal>
|
</Portal>
|
||||||
)}
|
)}
|
||||||
{isManual && activeFocus && advancedRect && closePosition && (
|
{isManual && activeFocus && advancedRect && closePosition && (
|
||||||
@@ -357,10 +394,7 @@ const LoadedBoardItemContent = ({
|
|||||||
contentRef={setManualSurface}
|
contentRef={setManualSurface}
|
||||||
onClose={() => close()}
|
onClose={() => close()}
|
||||||
>
|
>
|
||||||
<div
|
<div ref={mountManualHost} className={advancedFocusClasses.manualSurfaceMount} />
|
||||||
ref={(node) => mountPortalTarget(node, "manual")}
|
|
||||||
className={advancedFocusClasses.manualSurfaceMount}
|
|
||||||
/>
|
|
||||||
</AdvancedFocusManualSurface>
|
</AdvancedFocusManualSurface>
|
||||||
)}
|
)}
|
||||||
</Box>
|
</Box>
|
||||||
@@ -400,7 +434,7 @@ interface InnerContentProps {
|
|||||||
Component: ComponentType<WidgetComponentProps<SectionItem["kind"]>>;
|
Component: ComponentType<WidgetComponentProps<SectionItem["kind"]>>;
|
||||||
}
|
}
|
||||||
|
|
||||||
const InnerContent = ({ item, definition, Component, ...dimensions }: InnerContentProps) => {
|
const InnerContent = memo(function InnerContent({ item, definition, Component, ...dimensions }: InnerContentProps) {
|
||||||
const settings = useSettings();
|
const settings = useSettings();
|
||||||
const board = useRequiredBoard();
|
const board = useRequiredBoard();
|
||||||
const [isEditMode] = useEditMode();
|
const [isEditMode] = useEditMode();
|
||||||
@@ -474,7 +508,7 @@ const InnerContent = ({ item, definition, Component, ...dimensions }: InnerConte
|
|||||||
)}
|
)}
|
||||||
</QueryErrorResetBoundary>
|
</QueryErrorResetBoundary>
|
||||||
);
|
);
|
||||||
};
|
});
|
||||||
|
|
||||||
const Throw = ({ when, error }: { when: boolean; error: Error }) => {
|
const Throw = ({ when, error }: { when: boolean; error: Error }) => {
|
||||||
if (when) throw error;
|
if (when) throw error;
|
||||||
|
|||||||
@@ -5,12 +5,14 @@ The board uses fixed logical units:
|
|||||||
- one `1 × 1` item is exactly `200 × 200` logical pixels;
|
- one `1 × 1` item is exactly `200 × 200` logical pixels;
|
||||||
- the gap is always `24` logical pixels, giving a `224` pixel track pitch;
|
- the gap is always `24` logical pixels, giving a `224` pixel track pitch;
|
||||||
- multi-cell items include the gaps between their cells (`2 × 1` is `424 × 200`);
|
- multi-cell items include the gaps between their cells (`2 × 1` is `424 × 200`);
|
||||||
- the canvas is transformed once with one uniform scale derived from its available width.
|
- the canvas is zoomed once with one uniform scale derived from its available width.
|
||||||
|
|
||||||
Items keep the same logical dimensions at every viewport. The viewport reserves
|
Items keep the same logical dimensions at every viewport. The viewport reserves
|
||||||
the painted size while the inner canvas remains at its logical dimensions, so a
|
the painted size while the inner canvas remains at its logical dimensions, so a
|
||||||
widget's `clientWidth`, `clientHeight`, and `ResizeObserver` measurements stay
|
widget's `clientWidth`, `clientHeight`, and `ResizeObserver` measurements stay
|
||||||
stable.
|
stable. The visual canvas always fits the available width, every root lane
|
||||||
|
keeps at least one viewport of height, and edit-mode previews extend it downward
|
||||||
|
as needed.
|
||||||
|
|
||||||
The read-only renderer should:
|
The read-only renderer should:
|
||||||
|
|
||||||
|
|||||||
@@ -5,6 +5,5 @@
|
|||||||
export const LOGICAL_GRID_CELL_SIZE = 200;
|
export const LOGICAL_GRID_CELL_SIZE = 200;
|
||||||
export const LOGICAL_GRID_GAP = 24;
|
export const LOGICAL_GRID_GAP = 24;
|
||||||
export const LOGICAL_GRID_PITCH = LOGICAL_GRID_CELL_SIZE + LOGICAL_GRID_GAP;
|
export const LOGICAL_GRID_PITCH = LOGICAL_GRID_CELL_SIZE + LOGICAL_GRID_GAP;
|
||||||
export const MIN_ACCESSIBLE_CANVAS_SCALE = 0.75;
|
|
||||||
|
|
||||||
export const COLLAPSED_SECTION_ROW_COUNT = 0.5;
|
export const COLLAPSED_SECTION_ROW_COUNT = 0.5;
|
||||||
@@ -21,6 +21,13 @@ export const getLogicalItemStyle = ({ x, y, w, h }: GridCoordinates): CSSPropert
|
|||||||
export const getLayoutRowCount = (placements: readonly GridCoordinates[]) =>
|
export const getLayoutRowCount = (placements: readonly GridCoordinates[]) =>
|
||||||
placements.reduce((rowCount, placement) => Math.max(rowCount, placement.y + placement.h), 0);
|
placements.reduce((rowCount, placement) => Math.max(rowCount, placement.y + placement.h), 0);
|
||||||
|
|
||||||
|
export const getGridRowCountForVisualHeight = (visualHeight: number, visualScale: number) => {
|
||||||
|
if (!Number.isFinite(visualHeight) || visualHeight <= 0) return 1;
|
||||||
|
if (!Number.isFinite(visualScale) || visualScale <= 0) return 1;
|
||||||
|
|
||||||
|
return Math.max(1, Math.ceil((visualHeight / visualScale + LOGICAL_GRID_GAP) / LOGICAL_GRID_PITCH));
|
||||||
|
};
|
||||||
|
|
||||||
export const normalizeGridPlacement = <TPlacement extends GridPlacement>(
|
export const normalizeGridPlacement = <TPlacement extends GridPlacement>(
|
||||||
placement: TPlacement,
|
placement: TPlacement,
|
||||||
columnCount: number,
|
columnCount: number,
|
||||||
|
|||||||
@@ -2,9 +2,7 @@
|
|||||||
width: 100%;
|
width: 100%;
|
||||||
max-width: 100%;
|
max-width: 100%;
|
||||||
min-width: 0;
|
min-width: 0;
|
||||||
overflow: visible;
|
overflow: clip;
|
||||||
overflow-x: auto;
|
|
||||||
overscroll-behavior-inline: contain;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.viewport[data-board-hydrated="false"] {
|
.viewport[data-board-hydrated="false"] {
|
||||||
@@ -18,8 +16,6 @@
|
|||||||
.canvas {
|
.canvas {
|
||||||
position: absolute;
|
position: absolute;
|
||||||
inset: 0 auto auto 0;
|
inset: 0 auto auto 0;
|
||||||
transform-origin: top left;
|
|
||||||
will-change: transform;
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Keep dashboard UI at its normal readable density while the fixed canvas
|
* Keep dashboard UI at its normal readable density while the fixed canvas
|
||||||
@@ -44,9 +40,3 @@
|
|||||||
--mantine-h5-font-size: calc(1rem * var(--board-canvas-ui-scale, 1));
|
--mantine-h5-font-size: calc(1rem * var(--board-canvas-ui-scale, 1));
|
||||||
--mantine-h6-font-size: calc(0.875rem * var(--board-canvas-ui-scale, 1));
|
--mantine-h6-font-size: calc(0.875rem * var(--board-canvas-ui-scale, 1));
|
||||||
}
|
}
|
||||||
|
|
||||||
@media (prefers-reduced-motion: reduce) {
|
|
||||||
.canvas {
|
|
||||||
will-change: auto;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -5,11 +5,8 @@ import { createContext, useContext, useEffect, useMemo, useState } from "react";
|
|||||||
import { Box } from "@mantine/core";
|
import { Box } from "@mantine/core";
|
||||||
import { useElementSize } from "@mantine/hooks";
|
import { useElementSize } from "@mantine/hooks";
|
||||||
|
|
||||||
import { MIN_ACCESSIBLE_CANVAS_SCALE } from "./constants";
|
|
||||||
import classes from "./scaled-board-canvas.module.css";
|
import classes from "./scaled-board-canvas.module.css";
|
||||||
|
|
||||||
export { MIN_ACCESSIBLE_CANVAS_SCALE };
|
|
||||||
|
|
||||||
const BoardCanvasScaleContext = createContext(1);
|
const BoardCanvasScaleContext = createContext(1);
|
||||||
|
|
||||||
export const useBoardCanvasScale = () => useContext(BoardCanvasScaleContext);
|
export const useBoardCanvasScale = () => useContext(BoardCanvasScaleContext);
|
||||||
@@ -18,7 +15,7 @@ export const calculateBoardCanvasScale = (availableWidth: number, logicalWidth:
|
|||||||
if (!Number.isFinite(availableWidth) || !Number.isFinite(logicalWidth)) return 1;
|
if (!Number.isFinite(availableWidth) || !Number.isFinite(logicalWidth)) return 1;
|
||||||
if (availableWidth <= 0 || logicalWidth <= 0) return 1;
|
if (availableWidth <= 0 || logicalWidth <= 0) return 1;
|
||||||
|
|
||||||
return Math.max(MIN_ACCESSIBLE_CANVAS_SCALE, availableWidth / logicalWidth);
|
return availableWidth / logicalWidth;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const calculateBoardUiScale = (canvasScale: number) => {
|
export const calculateBoardUiScale = (canvasScale: number) => {
|
||||||
@@ -36,9 +33,8 @@ interface ScaledBoardCanvasProps {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Scales the complete board as one surface while keeping widget layout in
|
* Scales the complete board as one surface while keeping widget layout in
|
||||||
* fixed logical pixels. The scale floor deliberately allows horizontal
|
* fixed logical pixels. The complete canvas always fits its viewport so board
|
||||||
* overflow so browser zoom still magnifies content instead of being cancelled
|
* content can never widen the document or require horizontal scrolling.
|
||||||
* by responsive downscaling.
|
|
||||||
*/
|
*/
|
||||||
export const ScaledBoardCanvas = ({
|
export const ScaledBoardCanvas = ({
|
||||||
logicalWidth,
|
logicalWidth,
|
||||||
@@ -62,6 +58,7 @@ export const ScaledBoardCanvas = ({
|
|||||||
[logicalWidth, resolvedAvailableWidth],
|
[logicalWidth, resolvedAvailableWidth],
|
||||||
);
|
);
|
||||||
const uiScale = calculateBoardUiScale(scale);
|
const uiScale = calculateBoardUiScale(scale);
|
||||||
|
const inverseScale = scale > 0 ? 1 / scale : 1;
|
||||||
const visualWidth = logicalWidth * scale;
|
const visualWidth = logicalWidth * scale;
|
||||||
const hasHorizontalOverflow = resolvedAvailableWidth > 0 && visualWidth - resolvedAvailableWidth > 0.5;
|
const hasHorizontalOverflow = resolvedAvailableWidth > 0 && visualWidth - resolvedAvailableWidth > 0.5;
|
||||||
|
|
||||||
@@ -84,8 +81,9 @@ export const ScaledBoardCanvas = ({
|
|||||||
className={classes.canvas}
|
className={classes.canvas}
|
||||||
w={logicalWidth}
|
w={logicalWidth}
|
||||||
style={{
|
style={{
|
||||||
|
"--board-canvas-inverse-scale": inverseScale,
|
||||||
"--board-canvas-ui-scale": uiScale,
|
"--board-canvas-ui-scale": uiScale,
|
||||||
transform: `scale(${scale})`,
|
zoom: scale,
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<BoardCanvasScaleContext.Provider value={scale}>{children}</BoardCanvasScaleContext.Provider>
|
<BoardCanvasScaleContext.Provider value={scale}>{children}</BoardCanvasScaleContext.Provider>
|
||||||
|
|||||||
@@ -1,6 +1,12 @@
|
|||||||
import { describe, expect, test } from "vitest";
|
import { describe, expect, test } from "vitest";
|
||||||
|
|
||||||
import { getLayoutRowCount, getLogicalItemStyle, getLogicalTrackSize, normalizeGridPlacement } from "../index";
|
import {
|
||||||
|
getGridRowCountForVisualHeight,
|
||||||
|
getLayoutRowCount,
|
||||||
|
getLogicalItemStyle,
|
||||||
|
getLogicalTrackSize,
|
||||||
|
normalizeGridPlacement,
|
||||||
|
} from "../index";
|
||||||
|
|
||||||
describe("fixed dashboard geometry", () => {
|
describe("fixed dashboard geometry", () => {
|
||||||
test("keeps a 1x1 item exactly 200px with a fixed 24px gap", () => {
|
test("keeps a 1x1 item exactly 200px with a fixed 24px gap", () => {
|
||||||
@@ -24,4 +30,12 @@ describe("fixed dashboard geometry", () => {
|
|||||||
expect(placement).toEqual({ id: "wide", x: 0, y: 0, w: 4, h: 2 });
|
expect(placement).toEqual({ id: "wide", x: 0, y: 0, w: 4, h: 2 });
|
||||||
expect(getLayoutRowCount([placement, { x: 0, y: 4, w: 1, h: 3 }])).toBe(7);
|
expect(getLayoutRowCount([placement, { x: 0, y: 4, w: 1, h: 3 }])).toBe(7);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("derives enough logical rows to fill the visual viewport at any canvas scale", () => {
|
||||||
|
expect(getGridRowCountForVisualHeight(1200, 1)).toBe(6);
|
||||||
|
expect(getLogicalTrackSize(getGridRowCountForVisualHeight(1200, 1))).toBeGreaterThanOrEqual(1200);
|
||||||
|
|
||||||
|
expect(getGridRowCountForVisualHeight(1200, 0.5)).toBe(11);
|
||||||
|
expect(getLogicalTrackSize(getGridRowCountForVisualHeight(1200, 0.5)) * 0.5).toBeGreaterThanOrEqual(1200);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
@@ -1,9 +1,9 @@
|
|||||||
import { describe, expect, test } from "vitest";
|
import { describe, expect, test } from "vitest";
|
||||||
|
|
||||||
import { calculateBoardCanvasScale, calculateBoardUiScale, MIN_ACCESSIBLE_CANVAS_SCALE } from "../scaled-board-canvas";
|
import { calculateBoardCanvasScale, calculateBoardUiScale } from "../scaled-board-canvas";
|
||||||
|
|
||||||
describe("board canvas scale policy", () => {
|
describe("board canvas scale policy", () => {
|
||||||
test("fits the logical canvas exactly when the viewport can preserve the minimum scale", () => {
|
test("fits the logical canvas exactly", () => {
|
||||||
const scale = calculateBoardCanvasScale(840, 1000);
|
const scale = calculateBoardCanvasScale(840, 1000);
|
||||||
|
|
||||||
expect(scale).toBe(0.84);
|
expect(scale).toBe(0.84);
|
||||||
@@ -14,16 +14,16 @@ describe("board canvas scale policy", () => {
|
|||||||
expect(calculateBoardCanvasScale(1800, 1000)).toBe(1.8);
|
expect(calculateBoardCanvasScale(1800, 1000)).toBe(1.8);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("stops counter-scaling at 0.75 and lets the canvas overflow", () => {
|
test("keeps fitting narrow viewports without horizontal overflow", () => {
|
||||||
const availableWidth = 600;
|
const availableWidth = 600;
|
||||||
const logicalWidth = 1000;
|
const logicalWidth = 1000;
|
||||||
const scale = calculateBoardCanvasScale(availableWidth, logicalWidth);
|
const scale = calculateBoardCanvasScale(availableWidth, logicalWidth);
|
||||||
|
|
||||||
expect(scale).toBe(MIN_ACCESSIBLE_CANVAS_SCALE);
|
expect(scale).toBe(0.6);
|
||||||
expect(logicalWidth * scale).toBeGreaterThan(availableWidth);
|
expect(logicalWidth * scale).toBe(availableWidth);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("keeps content materially magnified at 200% effective zoom", () => {
|
test("keeps the board fitted at 200% effective zoom", () => {
|
||||||
const logicalWidth = 1696;
|
const logicalWidth = 1696;
|
||||||
const normalAvailableWidth = 1872;
|
const normalAvailableWidth = 1872;
|
||||||
const normalScale = calculateBoardCanvasScale(normalAvailableWidth, logicalWidth);
|
const normalScale = calculateBoardCanvasScale(normalAvailableWidth, logicalWidth);
|
||||||
@@ -31,8 +31,8 @@ describe("board canvas scale policy", () => {
|
|||||||
const normalPaintedCellSize = 200 * normalScale;
|
const normalPaintedCellSize = 200 * normalScale;
|
||||||
const zoomedPaintedCellSize = 200 * zoomedScale * 2;
|
const zoomedPaintedCellSize = 200 * zoomedScale * 2;
|
||||||
|
|
||||||
expect(zoomedScale).toBe(MIN_ACCESSIBLE_CANVAS_SCALE);
|
expect(zoomedScale).toBeCloseTo(normalScale / 2);
|
||||||
expect(zoomedPaintedCellSize).toBeGreaterThan(normalPaintedCellSize * 1.25);
|
expect(zoomedPaintedCellSize).toBeCloseTo(normalPaintedCellSize);
|
||||||
});
|
});
|
||||||
|
|
||||||
test.each([
|
test.each([
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ export const BoardEmptySection = ({ section, columnCount, requestedRowCount, rai
|
|||||||
const [isEditMode] = useEditMode();
|
const [isEditMode] = useEditMode();
|
||||||
const t = useScopedI18n("board.landmark");
|
const t = useScopedI18n("board.landmark");
|
||||||
|
|
||||||
if (totalLength === 0 && !isEditMode && requestedRowCount === 0) return null;
|
if (totalLength === 0 && !isEditMode && requestedRowCount === 0 && railPlacement !== "main") return null;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<SectionGrid
|
<SectionGrid
|
||||||
|
|||||||
@@ -86,6 +86,10 @@ body[data-board-grid-interacting="drag"] .board-grid-placeholder {
|
|||||||
overflow: visible;
|
overflow: visible;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
body[data-board-grid-interacting="resize"] .board-grid-entry[data-dnd-active="true"] > .board-grid-content-mount {
|
||||||
|
overflow: clip;
|
||||||
|
}
|
||||||
|
|
||||||
.board-grid-placeholder {
|
.board-grid-placeholder {
|
||||||
z-index: 0;
|
z-index: 0;
|
||||||
background: color-mix(in srgb, var(--mantine-primary-color-filled) 16%, transparent);
|
background: color-mix(in srgb, var(--mantine-primary-color-filled) 16%, transparent);
|
||||||
@@ -178,7 +182,7 @@ body[data-board-grid-interacting="drag"] .board-grid-placeholder {
|
|||||||
.board-grid-resize-handle[data-grid-resize-handle="s"] {
|
.board-grid-resize-handle[data-grid-resize-handle="s"] {
|
||||||
right: 44px;
|
right: 44px;
|
||||||
left: 44px;
|
left: 44px;
|
||||||
height: 32px;
|
height: max(32px, calc(25px * var(--board-canvas-inverse-scale, 1)));
|
||||||
cursor: ns-resize;
|
cursor: ns-resize;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -194,7 +198,7 @@ body[data-board-grid-interacting="drag"] .board-grid-placeholder {
|
|||||||
.board-grid-resize-handle[data-grid-resize-handle="w"] {
|
.board-grid-resize-handle[data-grid-resize-handle="w"] {
|
||||||
top: 44px;
|
top: 44px;
|
||||||
bottom: 44px;
|
bottom: 44px;
|
||||||
width: 32px;
|
width: max(32px, calc(25px * var(--board-canvas-inverse-scale, 1)));
|
||||||
cursor: ew-resize;
|
cursor: ew-resize;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -217,8 +221,8 @@ body[data-board-grid-interacting="drag"] .board-grid-placeholder {
|
|||||||
.board-grid-resize-handle[data-grid-resize-handle="sw"],
|
.board-grid-resize-handle[data-grid-resize-handle="sw"],
|
||||||
.board-grid-resize-handle[data-grid-resize-handle="nw"] {
|
.board-grid-resize-handle[data-grid-resize-handle="nw"] {
|
||||||
z-index: 9;
|
z-index: 9;
|
||||||
width: 44px;
|
width: max(44px, calc(25px * var(--board-canvas-inverse-scale, 1)));
|
||||||
height: 44px;
|
height: max(44px, calc(25px * var(--board-canvas-inverse-scale, 1)));
|
||||||
}
|
}
|
||||||
|
|
||||||
.board-grid-resize-handle[data-grid-resize-handle="ne"] {
|
.board-grid-resize-handle[data-grid-resize-handle="ne"] {
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import { CollisionPriority } from "@dnd-kit/abstract";
|
|||||||
import { pointerIntersection } from "@dnd-kit/collision";
|
import { pointerIntersection } from "@dnd-kit/collision";
|
||||||
import type { DragDropManager, Draggable as DomDraggable } from "@dnd-kit/dom";
|
import type { DragDropManager, Draggable as DomDraggable } from "@dnd-kit/dom";
|
||||||
import { Accessibility, AutoScroller, Feedback, PointerActivationConstraints, PointerSensor } from "@dnd-kit/dom";
|
import { Accessibility, AutoScroller, Feedback, PointerActivationConstraints, PointerSensor } from "@dnd-kit/dom";
|
||||||
|
import { RestrictToElement } from "@dnd-kit/dom/modifiers";
|
||||||
import { getEventCoordinates, getFrameTransform, isPointerEvent } from "@dnd-kit/dom/utilities";
|
import { getEventCoordinates, getFrameTransform, isPointerEvent } from "@dnd-kit/dom/utilities";
|
||||||
import type {
|
import type {
|
||||||
BeforeDragStartEvent,
|
BeforeDragStartEvent,
|
||||||
@@ -720,6 +721,7 @@ export default function GridEditor({ sectionId, columnCount, rowCount, placement
|
|||||||
if (!previewGrid || !interaction) return placements;
|
if (!previewGrid || !interaction) return placements;
|
||||||
|
|
||||||
if (interaction.sourceGridId === sectionId) {
|
if (interaction.sourceGridId === sectionId) {
|
||||||
|
if (interaction.mode === "resize") return previewGrid.placements;
|
||||||
const original = controlledById.get(interaction.activeId);
|
const original = controlledById.get(interaction.activeId);
|
||||||
if (!original) return previewGrid.placements;
|
if (!original) return previewGrid.placements;
|
||||||
return previewGrid.placements.some((placement) => placement.id === interaction.activeId)
|
return previewGrid.placements.some((placement) => placement.id === interaction.activeId)
|
||||||
@@ -734,9 +736,16 @@ export default function GridEditor({ sectionId, columnCount, rowCount, placement
|
|||||||
);
|
);
|
||||||
const targetPlacement =
|
const targetPlacement =
|
||||||
interaction?.valid && interaction.targetGridId === sectionId ? interaction.targetPlacement : null;
|
interaction?.valid && interaction.targetGridId === sectionId ? interaction.targetPlacement : null;
|
||||||
|
const growsDuringDrag =
|
||||||
|
interaction?.mode === "drag" &&
|
||||||
|
(interaction.targetGridId === sectionId ||
|
||||||
|
(interaction.targetGridId === null && interaction.sourceGridId === sectionId));
|
||||||
|
const participatesInInteraction =
|
||||||
|
interaction && (interaction.sourceGridId === sectionId || interaction.targetGridId === sectionId);
|
||||||
|
const previewRowCount = getLayoutRowCount(previewGrid?.placements ?? renderPlacements);
|
||||||
const renderedRowCount =
|
const renderedRowCount =
|
||||||
section.kind !== "container" && interaction?.mode === "resize"
|
section.kind !== "container" && participatesInInteraction
|
||||||
? Math.max(rowCount, getLayoutRowCount(renderPlacements))
|
? Math.max(rowCount, previewRowCount) + (growsDuringDrag ? 1 : 0)
|
||||||
: rowCount;
|
: rowCount;
|
||||||
|
|
||||||
const { ref: droppableRef, isDropTarget } = useDroppable<GridTargetData>({
|
const { ref: droppableRef, isDropTarget } = useDroppable<GridTargetData>({
|
||||||
@@ -876,6 +885,14 @@ const DndGridEntry = ({ sectionId, placement, label, columnCount, maxRowCount }:
|
|||||||
],
|
],
|
||||||
[],
|
[],
|
||||||
);
|
);
|
||||||
|
const modifiers = useMemo(
|
||||||
|
() => [
|
||||||
|
RestrictToElement.configure({
|
||||||
|
element: () => shellRef.current?.closest('[data-testid="board-canvas"]') ?? null,
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
[],
|
||||||
|
);
|
||||||
const {
|
const {
|
||||||
ref: draggableRef,
|
ref: draggableRef,
|
||||||
handleRef,
|
handleRef,
|
||||||
@@ -886,6 +903,7 @@ const DndGridEntry = ({ sectionId, placement, label, columnCount, maxRowCount }:
|
|||||||
type: GRID_ENTRY_TYPE,
|
type: GRID_ENTRY_TYPE,
|
||||||
data: sourceData,
|
data: sourceData,
|
||||||
sensors,
|
sensors,
|
||||||
|
modifiers,
|
||||||
});
|
});
|
||||||
const setShellRef = useCallback(
|
const setShellRef = useCallback(
|
||||||
(element: HTMLDivElement | null) => {
|
(element: HTMLDivElement | null) => {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useMemo } from "react";
|
import { useEffect, useMemo, useState } from "react";
|
||||||
import dynamic from "next/dynamic";
|
import dynamic from "next/dynamic";
|
||||||
import { Box, LoadingOverlay } from "@mantine/core";
|
import { Box, LoadingOverlay } from "@mantine/core";
|
||||||
import combineClasses from "clsx";
|
import combineClasses from "clsx";
|
||||||
@@ -13,12 +13,14 @@ import type { ContainerSectionItem, Section } from "~/app/[locale]/boards/_types
|
|||||||
import {
|
import {
|
||||||
getCollapsedDisplayLayout,
|
getCollapsedDisplayLayout,
|
||||||
getEditableCanvasAttributes,
|
getEditableCanvasAttributes,
|
||||||
|
getGridRowCountForVisualHeight,
|
||||||
getLayoutRowCount,
|
getLayoutRowCount,
|
||||||
getLogicalItemStyle,
|
getLogicalItemStyle,
|
||||||
getLogicalTrackSize,
|
getLogicalTrackSize,
|
||||||
getReadonlyCanvasAttributes,
|
getReadonlyCanvasAttributes,
|
||||||
normalizeGridPlacement,
|
normalizeGridPlacement,
|
||||||
} from "~/components/board/layout";
|
} from "~/components/board/layout";
|
||||||
|
import { useBoardCanvasScale } from "~/components/board/layout/scaled-board-canvas";
|
||||||
import { loadGridEditorAsync } from "./grid-editor-loader";
|
import { loadGridEditorAsync } from "./grid-editor-loader";
|
||||||
import { useGridEditorRuntimeStatus } from "./grid-editor-runtime";
|
import { useGridEditorRuntimeStatus } from "./grid-editor-runtime";
|
||||||
import type { SectionGridPlacement } from "./use-grid-layout-actions";
|
import type { SectionGridPlacement } from "./use-grid-layout-actions";
|
||||||
@@ -81,6 +83,7 @@ export const SectionGrid = ({
|
|||||||
className,
|
className,
|
||||||
}: SectionGridProps) => {
|
}: SectionGridProps) => {
|
||||||
const [isEditMode] = useEditMode();
|
const [isEditMode] = useEditMode();
|
||||||
|
const canvasScale = useBoardCanvasScale();
|
||||||
const editorRuntimeStatus = useGridEditorRuntimeStatus();
|
const editorRuntimeStatus = useGridEditorRuntimeStatus();
|
||||||
const board = useRequiredBoard();
|
const board = useRequiredBoard();
|
||||||
const currentLayoutId = useCurrentLayout();
|
const currentLayoutId = useCurrentLayout();
|
||||||
@@ -144,8 +147,9 @@ export const SectionGrid = ({
|
|||||||
);
|
);
|
||||||
const displayedItems = items.map((item) => withPlacement(item, placementById.get(item.id)));
|
const displayedItems = items.map((item) => withPlacement(item, placementById.get(item.id)));
|
||||||
const displayedInnerSections = innerSections.map((item) => withPlacement(item, placementById.get(item.id)));
|
const displayedInnerSections = innerSections.map((item) => withPlacement(item, placementById.get(item.id)));
|
||||||
|
const minimumViewportRowCount = useMinimumViewportRowCount(section.kind === "empty", canvasScale);
|
||||||
const contentRowCount = Math.max(1, getLayoutRowCount(displayPlacements));
|
const contentRowCount = Math.max(1, getLayoutRowCount(displayPlacements));
|
||||||
const rowCount = Math.max(contentRowCount, requestedRowCount);
|
const rowCount = Math.max(contentRowCount, requestedRowCount, minimumViewportRowCount);
|
||||||
const logicalWidth = getLogicalTrackSize(columnCount);
|
const logicalWidth = getLogicalTrackSize(columnCount);
|
||||||
const logicalHeight = getLogicalTrackSize(rowCount);
|
const logicalHeight = getLogicalTrackSize(rowCount);
|
||||||
const canvasAttributes = isEditMode
|
const canvasAttributes = isEditMode
|
||||||
@@ -199,6 +203,24 @@ export const SectionGrid = ({
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const useMinimumViewportRowCount = (enabled: boolean, canvasScale: number) => {
|
||||||
|
const [visualHeight, setVisualHeight] = useState(0);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!enabled) return;
|
||||||
|
const update = () => setVisualHeight(window.visualViewport?.height ?? window.innerHeight);
|
||||||
|
update();
|
||||||
|
window.addEventListener("resize", update, { passive: true });
|
||||||
|
window.visualViewport?.addEventListener("resize", update, { passive: true });
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener("resize", update);
|
||||||
|
window.visualViewport?.removeEventListener("resize", update);
|
||||||
|
};
|
||||||
|
}, [enabled]);
|
||||||
|
|
||||||
|
return enabled ? getGridRowCountForVisualHeight(visualHeight, canvasScale) : 0;
|
||||||
|
};
|
||||||
|
|
||||||
const getContainerMinimumSize = (
|
const getContainerMinimumSize = (
|
||||||
board: ReturnType<typeof useRequiredBoard>,
|
board: ReturnType<typeof useRequiredBoard>,
|
||||||
layoutId: string,
|
layoutId: string,
|
||||||
|
|||||||
@@ -27,6 +27,7 @@ describe("board grid import boundary", () => {
|
|||||||
{ file: "components/board/sections/grid/grid-editor.tsx", kind: "static", specifier: "@dnd-kit/abstract" },
|
{ file: "components/board/sections/grid/grid-editor.tsx", kind: "static", specifier: "@dnd-kit/abstract" },
|
||||||
{ file: "components/board/sections/grid/grid-editor.tsx", kind: "static", specifier: "@dnd-kit/collision" },
|
{ file: "components/board/sections/grid/grid-editor.tsx", kind: "static", specifier: "@dnd-kit/collision" },
|
||||||
{ file: "components/board/sections/grid/grid-editor.tsx", kind: "static", specifier: "@dnd-kit/dom" },
|
{ file: "components/board/sections/grid/grid-editor.tsx", kind: "static", specifier: "@dnd-kit/dom" },
|
||||||
|
{ file: "components/board/sections/grid/grid-editor.tsx", kind: "static", specifier: "@dnd-kit/dom/modifiers" },
|
||||||
{ file: "components/board/sections/grid/grid-editor.tsx", kind: "static", specifier: "@dnd-kit/dom/utilities" },
|
{ file: "components/board/sections/grid/grid-editor.tsx", kind: "static", specifier: "@dnd-kit/dom/utilities" },
|
||||||
{ file: "components/board/sections/grid/grid-editor.tsx", kind: "static", specifier: "@dnd-kit/react" },
|
{ file: "components/board/sections/grid/grid-editor.tsx", kind: "static", specifier: "@dnd-kit/react" },
|
||||||
]);
|
]);
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ import { useState } from "react";
|
|||||||
import { Button, Modal } from "@mantine/core";
|
import { Button, Modal } from "@mantine/core";
|
||||||
import { IconDownload } from "@tabler/icons-react";
|
import { IconDownload } from "@tabler/icons-react";
|
||||||
|
|
||||||
|
import { modalSizeSelect } from "@homarr/modals";
|
||||||
|
|
||||||
import { WorkshopBrowser } from "./workshop-browser";
|
import { WorkshopBrowser } from "./workshop-browser";
|
||||||
|
|
||||||
export function WorkshopCssImportButton({ onImport }: { onImport(css: string): void }) {
|
export function WorkshopCssImportButton({ onImport }: { onImport(css: string): void }) {
|
||||||
@@ -14,7 +16,7 @@ export function WorkshopCssImportButton({ onImport }: { onImport(css: string): v
|
|||||||
<Button type="button" variant="light" leftSection={<IconDownload size={16} />} onClick={() => setOpened(true)}>
|
<Button type="button" variant="light" leftSection={<IconDownload size={16} />} onClick={() => setOpened(true)}>
|
||||||
Import from Workshop
|
Import from Workshop
|
||||||
</Button>
|
</Button>
|
||||||
<Modal opened={opened} onClose={() => setOpened(false)} title="Import Custom CSS" size="xl">
|
<Modal opened={opened} onClose={() => setOpened(false)} title="Import Custom CSS" size={modalSizeSelect}>
|
||||||
<WorkshopBrowser
|
<WorkshopBrowser
|
||||||
type="customCss"
|
type="customCss"
|
||||||
onUseCss={(css) => {
|
onUseCss={(css) => {
|
||||||
|
|||||||
@@ -130,7 +130,11 @@ describe("Board advanced interactions", () => {
|
|||||||
await interactivePreviewProbe.evaluate((element) => element.remove());
|
await interactivePreviewProbe.evaluate((element) => element.remove());
|
||||||
await page.mouse.move(compactBounds.x + 4, compactBounds.y + 4);
|
await page.mouse.move(compactBounds.x + 4, compactBounds.y + 4);
|
||||||
await page.mouse.move(otherBounds.x + otherBounds.width / 2, otherBounds.y + otherBounds.height / 2);
|
await page.mouse.move(otherBounds.x + otherBounds.width / 2, otherBounds.y + otherBounds.height / 2);
|
||||||
|
await expect(previewSurface).toBeVisible();
|
||||||
|
await expect(bookmarksPreviewSurface).toBeHidden();
|
||||||
|
await page.mouse.move(4, 4);
|
||||||
await expect(previewSurface).toBeHidden();
|
await expect(previewSurface).toBeHidden();
|
||||||
|
await otherWidget.hover({ position: { x: 4, y: 4 } });
|
||||||
await expect(bookmarksPreviewSurface).toBeVisible({ timeout: 2_000 });
|
await expect(bookmarksPreviewSurface).toBeVisible({ timeout: 2_000 });
|
||||||
await page.keyboard.up("Shift");
|
await page.keyboard.up("Shift");
|
||||||
await expect(bookmarksPreviewSurface).toBeHidden();
|
await expect(bookmarksPreviewSurface).toBeHidden();
|
||||||
|
|||||||
+72
-52
@@ -6,11 +6,7 @@ import { createId } from "@paralleldrive/cuid2";
|
|||||||
import { stringify as stringifySuperJSON } from "superjson";
|
import { stringify as stringifySuperJSON } from "superjson";
|
||||||
import { describe, test } from "vitest";
|
import { describe, test } from "vitest";
|
||||||
|
|
||||||
import {
|
import { LOGICAL_GRID_CELL_SIZE, LOGICAL_GRID_GAP } from "../apps/nextjs/src/components/board/layout/constants";
|
||||||
LOGICAL_GRID_CELL_SIZE,
|
|
||||||
LOGICAL_GRID_GAP,
|
|
||||||
MIN_ACCESSIBLE_CANVAS_SCALE,
|
|
||||||
} from "../apps/nextjs/src/components/board/layout/constants";
|
|
||||||
import * as sqliteSchema from "../packages/db/schema/sqlite";
|
import * as sqliteSchema from "../packages/db/schema/sqlite";
|
||||||
import { createHomarrContainer } from "./shared/create-homarr-container";
|
import { createHomarrContainer } from "./shared/create-homarr-container";
|
||||||
import { createSqliteDbFileAsync } from "./shared/e2e-db";
|
import { createSqliteDbFileAsync } from "./shared/e2e-db";
|
||||||
@@ -26,7 +22,6 @@ const gridRuntimeMarker = "homarr-dnd-kit-v1";
|
|||||||
const dndKitPayloadMarker = "dnd-kit-description";
|
const dndKitPayloadMarker = "dnd-kit-description";
|
||||||
const logicalCellSize = LOGICAL_GRID_CELL_SIZE;
|
const logicalCellSize = LOGICAL_GRID_CELL_SIZE;
|
||||||
const logicalCellPitch = LOGICAL_GRID_CELL_SIZE + LOGICAL_GRID_GAP;
|
const logicalCellPitch = LOGICAL_GRID_CELL_SIZE + LOGICAL_GRID_GAP;
|
||||||
const minimumCanvasScale = MIN_ACCESSIBLE_CANVAS_SCALE;
|
|
||||||
|
|
||||||
describe("Board grid", () => {
|
describe("Board grid", () => {
|
||||||
test("supports fixed, nested, rail, pointer, keyboard and reconciliation workflows", async () => {
|
test("supports fixed, nested, rail, pointer, keyboard and reconciliation workflows", async () => {
|
||||||
@@ -100,6 +95,11 @@ describe("Board grid", () => {
|
|||||||
await expect(rail).toBeVisible();
|
await expect(rail).toBeVisible();
|
||||||
await expect(rail).toHaveAttribute("data-board-gutter", "left");
|
await expect(rail).toHaveAttribute("data-board-gutter", "left");
|
||||||
await expect(railRootSection).toHaveAttribute("data-rail-placement", "left");
|
await expect(railRootSection).toHaveAttribute("data-rail-placement", "left");
|
||||||
|
await expect(rail).toHaveCSS("overflow-x", "hidden");
|
||||||
|
const initialRailBox = await expectBoundingBoxAsync(rail);
|
||||||
|
const initialRailRootBox = await expectBoundingBoxAsync(railRootSection);
|
||||||
|
expect(initialRailRootBox.width).toBeCloseTo(initialRailBox.width, 1);
|
||||||
|
expect(initialRailRootBox.height).toBeGreaterThanOrEqual(initialRailBox.height - 1);
|
||||||
await expect(railItem).toHaveAttribute("data-grid-x", "0");
|
await expect(railItem).toHaveAttribute("data-grid-x", "0");
|
||||||
await expect(containerSection).toHaveAttribute("data-grid-w", "2");
|
await expect(containerSection).toHaveAttribute("data-grid-w", "2");
|
||||||
await expect(containerSection).toHaveAttribute("data-grid-h", "2");
|
await expect(containerSection).toHaveAttribute("data-grid-h", "2");
|
||||||
@@ -174,21 +174,15 @@ describe("Board grid", () => {
|
|||||||
expect(await readLayoutShiftScoreAsync(page)).toBeLessThan(0.01);
|
expect(await readLayoutShiftScoreAsync(page)).toBeLessThan(0.01);
|
||||||
|
|
||||||
// CSS zoom exercises Chromium's browser-zoom layout path without relying
|
// CSS zoom exercises Chromium's browser-zoom layout path without relying
|
||||||
// on desktop browser chrome. At 200% the scale floor must preserve
|
// on desktop browser chrome. The board must keep fitting without adding
|
||||||
// magnification and expose horizontal scrolling instead of shrinking the
|
// horizontal scrolling at any effective zoom.
|
||||||
// board by the inverse zoom factor.
|
|
||||||
await setDocumentZoomAsync(page, 2);
|
await setDocumentZoomAsync(page, 2);
|
||||||
await expect(canvas).toHaveAttribute("data-canvas-scale", String(minimumCanvasScale));
|
const zoomedCanvasScale = await readCanvasScaleAsync(canvas);
|
||||||
await expect(canvas).toHaveAttribute("data-canvas-overflow", "true");
|
expect(zoomedCanvasScale).toBeLessThan(normalCanvasScale);
|
||||||
|
await expect(canvas).toHaveAttribute("data-canvas-overflow", "false");
|
||||||
await expectFixedLogicalTileAsync(logicalTile);
|
await expectFixedLogicalTileAsync(logicalTile);
|
||||||
await expectUniformVisualScaleAsync(logicalTile);
|
await expectUniformVisualScaleAsync(logicalTile);
|
||||||
const fittedClockFontSize = await firstItem.locator(".clock-time-text").evaluate((element) => {
|
await expect(canvas).toHaveCSS("overflow-x", "clip");
|
||||||
return Number.parseFloat(getComputedStyle(element).fontSize);
|
|
||||||
});
|
|
||||||
expect(fittedClockFontSize * minimumCanvasScale).toBeGreaterThanOrEqual(25);
|
|
||||||
const zoomedTileBox = await expectBoundingBoxAsync(logicalTile);
|
|
||||||
expect(zoomedTileBox.width).toBeGreaterThan(normalZoomTileBox.width * 1.25);
|
|
||||||
await expectHorizontalOverflowAsync(canvas);
|
|
||||||
await expectDocumentNotHorizontallyScrollableAsync(page);
|
await expectDocumentNotHorizontallyScrollableAsync(page);
|
||||||
const overflowRailY = (await expectBoundingBoxAsync(rail)).y;
|
const overflowRailY = (await expectBoundingBoxAsync(rail)).y;
|
||||||
await page.evaluate(() => window.scrollTo({ top: 300, behavior: "auto" }));
|
await page.evaluate(() => window.scrollTo({ top: 300, behavior: "auto" }));
|
||||||
@@ -251,6 +245,14 @@ describe("Board grid", () => {
|
|||||||
await expect(page.locator(`[data-grid-runtime="${gridRuntimeMarker}"]`)).toHaveCount(3);
|
await expect(page.locator(`[data-grid-runtime="${gridRuntimeMarker}"]`)).toHaveCount(3);
|
||||||
await expect(page.getByTestId("board-grid-editor-loading")).toHaveCount(0);
|
await expect(page.getByTestId("board-grid-editor-loading")).toHaveCount(0);
|
||||||
await expect(page.getByTestId("board-canvas-row-count-button")).toHaveCount(0);
|
await expect(page.getByTestId("board-canvas-row-count-button")).toHaveCount(0);
|
||||||
|
await expect(rail).toHaveAttribute("data-board-editing", "true");
|
||||||
|
await expect(rail).toHaveCSS("position", "sticky");
|
||||||
|
await expect(rail).toHaveCSS("transform", "none");
|
||||||
|
const railBox = await expectBoundingBoxAsync(rail);
|
||||||
|
expect(railBox.height + railBox.y).toBeCloseTo(page.viewportSize()?.height ?? 0, 0);
|
||||||
|
expect(await rail.evaluate((element) => getComputedStyle(element, "::before").content.replaceAll('"', ""))).toBe(
|
||||||
|
"Left dashboard rail",
|
||||||
|
);
|
||||||
await expect(logicalTile).toHaveCSS("overflow-x", "hidden");
|
await expect(logicalTile).toHaveCSS("overflow-x", "hidden");
|
||||||
await expect(logicalTile).toHaveCSS("overflow-y", "auto");
|
await expect(logicalTile).toHaveCSS("overflow-y", "auto");
|
||||||
await logicalTile.evaluate((element) => {
|
await logicalTile.evaluate((element) => {
|
||||||
@@ -337,8 +339,11 @@ describe("Board grid", () => {
|
|||||||
await expect(itemSelectDialog).toHaveCount(0);
|
await expect(itemSelectDialog).toHaveCount(0);
|
||||||
|
|
||||||
const mainGrid = page.locator(`[data-grid-section-id="${fixture.sectionId}"]`);
|
const mainGrid = page.locator(`[data-grid-section-id="${fixture.sectionId}"]`);
|
||||||
|
const editorViewport = page.viewportSize();
|
||||||
|
if (!editorViewport) throw new Error("Expected a browser viewport");
|
||||||
|
expect((await expectBoundingBoxAsync(mainGrid)).height).toBeGreaterThanOrEqual(editorViewport.height - 1);
|
||||||
const interactionSnapshot = await readEditorGridSnapshotAsync(mainGrid);
|
const interactionSnapshot = await readEditorGridSnapshotAsync(mainGrid);
|
||||||
await expectGridBoundaryRejectsOverflowAsync(page, mainGrid, firstItem);
|
await expectGridGrowsAtBoundaryAsync(page, canvas, mainGrid, firstItem);
|
||||||
await firstItem.locator("[data-grid-item-content]").evaluate((element) => {
|
await firstItem.locator("[data-grid-item-content]").evaluate((element) => {
|
||||||
const iframe = document.createElement("iframe");
|
const iframe = document.createElement("iframe");
|
||||||
iframe.dataset.e2eDragIframe = "true";
|
iframe.dataset.e2eDragIframe = "true";
|
||||||
@@ -367,8 +372,8 @@ describe("Board grid", () => {
|
|||||||
.evaluateAll((elements) => elements.forEach((element) => element.remove()));
|
.evaluateAll((elements) => elements.forEach((element) => element.remove()));
|
||||||
|
|
||||||
await page.setViewportSize({ width: 600, height: 1200 });
|
await page.setViewportSize({ width: 600, height: 1200 });
|
||||||
await expect(canvas).toHaveAttribute("data-canvas-scale", String(minimumCanvasScale));
|
await expect(canvas).toHaveAttribute("data-canvas-overflow", "false");
|
||||||
await expectHorizontalOverflowAsync(canvas);
|
await expect(canvas).toHaveCSS("overflow-x", "clip");
|
||||||
await expectDocumentNotHorizontallyScrollableAsync(page);
|
await expectDocumentNotHorizontallyScrollableAsync(page);
|
||||||
for (const direction of ["n", "ne", "e", "se", "s", "sw", "w", "nw"] as const) {
|
for (const direction of ["n", "ne", "e", "se", "s", "sw", "w", "nw"] as const) {
|
||||||
await expectTargetSizeAsync(firstItem.locator(`:scope > [data-grid-resize-handle="${direction}"]`));
|
await expectTargetSizeAsync(firstItem.locator(`:scope > [data-grid-resize-handle="${direction}"]`));
|
||||||
@@ -718,13 +723,12 @@ describe("Board grid", () => {
|
|||||||
expect(continuousResizeWidth).toBeGreaterThan(logicalCellSize * canvasScale);
|
expect(continuousResizeWidth).toBeGreaterThan(logicalCellSize * canvasScale);
|
||||||
|
|
||||||
await page.mouse.move(eastResizeStart.x - logicalCellPitch * canvasScale, eastResizeStart.y, { steps: 6 });
|
await page.mouse.move(eastResizeStart.x - logicalCellPitch * canvasScale, eastResizeStart.y, { steps: 6 });
|
||||||
await expect(containerSection).toHaveAttribute("data-grid-w", "2");
|
await expect(containerSection).toHaveAttribute("data-grid-w", "1");
|
||||||
await expect(resizePlaceholder).toHaveAttribute("data-grid-w", "1");
|
await expect(resizePlaceholder).toHaveAttribute("data-grid-w", "1");
|
||||||
expect((await expectBoundingBoxAsync(resizeOutline)).width).toBeCloseTo(logicalCellSize * canvasScale, 1);
|
expect((await expectBoundingBoxAsync(resizeOutline)).width).toBeCloseTo(logicalCellSize * canvasScale, 1);
|
||||||
const liveNestedGridBox = await expectBoundingBoxAsync(nestedEditor);
|
|
||||||
const liveContainerBox = await expectBoundingBoxAsync(containerSection);
|
const liveContainerBox = await expectBoundingBoxAsync(containerSection);
|
||||||
expect(liveNestedGridBox.width).toBeCloseTo(originalResizeWidth, 1);
|
expect(liveContainerBox.width).toBeCloseTo(logicalCellSize * canvasScale, 1);
|
||||||
expect(liveNestedGridBox.width).toBeLessThanOrEqual(liveContainerBox.width + 1);
|
await expect(containerSection.locator(":scope > .board-grid-content-mount")).toHaveCSS("overflow", "clip");
|
||||||
await page.mouse.up();
|
await page.mouse.up();
|
||||||
await expect(containerSection).toHaveAttribute("data-grid-w", "1");
|
await expect(containerSection).toHaveAttribute("data-grid-w", "1");
|
||||||
await expect(resizeOutline).toHaveCount(0);
|
await expect(resizeOutline).toHaveCount(0);
|
||||||
@@ -759,15 +763,26 @@ describe("Board grid", () => {
|
|||||||
await expect(containerSection).toHaveAttribute("data-grid-h", "2");
|
await expect(containerSection).toHaveAttribute("data-grid-h", "2");
|
||||||
|
|
||||||
const southResizeHandle = containerSection.locator(':scope > [data-grid-resize-handle="s"]');
|
const southResizeHandle = containerSection.locator(':scope > [data-grid-resize-handle="s"]');
|
||||||
await dragLocatorByAsync(page, southResizeHandle, 0, logicalCellPitch * canvasScale);
|
const gridHeightBeforeSouthResize = (await expectBoundingBoxAsync(mainGrid)).height;
|
||||||
|
const southResizeBox = await expectBoundingBoxAsync(southResizeHandle);
|
||||||
|
const southResizeStart = {
|
||||||
|
x: southResizeBox.x + southResizeBox.width / 2,
|
||||||
|
y: southResizeBox.y + southResizeBox.height / 2,
|
||||||
|
};
|
||||||
|
await page.mouse.move(southResizeStart.x, southResizeStart.y);
|
||||||
|
await page.mouse.down();
|
||||||
|
await page.mouse.move(southResizeStart.x, southResizeStart.y + logicalCellPitch * canvasScale, { steps: 8 });
|
||||||
await expect(containerSection).toHaveAttribute("data-grid-h", "3");
|
await expect(containerSection).toHaveAttribute("data-grid-h", "3");
|
||||||
await expect(belowItem).toHaveAttribute("data-grid-y", "3");
|
await expect(belowItem).toHaveAttribute("data-grid-y", "3");
|
||||||
|
await expect
|
||||||
|
.poll(async () => (await expectBoundingBoxAsync(mainGrid)).height)
|
||||||
|
.toBeGreaterThanOrEqual(gridHeightBeforeSouthResize);
|
||||||
|
await page.mouse.up();
|
||||||
expect(
|
expect(
|
||||||
gridLayoutsOverlap(await readGridLayoutAsync(containerSection), await readGridLayoutAsync(belowItem)),
|
gridLayoutsOverlap(await readGridLayoutAsync(containerSection), await readGridLayoutAsync(belowItem)),
|
||||||
).toBe(false);
|
).toBe(false);
|
||||||
|
|
||||||
// Auto-scroll needs real document overflow. Grow the canvas through an
|
// Grow the canvas further to exercise sustained document auto-scroll.
|
||||||
// explicit resize instead of relying on edit mode to add empty rows.
|
|
||||||
await dragLocatorByAsync(page, southResizeHandle, 0, logicalCellPitch * canvasScale * 6);
|
await dragLocatorByAsync(page, southResizeHandle, 0, logicalCellPitch * canvasScale * 6);
|
||||||
await expect(containerSection).toHaveAttribute("data-grid-h", "9");
|
await expect(containerSection).toHaveAttribute("data-grid-h", "9");
|
||||||
await expect(belowItem).toHaveAttribute("data-grid-y", "9");
|
await expect(belowItem).toHaveAttribute("data-grid-y", "9");
|
||||||
@@ -843,14 +858,10 @@ describe("Board grid", () => {
|
|||||||
false,
|
false,
|
||||||
);
|
);
|
||||||
|
|
||||||
const stickyRailY = (await expectBoundingBoxAsync(rail)).y;
|
|
||||||
await page.evaluate(() => window.scrollTo({ top: 500, behavior: "auto" }));
|
await page.evaluate(() => window.scrollTo({ top: 500, behavior: "auto" }));
|
||||||
await expect
|
const stickyRailY = (await expectBoundingBoxAsync(rail)).y;
|
||||||
.poll(async () => {
|
await page.evaluate(() => window.scrollTo({ top: 600, behavior: "auto" }));
|
||||||
const y = (await expectBoundingBoxAsync(rail)).y;
|
await expect.poll(async () => (await expectBoundingBoxAsync(rail)).y).toBeCloseTo(stickyRailY, 0);
|
||||||
return y >= 0 && y <= stickyRailY + 0.5;
|
|
||||||
})
|
|
||||||
.toBe(true);
|
|
||||||
await page.evaluate(() => window.scrollTo({ top: 0, behavior: "auto" }));
|
await page.evaluate(() => window.scrollTo({ top: 0, behavior: "auto" }));
|
||||||
|
|
||||||
await setDocumentZoomAsync(page, 1.25);
|
await setDocumentZoomAsync(page, 1.25);
|
||||||
@@ -979,6 +990,15 @@ describe("Board grid", () => {
|
|||||||
const emptyRightGutter = page.getByRole("complementary", { name: "Right dashboard rail" });
|
const emptyRightGutter = page.getByRole("complementary", { name: "Right dashboard rail" });
|
||||||
await expect(emptyRightGutter).toHaveCount(1);
|
await expect(emptyRightGutter).toHaveCount(1);
|
||||||
expect((await expectBoundingBoxAsync(emptyRightGutter)).width).toBeGreaterThan(0);
|
expect((await expectBoundingBoxAsync(emptyRightGutter)).width).toBeGreaterThan(0);
|
||||||
|
await page.getByTestId("board-edit-mode-toggle").click();
|
||||||
|
await expect(emptyRightGutter).toHaveAttribute("data-board-editing", "true");
|
||||||
|
expect(
|
||||||
|
await emptyRightGutter.evaluate((element) => ({
|
||||||
|
content: getComputedStyle(element, "::before").content.replaceAll('"', ""),
|
||||||
|
insetInlineStart: getComputedStyle(element, "::before").insetInlineStart,
|
||||||
|
top: getComputedStyle(element, "::before").top,
|
||||||
|
})),
|
||||||
|
).toEqual({ content: "Right dashboard rail", insetInlineStart: "0px", top: "0px" });
|
||||||
expect(pageErrors).toEqual([]);
|
expect(pageErrors).toEqual([]);
|
||||||
} finally {
|
} finally {
|
||||||
runtimeResources?.stop();
|
runtimeResources?.stop();
|
||||||
@@ -1713,9 +1733,10 @@ const expectImmediateOutsideReleaseRestoresSnapshotAsync = async (page: Page, gr
|
|||||||
await expect.poll(async () => await readEditorGridSnapshotAsync(grid)).toEqual(snapshot);
|
await expect.poll(async () => await readEditorGridSnapshotAsync(grid)).toEqual(snapshot);
|
||||||
};
|
};
|
||||||
|
|
||||||
const expectGridBoundaryRejectsOverflowAsync = async (page: Page, grid: Locator, locator: Locator) => {
|
const expectGridGrowsAtBoundaryAsync = async (page: Page, canvas: Locator, grid: Locator, locator: Locator) => {
|
||||||
const snapshot = await readEditorGridSnapshotAsync(grid);
|
const snapshot = await readEditorGridSnapshotAsync(grid);
|
||||||
const gridBox = await expectBoundingBoxAsync(grid);
|
const gridBox = await expectBoundingBoxAsync(grid);
|
||||||
|
const canvasBox = await expectBoundingBoxAsync(canvas);
|
||||||
const itemBox = await expectBoundingBoxAsync(locator);
|
const itemBox = await expectBoundingBoxAsync(locator);
|
||||||
const start = { x: itemBox.x + itemBox.width * 0.63, y: itemBox.y + itemBox.height * 0.42 };
|
const start = { x: itemBox.x + itemBox.width * 0.63, y: itemBox.y + itemBox.height * 0.42 };
|
||||||
|
|
||||||
@@ -1723,14 +1744,25 @@ const expectGridBoundaryRejectsOverflowAsync = async (page: Page, grid: Locator,
|
|||||||
await page.mouse.down();
|
await page.mouse.down();
|
||||||
await page.mouse.move(start.x + 8, start.y);
|
await page.mouse.move(start.x + 8, start.y);
|
||||||
await expect(locator).toHaveAttribute("data-dnd-drag-source", "true");
|
await expect(locator).toHaveAttribute("data-dnd-drag-source", "true");
|
||||||
await page.mouse.move(gridBox.x + gridBox.width / 2, gridBox.y + gridBox.height + logicalCellPitch, { steps: 12 });
|
await expect.poll(async () => (await expectBoundingBoxAsync(grid)).height).toBeGreaterThan(gridBox.height);
|
||||||
await expect(page.locator("[data-grid-placeholder-for]")).toHaveCount(0);
|
|
||||||
const activeGridBox = await expectBoundingBoxAsync(grid);
|
|
||||||
expect(activeGridBox.height).toBeCloseTo(gridBox.height, 1);
|
|
||||||
|
|
||||||
|
await page.mouse.move(gridBox.x + gridBox.width / 2, gridBox.y + gridBox.height + logicalCellPitch / 2, {
|
||||||
|
steps: 12,
|
||||||
|
});
|
||||||
|
await expect(page.locator("[data-grid-placeholder-for]")).toHaveCount(1);
|
||||||
|
const activeGridBox = await expectBoundingBoxAsync(grid);
|
||||||
|
expect(activeGridBox.height).toBeGreaterThan(gridBox.height);
|
||||||
|
|
||||||
|
await page.mouse.move(canvasBox.x + canvasBox.width + 1000, start.y, { steps: 12 });
|
||||||
|
const overlayBox = await expectBoundingBoxAsync(page.locator(".board-grid-drag-overlay[data-dnd-dragging]"));
|
||||||
|
expect(overlayBox.x + overlayBox.width).toBeLessThanOrEqual(canvasBox.x + canvasBox.width + 1);
|
||||||
|
|
||||||
|
await page.keyboard.press("Escape");
|
||||||
await page.mouse.up();
|
await page.mouse.up();
|
||||||
await expect(page.locator("body")).not.toHaveAttribute("data-board-grid-interacting");
|
await expect(page.locator("body")).not.toHaveAttribute("data-board-grid-interacting");
|
||||||
await expect.poll(async () => await readEditorGridSnapshotAsync(grid)).toEqual(snapshot);
|
await expect.poll(async () => await readEditorGridSnapshotAsync(grid)).toEqual(snapshot);
|
||||||
|
await locator.evaluate((element) => element.scrollIntoView({ block: "center", behavior: "instant" }));
|
||||||
|
await expectGridEntryGeometrySettledAsync(locator);
|
||||||
};
|
};
|
||||||
|
|
||||||
const expectInvalidNestedDropRestoresSnapshotAsync = async (
|
const expectInvalidNestedDropRestoresSnapshotAsync = async (
|
||||||
@@ -2036,18 +2068,6 @@ const expectUniformVisualScaleAsync = async (locator: Locator) => {
|
|||||||
expect(scale.horizontal).toBeCloseTo(scale.vertical, 3);
|
expect(scale.horizontal).toBeCloseTo(scale.vertical, 3);
|
||||||
};
|
};
|
||||||
|
|
||||||
const expectHorizontalOverflowAsync = async (locator: Locator) => {
|
|
||||||
const dimensions = await locator.evaluate((element) => {
|
|
||||||
const htmlElement = element as HTMLElement;
|
|
||||||
return {
|
|
||||||
clientWidth: htmlElement.clientWidth,
|
|
||||||
scrollWidth: htmlElement.scrollWidth,
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(dimensions.scrollWidth).toBeGreaterThan(dimensions.clientWidth);
|
|
||||||
};
|
|
||||||
|
|
||||||
const expectDocumentNotHorizontallyScrollableAsync = async (page: Page) => {
|
const expectDocumentNotHorizontallyScrollableAsync = async (page: Page) => {
|
||||||
await expect
|
await expect
|
||||||
.poll(
|
.poll(
|
||||||
|
|||||||
@@ -0,0 +1,22 @@
|
|||||||
|
import { TRPCError } from "@trpc/server";
|
||||||
|
import { z } from "zod/v4";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Authoring inputs that use templateLines can only validate the joined JSX after the tRPC input
|
||||||
|
* parser has run. Preserve those Zod issues as a client-safe BAD_REQUEST instead of letting tRPC
|
||||||
|
* turn them into a generic internal error.
|
||||||
|
*/
|
||||||
|
export function parseCustomWidgetAuthoringInput<T>(parse: () => T): T {
|
||||||
|
try {
|
||||||
|
return parse();
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof z.ZodError) {
|
||||||
|
throw new TRPCError({
|
||||||
|
code: "BAD_REQUEST",
|
||||||
|
message: "The custom widget authoring input is invalid",
|
||||||
|
cause: error,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -10,9 +10,12 @@ import {
|
|||||||
customWidgetCreateSchema,
|
customWidgetCreateSchema,
|
||||||
customWidgetDefinitionSchema,
|
customWidgetDefinitionSchema,
|
||||||
customWidgetUpdateSchema,
|
customWidgetUpdateSchema,
|
||||||
|
normalizeCustomWidgetAuthoringDefinition,
|
||||||
|
normalizeCustomWidgetAuthoringUpdate,
|
||||||
} from "@homarr/custom-widgets/core";
|
} from "@homarr/custom-widgets/core";
|
||||||
|
|
||||||
import { createTRPCRouter, permissionRequiredProcedure } from "../../trpc";
|
import { createTRPCRouter, permissionRequiredProcedure } from "../../trpc";
|
||||||
|
import { parseCustomWidgetAuthoringInput } from "./authoring-validation";
|
||||||
import { insertCustomWidgetDefinition } from "./definition-insert";
|
import { insertCustomWidgetDefinition } from "./definition-insert";
|
||||||
import { managementQueryProcedures } from "./management-queries";
|
import { managementQueryProcedures } from "./management-queries";
|
||||||
import { metadataProcedures } from "./metadata-procedures";
|
import { metadataProcedures } from "./metadata-procedures";
|
||||||
@@ -38,20 +41,43 @@ export const customWidgetRouter = createTRPCRouter({
|
|||||||
|
|
||||||
create: permissionRequiredProcedure
|
create: permissionRequiredProcedure
|
||||||
.requiresPermission("admin")
|
.requiresPermission("admin")
|
||||||
.meta({ mcp: { enabled: true, description: "Create one validated Custom JSX widget." } })
|
.meta({
|
||||||
|
mcp: {
|
||||||
|
enabled: true,
|
||||||
|
description:
|
||||||
|
"Create a Custom JSX widget only after customWidget_validate, customWidget_previewCreate, and every returned preview query succeed. Prefer templateLines for multiline JSX. Returns a client-navigable edit link.",
|
||||||
|
},
|
||||||
|
})
|
||||||
.input(customWidgetCreateSchema)
|
.input(customWidgetCreateSchema)
|
||||||
.mutation(async ({ ctx, input }) => {
|
.mutation(async ({ ctx, input }) => {
|
||||||
const { secrets, ...candidate } = input;
|
const { secrets, ...candidate } = input;
|
||||||
const definition = customWidgetDefinitionSchema.parse(candidate);
|
const definition = parseCustomWidgetAuthoringInput(() => normalizeCustomWidgetAuthoringDefinition(candidate));
|
||||||
assertSecretSources(definition.sources, secrets);
|
assertSecretSources(definition.sources, secrets);
|
||||||
const id = await insertCustomWidgetDefinition(ctx.db, definition, ctx.session.user.id, secrets);
|
const id = await insertCustomWidgetDefinition(ctx.db, definition, ctx.session.user.id, secrets);
|
||||||
logger.info("Created custom widget definition", { id, name: definition.name });
|
logger.info("Created custom widget definition", { id, name: definition.name });
|
||||||
return { id };
|
return {
|
||||||
|
id,
|
||||||
|
managementPath: `/manage/custom-widgets/edit/${id}`,
|
||||||
|
nextAction: {
|
||||||
|
type: "place-custom-widget" as const,
|
||||||
|
widgetKind: "customApi" as const,
|
||||||
|
options: { definitionId: id },
|
||||||
|
whenTargetIsKnown: "Call configure_widget now with the requested board and these exact widget options.",
|
||||||
|
whenTargetIsUnknown:
|
||||||
|
"Call ask_user now with 'Place on a board' and 'Leave unplaced'. Never ask this choice in prose.",
|
||||||
|
},
|
||||||
|
};
|
||||||
}),
|
}),
|
||||||
|
|
||||||
update: permissionRequiredProcedure
|
update: permissionRequiredProcedure
|
||||||
.requiresPermission("admin")
|
.requiresPermission("admin")
|
||||||
.meta({ mcp: { enabled: true, description: "Update one Custom JSX widget." } })
|
.meta({
|
||||||
|
mcp: {
|
||||||
|
enabled: true,
|
||||||
|
description:
|
||||||
|
"Update one Custom JSX widget. Prefer templateLines for multiline JSX changes. Returns a client-navigable edit link.",
|
||||||
|
},
|
||||||
|
})
|
||||||
.input(customWidgetUpdateSchema)
|
.input(customWidgetUpdateSchema)
|
||||||
.mutation(async ({ ctx, input }) => {
|
.mutation(async ({ ctx, input }) => {
|
||||||
const existing = await ctx.db.query.customWidgetDefinitions.findFirst({
|
const existing = await ctx.db.query.customWidgetDefinitions.findFirst({
|
||||||
@@ -60,8 +86,11 @@ export const customWidgetRouter = createTRPCRouter({
|
|||||||
if (!existing) throw new TRPCError({ code: "NOT_FOUND" });
|
if (!existing) throw new TRPCError({ code: "NOT_FOUND" });
|
||||||
|
|
||||||
const current = parseStoredCustomWidgetDefinition(existing);
|
const current = parseStoredCustomWidgetDefinition(existing);
|
||||||
const { id, secrets, ...changes } = input;
|
const { id, secrets, ...authoringChanges } = input;
|
||||||
const definition = customWidgetDefinitionSchema.parse({ ...current, ...changes });
|
const definition = parseCustomWidgetAuthoringInput(() => {
|
||||||
|
const changes = normalizeCustomWidgetAuthoringUpdate(authoringChanges);
|
||||||
|
return customWidgetDefinitionSchema.parse({ ...current, ...changes });
|
||||||
|
});
|
||||||
if (secrets) assertSecretSources(definition.sources, secrets);
|
if (secrets) assertSecretSources(definition.sources, secrets);
|
||||||
const definitionChanges = { ...serializeCustomWidgetDefinition(definition), updatedAt: new Date() };
|
const definitionChanges = { ...serializeCustomWidgetDefinition(definition), updatedAt: new Date() };
|
||||||
const secretRows = secrets?.map((secret) => ({
|
const secretRows = secrets?.map((secret) => ({
|
||||||
@@ -178,6 +207,7 @@ export const customWidgetRouter = createTRPCRouter({
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
logger.info("Updated custom widget definition", { id });
|
logger.info("Updated custom widget definition", { id });
|
||||||
|
return { id, managementPath: `/manage/custom-widgets/edit/${id}` };
|
||||||
}),
|
}),
|
||||||
|
|
||||||
...secretProcedures,
|
...secretProcedures,
|
||||||
|
|||||||
@@ -65,6 +65,7 @@ export const managementQueryProcedures = {
|
|||||||
if (!definition) throw new TRPCError({ code: "NOT_FOUND", message: "Legacy custom widget not found" });
|
if (!definition) throw new TRPCError({ code: "NOT_FOUND", message: "Legacy custom widget not found" });
|
||||||
return {
|
return {
|
||||||
id: definition.id,
|
id: definition.id,
|
||||||
|
managementPath: "/manage/custom-widgets",
|
||||||
version: 1 as const,
|
version: 1 as const,
|
||||||
prompt: buildLegacyCustomWidgetMigrationPrompt(
|
prompt: buildLegacyCustomWidgetMigrationPrompt(
|
||||||
definition,
|
definition,
|
||||||
@@ -85,6 +86,7 @@ export const managementQueryProcedures = {
|
|||||||
if (!definition) throw new TRPCError({ code: "NOT_FOUND", message: "Custom widget definition not found" });
|
if (!definition) throw new TRPCError({ code: "NOT_FOUND", message: "Custom widget definition not found" });
|
||||||
return {
|
return {
|
||||||
id: definition.id,
|
id: definition.id,
|
||||||
|
managementPath: `/manage/custom-widgets/edit/${definition.id}`,
|
||||||
...parseStoredCustomWidgetDefinition(definition),
|
...parseStoredCustomWidgetDefinition(definition),
|
||||||
enabled: definition.enabled,
|
enabled: definition.enabled,
|
||||||
createdAt: definition.createdAt,
|
createdAt: definition.createdAt,
|
||||||
|
|||||||
@@ -26,6 +26,7 @@ export function mapCustomWidgetListItem(definition: StoredDefinition & { secrets
|
|||||||
});
|
});
|
||||||
return {
|
return {
|
||||||
id: definition.id,
|
id: definition.id,
|
||||||
|
managementPath: `/manage/custom-widgets/edit/${definition.id}`,
|
||||||
name: definition.name,
|
name: definition.name,
|
||||||
description: definition.description ?? undefined,
|
description: definition.description ?? undefined,
|
||||||
iconUrl: definition.iconUrl ?? undefined,
|
iconUrl: definition.iconUrl ?? undefined,
|
||||||
@@ -45,6 +46,7 @@ export function mapCustomWidgetListItem(definition: StoredDefinition & { secrets
|
|||||||
const configuredSecrets = new Set(definition.secrets.map((secret) => `${secret.sourceId}:${secret.kind}`));
|
const configuredSecrets = new Set(definition.secrets.map((secret) => `${secret.sourceId}:${secret.kind}`));
|
||||||
return {
|
return {
|
||||||
id: definition.id,
|
id: definition.id,
|
||||||
|
managementPath: `/manage/custom-widgets/edit/${definition.id}`,
|
||||||
name: widget.name,
|
name: widget.name,
|
||||||
description: widget.description,
|
description: widget.description,
|
||||||
iconUrl: widget.iconUrl,
|
iconUrl: widget.iconUrl,
|
||||||
@@ -71,6 +73,7 @@ export function mapCustomWidgetListItem(definition: StoredDefinition & { secrets
|
|||||||
export function mapLegacyCustomWidgetListItem(definition: LegacyDefinition) {
|
export function mapLegacyCustomWidgetListItem(definition: LegacyDefinition) {
|
||||||
return {
|
return {
|
||||||
id: definition.id,
|
id: definition.id,
|
||||||
|
managementPath: "/manage/custom-widgets",
|
||||||
name: definition.name,
|
name: definition.name,
|
||||||
description: definition.description ?? undefined,
|
description: definition.description ?? undefined,
|
||||||
iconUrl: definition.iconUrl ?? undefined,
|
iconUrl: definition.iconUrl ?? undefined,
|
||||||
|
|||||||
@@ -1,8 +1,19 @@
|
|||||||
|
import { TRPCError } from "@trpc/server";
|
||||||
import { z } from "zod/v4";
|
import { z } from "zod/v4";
|
||||||
|
|
||||||
import { CUSTOM_WIDGET_MCP_AUTHORING_PROMPT } from "@homarr/custom-widgets/authoring-prompt";
|
import { CUSTOM_WIDGET_MCP_AUTHORING_PROMPT } from "@homarr/custom-widgets/authoring-prompt";
|
||||||
import { getCustomWidgetSkill } from "@homarr/custom-widgets/authoring-resources";
|
import {
|
||||||
import { customWidgetImportSchema, getCustomWidgetJsonSchema } from "@homarr/custom-widgets/core";
|
getCustomWidgetComponent,
|
||||||
|
getCustomWidgetComponentCatalog,
|
||||||
|
getCustomWidgetExample,
|
||||||
|
getCustomWidgetSharedProps,
|
||||||
|
getCustomWidgetSkill,
|
||||||
|
} from "@homarr/custom-widgets/authoring-resources";
|
||||||
|
import {
|
||||||
|
customWidgetAuthoringDefinitionSchema,
|
||||||
|
getCustomWidgetJsonSchema,
|
||||||
|
normalizeCustomWidgetAuthoringDefinition,
|
||||||
|
} from "@homarr/custom-widgets/core";
|
||||||
|
|
||||||
import { permissionRequiredProcedure } from "../../trpc";
|
import { permissionRequiredProcedure } from "../../trpc";
|
||||||
|
|
||||||
@@ -28,25 +39,133 @@ export const metadataProcedures = {
|
|||||||
|
|
||||||
getSkill: permissionRequiredProcedure
|
getSkill: permissionRequiredProcedure
|
||||||
.requiresPermission("admin")
|
.requiresPermission("admin")
|
||||||
.meta({ mcp: { enabled: true, description: "Get the portable Homarr Custom Widget skill." } })
|
.meta({
|
||||||
|
mcp: {
|
||||||
|
enabled: true,
|
||||||
|
description:
|
||||||
|
"Load the complete Homarr Custom Widget authoring skill in one response, including SKILL.md and every bundled reference. Call this before authoring, repairing, validating, previewing, or creating a custom widget.",
|
||||||
|
},
|
||||||
|
})
|
||||||
.query(() => getCustomWidgetSkill()),
|
.query(() => getCustomWidgetSkill()),
|
||||||
|
|
||||||
|
getComponentCatalog: permissionRequiredProcedure
|
||||||
|
.requiresPermission("admin")
|
||||||
|
.meta({
|
||||||
|
mcp: {
|
||||||
|
enabled: true,
|
||||||
|
description:
|
||||||
|
"List a compact index of supported Custom JSX component names, categories, shared prop names, safety policies, and example IDs. Fetch only the named details needed for the widget.",
|
||||||
|
},
|
||||||
|
})
|
||||||
|
.query(() => getCustomWidgetComponentCatalog()),
|
||||||
|
|
||||||
|
getComponent: permissionRequiredProcedure
|
||||||
|
.requiresPermission("admin")
|
||||||
|
.meta({
|
||||||
|
mcp: {
|
||||||
|
enabled: true,
|
||||||
|
description:
|
||||||
|
"Get the installed Custom JSX documentation, allowed props, blocked props, and accessibility requirements for one named component.",
|
||||||
|
},
|
||||||
|
})
|
||||||
|
.input(z.object({ name: z.string().trim().min(1).max(128).describe("A component name from the catalog.") }))
|
||||||
|
.query(({ input }) => {
|
||||||
|
const component = getCustomWidgetComponent(input.name);
|
||||||
|
if (!component) throw new TRPCError({ code: "NOT_FOUND", message: "Custom JSX component not found" });
|
||||||
|
return component;
|
||||||
|
}),
|
||||||
|
|
||||||
|
getSharedProps: permissionRequiredProcedure
|
||||||
|
.requiresPermission("admin")
|
||||||
|
.meta({
|
||||||
|
mcp: {
|
||||||
|
enabled: true,
|
||||||
|
description:
|
||||||
|
"Get documentation for only the named shared Custom JSX props. Collect the shared prop names needed by all selected components and fetch them together once.",
|
||||||
|
},
|
||||||
|
})
|
||||||
|
.input(
|
||||||
|
z.object({
|
||||||
|
names: z
|
||||||
|
.array(z.string().trim().min(1).max(128))
|
||||||
|
.min(1)
|
||||||
|
.max(64)
|
||||||
|
.describe("Shared prop names from customWidget_getComponentCatalog.sharedProps.names."),
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.query(({ input }) => getCustomWidgetSharedProps(input.names)),
|
||||||
|
|
||||||
|
getExample: permissionRequiredProcedure
|
||||||
|
.requiresPermission("admin")
|
||||||
|
.meta({
|
||||||
|
mcp: {
|
||||||
|
enabled: true,
|
||||||
|
description:
|
||||||
|
"Get one installed Custom JSX example by its catalog ID. Fetch only an example relevant to the requested interaction pattern.",
|
||||||
|
},
|
||||||
|
})
|
||||||
|
.input(z.object({ name: z.string().trim().min(1).max(128).describe("An example ID from the catalog.") }))
|
||||||
|
.query(({ input }) => {
|
||||||
|
const example = getCustomWidgetExample(input.name);
|
||||||
|
if (!example) throw new TRPCError({ code: "NOT_FOUND", message: "Custom JSX example not found" });
|
||||||
|
return example;
|
||||||
|
}),
|
||||||
|
|
||||||
validate: permissionRequiredProcedure
|
validate: permissionRequiredProcedure
|
||||||
.requiresPermission("admin")
|
.requiresPermission("admin")
|
||||||
.meta({ mcp: { enabled: true, description: "Validate one Custom JSX widget without saving it." } })
|
.meta({
|
||||||
.input(z.object({ widget: z.unknown() }))
|
mcp: {
|
||||||
|
enabled: true,
|
||||||
|
description:
|
||||||
|
"Validate one complete Custom JSX widget without saving it. Multiline JSX may be supplied as templateLines; the result returns precise issue paths to repair before previewing.",
|
||||||
|
},
|
||||||
|
})
|
||||||
|
.input(
|
||||||
|
z.object({
|
||||||
|
widget: z
|
||||||
|
.unknown()
|
||||||
|
.describe("A complete Homarr Custom Widget v2 definition using either template or templateLines."),
|
||||||
|
}),
|
||||||
|
)
|
||||||
.query(({ input }) => {
|
.query(({ input }) => {
|
||||||
const result = customWidgetImportSchema.safeParse(input.widget);
|
const authoringResult = customWidgetAuthoringDefinitionSchema.safeParse(input.widget);
|
||||||
if (!result.success) {
|
if (!authoringResult.success) {
|
||||||
return {
|
return {
|
||||||
valid: false as const,
|
valid: false as const,
|
||||||
issues: result.error.issues.map((issue) => ({
|
issues: authoringResult.error.issues.map((issue) => ({
|
||||||
path: issue.path.map(String).join("."),
|
path: issue.path.map(String).join("."),
|
||||||
code: issue.code,
|
code: issue.code,
|
||||||
message: issue.message,
|
message: issue.message,
|
||||||
})),
|
})),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
return { valid: true as const, issues: [], widget: result.data };
|
try {
|
||||||
|
const widget = normalizeCustomWidgetAuthoringDefinition(authoringResult.data);
|
||||||
|
return {
|
||||||
|
valid: true as const,
|
||||||
|
issues: [],
|
||||||
|
summary: {
|
||||||
|
name: widget.name,
|
||||||
|
sourceIds: Object.keys(widget.sources),
|
||||||
|
requestIds: Object.keys(widget.requests),
|
||||||
|
optionIds: Object.keys(widget.options),
|
||||||
|
templateLineCount: widget.template.split("\n").length,
|
||||||
|
},
|
||||||
|
nextStep:
|
||||||
|
"Reuse the validated authoring definition with customWidget_previewCreate, then run every returned query.",
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof z.ZodError) {
|
||||||
|
return {
|
||||||
|
valid: false as const,
|
||||||
|
issues: error.issues.map((issue) => ({
|
||||||
|
path: issue.path.map(String).join("."),
|
||||||
|
code: issue.code,
|
||||||
|
message: issue.message,
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
}),
|
}),
|
||||||
};
|
};
|
||||||
@@ -3,22 +3,25 @@ import { z } from "zod/v4";
|
|||||||
|
|
||||||
import { decryptSecret } from "@homarr/common/server";
|
import { decryptSecret } from "@homarr/common/server";
|
||||||
import {
|
import {
|
||||||
customWidgetDefinitionSchema,
|
collectCustomWidgetRequestReferences,
|
||||||
|
customWidgetAuthoringDefinitionSchema,
|
||||||
customWidgetSecretsInputSchema,
|
customWidgetSecretsInputSchema,
|
||||||
getCustomWidgetConfirmation,
|
getCustomWidgetConfirmation,
|
||||||
getCustomWidgetDefaultOptions,
|
getCustomWidgetDefaultOptions,
|
||||||
|
normalizeCustomWidgetAuthoringDefinition,
|
||||||
validateCustomWidgetOptions,
|
validateCustomWidgetOptions,
|
||||||
} from "@homarr/custom-widgets/core";
|
} from "@homarr/custom-widgets/core";
|
||||||
import { eq } from "@homarr/db";
|
import { eq } from "@homarr/db";
|
||||||
import { customWidgetDefinitions } from "@homarr/db/schema";
|
import { customWidgetDefinitions } from "@homarr/db/schema";
|
||||||
|
|
||||||
import { permissionRequiredProcedure } from "../../trpc";
|
import { permissionRequiredProcedure } from "../../trpc";
|
||||||
|
import { parseCustomWidgetAuthoringInput } from "./authoring-validation";
|
||||||
import { createPreviewSession, getPreviewSession } from "./preview-sessions";
|
import { createPreviewSession, getPreviewSession } from "./preview-sessions";
|
||||||
import { hasSameSecretBinding, requiredSecretKinds } from "./secret-policy";
|
import { hasSameSecretBinding, requiredSecretKinds } from "./secret-policy";
|
||||||
import { parseStoredCustomWidgetDefinition } from "./stored-definition";
|
import { parseStoredCustomWidgetDefinition } from "./stored-definition";
|
||||||
|
|
||||||
const previewCreateInputSchema = z.object({
|
const previewCreateInputSchema = z.object({
|
||||||
definition: customWidgetDefinitionSchema,
|
definition: customWidgetAuthoringDefinitionSchema,
|
||||||
secrets: customWidgetSecretsInputSchema.default([]),
|
secrets: customWidgetSecretsInputSchema.default([]),
|
||||||
definitionId: z.string().optional(),
|
definitionId: z.string().optional(),
|
||||||
options: z.record(z.string(), z.unknown()).optional(),
|
options: z.record(z.string(), z.unknown()).optional(),
|
||||||
@@ -26,11 +29,20 @@ const previewCreateInputSchema = z.object({
|
|||||||
|
|
||||||
const previewCreateProcedure = permissionRequiredProcedure
|
const previewCreateProcedure = permissionRequiredProcedure
|
||||||
.requiresPermission("admin")
|
.requiresPermission("admin")
|
||||||
.meta({ mcp: { enabled: true, description: "Create a short-lived preview session for one unsaved custom widget." } })
|
.meta({
|
||||||
|
mcp: {
|
||||||
|
enabled: true,
|
||||||
|
description:
|
||||||
|
"Create a short-lived preview for an unsaved custom widget after validation. Prefer templateLines for multiline JSX. The result lists every query that must be tested with customWidget_previewQuery before saving.",
|
||||||
|
},
|
||||||
|
})
|
||||||
.input(previewCreateInputSchema)
|
.input(previewCreateInputSchema)
|
||||||
.mutation(async ({ ctx, input }) => {
|
.mutation(async ({ ctx, input }) => {
|
||||||
const options = input.options ?? getCustomWidgetDefaultOptions(input.definition.options);
|
const definition = parseCustomWidgetAuthoringInput(() =>
|
||||||
const optionIssues = validateCustomWidgetOptions(input.definition.options, options);
|
normalizeCustomWidgetAuthoringDefinition(input.definition),
|
||||||
|
);
|
||||||
|
const options = input.options ?? getCustomWidgetDefaultOptions(definition.options);
|
||||||
|
const optionIssues = validateCustomWidgetOptions(definition.options, options);
|
||||||
if (optionIssues.length > 0) {
|
if (optionIssues.length > 0) {
|
||||||
const issue = optionIssues[0];
|
const issue = optionIssues[0];
|
||||||
throw new TRPCError({
|
throw new TRPCError({
|
||||||
@@ -48,7 +60,7 @@ const previewCreateProcedure = permissionRequiredProcedure
|
|||||||
if (!existing) throw new TRPCError({ code: "NOT_FOUND", message: "Custom widget definition not found" });
|
if (!existing) throw new TRPCError({ code: "NOT_FOUND", message: "Custom widget definition not found" });
|
||||||
const existingDefinition = parseStoredCustomWidgetDefinition(existing);
|
const existingDefinition = parseStoredCustomWidgetDefinition(existing);
|
||||||
for (const [sourceId, existingSource] of Object.entries(existingDefinition.sources)) {
|
for (const [sourceId, existingSource] of Object.entries(existingDefinition.sources)) {
|
||||||
const submittedSource = input.definition.sources[sourceId];
|
const submittedSource = definition.sources[sourceId];
|
||||||
const hasStoredSecrets = existing.secrets.some((secret) => secret.sourceId === sourceId);
|
const hasStoredSecrets = existing.secrets.some((secret) => secret.sourceId === sourceId);
|
||||||
if (!submittedSource || !hasStoredSecrets || hasSameSecretBinding(existingSource, submittedSource)) continue;
|
if (!submittedSource || !hasStoredSecrets || hasSameSecretBinding(existingSource, submittedSource)) continue;
|
||||||
|
|
||||||
@@ -65,7 +77,7 @@ const previewCreateProcedure = permissionRequiredProcedure
|
|||||||
}
|
}
|
||||||
for (const secret of existing.secrets) {
|
for (const secret of existing.secrets) {
|
||||||
const existingSource = existingDefinition.sources[secret.sourceId];
|
const existingSource = existingDefinition.sources[secret.sourceId];
|
||||||
const submittedSource = input.definition.sources[secret.sourceId];
|
const submittedSource = definition.sources[secret.sourceId];
|
||||||
if (
|
if (
|
||||||
existingSource &&
|
existingSource &&
|
||||||
submittedSource &&
|
submittedSource &&
|
||||||
@@ -78,7 +90,7 @@ const previewCreateProcedure = permissionRequiredProcedure
|
|||||||
}
|
}
|
||||||
|
|
||||||
const invalid = secrets.find((secret) => {
|
const invalid = secrets.find((secret) => {
|
||||||
const source = input.definition.sources[secret.sourceId];
|
const source = definition.sources[secret.sourceId];
|
||||||
const authType = typeof source?.auth === "string" ? source.auth : source?.auth.type;
|
const authType = typeof source?.auth === "string" ? source.auth : source?.auth.type;
|
||||||
const kinds =
|
const kinds =
|
||||||
authType === "basic"
|
authType === "basic"
|
||||||
@@ -94,26 +106,32 @@ const previewCreateProcedure = permissionRequiredProcedure
|
|||||||
|
|
||||||
const previewSession = await createPreviewSession({
|
const previewSession = await createPreviewSession({
|
||||||
userId: ctx.session.user.id,
|
userId: ctx.session.user.id,
|
||||||
sources: input.definition.sources,
|
sources: definition.sources,
|
||||||
requests: input.definition.requests,
|
requests: definition.requests,
|
||||||
name: input.definition.name,
|
name: definition.name,
|
||||||
template: input.definition.template,
|
template: definition.template,
|
||||||
optionDefinitions: input.definition.options,
|
optionDefinitions: definition.options,
|
||||||
options,
|
options,
|
||||||
secrets,
|
secrets,
|
||||||
definitionId: input.definitionId,
|
definitionId: input.definitionId,
|
||||||
});
|
});
|
||||||
|
const previewPath = `/manage/custom-widgets/preview/${previewSession.id}`;
|
||||||
return {
|
return {
|
||||||
success: true as const,
|
success: true as const,
|
||||||
previewSession,
|
previewSession,
|
||||||
previewUrl: new URL(
|
previewPath,
|
||||||
`/manage/custom-widgets/preview/${previewSession.id}`,
|
previewUrl: new URL(previewPath, ctx.baseUrl ?? "http://localhost").toString(),
|
||||||
ctx.baseUrl ?? "http://localhost",
|
queries: Object.entries(definition.requests).flatMap(([requestId, request]) => {
|
||||||
).toString(),
|
if (request.kind !== "query") return [];
|
||||||
definition: {
|
return [
|
||||||
template: input.definition.template,
|
{
|
||||||
defaultOptions: getCustomWidgetDefaultOptions(input.definition.options),
|
requestId,
|
||||||
},
|
trigger: request.trigger,
|
||||||
|
parameterNames: [...collectCustomWidgetRequestReferences(request).params],
|
||||||
|
nextStep: `Call customWidget_previewQuery with sessionId '${previewSession.id}' and requestId '${requestId}'.`,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
}),
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -10,9 +10,16 @@ import { resolveCustomWidgetRequestValues } from "./request-manifest";
|
|||||||
const logger = createLogger({ module: "custom-widget-preview" });
|
const logger = createLogger({ module: "custom-widget-preview" });
|
||||||
|
|
||||||
export const previewSessionRequestSchema = z.object({
|
export const previewSessionRequestSchema = z.object({
|
||||||
sessionId: z.string().min(1),
|
sessionId: z.string().min(1).describe("The previewSession.id returned by customWidget_previewCreate."),
|
||||||
requestId: z.string().min(1).max(64),
|
requestId: z
|
||||||
params: z.record(z.string(), z.union([z.string(), z.number(), z.boolean()])).default({}),
|
.string()
|
||||||
|
.min(1)
|
||||||
|
.max(64)
|
||||||
|
.describe("One query requestId from customWidget_previewCreate.queries. Test every returned query."),
|
||||||
|
params: z
|
||||||
|
.record(z.string(), z.union([z.string(), z.number(), z.boolean()]))
|
||||||
|
.default({})
|
||||||
|
.describe("Invocation parameters required by a manual query. Load queries use an empty object."),
|
||||||
});
|
});
|
||||||
|
|
||||||
export const recordPreviewJournal = async (...args: Parameters<typeof appendPreviewJournal>) => {
|
export const recordPreviewJournal = async (...args: Parameters<typeof appendPreviewJournal>) => {
|
||||||
|
|||||||
@@ -19,7 +19,8 @@ export const previewQueryProcedures = {
|
|||||||
.meta({
|
.meta({
|
||||||
mcp: {
|
mcp: {
|
||||||
enabled: true,
|
enabled: true,
|
||||||
description: "Run one named query from a short-lived custom widget preview session.",
|
description:
|
||||||
|
"Execute one real API query from customWidget_previewCreate.queries and return its HTTP status plus parsed data so request paths and template bindings can be verified. Call once for every returned query before customWidget_create.",
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
.input(previewSessionRequestSchema)
|
.input(previewSessionRequestSchema)
|
||||||
|
|||||||
@@ -100,6 +100,86 @@ async function insertLegacyJellyfin(db: ReturnType<typeof createDb>) {
|
|||||||
const secret = { sourceId: "default", kind: "apiKey" as const, value: "test-secret" };
|
const secret = { sourceId: "default", kind: "apiKey" as const, value: "test-secret" };
|
||||||
|
|
||||||
describe("custom widget definition persistence", () => {
|
describe("custom widget definition persistence", () => {
|
||||||
|
test("creates and previews MCP-friendly multiline templateLines without losing the JSX", async () => {
|
||||||
|
const db = await prepareDatabase();
|
||||||
|
const caller = createCaller(db);
|
||||||
|
const { template, ...definition } = jellyfin;
|
||||||
|
const templateLines = template.split("\n");
|
||||||
|
|
||||||
|
const validation = await caller.validate({ widget: { ...definition, templateLines } });
|
||||||
|
expect(validation).toMatchObject({
|
||||||
|
valid: true,
|
||||||
|
summary: {
|
||||||
|
name: jellyfin.name,
|
||||||
|
sourceIds: Object.keys(jellyfin.sources),
|
||||||
|
requestIds: Object.keys(jellyfin.requests),
|
||||||
|
templateLineCount: templateLines.length,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
expect(validation).not.toHaveProperty("widget");
|
||||||
|
expect(validation).not.toHaveProperty("templateLines");
|
||||||
|
expect(Buffer.byteLength(JSON.stringify(validation), "utf8")).toBeLessThan(2_000);
|
||||||
|
const preview = await caller.previewCreate({ definition: { ...definition, templateLines }, secrets: [] });
|
||||||
|
expect(preview).toMatchObject({
|
||||||
|
success: true,
|
||||||
|
previewPath: `/manage/custom-widgets/preview/${preview.previewSession.id}`,
|
||||||
|
});
|
||||||
|
expect(preview).not.toHaveProperty("definition");
|
||||||
|
expect(Buffer.byteLength(JSON.stringify(preview), "utf8")).toBeLessThan(4_000);
|
||||||
|
expect(preview.queries.map(({ requestId }) => requestId)).toEqual(Object.keys(jellyfin.requests));
|
||||||
|
expect(preview.queries.every(({ nextStep }) => nextStep.includes("customWidget_previewQuery"))).toBe(true);
|
||||||
|
|
||||||
|
const created = await caller.create({ ...definition, templateLines, secrets: [] });
|
||||||
|
expect(created.managementPath).toBe(`/manage/custom-widgets/edit/${created.id}`);
|
||||||
|
expect(created.nextAction).toEqual({
|
||||||
|
type: "place-custom-widget",
|
||||||
|
widgetKind: "customApi",
|
||||||
|
options: { definitionId: created.id },
|
||||||
|
whenTargetIsKnown: "Call configure_widget now with the requested board and these exact widget options.",
|
||||||
|
whenTargetIsUnknown:
|
||||||
|
"Call ask_user now with 'Place on a board' and 'Leave unplaced'. Never ask this choice in prose.",
|
||||||
|
});
|
||||||
|
expect((await caller.get({ id: created.id })).template).toBe(template);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("updates a saved widget with MCP-friendly multiline templateLines", async () => {
|
||||||
|
const db = await prepareDatabase();
|
||||||
|
const caller = createCaller(db);
|
||||||
|
const created = await caller.create({ ...jellyfin, secrets: [] });
|
||||||
|
const updatedTemplate = jellyfin.template.replace("Jellyfin library", "Updated Jellyfin library");
|
||||||
|
|
||||||
|
const updated = await caller.update({ id: created.id, templateLines: updatedTemplate.split("\n") });
|
||||||
|
|
||||||
|
expect(updated.managementPath).toBe(`/manage/custom-widgets/edit/${created.id}`);
|
||||||
|
expect((await caller.get({ id: created.id })).template).toBe(updatedTemplate);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("reports joined templateLines validation issues as BAD_REQUEST for create and update", async () => {
|
||||||
|
const db = await prepareDatabase();
|
||||||
|
const caller = createCaller(db);
|
||||||
|
const { template: _template, ...definition } = jellyfin;
|
||||||
|
const invalidTemplateLines = ["<Stack>", ' <img src="https://example.com/logo.png" />', "</Stack>"];
|
||||||
|
|
||||||
|
const createError = await caller
|
||||||
|
.create({ ...definition, templateLines: invalidTemplateLines, secrets: [] })
|
||||||
|
.catch((error: unknown) => error);
|
||||||
|
expect(createError).toMatchObject({
|
||||||
|
code: "BAD_REQUEST",
|
||||||
|
cause: { issues: [expect.objectContaining({ path: ["template"] })] },
|
||||||
|
});
|
||||||
|
expect(await db.query.customWidgetDefinitions.findMany()).toHaveLength(0);
|
||||||
|
|
||||||
|
const created = await caller.create({ ...jellyfin, secrets: [] });
|
||||||
|
const updateError = await caller
|
||||||
|
.update({ id: created.id, templateLines: invalidTemplateLines })
|
||||||
|
.catch((error: unknown) => error);
|
||||||
|
expect(updateError).toMatchObject({
|
||||||
|
code: "BAD_REQUEST",
|
||||||
|
cause: { issues: [expect.objectContaining({ path: ["template"] })] },
|
||||||
|
});
|
||||||
|
expect((await caller.get({ id: created.id })).template).toBe(jellyfin.template);
|
||||||
|
});
|
||||||
|
|
||||||
test("atomically creates a v2 replacement while preserving the legacy widget and its stable ID", async () => {
|
test("atomically creates a v2 replacement while preserving the legacy widget and its stable ID", async () => {
|
||||||
const db = await prepareDatabase();
|
const db = await prepareDatabase();
|
||||||
const legacy = await insertLegacyJellyfin(db);
|
const legacy = await insertLegacyJellyfin(db);
|
||||||
|
|||||||
@@ -0,0 +1,94 @@
|
|||||||
|
import type { Session } from "@homarr/auth";
|
||||||
|
import { createId } from "@homarr/common";
|
||||||
|
import { createDb } from "@homarr/db/test";
|
||||||
|
import { users } from "@homarr/db/schema";
|
||||||
|
import { CUSTOM_WIDGET_STARTER } from "@homarr/custom-widgets/core";
|
||||||
|
import { beforeEach, describe, expect, test, vi } from "vitest";
|
||||||
|
|
||||||
|
const mocks = vi.hoisted(() => ({
|
||||||
|
executeRequest: vi.fn(async (_input: unknown) => ({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
statusText: "OK",
|
||||||
|
data: { fixtures: [{ id: "match-1", home_team: { name: "PSG" }, away_team: { name: "Lyon" } }] },
|
||||||
|
})),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("../../custom-widget/request-executor", () => ({
|
||||||
|
executeCustomWidgetRequest: mocks.executeRequest,
|
||||||
|
invalidateCustomWidgetResponseCache: vi.fn(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("../../custom-widget/request-limits", () => ({
|
||||||
|
acquireCustomWidgetRequestLimit: vi.fn(async () => async () => undefined),
|
||||||
|
}));
|
||||||
|
|
||||||
|
import { customWidgetRouter } from "../../custom-widget/custom-widget-router";
|
||||||
|
|
||||||
|
describe("custom widget agent preview workflow", () => {
|
||||||
|
beforeEach(() => mocks.executeRequest.mockClear());
|
||||||
|
|
||||||
|
test("runs a named preview query and returns the real response shape to the agent", async () => {
|
||||||
|
const db = createDb();
|
||||||
|
const userId = createId();
|
||||||
|
await db.insert(users).values({ id: userId });
|
||||||
|
const session = {
|
||||||
|
user: { id: userId, permissions: ["admin"], colorScheme: "light" },
|
||||||
|
expires: new Date(Date.now() + 60_000).toISOString(),
|
||||||
|
} satisfies Session;
|
||||||
|
const caller = customWidgetRouter.createCaller({ db, deviceType: undefined, session });
|
||||||
|
const { template, ...definition } = CUSTOM_WIDGET_STARTER;
|
||||||
|
const preview = await caller.previewCreate({
|
||||||
|
definition: {
|
||||||
|
...definition,
|
||||||
|
requests: { fixtures: { path: "/fixtures", query: { season: 2026 } } },
|
||||||
|
templateLines: template.split("\n"),
|
||||||
|
},
|
||||||
|
secrets: [],
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(preview.queries).toEqual([
|
||||||
|
expect.objectContaining({ requestId: "fixtures", trigger: "load", parameterNames: [] }),
|
||||||
|
]);
|
||||||
|
await expect(
|
||||||
|
caller.previewQuery({ sessionId: preview.previewSession.id, requestId: "fixtures", params: {} }),
|
||||||
|
).resolves.toEqual(
|
||||||
|
expect.objectContaining({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
data: { fixtures: [expect.objectContaining({ id: "match-1" })] },
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
const request = mocks.executeRequest.mock.calls[0]?.[0] as { targetUrl: string | URL; kind: string } | undefined;
|
||||||
|
expect(String(request?.targetUrl)).toBe("https://example.com/fixtures?season=2026");
|
||||||
|
expect(request?.kind).toBe("query");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("reports joined preview templateLines validation issues as BAD_REQUEST", async () => {
|
||||||
|
const db = createDb();
|
||||||
|
const userId = createId();
|
||||||
|
await db.insert(users).values({ id: userId });
|
||||||
|
const session = {
|
||||||
|
user: { id: userId, permissions: ["admin"], colorScheme: "light" },
|
||||||
|
expires: new Date(Date.now() + 60_000).toISOString(),
|
||||||
|
} satisfies Session;
|
||||||
|
const caller = customWidgetRouter.createCaller({ db, deviceType: undefined, session });
|
||||||
|
const { template: _template, ...definition } = CUSTOM_WIDGET_STARTER;
|
||||||
|
|
||||||
|
const error = await caller
|
||||||
|
.previewCreate({
|
||||||
|
definition: {
|
||||||
|
...definition,
|
||||||
|
templateLines: ["<Stack>", ' <img src="https://example.com/logo.png" />', "</Stack>"],
|
||||||
|
},
|
||||||
|
secrets: [],
|
||||||
|
})
|
||||||
|
.catch((cause: unknown) => cause);
|
||||||
|
|
||||||
|
expect(error).toMatchObject({
|
||||||
|
code: "BAD_REQUEST",
|
||||||
|
cause: { issues: [expect.objectContaining({ path: ["template"] })] },
|
||||||
|
});
|
||||||
|
expect(mocks.executeRequest).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -23,6 +23,10 @@ const MCP_TOOL_ALLOWLIST = {
|
|||||||
"calendar_findAllEvents",
|
"calendar_findAllEvents",
|
||||||
"customWidget_get",
|
"customWidget_get",
|
||||||
"customWidget_getAuthoringPrompt",
|
"customWidget_getAuthoringPrompt",
|
||||||
|
"customWidget_getComponent",
|
||||||
|
"customWidget_getComponentCatalog",
|
||||||
|
"customWidget_getExample",
|
||||||
|
"customWidget_getSharedProps",
|
||||||
"customWidget_getSkill",
|
"customWidget_getSkill",
|
||||||
"customWidget_legacyMigrationPrompt",
|
"customWidget_legacyMigrationPrompt",
|
||||||
"customWidget_list",
|
"customWidget_list",
|
||||||
@@ -186,6 +190,10 @@ describe("custom widget authoring procedure access", () => {
|
|||||||
const calls = [
|
const calls = [
|
||||||
unauthenticatedCaller.customWidget.schema(),
|
unauthenticatedCaller.customWidget.schema(),
|
||||||
unauthenticatedCaller.customWidget.getAuthoringPrompt(),
|
unauthenticatedCaller.customWidget.getAuthoringPrompt(),
|
||||||
|
unauthenticatedCaller.customWidget.getComponentCatalog(),
|
||||||
|
unauthenticatedCaller.customWidget.getComponent({ name: "Stack" }),
|
||||||
|
unauthenticatedCaller.customWidget.getExample({ name: "service-dashboard" }),
|
||||||
|
unauthenticatedCaller.customWidget.getSharedProps({ names: ["p"] }),
|
||||||
unauthenticatedCaller.customWidget.getSkill(),
|
unauthenticatedCaller.customWidget.getSkill(),
|
||||||
unauthenticatedCaller.customWidget.list(),
|
unauthenticatedCaller.customWidget.list(),
|
||||||
unauthenticatedCaller.customWidget.validate({ widget: {} }),
|
unauthenticatedCaller.customWidget.validate({ widget: {} }),
|
||||||
@@ -208,6 +216,10 @@ describe("custom widget authoring procedure access", () => {
|
|||||||
const calls = [
|
const calls = [
|
||||||
nonAdminCaller.customWidget.schema(),
|
nonAdminCaller.customWidget.schema(),
|
||||||
nonAdminCaller.customWidget.getAuthoringPrompt(),
|
nonAdminCaller.customWidget.getAuthoringPrompt(),
|
||||||
|
nonAdminCaller.customWidget.getComponentCatalog(),
|
||||||
|
nonAdminCaller.customWidget.getComponent({ name: "Stack" }),
|
||||||
|
nonAdminCaller.customWidget.getExample({ name: "service-dashboard" }),
|
||||||
|
nonAdminCaller.customWidget.getSharedProps({ names: ["p"] }),
|
||||||
nonAdminCaller.customWidget.getSkill(),
|
nonAdminCaller.customWidget.getSkill(),
|
||||||
nonAdminCaller.customWidget.secretSet({
|
nonAdminCaller.customWidget.secretSet({
|
||||||
definitionId: "widget",
|
definitionId: "widget",
|
||||||
@@ -233,5 +245,27 @@ describe("custom widget authoring procedure access", () => {
|
|||||||
await expect(adminCaller.customWidget.getSkill()).resolves.toMatchObject({
|
await expect(adminCaller.customWidget.getSkill()).resolves.toMatchObject({
|
||||||
name: expect.any(String),
|
name: expect.any(String),
|
||||||
});
|
});
|
||||||
|
await expect(adminCaller.customWidget.getComponentCatalog()).resolves.toMatchObject({
|
||||||
|
components: expect.arrayContaining([expect.objectContaining({ name: "Stack" })]),
|
||||||
|
examples: expect.arrayContaining([expect.objectContaining({ id: "service-dashboard" })]),
|
||||||
|
});
|
||||||
|
await expect(adminCaller.customWidget.getComponent({ name: "Stack" })).resolves.toMatchObject({
|
||||||
|
name: "Stack",
|
||||||
|
props: expect.anything(),
|
||||||
|
});
|
||||||
|
await expect(adminCaller.customWidget.getExample({ name: "service-dashboard" })).resolves.toMatchObject({
|
||||||
|
id: "service-dashboard",
|
||||||
|
widget: expect.objectContaining({ $schema: "homarr-custom-widget-v2" }),
|
||||||
|
});
|
||||||
|
await expect(adminCaller.customWidget.getSharedProps({ names: ["p", "m"] })).resolves.toMatchObject({
|
||||||
|
props: [expect.objectContaining({ name: "p" }), expect.objectContaining({ name: "m" })],
|
||||||
|
notFound: [],
|
||||||
|
});
|
||||||
|
await expect(adminCaller.customWidget.getComponent({ name: "NotAComponent" })).rejects.toEqual(
|
||||||
|
expect.objectContaining<Partial<TRPCError>>({ code: "NOT_FOUND" }),
|
||||||
|
);
|
||||||
|
await expect(adminCaller.customWidget.getExample({ name: "not-an-example" })).rejects.toEqual(
|
||||||
|
expect.objectContaining<Partial<TRPCError>>({ code: "NOT_FOUND" }),
|
||||||
|
);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -127,7 +127,11 @@ export const CUSTOM_WIDGET_AUTHORING_PROMPT = AUTHORING_PROMPT;
|
|||||||
|
|
||||||
export const CUSTOM_WIDGET_MCP_AUTHORING_PROMPT = `Author one Homarr Custom JSX v2 widget at a time.
|
export const CUSTOM_WIDGET_MCP_AUTHORING_PROMPT = `Author one Homarr Custom JSX v2 widget at a time.
|
||||||
|
|
||||||
Read the live schema and only the component resources needed for the design. Construct a credential-free widget, validate it, create a preview, test queries and simulated actions, visually inspect it, then create it. Configure deployment-specific source URLs and request credentials through Homarr when needed; never repeat plaintext. The live resources are authoritative for this Homarr release.
|
First call customWidget_getSkill. Its single lazy response contains the complete installed SKILL.md and every bundled reference; follow all of it. Read the live schema and compact component catalog. Fetch only the named component and example resources needed for the design. Component resources contain component-specific props; if shared props are needed, collect their catalog names and fetch those docs together once with customWidget_getSharedProps. The live resources are authoritative for this Homarr release.
|
||||||
|
|
||||||
|
Follow this lifecycle without skipping steps: construct one credential-free definition; call customWidget_validate; repair every reported issue; call customWidget_previewCreate; call customWidget_previewQuery once for every query returned by that preview (supplying required manual parameters); inspect the real response shape and HTTP status; adjust paths and template bindings; validate and preview again after changes; open or provide the returned previewPath for visual review; only then call customWidget_create. Prefer templateLines over a JSON-escaped template string for multiline JSX in validate, preview, and create tool inputs.
|
||||||
|
|
||||||
|
Do not claim a query works when it has not returned a successful preview response. Configure deployment-specific source URLs and request credentials through Homarr when needed; never repeat plaintext. Use simulated preview actions unless the user explicitly enables live preview actions.
|
||||||
|
|
||||||
Use the lean keyed sources, requests, and options contract. Bind saved values directly with $option and invocation values with $param. Load queries cannot use $param. Keep the design responsive, accessible, theme-safe, loading-aware, empty-aware, and error-aware.
|
Use the lean keyed sources, requests, and options contract. Bind saved values directly with $option and invocation values with $param. Load queries cannot use $param. Keep the design responsive, accessible, theme-safe, loading-aware, empty-aware, and error-aware.
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,8 @@
|
|||||||
import { customJsxAuthoringCatalog, getCustomJsxComponentProps } from "./component-catalog";
|
import {
|
||||||
|
customJsxAuthoringCatalog,
|
||||||
|
customJsxCatalogGlobalPropByName,
|
||||||
|
resolveCustomJsxPropDescriptor,
|
||||||
|
} from "./component-catalog";
|
||||||
import { customJsxExamples } from "./examples";
|
import { customJsxExamples } from "./examples";
|
||||||
import { customJsxTablerIconNames } from "./tabler-icons";
|
import { customJsxTablerIconNames } from "./tabler-icons";
|
||||||
|
|
||||||
@@ -7,7 +11,58 @@ export const CUSTOM_WIDGET_SKILL_SOURCE_URL =
|
|||||||
"https://github.com/homarr-labs/homarr/tree/HEAD/.agents/skills/homarr-custom-widget";
|
"https://github.com/homarr-labs/homarr/tree/HEAD/.agents/skills/homarr-custom-widget";
|
||||||
export const CUSTOM_WIDGET_SKILL_INSTALL_COMMAND =
|
export const CUSTOM_WIDGET_SKILL_INSTALL_COMMAND =
|
||||||
"npx skills add https://github.com/homarr-labs/homarr --skill homarr-custom-widget";
|
"npx skills add https://github.com/homarr-labs/homarr --skill homarr-custom-widget";
|
||||||
export const CUSTOM_WIDGET_SKILL_VERSION = "2.1.0";
|
export const CUSTOM_WIDGET_SKILL_VERSION = "2.2.0";
|
||||||
|
|
||||||
|
export const CUSTOM_WIDGET_SKILL_REFERENCES = {
|
||||||
|
"references/schema.md": `# Schema
|
||||||
|
|
||||||
|
\`\`\`ts
|
||||||
|
interface HomarrCustomWidgetV2 {
|
||||||
|
$schema: "homarr-custom-widget-v2";
|
||||||
|
name: string;
|
||||||
|
description?: string;
|
||||||
|
iconUrl?: string;
|
||||||
|
sources: Record<string, CustomWidgetSource>;
|
||||||
|
requests: Record<string, CustomWidgetRequest>;
|
||||||
|
options?: Record<string, CustomWidgetOption>;
|
||||||
|
template: string;
|
||||||
|
}
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
Sources require \`default\`. A request defaults to the default source, query, GET, load, inherited auth, and view permission. An action defaults to manual and modify permission. DELETE uses full permission and confirmation.
|
||||||
|
|
||||||
|
Use stable real URLs for public APIs and clear suggested URLs for self-hosted services. Homarr collects the installer's server URL, network scope, and credentials as source setup; credentials remain outside the manifest.
|
||||||
|
|
||||||
|
Paths use \`{option:name}\` and \`{param:name}\`. Query/body data uses \`{ "$option": "name" }\` and \`{ "$param": "name" }\`. Load queries cannot use params. Runtime parameter names and primitive values are inferred from references.
|
||||||
|
|
||||||
|
Every option has \`label\`, \`control\`, and \`default\`. Optional fields are \`description\`, \`choices\`, \`choicesFrom\`, \`min\`, \`max\`, \`step\`, \`advanced\`, and \`group\`.
|
||||||
|
`,
|
||||||
|
"references/runtime.md": `# Runtime
|
||||||
|
|
||||||
|
Templates read \`data.requestId\`, \`status.requestId\`, \`options.name\`, and temporary \`inputs.name\`. Status contains \`loading\`, \`ok\`, \`status\`, \`statusText\`, and \`error\`.
|
||||||
|
|
||||||
|
\`bind="search"\` creates an in-memory input. It is never persisted. Supply invocation values only through \`params\`, for example:
|
||||||
|
|
||||||
|
\`\`\`jsx
|
||||||
|
<TextInput bind="search" label="Search" />
|
||||||
|
<SubFetch requestId="search" params={{ query: inputs.search }}>
|
||||||
|
{(items) => <Stack>{(items ?? []).map(item => <Text key={item.id}>{item.name}</Text>)}</Stack>}
|
||||||
|
</SubFetch>
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
\`SubFetch\` with \`trigger="manual"\` renders its own load button. To make a card or image launch the request, pass that node through \`triggerContent\` and provide \`triggerAriaLabel\`; Homarr supplies the click and keyboard behavior. Its optional second callback argument contains \`{ ok, status, statusText, loading: false }\`; loading and request failures are rendered by \`SubFetch\` before the callback runs. Do not author \`onClick\` or a fetch callback.
|
||||||
|
|
||||||
|
Use expression callbacks for supported collection methods and trusted slots. Do not use callback blocks, IIFEs, authored recursion, or raw events. Bounded regex literals work only with safe string matching/replacement operations.
|
||||||
|
`,
|
||||||
|
"references/security.md": `# Security
|
||||||
|
|
||||||
|
All requests use Homarr's protected server executor. Source origin, network scope, DNS, redirects, SSRF, rate limits, permissions, size limits, timeouts, and encrypted credential injection remain enforced.
|
||||||
|
|
||||||
|
The JSX interpreter blocks imports, hooks, refs, raw event callbacks, browser requests, eval, arbitrary functions, prototype access, unsafe URLs, global CSS escape, arbitrary portals, bigint, statement blocks, IIFEs, and recursion. Regex literals must be bounded and reject backreferences, lookbehind, nested quantifiers, excessive length, and unsupported flags.
|
||||||
|
|
||||||
|
Credentials are stored separately and never exported or returned to an agent. A published self-hosted source URL is only a suggestion: installers must confirm or replace private and loopback URLs for their own Homarr deployment. Source origins cannot be controlled through widget options.
|
||||||
|
`,
|
||||||
|
} as const;
|
||||||
|
|
||||||
export const CUSTOM_WIDGET_SKILL_MD = `---
|
export const CUSTOM_WIDGET_SKILL_MD = `---
|
||||||
name: homarr-custom-widget
|
name: homarr-custom-widget
|
||||||
@@ -39,11 +94,19 @@ Preview-scoped configuration expires with the preview. To persist user-entered v
|
|||||||
When this skill is installed from the repository, optional offline details are in \`references/schema.md\`, \`references/runtime.md\`, and \`references/security.md\`. MCP-only clients should use the live Homarr resources instead.
|
When this skill is installed from the repository, optional offline details are in \`references/schema.md\`, \`references/runtime.md\`, and \`references/security.md\`. MCP-only clients should use the live Homarr resources instead.
|
||||||
`;
|
`;
|
||||||
|
|
||||||
|
const CUSTOM_WIDGET_SKILL_BUNDLE_MD = [
|
||||||
|
CUSTOM_WIDGET_SKILL_MD.trimEnd(),
|
||||||
|
...Object.entries(CUSTOM_WIDGET_SKILL_REFERENCES).map(
|
||||||
|
([file, content]) => `\n\n---\n\n# Bundled file: ${file}\n\n${content.trimEnd()}`,
|
||||||
|
),
|
||||||
|
].join("");
|
||||||
|
|
||||||
export function getCustomWidgetSkill() {
|
export function getCustomWidgetSkill() {
|
||||||
return {
|
return {
|
||||||
name: "homarr-custom-widget",
|
name: "homarr-custom-widget",
|
||||||
version: CUSTOM_WIDGET_SKILL_VERSION,
|
version: CUSTOM_WIDGET_SKILL_VERSION,
|
||||||
skillMd: CUSTOM_WIDGET_SKILL_MD,
|
skillMd: CUSTOM_WIDGET_SKILL_MD,
|
||||||
|
references: CUSTOM_WIDGET_SKILL_REFERENCES,
|
||||||
skillsShUrl: CUSTOM_WIDGET_SKILLS_SH_URL,
|
skillsShUrl: CUSTOM_WIDGET_SKILLS_SH_URL,
|
||||||
sourceUrl: CUSTOM_WIDGET_SKILL_SOURCE_URL,
|
sourceUrl: CUSTOM_WIDGET_SKILL_SOURCE_URL,
|
||||||
installCommand: CUSTOM_WIDGET_SKILL_INSTALL_COMMAND,
|
installCommand: CUSTOM_WIDGET_SKILL_INSTALL_COMMAND,
|
||||||
@@ -51,11 +114,28 @@ export function getCustomWidgetSkill() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function getCustomWidgetSkillContent() {
|
export function getCustomWidgetSkillContent() {
|
||||||
return CUSTOM_WIDGET_SKILL_MD;
|
return CUSTOM_WIDGET_SKILL_BUNDLE_MD;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getCustomWidgetComponentCatalog() {
|
export function getCustomWidgetComponentCatalog() {
|
||||||
return customJsxAuthoringCatalog;
|
return {
|
||||||
|
schemaVersion: customJsxAuthoringCatalog.schemaVersion,
|
||||||
|
mantineVersion: customJsxAuthoringCatalog.mantineVersion,
|
||||||
|
customWidgetVersion: customJsxAuthoringCatalog.customWidgetVersion,
|
||||||
|
components: customJsxAuthoringCatalog.components.map(({ name, category, safety }) => ({ name, category, safety })),
|
||||||
|
sharedProps: {
|
||||||
|
count: customJsxAuthoringCatalog.globalProps.length,
|
||||||
|
names: customJsxAuthoringCatalog.globalProps.map(({ name }) => name),
|
||||||
|
fetchTool: "customWidget_getSharedProps" as const,
|
||||||
|
maxPerRequest: 64,
|
||||||
|
},
|
||||||
|
blockedCapabilities: customJsxAuthoringCatalog.blockedCapabilities,
|
||||||
|
examples: getCustomWidgetExampleCatalog(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getCustomWidgetExampleCatalog() {
|
||||||
|
return customJsxExamples.map(({ id, title, description }) => ({ id, title, description }));
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getCustomWidgetComponent(name: string) {
|
export function getCustomWidgetComponent(name: string) {
|
||||||
@@ -71,17 +151,37 @@ export function getCustomWidgetComponent(name: string) {
|
|||||||
category: component.category,
|
category: component.category,
|
||||||
safety: component.safety,
|
safety: component.safety,
|
||||||
description: component.description,
|
description: component.description,
|
||||||
props: getCustomJsxComponentProps(canonicalName),
|
props: component.props.map((prop) => resolveCustomJsxPropDescriptor(prop)),
|
||||||
blockedProps: component.blockedProps,
|
blockedProps: component.blockedProps,
|
||||||
bind: component.bind,
|
bind: component.bind,
|
||||||
subcomponents: component.subcomponents,
|
subcomponents: component.subcomponents,
|
||||||
accessibilityRequirements: component.accessibilityRequirements,
|
accessibilityRequirements: component.accessibilityRequirements,
|
||||||
documentationUrl: component.documentationUrl,
|
documentationUrl: component.documentationUrl,
|
||||||
|
sharedProps:
|
||||||
|
component.safety === "denied"
|
||||||
|
? undefined
|
||||||
|
: {
|
||||||
|
catalogField: "sharedProps.names" as const,
|
||||||
|
fetchTool: "customWidget_getSharedProps" as const,
|
||||||
|
maxPerRequest: 64,
|
||||||
|
appliesExceptBlockedProps: true as const,
|
||||||
|
},
|
||||||
knownValues: component.name === "TablerIcon" ? { name: customJsxTablerIconNames } : undefined,
|
knownValues: component.name === "TablerIcon" ? { name: customJsxTablerIconNames } : undefined,
|
||||||
deniedReason: component.deniedReason,
|
deniedReason: component.deniedReason,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function getCustomWidgetSharedProps(names: readonly string[]) {
|
||||||
|
const props: ReturnType<typeof resolveCustomJsxPropDescriptor>[] = [];
|
||||||
|
const notFound: string[] = [];
|
||||||
|
for (const name of new Set(names)) {
|
||||||
|
const prop = customJsxCatalogGlobalPropByName.get(name);
|
||||||
|
if (prop) props.push(resolveCustomJsxPropDescriptor(prop));
|
||||||
|
else notFound.push(name);
|
||||||
|
}
|
||||||
|
return { props, notFound };
|
||||||
|
}
|
||||||
|
|
||||||
export function getCustomWidgetExample(name: string) {
|
export function getCustomWidgetExample(name: string) {
|
||||||
return customJsxExamples.find((example) => example.id === name) ?? null;
|
return customJsxExamples.find((example) => example.id === name) ?? null;
|
||||||
}
|
}
|
||||||
@@ -17,6 +17,7 @@ import { getCustomWidgetHttpUrlIssue } from "./url-policy";
|
|||||||
export * from "./options-schema";
|
export * from "./options-schema";
|
||||||
export * from "./request-schema";
|
export * from "./request-schema";
|
||||||
export const CUSTOM_WIDGET_SCHEMA = "homarr-custom-widget-v2";
|
export const CUSTOM_WIDGET_SCHEMA = "homarr-custom-widget-v2";
|
||||||
|
const CUSTOM_WIDGET_TEMPLATE_MAX_LENGTH = 50_000;
|
||||||
|
|
||||||
export const customWidgetBindingIdentifierSchema = z
|
export const customWidgetBindingIdentifierSchema = z
|
||||||
.string()
|
.string()
|
||||||
@@ -30,7 +31,7 @@ export const customWidgetBindingIdentifierSchema = z
|
|||||||
export const customJsxTemplateSchema = z
|
export const customJsxTemplateSchema = z
|
||||||
.string()
|
.string()
|
||||||
.min(1)
|
.min(1)
|
||||||
.max(50_000)
|
.max(CUSTOM_WIDGET_TEMPLATE_MAX_LENGTH)
|
||||||
.superRefine((template, ctx) => {
|
.superRefine((template, ctx) => {
|
||||||
for (const diagnostic of validateCustomJsxTemplate(template)) {
|
for (const diagnostic of validateCustomJsxTemplate(template)) {
|
||||||
if (diagnostic.severity === "error") {
|
if (diagnostic.severity === "error") {
|
||||||
@@ -193,13 +194,84 @@ function validateTemplateRequests(template: string, requests: Record<string, Cus
|
|||||||
|
|
||||||
export type HomarrCustomWidgetV2 = z.infer<typeof customWidgetDefinitionSchema>;
|
export type HomarrCustomWidgetV2 = z.infer<typeof customWidgetDefinitionSchema>;
|
||||||
export type HomarrCustomWidgetV2Input = z.input<typeof customWidgetDefinitionSchema>;
|
export type HomarrCustomWidgetV2Input = z.input<typeof customWidgetDefinitionSchema>;
|
||||||
export const customWidgetCreateSchema = customWidgetDefinitionSchema.safeExtend({
|
|
||||||
|
const customWidgetTemplateLinesSchema = z
|
||||||
|
.array(z.string().max(10_000))
|
||||||
|
.min(1)
|
||||||
|
.max(2_000)
|
||||||
|
.refine(
|
||||||
|
(lines) => lines.reduce((length, line) => length + line.length, Math.max(0, lines.length - 1)) <= 50_000,
|
||||||
|
`The complete JSX template must contain at most ${CUSTOM_WIDGET_TEMPLATE_MAX_LENGTH} characters`,
|
||||||
|
)
|
||||||
|
.describe(
|
||||||
|
"The complete JSX template split into lines. Prefer this over template for generated multiline JSX. Do not send both fields.",
|
||||||
|
);
|
||||||
|
|
||||||
|
export const customWidgetAuthoringDefinitionSchema = z
|
||||||
|
.strictObject({
|
||||||
|
...customWidgetDefinitionSchema.shape,
|
||||||
|
template: customJsxTemplateSchema
|
||||||
|
.optional()
|
||||||
|
.describe("The complete JSX template as one string. For multiline JSX, prefer templateLines instead."),
|
||||||
|
templateLines: customWidgetTemplateLinesSchema.optional(),
|
||||||
|
})
|
||||||
|
.superRefine((definition, ctx) => {
|
||||||
|
if (definition.template === undefined && definition.templateLines === undefined) {
|
||||||
|
ctx.addIssue({ code: "custom", path: ["template"], message: "Provide template or templateLines" });
|
||||||
|
}
|
||||||
|
if (definition.template !== undefined && definition.templateLines !== undefined) {
|
||||||
|
ctx.addIssue({
|
||||||
|
code: "custom",
|
||||||
|
path: ["templateLines"],
|
||||||
|
message: "Provide template or templateLines, not both",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
export type CustomWidgetAuthoringDefinitionInput = z.input<typeof customWidgetAuthoringDefinitionSchema>;
|
||||||
|
|
||||||
|
export function normalizeCustomWidgetAuthoringDefinition(input: CustomWidgetAuthoringDefinitionInput) {
|
||||||
|
const { templateLines, ...definition } = input;
|
||||||
|
return customWidgetDefinitionSchema.parse({
|
||||||
|
...definition,
|
||||||
|
template: definition.template ?? templateLines?.join("\n"),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const customWidgetAuthoringUpdateSchema = z
|
||||||
|
.strictObject({
|
||||||
|
...customWidgetDefinitionSchema.shape,
|
||||||
|
options: customWidgetOptionsSchema.removeDefault(),
|
||||||
|
templateLines: customWidgetTemplateLinesSchema.optional(),
|
||||||
|
})
|
||||||
|
.partial()
|
||||||
|
.superRefine((definition, ctx) => {
|
||||||
|
if (definition.template !== undefined && definition.templateLines !== undefined) {
|
||||||
|
ctx.addIssue({
|
||||||
|
code: "custom",
|
||||||
|
path: ["templateLines"],
|
||||||
|
message: "Provide template or templateLines, not both",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
export type CustomWidgetAuthoringUpdateInput = z.input<typeof customWidgetAuthoringUpdateSchema>;
|
||||||
|
|
||||||
|
export function normalizeCustomWidgetAuthoringUpdate(input: CustomWidgetAuthoringUpdateInput) {
|
||||||
|
const { templateLines, ...definition } = input;
|
||||||
|
return {
|
||||||
|
...definition,
|
||||||
|
...(templateLines === undefined ? {} : { template: templateLines.join("\n") }),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export const customWidgetCreateSchema = customWidgetAuthoringDefinitionSchema.safeExtend({
|
||||||
secrets: customWidgetSecretsInputSchema.default([]),
|
secrets: customWidgetSecretsInputSchema.default([]),
|
||||||
});
|
});
|
||||||
export const customWidgetUpdateSchema = z
|
export const customWidgetUpdateSchema = customWidgetAuthoringUpdateSchema.safeExtend({
|
||||||
.strictObject(customWidgetDefinitionSchema.shape)
|
id: z.string().min(1),
|
||||||
.partial()
|
secrets: customWidgetSecretsInputSchema.optional(),
|
||||||
.extend({ id: z.string().min(1), secrets: customWidgetSecretsInputSchema.optional() });
|
});
|
||||||
export const customWidgetImportSchema = customWidgetDefinitionSchema;
|
export const customWidgetImportSchema = customWidgetDefinitionSchema;
|
||||||
export type CustomWidgetCreateInput = z.infer<typeof customWidgetCreateSchema>;
|
export type CustomWidgetCreateInput = z.infer<typeof customWidgetCreateSchema>;
|
||||||
export type CustomWidgetUpdateInput = z.infer<typeof customWidgetUpdateSchema>;
|
export type CustomWidgetUpdateInput = z.infer<typeof customWidgetUpdateSchema>;
|
||||||
|
|||||||
@@ -1,6 +1,10 @@
|
|||||||
import { describe, expect, it } from "vitest";
|
import { describe, expect, it } from "vitest";
|
||||||
|
|
||||||
import { buildCustomWidgetAiPrompt, CUSTOM_WIDGET_FINAL_OUTPUT_INSTRUCTION } from "../core/ai-prompt";
|
import {
|
||||||
|
buildCustomWidgetAiPrompt,
|
||||||
|
CUSTOM_WIDGET_FINAL_OUTPUT_INSTRUCTION,
|
||||||
|
CUSTOM_WIDGET_MCP_AUTHORING_PROMPT,
|
||||||
|
} from "../core/ai-prompt";
|
||||||
|
|
||||||
describe("AI prompt", () => {
|
describe("AI prompt", () => {
|
||||||
it("is self-contained, request-first, and compact", () => {
|
it("is self-contained, request-first, and compact", () => {
|
||||||
@@ -36,6 +40,18 @@ describe("AI prompt", () => {
|
|||||||
expect(prompt.match(/Recommended components:/gu)).toHaveLength(1);
|
expect(prompt.match(/Recommended components:/gu)).toHaveLength(1);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("makes the connected MCP workflow load the complete skill and test every preview query", () => {
|
||||||
|
expect(CUSTOM_WIDGET_MCP_AUTHORING_PROMPT).toContain("First call customWidget_getSkill");
|
||||||
|
expect(CUSTOM_WIDGET_MCP_AUTHORING_PROMPT).toContain("customWidget_validate");
|
||||||
|
expect(CUSTOM_WIDGET_MCP_AUTHORING_PROMPT).toContain("customWidget_previewCreate");
|
||||||
|
expect(CUSTOM_WIDGET_MCP_AUTHORING_PROMPT).toContain("customWidget_previewQuery once for every query");
|
||||||
|
expect(CUSTOM_WIDGET_MCP_AUTHORING_PROMPT).toContain("customWidget_getSharedProps");
|
||||||
|
expect(CUSTOM_WIDGET_MCP_AUTHORING_PROMPT).toContain("Prefer templateLines");
|
||||||
|
expect(CUSTOM_WIDGET_MCP_AUTHORING_PROMPT.indexOf("customWidget_previewQuery")).toBeLessThan(
|
||||||
|
CUSTOM_WIDGET_MCP_AUTHORING_PROMPT.indexOf("customWidget_create"),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
it("redacts secrets and preserves the final instruction when optional context is large", () => {
|
it("redacts secrets and preserves the final instruction when optional context is large", () => {
|
||||||
const prompt = buildCustomWidgetAiPrompt(
|
const prompt = buildCustomWidgetAiPrompt(
|
||||||
undefined,
|
undefined,
|
||||||
|
|||||||
@@ -5,28 +5,73 @@ import { describe, expect, it } from "vitest";
|
|||||||
import {
|
import {
|
||||||
getCustomWidgetComponent,
|
getCustomWidgetComponent,
|
||||||
getCustomWidgetComponentCatalog,
|
getCustomWidgetComponentCatalog,
|
||||||
|
getCustomWidgetSharedProps,
|
||||||
getCustomWidgetSkill,
|
getCustomWidgetSkill,
|
||||||
getCustomWidgetSkillContent,
|
getCustomWidgetSkillContent,
|
||||||
} from "../core/authoring-resources";
|
} from "../core/authoring-resources";
|
||||||
|
|
||||||
|
const skillSourceDirectory = path.resolve(import.meta.dirname, "../../../../.agents/skills/homarr-custom-widget");
|
||||||
|
|
||||||
describe("authoring resources", () => {
|
describe("authoring resources", () => {
|
||||||
it("returns the concise skills.sh discovery shape", () => {
|
it("returns the complete portable skill and keeps every bundled source file in sync", () => {
|
||||||
const skill = getCustomWidgetSkill();
|
const skill = getCustomWidgetSkill();
|
||||||
expect(skill).toMatchObject({ name: "homarr-custom-widget", version: "2.1.0" });
|
expect(skill).toMatchObject({ name: "homarr-custom-widget", version: "2.2.0" });
|
||||||
expect(skill.skillsShUrl).toContain("skills.sh/homarr-labs/homarr");
|
expect(skill.skillsShUrl).toContain("skills.sh/homarr-labs/homarr");
|
||||||
expect(skill.sourceUrl).toContain("/tree/HEAD/.agents/skills/homarr-custom-widget");
|
expect(skill.sourceUrl).toContain("/tree/HEAD/.agents/skills/homarr-custom-widget");
|
||||||
expect(skill.installCommand).toContain("--skill homarr-custom-widget");
|
expect(skill.installCommand).toContain("--skill homarr-custom-widget");
|
||||||
expect(skill).not.toHaveProperty("files");
|
|
||||||
expect(skill).not.toHaveProperty("componentCatalog");
|
expect(skill).not.toHaveProperty("componentCatalog");
|
||||||
expect(getCustomWidgetSkillContent()).toBe(skill.skillMd);
|
expect(skill).not.toHaveProperty("entrypointMd");
|
||||||
expect(skill.skillMd.trim()).toBe(
|
expect(skill).not.toHaveProperty("bundledMarkdown");
|
||||||
readFileSync(path.join(process.cwd(), ".agents/skills/homarr-custom-widget/SKILL.md"), "utf8").trim(),
|
expect(skill.skillMd.trim()).toBe(readFileSync(path.join(skillSourceDirectory, "SKILL.md"), "utf8").trim());
|
||||||
);
|
const bundledContent = getCustomWidgetSkillContent();
|
||||||
|
for (const [file, content] of Object.entries(skill.references)) {
|
||||||
|
expect(content.trim()).toBe(readFileSync(path.join(skillSourceDirectory, file), "utf8").trim());
|
||||||
|
expect(bundledContent).toContain(`# Bundled file: ${file}`);
|
||||||
|
expect(bundledContent).toContain(content.trim());
|
||||||
|
}
|
||||||
|
expect(bundledContent).toContain(skill.skillMd.trim());
|
||||||
|
expect(Buffer.byteLength(JSON.stringify(skill), "utf8")).toBeLessThan(12_000);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("keeps the full catalog retrieval-based", () => {
|
it("keeps catalog discovery compact and component details lazy", () => {
|
||||||
expect(getCustomWidgetComponentCatalog().components.length).toBeGreaterThan(100);
|
const catalog = getCustomWidgetComponentCatalog();
|
||||||
expect(getCustomWidgetComponent("Stack")?.name).toBe("Stack");
|
expect(catalog.components.length).toBeGreaterThan(100);
|
||||||
|
expect(catalog.components).toEqual(
|
||||||
|
expect.arrayContaining([expect.objectContaining({ name: "Stack", category: expect.any(String) })]),
|
||||||
|
);
|
||||||
|
expect(catalog.examples).toEqual(expect.arrayContaining([expect.objectContaining({ id: "service-dashboard" })]));
|
||||||
|
expect(catalog.sharedProps).toMatchObject({
|
||||||
|
count: expect.any(Number),
|
||||||
|
fetchTool: "customWidget_getSharedProps",
|
||||||
|
maxPerRequest: 64,
|
||||||
|
});
|
||||||
|
expect(catalog.sharedProps.names).toContain("p");
|
||||||
|
expect(Buffer.byteLength(JSON.stringify(catalog), "utf8")).toBeLessThan(45_000);
|
||||||
|
|
||||||
|
const stack = getCustomWidgetComponent("Stack");
|
||||||
|
expect(stack).toMatchObject({
|
||||||
|
name: "Stack",
|
||||||
|
sharedProps: { fetchTool: "customWidget_getSharedProps" },
|
||||||
|
});
|
||||||
|
expect(stack?.props.some(({ source }) => source === "global")).toBe(false);
|
||||||
|
expect(Buffer.byteLength(JSON.stringify(stack), "utf8")).toBeLessThan(20_000);
|
||||||
expect(getCustomWidgetComponent("Icon")?.knownValues?.name.length).toBeGreaterThan(100);
|
expect(getCustomWidgetComponent("Icon")?.knownValues?.name.length).toBeGreaterThan(100);
|
||||||
|
|
||||||
|
const largestComponentPayload = Math.max(
|
||||||
|
...catalog.components.map(({ name }) =>
|
||||||
|
Buffer.byteLength(JSON.stringify(getCustomWidgetComponent(name)), "utf8"),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
expect(largestComponentPayload).toBeLessThan(20_000);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns only requested shared prop documentation in one bounded payload", () => {
|
||||||
|
const result = getCustomWidgetSharedProps(["p", "m", "not-a-shared-prop", "p"]);
|
||||||
|
expect(result.props.map(({ name }) => name)).toEqual(["p", "m"]);
|
||||||
|
expect(result.notFound).toEqual(["not-a-shared-prop"]);
|
||||||
|
expect(Buffer.byteLength(JSON.stringify(result), "utf8")).toBeLessThan(4_000);
|
||||||
|
|
||||||
|
const boundedBatch = getCustomWidgetSharedProps(getCustomWidgetComponentCatalog().sharedProps.names.slice(0, 64));
|
||||||
|
expect(Buffer.byteLength(JSON.stringify(boundedBatch), "utf8")).toBeLessThan(15_000);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -71,17 +71,16 @@ describe("lean Custom Widget options", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("replaces stale values with current defaults", () => {
|
it("replaces stale values with current defaults", () => {
|
||||||
const options = customWidgetDefinitionSchema.parse({
|
const options = {
|
||||||
$schema: "homarr-custom-widget-v2",
|
limit: customWidgetOptionSchema.parse({
|
||||||
name: "Updated options",
|
label: "Limit",
|
||||||
sources: {},
|
control: "slider",
|
||||||
requests: {},
|
default: 5,
|
||||||
options: {
|
min: 1,
|
||||||
limit: { label: "Limit", control: "slider", default: 5, min: 1, max: 10 },
|
max: 10,
|
||||||
label: { label: "Label", control: "text", default: "Default" },
|
}),
|
||||||
},
|
label: customWidgetOptionSchema.parse({ label: "Label", control: "text", default: "Default" }),
|
||||||
template: "<Text>{options.limit}</Text>",
|
};
|
||||||
}).options;
|
|
||||||
|
|
||||||
const normalized = normalizeCustomWidgetOptions(options, {
|
const normalized = normalizeCustomWidgetOptions(options, {
|
||||||
limit: "5",
|
limit: "5",
|
||||||
|
|||||||
@@ -2,13 +2,16 @@ import { describe, expect, it } from "vitest";
|
|||||||
|
|
||||||
import {
|
import {
|
||||||
CUSTOM_WIDGET_STARTER,
|
CUSTOM_WIDGET_STARTER,
|
||||||
|
customWidgetAuthoringDefinitionSchema,
|
||||||
customWidgetDefinitionSchema,
|
customWidgetDefinitionSchema,
|
||||||
|
customWidgetUpdateSchema,
|
||||||
customJsxRequestSchema,
|
customJsxRequestSchema,
|
||||||
getCustomWidgetDefaultOptions,
|
getCustomWidgetDefaultOptions,
|
||||||
getCustomWidgetSecretRequirements,
|
getCustomWidgetSecretRequirements,
|
||||||
getCustomWidgetSourceSetups,
|
getCustomWidgetSourceSetups,
|
||||||
hasSameCustomWidgetSourceAuthentication,
|
hasSameCustomWidgetSourceAuthentication,
|
||||||
applyCustomWidgetSourceSetup,
|
applyCustomWidgetSourceSetup,
|
||||||
|
normalizeCustomWidgetAuthoringDefinition,
|
||||||
} from "../core";
|
} from "../core";
|
||||||
|
|
||||||
describe("lean Custom Widget schema", () => {
|
describe("lean Custom Widget schema", () => {
|
||||||
@@ -61,6 +64,56 @@ describe("lean Custom Widget schema", () => {
|
|||||||
expect(customWidgetDefinitionSchema.parse(withoutOptions).options).toEqual({});
|
expect(customWidgetDefinitionSchema.parse(withoutOptions).options).toEqual({});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("accepts and normalizes realistic multiline JSX without JSON string escaping", () => {
|
||||||
|
const { template: _template, ...definition } = CUSTOM_WIDGET_STARTER;
|
||||||
|
const templateLines = [
|
||||||
|
'<Stack gap="sm">',
|
||||||
|
' <Group justify="space-between">',
|
||||||
|
" <Text fw={700}>Upcoming fixtures</Text>",
|
||||||
|
' <Badge color="blue">{(data.fixtures ?? []).length} matches</Badge>',
|
||||||
|
" </Group>",
|
||||||
|
" {(data.fixtures ?? []).map(fixture => (",
|
||||||
|
' <Paper key={fixture.id} p="sm" withBorder>',
|
||||||
|
" <Text>{fixture.home_team.name} vs {fixture.away_team.name}</Text>",
|
||||||
|
" </Paper>",
|
||||||
|
" ))}",
|
||||||
|
"</Stack>",
|
||||||
|
];
|
||||||
|
const candidate = customWidgetAuthoringDefinitionSchema.parse({
|
||||||
|
...definition,
|
||||||
|
requests: { fixtures: { path: "/fixtures" } },
|
||||||
|
templateLines,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(normalizeCustomWidgetAuthoringDefinition(candidate).template).toBe(templateLines.join("\n"));
|
||||||
|
});
|
||||||
|
|
||||||
|
it("requires exactly one authoring template representation", () => {
|
||||||
|
expect(
|
||||||
|
customWidgetAuthoringDefinitionSchema.safeParse({ ...CUSTOM_WIDGET_STARTER, templateLines: ["<Text />"] })
|
||||||
|
.success,
|
||||||
|
).toBe(false);
|
||||||
|
const { template: _template, ...withoutTemplate } = CUSTOM_WIDGET_STARTER;
|
||||||
|
expect(customWidgetAuthoringDefinitionSchema.safeParse(withoutTemplate).success).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps omitted update fields absent when using templateLines", () => {
|
||||||
|
expect(customWidgetUpdateSchema.parse({ id: "widget", templateLines: ["<Text />"] })).toEqual({
|
||||||
|
id: "widget",
|
||||||
|
templateLines: ["<Text />"],
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("applies the template size limit before joining templateLines", () => {
|
||||||
|
const { template: _template, ...definition } = CUSTOM_WIDGET_STARTER;
|
||||||
|
expect(
|
||||||
|
customWidgetAuthoringDefinitionSchema.safeParse({
|
||||||
|
...definition,
|
||||||
|
templateLines: Array.from({ length: 6 }, () => "x".repeat(10_000)),
|
||||||
|
}).success,
|
||||||
|
).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
it("rejects source IDs that collide case-insensitively", () => {
|
it("rejects source IDs that collide case-insensitively", () => {
|
||||||
const result = customWidgetDefinitionSchema.safeParse({
|
const result = customWidgetDefinitionSchema.safeParse({
|
||||||
...CUSTOM_WIDGET_STARTER,
|
...CUSTOM_WIDGET_STARTER,
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import { integrationDefs } from "../integration";
|
|||||||
|
|
||||||
describe("Icon url's of integrations should be valid and return 200", () => {
|
describe("Icon url's of integrations should be valid and return 200", () => {
|
||||||
objectEntries(integrationDefs).forEach(([integration, { iconUrl }]) => {
|
objectEntries(integrationDefs).forEach(([integration, { iconUrl }]) => {
|
||||||
it.concurrent(`should return 200 for ${integration}`, async () => {
|
it(`should return 200 for ${integration}`, { concurrent: true, retry: 2, timeout: 15_000 }, async () => {
|
||||||
const res = await fetch(iconUrl);
|
const res = await fetch(iconUrl);
|
||||||
expect(res.status).toBe(200);
|
expect(res.status).toBe(200);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -2100,7 +2100,8 @@
|
|||||||
"dismissQuote": "Remove quote",
|
"dismissQuote": "Remove quote",
|
||||||
"attachments": {
|
"attachments": {
|
||||||
"add": "Attach an image or document",
|
"add": "Attach an image or document",
|
||||||
"errorTitle": "Attachment could not be added"
|
"errorTitle": "Attachment could not be added",
|
||||||
|
"imageUnsupported": "The selected model does not support image input."
|
||||||
},
|
},
|
||||||
"mentions": {
|
"mentions": {
|
||||||
"menu": "Add Homarr context",
|
"menu": "Add Homarr context",
|
||||||
@@ -2170,6 +2171,10 @@
|
|||||||
},
|
},
|
||||||
"toolInput": "Input",
|
"toolInput": "Input",
|
||||||
"toolOutput": "Output",
|
"toolOutput": "Output",
|
||||||
|
"toolNavigation": {
|
||||||
|
"openPreview": "Open preview",
|
||||||
|
"openWidget": "Open widget"
|
||||||
|
},
|
||||||
"webSearch": {
|
"webSearch": {
|
||||||
"title": "Web search",
|
"title": "Web search",
|
||||||
"completed": "OpenRouter searched the live web for this response.",
|
"completed": "OpenRouter searched the live web for this response.",
|
||||||
@@ -6131,8 +6136,7 @@
|
|||||||
},
|
},
|
||||||
"options": {
|
"options": {
|
||||||
"homarr": {
|
"homarr": {
|
||||||
"label": "Homarr",
|
"label": "Homarr"
|
||||||
"description": "A Homarr-hosted OpenRouter proxy with the same model discovery, tool, and web search features. Available in a future release."
|
|
||||||
},
|
},
|
||||||
"openrouter": {
|
"openrouter": {
|
||||||
"label": "OpenRouter",
|
"label": "OpenRouter",
|
||||||
@@ -6189,10 +6193,6 @@
|
|||||||
"title": "API base URL",
|
"title": "API base URL",
|
||||||
"description": "Include the API prefix, usually /v1. In containers, localhost refers to the Homarr container."
|
"description": "Include the API prefix, usually /v1. In containers, localhost refers to the Homarr container."
|
||||||
},
|
},
|
||||||
"destinationChanged": {
|
|
||||||
"title": "Credentials will not follow this endpoint",
|
|
||||||
"description": "Changing the provider or base URL clears the stored API key and headers unless replacements are entered now. This prevents sending one provider's secrets to another service."
|
|
||||||
},
|
|
||||||
"apiKey": {
|
"apiKey": {
|
||||||
"title": "API key",
|
"title": "API key",
|
||||||
"required": "Required by this provider. The value is encrypted and write-only.",
|
"required": "Required by this provider. The value is encrypted and write-only.",
|
||||||
@@ -6260,7 +6260,7 @@
|
|||||||
"discovering": "Refreshing the models available from this provider…",
|
"discovering": "Refreshing the models available from this provider…",
|
||||||
"discovered": "{count, plural, one {Discovered # model. Tool support depends on the selected endpoint and model.} other {Discovered # models. Tool support depends on the selected endpoint and model.}}",
|
"discovered": "{count, plural, one {Discovered # model. Tool support depends on the selected endpoint and model.} other {Discovered # models. Tool support depends on the selected endpoint and model.}}",
|
||||||
"discoveryFailed": "Model discovery did not complete",
|
"discoveryFailed": "Model discovery did not complete",
|
||||||
"context": "{count, number} token context",
|
"context": "{count} context window",
|
||||||
"toolsConfirmed": "Tools advertised",
|
"toolsConfirmed": "Tools advertised",
|
||||||
"toolsUnknown": "Verify tool support"
|
"toolsUnknown": "Verify tool support"
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -88,8 +88,16 @@ describe("section behavior validation", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
test.each(["category", "dynamic"])("rejects the legacy %s kind", (kind) => {
|
test("normalizes the legacy dynamic kind to a container", () => {
|
||||||
expect(() => sectionSchema.parse({ id: "legacy", kind, layouts: [] })).toThrow();
|
expect(sectionSchema.parse({ id: "legacy", kind: "dynamic", layouts: [] })).toMatchObject({
|
||||||
|
id: "legacy",
|
||||||
|
kind: "container",
|
||||||
|
layouts: [],
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test("rejects the legacy category kind", () => {
|
||||||
|
expect(() => sectionSchema.parse({ id: "legacy", kind: "category", layouts: [] })).toThrow();
|
||||||
});
|
});
|
||||||
|
|
||||||
test.each([
|
test.each([
|
||||||
|
|||||||
@@ -93,4 +93,8 @@ const containerSectionSchema = z.object({
|
|||||||
),
|
),
|
||||||
});
|
});
|
||||||
|
|
||||||
export const sectionSchema = z.union([emptySectionSchema, containerSectionSchema]);
|
const legacyDynamicSectionSchema = containerSectionSchema
|
||||||
|
.extend({ kind: z.literal("dynamic") })
|
||||||
|
.transform((section) => ({ ...section, kind: "container" as const }));
|
||||||
|
|
||||||
|
export const sectionSchema = z.union([emptySectionSchema, containerSectionSchema, legacyDynamicSectionSchema]);
|
||||||
@@ -10,7 +10,6 @@ const advancedFocusWidgetKinds = [
|
|||||||
"bookmarks",
|
"bookmarks",
|
||||||
"calendar",
|
"calendar",
|
||||||
"clock",
|
"clock",
|
||||||
"dockerContainers",
|
|
||||||
"downloads",
|
"downloads",
|
||||||
"firewall",
|
"firewall",
|
||||||
"healthMonitoring",
|
"healthMonitoring",
|
||||||
|
|||||||
@@ -25,7 +25,6 @@ const columnTranslationKeyMap = {
|
|||||||
|
|
||||||
export const { definition, componentLoader } = createWidgetDefinition("dockerContainers", {
|
export const { definition, componentLoader } = createWidgetDefinition("dockerContainers", {
|
||||||
icon: IconBrandDocker,
|
icon: IconBrandDocker,
|
||||||
supportsAdvancedFocus: true,
|
|
||||||
queryKey: [["docker", "getContainers"]],
|
queryKey: [["docker", "getContainers"]],
|
||||||
refetchInterval: 30,
|
refetchInterval: 30,
|
||||||
createOptions() {
|
createOptions() {
|
||||||
|
|||||||
Generated
+160
@@ -561,6 +561,9 @@ catalogs:
|
|||||||
react-resizable-panels:
|
react-resizable-panels:
|
||||||
specifier: ^4.12.2
|
specifier: ^4.12.2
|
||||||
version: 4.12.2
|
version: 4.12.2
|
||||||
|
react-shiki:
|
||||||
|
specifier: ^0.11.0
|
||||||
|
version: 0.11.0
|
||||||
react-simple-code-editor:
|
react-simple-code-editor:
|
||||||
specifier: ^0.14.1
|
specifier: ^0.14.1
|
||||||
version: 0.14.1
|
version: 0.14.1
|
||||||
@@ -1218,6 +1221,9 @@ importers:
|
|||||||
react-error-boundary:
|
react-error-boundary:
|
||||||
specifier: 'catalog:'
|
specifier: 'catalog:'
|
||||||
version: 6.1.2(react@19.2.7)
|
version: 6.1.2(react@19.2.7)
|
||||||
|
react-shiki:
|
||||||
|
specifier: 'catalog:'
|
||||||
|
version: 0.11.0(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(supports-color@10.2.2)
|
||||||
react-simple-code-editor:
|
react-simple-code-editor:
|
||||||
specifier: 'catalog:'
|
specifier: 'catalog:'
|
||||||
version: 0.14.1(react-dom@19.2.7(react@19.2.7))(react@19.2.7)
|
version: 0.14.1(react-dom@19.2.7(react@19.2.7))(react@19.2.7)
|
||||||
@@ -8174,6 +8180,37 @@ packages:
|
|||||||
react:
|
react:
|
||||||
optional: true
|
optional: true
|
||||||
|
|
||||||
|
'@shikijs/core@4.4.2':
|
||||||
|
resolution: {integrity: sha512-StyzbAyxg2/tBGf78gwbBkGyeQ73lf8UiJArFaQhTQIDqQOCKPCQFanvrs4/Yv3Yfyc+ONInJM6K+FMIf+P+kA==}
|
||||||
|
engines: {node: '>=20'}
|
||||||
|
|
||||||
|
'@shikijs/engine-javascript@4.4.2':
|
||||||
|
resolution: {integrity: sha512-MnIkeqWdVPUWsxlx8gKLVCJFTsqrQJgpTPBPpQwaFeJ56lOnJxj5aN2LUFnfxUEcvOQuNocmbaMnVrCEln6rkw==}
|
||||||
|
engines: {node: '>=20'}
|
||||||
|
|
||||||
|
'@shikijs/engine-oniguruma@4.4.2':
|
||||||
|
resolution: {integrity: sha512-GLhowz1+jixjz+wiZ3wMnOn1jTxiFCGl2PkXufivbnwPHKuyw1AYqu5/hbWhZZ2oAb0NP05WUJhYeigY14drnw==}
|
||||||
|
engines: {node: '>=20'}
|
||||||
|
|
||||||
|
'@shikijs/langs@4.4.2':
|
||||||
|
resolution: {integrity: sha512-8DfeusD+Zdv/eYIDdXyJTUnSMHt+aAWjAOCXV20HNGAHRlInXpG8wh421v6B91WOm9TFwRLN+b/LG5F2NAIojg==}
|
||||||
|
engines: {node: '>=20'}
|
||||||
|
|
||||||
|
'@shikijs/primitive@4.4.2':
|
||||||
|
resolution: {integrity: sha512-l6fQQKsOMlz72n38fztmSgZ76MO6KSWuw8o+GJ+FhmqrpC9pIOJNQNXGgbb5yX2AwpzlEHwsaLPnk/8o4Fm+rA==}
|
||||||
|
engines: {node: '>=20'}
|
||||||
|
|
||||||
|
'@shikijs/themes@4.4.2':
|
||||||
|
resolution: {integrity: sha512-H0CFoL07ddDC2Dd6EdrPYNkRhUR6YCkJlnuYFceYYUJJA5TIm2b5B33qqiDYryBExgbKMndFJPb2u1gTuqO37g==}
|
||||||
|
engines: {node: '>=20'}
|
||||||
|
|
||||||
|
'@shikijs/types@4.4.2':
|
||||||
|
resolution: {integrity: sha512-PFYitV4vpDr/iPCIhnHp+Q4ftic5N5VeNJ3KQ1O8gn3h2ar8qgwMAXF7tq4m1CWaMS60fV4VqF6vfnWH4F7vqQ==}
|
||||||
|
engines: {node: '>=20'}
|
||||||
|
|
||||||
|
'@shikijs/vscode-textmate@10.0.2':
|
||||||
|
resolution: {integrity: sha512-83yeghZ2xxin3Nj8z1NMd/NCuca+gsYXswywDy5bHvwlWL8tpTQmzGeUuHd9FC3E/SBEMvzJRwWEOz5gGes9Qg==}
|
||||||
|
|
||||||
'@sideway/address@4.1.5':
|
'@sideway/address@4.1.5':
|
||||||
resolution: {integrity: sha512-IqO/DUQHUkPeixNQ8n0JA6102hT9CmaljNTPmQ1u8MEhBo/R4Q8eKLN/vGZxuebwOroDB4cbpjheD4+/sKFK4Q==}
|
resolution: {integrity: sha512-IqO/DUQHUkPeixNQ8n0JA6102hT9CmaljNTPmQ1u8MEhBo/R4Q8eKLN/vGZxuebwOroDB4cbpjheD4+/sKFK4Q==}
|
||||||
|
|
||||||
@@ -9205,6 +9242,9 @@ packages:
|
|||||||
'@types/hast@3.0.4':
|
'@types/hast@3.0.4':
|
||||||
resolution: {integrity: sha512-WPs+bbQw5aCj+x6laNGWLH3wviHtoCv/P3+otBhbOhJgG8qtpdAMlTCxLtsTWA7LH1Oh/bFCHsBn0TPS5m30EQ==}
|
resolution: {integrity: sha512-WPs+bbQw5aCj+x6laNGWLH3wviHtoCv/P3+otBhbOhJgG8qtpdAMlTCxLtsTWA7LH1Oh/bFCHsBn0TPS5m30EQ==}
|
||||||
|
|
||||||
|
'@types/hast@3.0.5':
|
||||||
|
resolution: {integrity: sha512-rp/ezSWaD1m44dPKICGhiskI13nVr7qTloFwDa/IYkhhf5nzwP+zIQcIJh3WIFSBOy/H1PzB40jPjMDksN4F+g==}
|
||||||
|
|
||||||
'@types/history@4.7.11':
|
'@types/history@4.7.11':
|
||||||
resolution: {integrity: sha512-qjDJRrmvBMiTx+jyLxvLfJU7UznFuokDv4f3WRuriHKERccVpFU+8XMQUAbDzoiJCsmexxRExQeMwwCdamSKDA==}
|
resolution: {integrity: sha512-qjDJRrmvBMiTx+jyLxvLfJU7UznFuokDv4f3WRuriHKERccVpFU+8XMQUAbDzoiJCsmexxRExQeMwwCdamSKDA==}
|
||||||
|
|
||||||
@@ -13715,6 +13755,12 @@ packages:
|
|||||||
resolution: {integrity: sha512-1FlR+gjXK7X+AsAHso35MnyN5KqGwJRi/31ft6x0M194ht7S+rWAvd7PHss9xSKMzE0asv1pyIHaJYq+BbacAQ==}
|
resolution: {integrity: sha512-1FlR+gjXK7X+AsAHso35MnyN5KqGwJRi/31ft6x0M194ht7S+rWAvd7PHss9xSKMzE0asv1pyIHaJYq+BbacAQ==}
|
||||||
engines: {node: '>=12'}
|
engines: {node: '>=12'}
|
||||||
|
|
||||||
|
oniguruma-parser@0.12.2:
|
||||||
|
resolution: {integrity: sha512-6HVa5oIrgMC6aA6WF6XyyqbhRPJrKR02L20+2+zpDtO5QAzGHAUGw5TKQvwi5vctNnRHkJYmjAhRVQF2EKdTQw==}
|
||||||
|
|
||||||
|
oniguruma-to-es@4.3.6:
|
||||||
|
resolution: {integrity: sha512-csuQ9x3Yr0cEIs/Zgx/OEt9iBw9vqIunAPQkx19R/fiMq2oGVTgcMqO/V3Ybqefr1TBvosI6jU539ksaBULJyA==}
|
||||||
|
|
||||||
open@10.2.0:
|
open@10.2.0:
|
||||||
resolution: {integrity: sha512-YgBpdJHPyQ2UE5x+hlSXcnejzAvD0b22U2OuAP+8OnlJT+PjWPxtgmGqKKc+RgTM63U9gN0YzrYc71R2WT/hTA==}
|
resolution: {integrity: sha512-YgBpdJHPyQ2UE5x+hlSXcnejzAvD0b22U2OuAP+8OnlJT+PjWPxtgmGqKKc+RgTM63U9gN0YzrYc71R2WT/hTA==}
|
||||||
engines: {node: '>=18'}
|
engines: {node: '>=18'}
|
||||||
@@ -14856,6 +14902,19 @@ packages:
|
|||||||
peerDependencies:
|
peerDependencies:
|
||||||
react: '>=15'
|
react: '>=15'
|
||||||
|
|
||||||
|
react-shiki@0.11.0:
|
||||||
|
resolution: {integrity: sha512-rqQtAvR8igCA9TVPfRhG6BSNeV+pLJZIkySms/K0/jYIoehG4/EsXD3cEhC94RXEpUVpmCrNkYhKR7RBO1YUGw==}
|
||||||
|
peerDependencies:
|
||||||
|
'@types/react': '>=16.14.0'
|
||||||
|
'@types/react-dom': '>=16.14.0'
|
||||||
|
react: '>=16.14.0'
|
||||||
|
react-dom: '>=16.14.0'
|
||||||
|
peerDependenciesMeta:
|
||||||
|
'@types/react':
|
||||||
|
optional: true
|
||||||
|
'@types/react-dom':
|
||||||
|
optional: true
|
||||||
|
|
||||||
react-simple-code-editor@0.14.1:
|
react-simple-code-editor@0.14.1:
|
||||||
resolution: {integrity: sha512-BR5DtNRy+AswWJECyA17qhUDvrrCZ6zXOCfkQY5zSmb96BVUbpVAv03WpcjcwtCwiLbIANx3gebHOcXYn1EHow==}
|
resolution: {integrity: sha512-BR5DtNRy+AswWJECyA17qhUDvrrCZ6zXOCfkQY5zSmb96BVUbpVAv03WpcjcwtCwiLbIANx3gebHOcXYn1EHow==}
|
||||||
peerDependencies:
|
peerDependencies:
|
||||||
@@ -14992,6 +15051,15 @@ packages:
|
|||||||
regenerate@1.4.2:
|
regenerate@1.4.2:
|
||||||
resolution: {integrity: sha512-zrceR/XhGYU/d/opr2EKO7aRHUeiBI8qjtfHqADTwZd6Szfy16la6kqD0MIUs5z5hx6AaKa+PixpPrR289+I0A==}
|
resolution: {integrity: sha512-zrceR/XhGYU/d/opr2EKO7aRHUeiBI8qjtfHqADTwZd6Szfy16la6kqD0MIUs5z5hx6AaKa+PixpPrR289+I0A==}
|
||||||
|
|
||||||
|
regex-recursion@6.0.2:
|
||||||
|
resolution: {integrity: sha512-0YCaSCq2VRIebiaUviZNs0cBz1kg5kVS2UKUfNIx8YVs1cN3AV7NTctO5FOKBA+UT2BPJIWZauYHPqJODG50cg==}
|
||||||
|
|
||||||
|
regex-utilities@2.3.0:
|
||||||
|
resolution: {integrity: sha512-8VhliFJAWRaUiVvREIiW2NXXTmHs4vMNnSzuJVhscgmGav3g9VDxLrQndI3dZZVVdp0ZO/5v0xmX516/7M9cng==}
|
||||||
|
|
||||||
|
regex@6.1.0:
|
||||||
|
resolution: {integrity: sha512-6VwtthbV4o/7+OaAF9I5L5V3llLEsoPyq9P1JVXkedTP33c7MfCG0/5NOPcSJn0TzXcG9YUrR0gQSWioew3LDg==}
|
||||||
|
|
||||||
regexpu-core@6.4.0:
|
regexpu-core@6.4.0:
|
||||||
resolution: {integrity: sha512-0ghuzq67LI9bLXpOX/ISfve/Mq33a4aFRzoQYhnnok1JOFpmE/A2TBGkNVenOGEeSBCjIiWcc6MVOG5HEQv0sA==}
|
resolution: {integrity: sha512-0ghuzq67LI9bLXpOX/ISfve/Mq33a4aFRzoQYhnnok1JOFpmE/A2TBGkNVenOGEeSBCjIiWcc6MVOG5HEQv0sA==}
|
||||||
engines: {node: '>=4'}
|
engines: {node: '>=4'}
|
||||||
@@ -15343,6 +15411,10 @@ packages:
|
|||||||
resolution: {integrity: sha512-VsC6n6vz1ihYYyZZwX7YZSF5l5x36ca17OC+a69h94YqB7X6XLwf+5MOgynYir2SLFUbl8gIYvBo8K8RoNQ6bQ==}
|
resolution: {integrity: sha512-VsC6n6vz1ihYYyZZwX7YZSF5l5x36ca17OC+a69h94YqB7X6XLwf+5MOgynYir2SLFUbl8gIYvBo8K8RoNQ6bQ==}
|
||||||
engines: {node: '>= 0.4'}
|
engines: {node: '>= 0.4'}
|
||||||
|
|
||||||
|
shiki@4.4.2:
|
||||||
|
resolution: {integrity: sha512-P8F/dFhRevaw2uSdeIYlq/5SXZNY85DPtmXQ947gD1Zj2JqO5AkNvVVBar0Me9JkFx3uzVud/qOtP5ek9NEQGA==}
|
||||||
|
engines: {node: '>=20'}
|
||||||
|
|
||||||
side-channel-list@1.0.0:
|
side-channel-list@1.0.0:
|
||||||
resolution: {integrity: sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==}
|
resolution: {integrity: sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==}
|
||||||
engines: {node: '>= 0.4'}
|
engines: {node: '>= 0.4'}
|
||||||
@@ -23191,6 +23263,46 @@ snapshots:
|
|||||||
'@types/react': 19.2.17
|
'@types/react': 19.2.17
|
||||||
react: 19.2.7
|
react: 19.2.7
|
||||||
|
|
||||||
|
'@shikijs/core@4.4.2':
|
||||||
|
dependencies:
|
||||||
|
'@shikijs/primitive': 4.4.2
|
||||||
|
'@shikijs/types': 4.4.2
|
||||||
|
'@shikijs/vscode-textmate': 10.0.2
|
||||||
|
'@types/hast': 3.0.5
|
||||||
|
hast-util-to-html: 9.0.5
|
||||||
|
|
||||||
|
'@shikijs/engine-javascript@4.4.2':
|
||||||
|
dependencies:
|
||||||
|
'@shikijs/types': 4.4.2
|
||||||
|
'@shikijs/vscode-textmate': 10.0.2
|
||||||
|
oniguruma-to-es: 4.3.6
|
||||||
|
|
||||||
|
'@shikijs/engine-oniguruma@4.4.2':
|
||||||
|
dependencies:
|
||||||
|
'@shikijs/types': 4.4.2
|
||||||
|
'@shikijs/vscode-textmate': 10.0.2
|
||||||
|
|
||||||
|
'@shikijs/langs@4.4.2':
|
||||||
|
dependencies:
|
||||||
|
'@shikijs/types': 4.4.2
|
||||||
|
|
||||||
|
'@shikijs/primitive@4.4.2':
|
||||||
|
dependencies:
|
||||||
|
'@shikijs/types': 4.4.2
|
||||||
|
'@shikijs/vscode-textmate': 10.0.2
|
||||||
|
'@types/hast': 3.0.5
|
||||||
|
|
||||||
|
'@shikijs/themes@4.4.2':
|
||||||
|
dependencies:
|
||||||
|
'@shikijs/types': 4.4.2
|
||||||
|
|
||||||
|
'@shikijs/types@4.4.2':
|
||||||
|
dependencies:
|
||||||
|
'@shikijs/vscode-textmate': 10.0.2
|
||||||
|
'@types/hast': 3.0.5
|
||||||
|
|
||||||
|
'@shikijs/vscode-textmate@10.0.2': {}
|
||||||
|
|
||||||
'@sideway/address@4.1.5':
|
'@sideway/address@4.1.5':
|
||||||
dependencies:
|
dependencies:
|
||||||
'@hapi/hoek': 9.3.0
|
'@hapi/hoek': 9.3.0
|
||||||
@@ -24193,6 +24305,10 @@ snapshots:
|
|||||||
dependencies:
|
dependencies:
|
||||||
'@types/unist': 3.0.3
|
'@types/unist': 3.0.3
|
||||||
|
|
||||||
|
'@types/hast@3.0.5':
|
||||||
|
dependencies:
|
||||||
|
'@types/unist': 3.0.3
|
||||||
|
|
||||||
'@types/history@4.7.11': {}
|
'@types/history@4.7.11': {}
|
||||||
|
|
||||||
'@types/html-minifier-terser@6.1.0': {}
|
'@types/html-minifier-terser@6.1.0': {}
|
||||||
@@ -29244,6 +29360,14 @@ snapshots:
|
|||||||
dependencies:
|
dependencies:
|
||||||
mimic-fn: 4.0.0
|
mimic-fn: 4.0.0
|
||||||
|
|
||||||
|
oniguruma-parser@0.12.2: {}
|
||||||
|
|
||||||
|
oniguruma-to-es@4.3.6:
|
||||||
|
dependencies:
|
||||||
|
oniguruma-parser: 0.12.2
|
||||||
|
regex: 6.1.0
|
||||||
|
regex-recursion: 6.0.2
|
||||||
|
|
||||||
open@10.2.0:
|
open@10.2.0:
|
||||||
dependencies:
|
dependencies:
|
||||||
default-browser: 5.5.0
|
default-browser: 5.5.0
|
||||||
@@ -30594,6 +30718,21 @@ snapshots:
|
|||||||
tiny-invariant: 1.3.3
|
tiny-invariant: 1.3.3
|
||||||
tiny-warning: 1.0.3
|
tiny-warning: 1.0.3
|
||||||
|
|
||||||
|
react-shiki@0.11.0(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(supports-color@10.2.2):
|
||||||
|
dependencies:
|
||||||
|
clsx: 2.1.1
|
||||||
|
dequal: 2.0.3
|
||||||
|
hast-util-to-jsx-runtime: 2.3.6(supports-color@10.2.2)
|
||||||
|
react: 19.2.7
|
||||||
|
react-dom: 19.2.7(react@19.2.7)
|
||||||
|
shiki: 4.4.2
|
||||||
|
unist-util-visit: 5.1.0
|
||||||
|
optionalDependencies:
|
||||||
|
'@types/react': 19.2.17
|
||||||
|
'@types/react-dom': 19.2.3(@types/react@19.2.17)
|
||||||
|
transitivePeerDependencies:
|
||||||
|
- supports-color
|
||||||
|
|
||||||
react-simple-code-editor@0.14.1(react-dom@19.2.7(react@19.2.7))(react@19.2.7):
|
react-simple-code-editor@0.14.1(react-dom@19.2.7(react@19.2.7))(react@19.2.7):
|
||||||
dependencies:
|
dependencies:
|
||||||
react: 19.2.7
|
react: 19.2.7
|
||||||
@@ -30785,6 +30924,16 @@ snapshots:
|
|||||||
|
|
||||||
regenerate@1.4.2: {}
|
regenerate@1.4.2: {}
|
||||||
|
|
||||||
|
regex-recursion@6.0.2:
|
||||||
|
dependencies:
|
||||||
|
regex-utilities: 2.3.0
|
||||||
|
|
||||||
|
regex-utilities@2.3.0: {}
|
||||||
|
|
||||||
|
regex@6.1.0:
|
||||||
|
dependencies:
|
||||||
|
regex-utilities: 2.3.0
|
||||||
|
|
||||||
regexpu-core@6.4.0:
|
regexpu-core@6.4.0:
|
||||||
dependencies:
|
dependencies:
|
||||||
regenerate: 1.4.2
|
regenerate: 1.4.2
|
||||||
@@ -31278,6 +31427,17 @@ snapshots:
|
|||||||
|
|
||||||
shell-quote@1.8.4: {}
|
shell-quote@1.8.4: {}
|
||||||
|
|
||||||
|
shiki@4.4.2:
|
||||||
|
dependencies:
|
||||||
|
'@shikijs/core': 4.4.2
|
||||||
|
'@shikijs/engine-javascript': 4.4.2
|
||||||
|
'@shikijs/engine-oniguruma': 4.4.2
|
||||||
|
'@shikijs/langs': 4.4.2
|
||||||
|
'@shikijs/themes': 4.4.2
|
||||||
|
'@shikijs/types': 4.4.2
|
||||||
|
'@shikijs/vscode-textmate': 10.0.2
|
||||||
|
'@types/hast': 3.0.5
|
||||||
|
|
||||||
side-channel-list@1.0.0:
|
side-channel-list@1.0.0:
|
||||||
dependencies:
|
dependencies:
|
||||||
es-errors: 1.3.0
|
es-errors: 1.3.0
|
||||||
|
|||||||
@@ -224,6 +224,7 @@ catalog:
|
|||||||
remark-breaks: ^4.0.0
|
remark-breaks: ^4.0.0
|
||||||
remark-directive: ^3.0.1
|
remark-directive: ^3.0.1
|
||||||
remark-gfm: ^4.0.1
|
remark-gfm: ^4.0.1
|
||||||
|
react-shiki: ^0.11.0
|
||||||
|
|
||||||
catalogMode: strict
|
catalogMode: strict
|
||||||
nodeLinker: hoisted
|
nodeLinker: hoisted
|
||||||
|
|||||||
Reference in new issue
Block a user