skybridge 0.0.0-dev.f1f2ce8 → 0.0.0-dev.f2073a1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +16 -14
- package/dist/cli/build-helpers.d.ts +1 -1
- package/dist/cli/build-helpers.js +4 -4
- package/dist/cli/build-helpers.js.map +1 -1
- package/dist/cli/build-helpers.test.js +6 -4
- package/dist/cli/build-helpers.test.js.map +1 -1
- package/dist/cli/build-steps.js +1 -1
- package/dist/cli/build-steps.js.map +1 -1
- package/dist/cli/build-steps.test.js +3 -3
- package/dist/cli/build-steps.test.js.map +1 -1
- package/dist/cli/detect-port.js +0 -1
- package/dist/cli/detect-port.js.map +1 -1
- package/dist/cli/run-plain.js +2 -1
- package/dist/cli/run-plain.js.map +1 -1
- package/dist/cli/telemetry.js +2 -0
- package/dist/cli/telemetry.js.map +1 -1
- package/dist/cli/use-execute-steps.d.ts +1 -1
- package/dist/cli/use-nodemon.d.ts +11 -1
- package/dist/cli/use-nodemon.js +30 -8
- package/dist/cli/use-nodemon.js.map +1 -1
- package/dist/cli/use-typescript-check.js +1 -1
- package/dist/cli/use-typescript-check.js.map +1 -1
- package/dist/commands/dev.js +4 -4
- package/dist/commands/dev.js.map +1 -1
- package/dist/commands/start.js +2 -2
- package/dist/commands/start.js.map +1 -1
- package/dist/context-warnings.d.ts +5 -0
- package/dist/context-warnings.js +31 -0
- package/dist/context-warnings.js.map +1 -0
- package/dist/context-warnings.test.js +28 -0
- package/dist/context-warnings.test.js.map +1 -0
- package/dist/server/app.d.ts +194 -0
- package/dist/server/app.js +266 -0
- package/dist/server/app.js.map +1 -0
- package/dist/server/app.test.js +97 -0
- package/dist/server/app.test.js.map +1 -0
- package/dist/server/auth/discovery.d.ts +2 -1
- package/dist/server/auth/discovery.js +2 -2
- package/dist/server/auth/discovery.js.map +1 -1
- package/dist/server/auth/index.d.ts +35 -5
- package/dist/server/auth/index.js.map +1 -1
- package/dist/server/auth/providers/auth0.d.ts +25 -3
- package/dist/server/auth/providers/auth0.js +13 -8
- package/dist/server/auth/providers/auth0.js.map +1 -1
- package/dist/server/auth/providers/auth0.test.js +5 -3
- package/dist/server/auth/providers/auth0.test.js.map +1 -1
- package/dist/server/auth/providers/authplane.d.ts +49 -0
- package/dist/server/auth/providers/authplane.js +57 -0
- package/dist/server/auth/providers/authplane.js.map +1 -0
- package/dist/server/auth/providers/authplane.test.js +143 -0
- package/dist/server/auth/providers/authplane.test.js.map +1 -0
- package/dist/server/auth/providers/clerk.d.ts +40 -3
- package/dist/server/auth/providers/clerk.js +4 -1
- package/dist/server/auth/providers/clerk.js.map +1 -1
- package/dist/server/auth/providers/clerk.test.js +5 -3
- package/dist/server/auth/providers/clerk.test.js.map +1 -1
- package/dist/server/auth/providers/custom.d.ts +16 -6
- package/dist/server/auth/providers/custom.js +14 -4
- package/dist/server/auth/providers/custom.js.map +1 -1
- package/dist/server/auth/providers/custom.test.js +24 -19
- package/dist/server/auth/providers/custom.test.js.map +1 -1
- package/dist/server/auth/providers/descope.d.ts +32 -3
- package/dist/server/auth/providers/descope.js.map +1 -1
- package/dist/server/auth/providers/descope.test.js +8 -6
- package/dist/server/auth/providers/descope.test.js.map +1 -1
- package/dist/server/auth/providers/stytch.d.ts +16 -3
- package/dist/server/auth/providers/stytch.js +4 -1
- package/dist/server/auth/providers/stytch.js.map +1 -1
- package/dist/server/auth/providers/verify-spy.d.ts +12 -0
- package/dist/server/auth/providers/verify-spy.js +21 -0
- package/dist/server/auth/providers/verify-spy.js.map +1 -0
- package/dist/server/auth/providers/workos.d.ts +28 -5
- package/dist/server/auth/providers/workos.js +6 -2
- package/dist/server/auth/providers/workos.js.map +1 -1
- package/dist/server/auth/setup.d.ts +1 -1
- package/dist/server/auth/setup.js +4 -5
- package/dist/server/auth/setup.js.map +1 -1
- package/dist/server/auth/setup.test.js +97 -57
- package/dist/server/auth/setup.test.js.map +1 -1
- package/dist/server/auth/verify.d.ts +42 -6
- package/dist/server/auth/verify.js +27 -3
- package/dist/server/auth/verify.js.map +1 -1
- package/dist/server/auth/verify.test.js +65 -0
- package/dist/server/auth/verify.test.js.map +1 -1
- package/dist/server/auth-extra.test-d.js +130 -0
- package/dist/server/auth-extra.test-d.js.map +1 -0
- package/dist/server/auth.d.ts +43 -6
- package/dist/server/auth.js +4 -5
- package/dist/server/auth.js.map +1 -1
- package/dist/server/build-manifest.test.js +7 -6
- package/dist/server/build-manifest.test.js.map +1 -1
- package/dist/server/content-helpers.d.ts +1 -1
- package/dist/server/content-helpers.js.map +1 -1
- package/dist/server/events.d.ts +113 -0
- package/dist/server/events.js +318 -0
- package/dist/server/events.js.map +1 -0
- package/dist/server/events.test.js +172 -0
- package/dist/server/events.test.js.map +1 -0
- package/dist/server/express.d.ts +23 -3
- package/dist/server/express.js +43 -32
- package/dist/server/express.js.map +1 -1
- package/dist/server/express.test.js +221 -103
- package/dist/server/express.test.js.map +1 -1
- package/dist/server/file-ref.d.ts +1 -1
- package/dist/server/file-ref.js +1 -1
- package/dist/server/file-ref.js.map +1 -1
- package/dist/server/form-input.d.ts +120 -0
- package/dist/server/form-input.js +89 -0
- package/dist/server/form-input.js.map +1 -0
- package/dist/server/index.d.ts +16 -8
- package/dist/server/index.js +9 -2
- package/dist/server/index.js.map +1 -1
- package/dist/server/mcp-errors.test.js +41 -0
- package/dist/server/mcp-errors.test.js.map +1 -0
- package/dist/server/middleware.d.ts +35 -10
- package/dist/server/middleware.js +33 -0
- package/dist/server/middleware.js.map +1 -1
- package/dist/server/middleware.test-d.js +1 -1
- package/dist/server/middleware.test-d.js.map +1 -1
- package/dist/server/middleware.test.js +242 -134
- package/dist/server/middleware.test.js.map +1 -1
- package/dist/server/register-tool.test.d.ts +1 -0
- package/dist/server/register-tool.test.js +230 -0
- package/dist/server/register-tool.test.js.map +1 -0
- package/dist/server/server.d.ts +337 -128
- package/dist/server/server.js +373 -305
- package/dist/server/server.js.map +1 -1
- package/dist/server/skills-integration.test.js +44 -21
- package/dist/server/skills-integration.test.js.map +1 -1
- package/dist/server/skills.d.ts +14 -10
- package/dist/server/skills.js +49 -39
- package/dist/server/skills.js.map +1 -1
- package/dist/server/skills.test.js +77 -44
- package/dist/server/skills.test.js.map +1 -1
- package/dist/server/templateHelper.d.ts +0 -3
- package/dist/server/templateHelper.js.map +1 -1
- package/dist/server/templates.generated.js +4 -8
- package/dist/server/templates.generated.js.map +1 -1
- package/dist/server/tool-extra.test.d.ts +1 -0
- package/dist/server/tool-extra.test.js +167 -0
- package/dist/server/tool-extra.test.js.map +1 -0
- package/dist/server/view-resource-resolution.test.js +18 -13
- package/dist/server/view-resource-resolution.test.js.map +1 -1
- package/dist/test/utils.d.ts +9 -11
- package/dist/test/utils.js +220 -201
- package/dist/test/utils.js.map +1 -1
- package/dist/test/view.test.js +41 -37
- package/dist/test/view.test.js.map +1 -1
- package/dist/views/index.d.ts +10 -0
- package/dist/views/index.js +3 -0
- package/dist/views/index.js.map +1 -0
- package/dist/{web/plugin → views}/scan-views.js +1 -1
- package/dist/views/scan-views.js.map +1 -0
- package/dist/views/scan-views.test.d.ts +1 -0
- package/dist/views/scan-views.test.js.map +1 -0
- package/dist/views/validate-view.d.ts +1 -0
- package/dist/{web/plugin → views}/validate-view.js +2 -2
- package/dist/views/validate-view.js.map +1 -0
- package/dist/views/validate-view.test.d.ts +1 -0
- package/dist/views/validate-view.test.js.map +1 -0
- package/dist/web/bridges/adaptor.d.ts +14 -3
- package/dist/web/bridges/adaptor.js +171 -30
- package/dist/web/bridges/adaptor.js.map +1 -1
- package/dist/web/bridges/adaptor.test.js +69 -13
- package/dist/web/bridges/adaptor.test.js.map +1 -1
- package/dist/web/bridges/apps-sdk/bridge.js +1 -1
- package/dist/web/bridges/apps-sdk/bridge.js.map +1 -1
- package/dist/web/bridges/apps-sdk/use-apps-sdk-context.d.ts +4 -4
- package/dist/web/bridges/apps-sdk/use-apps-sdk-context.js +4 -4
- package/dist/web/bridges/apps-sdk/use-apps-sdk-context.js.map +1 -1
- package/dist/web/bridges/get-adaptor.test.js +2 -2
- package/dist/web/bridges/get-adaptor.test.js.map +1 -1
- package/dist/web/bridges/mcp-app/bridge.d.ts +1 -1
- package/dist/web/bridges/mcp-app/bridge.js +10 -3
- package/dist/web/bridges/mcp-app/bridge.js.map +1 -1
- package/dist/web/bridges/mcp-app/bridge.test.js +2 -2
- package/dist/web/bridges/mcp-app/bridge.test.js.map +1 -1
- package/dist/web/bridges/mcp-app/types.d.ts +18 -3
- package/dist/web/bridges/mcp-app/types.js.map +1 -1
- package/dist/web/bridges/mcp-app/use-mcp-app-context.d.ts +2 -2
- package/dist/web/bridges/mcp-app/use-mcp-app-context.js +1 -1
- package/dist/web/bridges/mcp-app/use-mcp-app-context.js.map +1 -1
- package/dist/web/bridges/mcp-app/use-mcp-app-context.test.js +1 -1
- package/dist/web/bridges/mcp-app/use-mcp-app-context.test.js.map +1 -1
- package/dist/web/bridges/mcp-app/view-tools.test.js +1 -1
- package/dist/web/bridges/mcp-app/view-tools.test.js.map +1 -1
- package/dist/web/bridges/types.d.ts +74 -16
- package/dist/web/bridges/types.js +1 -1
- package/dist/web/bridges/types.js.map +1 -1
- package/dist/web/create-store.test.js +2 -2
- package/dist/web/create-store.test.js.map +1 -1
- package/dist/web/data-llm.js +3 -2
- package/dist/web/data-llm.js.map +1 -1
- package/dist/web/data-llm.test.js +11 -4
- package/dist/web/data-llm.test.js.map +1 -1
- package/dist/web/generate-helpers.d.ts +23 -19
- package/dist/web/generate-helpers.js +21 -17
- package/dist/web/generate-helpers.js.map +1 -1
- package/dist/web/generate-helpers.test-d.js +3 -3
- package/dist/web/generate-helpers.test-d.js.map +1 -1
- package/dist/web/generate-helpers.test.js +2 -2
- package/dist/web/generate-helpers.test.js.map +1 -1
- package/dist/web/hooks/index.d.ts +6 -2
- package/dist/web/hooks/index.js +6 -2
- package/dist/web/hooks/index.js.map +1 -1
- package/dist/web/hooks/openai-extensions.test.d.ts +1 -0
- package/dist/web/hooks/openai-extensions.test.js +107 -0
- package/dist/web/hooks/openai-extensions.test.js.map +1 -0
- package/dist/web/hooks/use-call-tool.d.ts +2 -2
- package/dist/web/hooks/use-call-tool.js +15 -10
- package/dist/web/hooks/use-call-tool.js.map +1 -1
- package/dist/web/hooks/use-call-tool.test.js +15 -4
- package/dist/web/hooks/use-call-tool.test.js.map +1 -1
- package/dist/web/hooks/use-deep-link.d.ts +22 -0
- package/dist/web/hooks/use-deep-link.js +34 -0
- package/dist/web/hooks/use-deep-link.js.map +1 -0
- package/dist/web/hooks/use-display-mode.d.ts +1 -1
- package/dist/web/hooks/use-display-mode.js +1 -1
- package/dist/web/hooks/use-display-mode.js.map +1 -1
- package/dist/web/hooks/use-display-mode.test.js +1 -1
- package/dist/web/hooks/use-display-mode.test.js.map +1 -1
- package/dist/web/hooks/use-download.d.ts +1 -3
- package/dist/web/hooks/use-download.js +1 -2
- package/dist/web/hooks/use-download.js.map +1 -1
- package/dist/web/hooks/use-download.test.js +7 -7
- package/dist/web/hooks/use-download.test.js.map +1 -1
- package/dist/web/hooks/use-file-resource.d.ts +37 -0
- package/dist/web/hooks/use-file-resource.js +98 -0
- package/dist/web/hooks/use-file-resource.js.map +1 -0
- package/dist/web/hooks/use-file-resource.test.d.ts +1 -0
- package/dist/web/hooks/use-file-resource.test.js +65 -0
- package/dist/web/hooks/use-file-resource.test.js.map +1 -0
- package/dist/web/hooks/use-files.test.js +1 -1
- package/dist/web/hooks/use-files.test.js.map +1 -1
- package/dist/web/hooks/use-host.d.ts +44 -0
- package/dist/web/hooks/use-host.js +45 -0
- package/dist/web/hooks/use-host.js.map +1 -0
- package/dist/web/hooks/use-host.test.d.ts +1 -0
- package/dist/web/hooks/{use-host-info.test.js → use-host.test.js} +7 -7
- package/dist/web/hooks/use-host.test.js.map +1 -0
- package/dist/web/hooks/use-model-context.d.ts +44 -0
- package/dist/web/hooks/use-model-context.js +63 -0
- package/dist/web/hooks/use-model-context.js.map +1 -0
- package/dist/web/hooks/use-open-external.test.js +2 -2
- package/dist/web/hooks/use-open-external.test.js.map +1 -1
- package/dist/web/hooks/use-open-file.d.ts +20 -0
- package/dist/web/hooks/use-open-file.js +25 -0
- package/dist/web/hooks/use-open-file.js.map +1 -0
- package/dist/web/hooks/use-register-view-tool.d.ts +3 -4
- package/dist/web/hooks/use-register-view-tool.js +1 -1
- package/dist/web/hooks/use-register-view-tool.js.map +1 -1
- package/dist/web/hooks/use-request-close.test.js +1 -1
- package/dist/web/hooks/use-request-close.test.js.map +1 -1
- package/dist/web/hooks/use-request-modal.test.js +1 -1
- package/dist/web/hooks/use-request-modal.test.js.map +1 -1
- package/dist/web/hooks/use-request-size.d.ts +1 -1
- package/dist/web/hooks/use-request-size.js +1 -1
- package/dist/web/hooks/use-request-size.js.map +1 -1
- package/dist/web/hooks/use-request-size.test.js +1 -1
- package/dist/web/hooks/use-request-size.test.js.map +1 -1
- package/dist/web/hooks/use-send-follow-up-message.d.ts +8 -2
- package/dist/web/hooks/use-send-follow-up-message.js +6 -0
- package/dist/web/hooks/use-send-follow-up-message.js.map +1 -1
- package/dist/web/hooks/use-set-open-in-app-url.test.js +2 -8
- package/dist/web/hooks/use-set-open-in-app-url.test.js.map +1 -1
- package/dist/web/hooks/use-tool-info.d.ts +1 -20
- package/dist/web/hooks/use-tool-info.js +0 -1
- package/dist/web/hooks/use-tool-info.js.map +1 -1
- package/dist/web/hooks/use-tool-info.test-d.js +0 -5
- package/dist/web/hooks/use-tool-info.test-d.js.map +1 -1
- package/dist/web/hooks/use-tool-info.test.js +2 -7
- package/dist/web/hooks/use-tool-info.test.js.map +1 -1
- package/dist/web/hooks/use-user.d.ts +3 -2
- package/dist/web/hooks/use-user.js +4 -3
- package/dist/web/hooks/use-user.js.map +1 -1
- package/dist/web/hooks/use-user.test.js +5 -3
- package/dist/web/hooks/use-user.test.js.map +1 -1
- package/dist/web/hooks/use-view-state.js +19 -9
- package/dist/web/hooks/use-view-state.js.map +1 -1
- package/dist/web/hooks/use-view-state.test.js +33 -2
- package/dist/web/hooks/use-view-state.test.js.map +1 -1
- package/dist/web/hooks/use-viewport.d.ts +20 -0
- package/dist/web/hooks/use-viewport.js +21 -0
- package/dist/web/hooks/use-viewport.js.map +1 -0
- package/dist/web/hooks/use-viewport.test.d.ts +1 -0
- package/dist/web/hooks/{use-layout.test.js → use-viewport.test.js} +12 -32
- package/dist/web/hooks/use-viewport.test.js.map +1 -0
- package/dist/web/mount-view.d.ts +3 -2
- package/dist/web/mount-view.js +5 -8
- package/dist/web/mount-view.js.map +1 -1
- package/package.json +17 -13
- package/dist/web/hooks/use-host-info.d.ts +0 -22
- package/dist/web/hooks/use-host-info.js +0 -30
- package/dist/web/hooks/use-host-info.js.map +0 -1
- package/dist/web/hooks/use-host-info.test.js.map +0 -1
- package/dist/web/hooks/use-layout.d.ts +0 -24
- package/dist/web/hooks/use-layout.js +0 -25
- package/dist/web/hooks/use-layout.js.map +0 -1
- package/dist/web/hooks/use-layout.test.js.map +0 -1
- package/dist/web/plugin/data-llm.test.js +0 -81
- package/dist/web/plugin/data-llm.test.js.map +0 -1
- package/dist/web/plugin/plugin.d.ts +0 -39
- package/dist/web/plugin/plugin.js +0 -189
- package/dist/web/plugin/plugin.js.map +0 -1
- package/dist/web/plugin/scan-views.js.map +0 -1
- package/dist/web/plugin/scan-views.test.js.map +0 -1
- package/dist/web/plugin/transform-data-llm.d.ts +0 -12
- package/dist/web/plugin/transform-data-llm.js +0 -96
- package/dist/web/plugin/transform-data-llm.js.map +0 -1
- package/dist/web/plugin/transform-data-llm.test.js +0 -81
- package/dist/web/plugin/transform-data-llm.test.js.map +0 -1
- package/dist/web/plugin/validate-view.d.ts +0 -1
- package/dist/web/plugin/validate-view.js.map +0 -1
- package/dist/web/plugin/validate-view.test.js.map +0 -1
- /package/dist/{web/hooks/use-host-info.test.d.ts → context-warnings.test.d.ts} +0 -0
- /package/dist/{web/hooks/use-layout.test.d.ts → server/app.test.d.ts} +0 -0
- /package/dist/{web/plugin/scan-views.test.d.ts → server/auth/providers/authplane.test.d.ts} +0 -0
- /package/dist/{web/plugin/data-llm.test.d.ts → server/auth-extra.test-d.d.ts} +0 -0
- /package/dist/{web/plugin/transform-data-llm.test.d.ts → server/events.test.d.ts} +0 -0
- /package/dist/{web/plugin/validate-view.test.d.ts → server/mcp-errors.test.d.ts} +0 -0
- /package/dist/{web/plugin → views}/scan-views.d.ts +0 -0
- /package/dist/{web/plugin → views}/scan-views.test.js +0 -0
- /package/dist/{web/plugin → views}/validate-view.test.js +0 -0
|
@@ -1,13 +1,12 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
import type {
|
|
1
|
+
import type { CallToolResult, ContentBlock, EmbeddedResource, ResourceLink, ToolAnnotations } from "@modelcontextprotocol/client";
|
|
2
|
+
import type { McpUiUpdateModelContextRequest } from "@modelcontextprotocol/ext-apps";
|
|
3
3
|
import type { useSyncExternalStore } from "react";
|
|
4
|
-
import type {
|
|
4
|
+
import type { output as ZodOutput, ZodType } from "zod/v4";
|
|
5
5
|
/**
|
|
6
|
-
* Globals injected on `window.skybridge` by the host. Tells the view
|
|
7
|
-
*
|
|
6
|
+
* Globals injected on `window.skybridge` by the host. Tells the view where to
|
|
7
|
+
* reach the MCP server.
|
|
8
8
|
*/
|
|
9
9
|
export type SkybridgeProperties = {
|
|
10
|
-
hostType: ViewHostType;
|
|
11
10
|
serverUrl: string;
|
|
12
11
|
};
|
|
13
12
|
declare global {
|
|
@@ -17,6 +16,16 @@ declare global {
|
|
|
17
16
|
}
|
|
18
17
|
/** Arguments passed to a tool call. `null` for tools that take no input. */
|
|
19
18
|
export type CallToolArgs = Record<string, unknown> | null;
|
|
19
|
+
/** Options for a tool call made from the view. */
|
|
20
|
+
export type CallToolOptions = {
|
|
21
|
+
/**
|
|
22
|
+
* Request timeout in milliseconds. Omit it to keep the SDK default (60s).
|
|
23
|
+
* Raise it for tools that wait on the user, such as ChatGPT forms.
|
|
24
|
+
*/
|
|
25
|
+
timeout?: number;
|
|
26
|
+
};
|
|
27
|
+
/** Payload of `ui/update-model-context`. Content blocks may carry `_meta`. */
|
|
28
|
+
export type ModelContextParams = McpUiUpdateModelContextRequest["params"];
|
|
20
29
|
/**
|
|
21
30
|
* Result of a tool call as surfaced to the view: MCP `content` blocks plus
|
|
22
31
|
* the typed `structuredContent` and optional `meta`. `isError` is set when
|
|
@@ -47,7 +56,7 @@ export type SafeAreaInsets = {
|
|
|
47
56
|
bottom: number;
|
|
48
57
|
left: number;
|
|
49
58
|
};
|
|
50
|
-
/** Wrapper around {@link SafeAreaInsets} exposed via {@link
|
|
59
|
+
/** Wrapper around {@link SafeAreaInsets} exposed via {@link useViewport}. */
|
|
51
60
|
export type SafeArea = {
|
|
52
61
|
insets: SafeAreaInsets;
|
|
53
62
|
};
|
|
@@ -63,7 +72,7 @@ export type UserAgent = {
|
|
|
63
72
|
};
|
|
64
73
|
/**
|
|
65
74
|
* Full snapshot of state the host exposes to the view. Most fields are
|
|
66
|
-
* better accessed through their dedicated hooks (`
|
|
75
|
+
* better accessed through their dedicated hooks (`useViewport`, `useUser`,
|
|
67
76
|
* `useToolInfo`, etc.) — read this directly only for advanced cases.
|
|
68
77
|
*/
|
|
69
78
|
export interface HostContext {
|
|
@@ -131,8 +140,45 @@ export type OpenExternalOptions = {
|
|
|
131
140
|
};
|
|
132
141
|
/** Options for {@link useSendFollowUpMessage}. */
|
|
133
142
|
export type SendFollowUpMessageOptions = {
|
|
143
|
+
/** Apps SDK only: set to `false` to keep the chat scroll position. */
|
|
134
144
|
scrollToBottom?: boolean;
|
|
145
|
+
/**
|
|
146
|
+
* ChatGPT only, from the OpenAI MCP extensions: `"new"` starts a new
|
|
147
|
+
* conversation with the message. Defaults to the active conversation.
|
|
148
|
+
* Rejects on hosts that don't advertise `openai/message`.
|
|
149
|
+
*/
|
|
150
|
+
target?: "active" | "new";
|
|
151
|
+
};
|
|
152
|
+
/** How the host should return a file resource's contents. */
|
|
153
|
+
export type ResourceRepresentation = "text" | "blob";
|
|
154
|
+
/** Contents of a file resource: text, or a base64 `blob`. */
|
|
155
|
+
export type FileResourceContent = {
|
|
156
|
+
text: string;
|
|
157
|
+
} | {
|
|
158
|
+
blob: string;
|
|
159
|
+
};
|
|
160
|
+
/** A file resource as read from the host. */
|
|
161
|
+
export type FileResource = FileResourceContent & {
|
|
162
|
+
mimeType?: string;
|
|
163
|
+
/** Whether the host accepts writes to this resource. */
|
|
164
|
+
writable: boolean;
|
|
165
|
+
/** Version token of these contents, sent back as `ifMatch` on write. */
|
|
166
|
+
etag?: string;
|
|
167
|
+
};
|
|
168
|
+
/** Result of `openai/resources/write`. */
|
|
169
|
+
export type FileResourceWriteResult = {
|
|
170
|
+
outcome: "saved" | "conflict";
|
|
171
|
+
etag: string;
|
|
172
|
+
} | {
|
|
173
|
+
outcome: "too-large";
|
|
174
|
+
maxBytes: number;
|
|
135
175
|
};
|
|
176
|
+
/**
|
|
177
|
+
* A follow-up message: plain text, or content blocks. On ChatGPT, a text or
|
|
178
|
+
* image block with `_meta["openai/title"]` becomes a labeled item the user can
|
|
179
|
+
* remove.
|
|
180
|
+
*/
|
|
181
|
+
export type FollowUpMessage = string | ContentBlock[];
|
|
136
182
|
/** Options for {@link useRequestSize}. Omit a dimension to leave it unchanged. */
|
|
137
183
|
export type RequestSizeOptions = {
|
|
138
184
|
width?: number;
|
|
@@ -144,21 +190,28 @@ export type DownloadParams = {
|
|
|
144
190
|
export type DownloadResult = {
|
|
145
191
|
isError?: boolean;
|
|
146
192
|
};
|
|
193
|
+
/**
|
|
194
|
+
* Shape of a view tool's `inputSchema`: a map of zod schemas. Narrower than
|
|
195
|
+
* the server's `Record<string, StandardSchemaWithJSON>` input shape because the MCP Apps bridge validates with
|
|
196
|
+
* `z.object()` at runtime — other Standard Schema libraries would type-check
|
|
197
|
+
* but throw on the first call.
|
|
198
|
+
*/
|
|
199
|
+
export type ViewToolInputShape = Record<string, ZodType>;
|
|
147
200
|
/**
|
|
148
201
|
* Args passed to a {@link ViewToolHandler}, inferred from the tool's
|
|
149
202
|
* `inputSchema` (optionality preserved). Mirrors the server's `registerTool`.
|
|
150
203
|
*/
|
|
151
|
-
export type InferViewToolArgs<Shape extends
|
|
152
|
-
[K in keyof Shape as undefined extends
|
|
204
|
+
export type InferViewToolArgs<Shape extends ViewToolInputShape> = {
|
|
205
|
+
[K in keyof Shape as undefined extends ZodOutput<Shape[K]> ? never : K]: ZodOutput<Shape[K]>;
|
|
153
206
|
} & {
|
|
154
|
-
[K in keyof Shape as undefined extends
|
|
207
|
+
[K in keyof Shape as undefined extends ZodOutput<Shape[K]> ? K : never]?: ZodOutput<Shape[K]>;
|
|
155
208
|
};
|
|
156
209
|
/**
|
|
157
210
|
* Declares a tool the view exposes to the host/model (the MCP Apps
|
|
158
211
|
* "app-provided tools" feature). Mirrors the server-side `registerTool` config.
|
|
159
212
|
* Namespace `name` (e.g. `chess_make_move`) to avoid clashing with server tools.
|
|
160
213
|
*/
|
|
161
|
-
export type ViewToolConfig<TInput extends
|
|
214
|
+
export type ViewToolConfig<TInput extends ViewToolInputShape = ViewToolInputShape> = {
|
|
162
215
|
name: string;
|
|
163
216
|
title?: string;
|
|
164
217
|
description?: string;
|
|
@@ -172,7 +225,7 @@ export type ViewToolConfig<TInput extends ZodRawShapeCompat = ZodRawShapeCompat>
|
|
|
172
225
|
*/
|
|
173
226
|
export type ViewToolResult = CallToolResult;
|
|
174
227
|
/** Handler run when the host calls a view tool. Receives validated, typed args. */
|
|
175
|
-
export type ViewToolHandler<TInput extends
|
|
228
|
+
export type ViewToolHandler<TInput extends ViewToolInputShape = ViewToolInputShape> = (args: InferViewToolArgs<TInput>) => ViewToolResult | Promise<ViewToolResult>;
|
|
176
229
|
/** @internal Untyped handler signature stored by the adaptor/bridge after type erasure. */
|
|
177
230
|
export type AnyViewToolHandler = (args: Record<string, unknown>) => ViewToolResult | Promise<ViewToolResult>;
|
|
178
231
|
/**
|
|
@@ -183,16 +236,21 @@ export type AnyViewToolHandler = (args: Record<string, unknown>) => ViewToolResu
|
|
|
183
236
|
*/
|
|
184
237
|
export interface Adaptor {
|
|
185
238
|
getHostContextStore<K extends keyof HostContext>(key: K): HostContextStore<K>;
|
|
186
|
-
callTool<ToolArgs extends CallToolArgs = null, ToolResponse extends CallToolResponse = CallToolResponse>(name: string, args: ToolArgs): Promise<ToolResponse>;
|
|
239
|
+
callTool<ToolArgs extends CallToolArgs = null, ToolResponse extends CallToolResponse = CallToolResponse>(name: string, args: ToolArgs, options?: CallToolOptions): Promise<ToolResponse>;
|
|
187
240
|
requestDisplayMode(mode: RequestDisplayMode): Promise<{
|
|
188
241
|
mode: RequestDisplayMode;
|
|
189
242
|
}>;
|
|
190
243
|
requestClose(): Promise<void>;
|
|
191
244
|
requestSize(size: RequestSizeOptions): Promise<void>;
|
|
192
|
-
sendFollowUpMessage(prompt:
|
|
245
|
+
sendFollowUpMessage(prompt: FollowUpMessage, options?: SendFollowUpMessageOptions): Promise<void>;
|
|
193
246
|
openExternal(href: string, options?: OpenExternalOptions): void;
|
|
194
247
|
download(params: DownloadParams): Promise<DownloadResult>;
|
|
195
248
|
setViewState(stateOrUpdater: SetViewStateAction): Promise<void>;
|
|
249
|
+
updateModelContext(params: ModelContextParams): Promise<string | undefined>;
|
|
250
|
+
openFile(path: string): Promise<void>;
|
|
251
|
+
readResource(uri: string, representation?: ResourceRepresentation): Promise<FileResource>;
|
|
252
|
+
watchResource(uri: string, onUpdate: () => void): () => void;
|
|
253
|
+
writeResource(uri: string, content: FileResourceContent, ifMatch?: string): Promise<FileResourceWriteResult>;
|
|
196
254
|
uploadFile(file: File, options?: UploadFileOptions): Promise<FileMetadata>;
|
|
197
255
|
getFileDownloadUrl(file: FileMetadata): Promise<{
|
|
198
256
|
downloadUrl: string;
|
|
@@ -205,7 +263,7 @@ export interface Adaptor {
|
|
|
205
263
|
}
|
|
206
264
|
/**
|
|
207
265
|
* Thrown when a host bridge method is called in a runtime that doesn't
|
|
208
|
-
* support it (e.g. `uploadFile` outside the
|
|
266
|
+
* support it (e.g. `uploadFile` outside the ChatGPT runtime).
|
|
209
267
|
*/
|
|
210
268
|
export declare class NotSupportedError extends Error {
|
|
211
269
|
readonly method: string;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Thrown when a host bridge method is called in a runtime that doesn't
|
|
3
|
-
* support it (e.g. `uploadFile` outside the
|
|
3
|
+
* support it (e.g. `uploadFile` outside the ChatGPT runtime).
|
|
4
4
|
*/
|
|
5
5
|
export class NotSupportedError extends Error {
|
|
6
6
|
method;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/web/bridges/types.ts"],"names":[],"mappings":"AAgQA;;;GAGG;AACH,MAAM,OAAO,iBAAkB,SAAQ,KAAK;IAExB;IACA;IAFlB,YACkB,MAAc,EACd,MAAe;QAE/B,KAAK,CACH,GAAG,MAAM,oCAAoC,MAAM,CAAC,CAAC,CAAC,KAAK,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,EAAE,CAC3E,CAAC;QALc,WAAM,GAAN,MAAM,CAAQ;QACd,WAAM,GAAN,MAAM,CAAS;QAK/B,IAAI,CAAC,IAAI,GAAG,mBAAmB,CAAC;IAClC,CAAC;CACF","sourcesContent":["import type {\n SchemaOutput,\n ZodRawShapeCompat,\n} from \"@modelcontextprotocol/sdk/server/zod-compat.js\";\nimport type {\n CallToolResult,\n EmbeddedResource,\n ResourceLink,\n ToolAnnotations,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport type { useSyncExternalStore } from \"react\";\nimport type { ViewHostType } from \"../../server/index.js\";\n\n/**\n * Globals injected on `window.skybridge` by the host. Tells the view which\n * runtime it's running under and where to reach the MCP server.\n */\nexport type SkybridgeProperties = {\n hostType: ViewHostType;\n serverUrl: string;\n};\n\ndeclare global {\n interface Window {\n skybridge: SkybridgeProperties;\n }\n}\n\n/** Arguments passed to a tool call. `null` for tools that take no input. */\nexport type CallToolArgs = Record<string, unknown> | null;\n\n/**\n * Result of a tool call as surfaced to the view: MCP `content` blocks plus\n * the typed `structuredContent` and optional `meta`. `isError` is set when\n * the server marks the call as failed.\n */\nexport type CallToolResponse = {\n content: CallToolResult[\"content\"];\n structuredContent: NonNullable<CallToolResult[\"structuredContent\"]>;\n isError: NonNullable<CallToolResult[\"isError\"]>;\n meta?: CallToolResult[\"_meta\"];\n};\n\n/**\n * How the view is laid out by the host. `\"modal\"` is host-driven (see\n * {@link useRequestModal}); `\"pip\"`, `\"inline\"`, and `\"fullscreen\"` are\n * requestable via {@link useDisplayMode}.\n */\nexport type DisplayMode = \"pip\" | \"inline\" | \"fullscreen\" | \"modal\";\n/** Subset of {@link DisplayMode} that the view can request from the host. */\nexport type RequestDisplayMode = Exclude<DisplayMode, \"modal\">;\n\n/** Host theme. Mirror this in your view's styling for a native feel. */\nexport type Theme = \"light\" | \"dark\";\n\n/** Coarse device class reported by the host. `\"unknown\"` when unavailable. */\nexport type DeviceType = \"mobile\" | \"tablet\" | \"desktop\" | \"unknown\";\n\n/** Pixel insets the view should keep clear of (notches, home indicators, etc.). */\nexport type SafeAreaInsets = {\n top: number;\n right: number;\n bottom: number;\n left: number;\n};\n\n/** Wrapper around {@link SafeAreaInsets} exposed via {@link useLayout}. */\nexport type SafeArea = {\n insets: SafeAreaInsets;\n};\n\n/** Device and input-capability hints exposed via {@link useUser}. */\nexport type UserAgent = {\n device: {\n type: DeviceType;\n };\n capabilities: {\n hover: boolean;\n touch: boolean;\n };\n};\n\n/**\n * Full snapshot of state the host exposes to the view. Most fields are\n * better accessed through their dedicated hooks (`useLayout`, `useUser`,\n * `useToolInfo`, etc.) — read this directly only for advanced cases.\n */\nexport interface HostContext {\n theme: Theme;\n locale: string;\n displayMode: DisplayMode;\n safeArea: SafeArea;\n maxHeight: number | undefined;\n userAgent: UserAgent;\n toolInput: Record<string, unknown> | null;\n toolOutput: Record<string, unknown> | null;\n toolResponseMetadata: Record<string, unknown> | null;\n display: {\n mode: DisplayMode;\n params?: Record<string, unknown>;\n };\n viewState: Record<string, unknown> | null;\n}\n\n/** @internal `useSyncExternalStore` subscribe signature, re-exported for bridge implementations. */\nexport type Subscribe = Parameters<typeof useSyncExternalStore>[0];\n\n/** @internal Bridge contract implemented by per-host bridge classes. */\nexport interface Bridge<Context> {\n subscribe(key: keyof Context): Subscribe;\n subscribe(keys: readonly (keyof Context)[]): Subscribe;\n getSnapshot<K extends keyof Context>(key: K): Context[K] | undefined;\n}\n\n/** @internal Per-key snapshot store backing {@link useHostContext}. */\nexport type HostContextStore<K extends keyof HostContext> = {\n subscribe: Subscribe;\n getSnapshot: () => HostContext[K];\n};\n\n/** Persisted view state shape (a plain object). See {@link useViewState}. */\nexport type ViewState = Record<string, unknown>;\n\n/** Updater form accepted when writing to view state. */\nexport type SetViewStateAction =\n | ViewState\n | ((prevState: ViewState | null) => ViewState);\n\n/** Reference to a host-managed file (returned by {@link useFiles}). */\nexport type FileMetadata = {\n fileId: string;\n fileName?: string;\n mimeType?: string;\n};\n\n/** Options for {@link useFiles}'s `upload`. `library: true` saves into the user's library when supported. */\nexport type UploadFileOptions = { library?: boolean };\n\n/** Options for {@link useRequestModal}'s `open` call. */\nexport type RequestModalOptions = {\n title?: string;\n params?: Record<string, unknown>;\n template?: string;\n anchor?: { top?: number; left?: number; width?: number; height?: number };\n};\n\n/**\n * Options for {@link useOpenExternal}. Set `redirectUrl: false` to tell the\n * host not to append its `?redirectUrl=…` tracking query parameter when\n * opening allowlisted targets.\n */\nexport type OpenExternalOptions = {\n redirectUrl?: false;\n};\n\n/** Options for {@link useSendFollowUpMessage}. */\nexport type SendFollowUpMessageOptions = { scrollToBottom?: boolean };\n\n/** Options for {@link useRequestSize}. Omit a dimension to leave it unchanged. */\nexport type RequestSizeOptions = {\n width?: number;\n height?: number;\n};\n\nexport type DownloadParams = {\n contents: (EmbeddedResource | ResourceLink)[];\n};\n\nexport type DownloadResult = {\n isError?: boolean;\n};\n\n/**\n * Args passed to a {@link ViewToolHandler}, inferred from the tool's\n * `inputSchema` (optionality preserved). Mirrors the server's `registerTool`.\n */\nexport type InferViewToolArgs<Shape extends ZodRawShapeCompat> = {\n [K in keyof Shape as undefined extends SchemaOutput<Shape[K]>\n ? never\n : K]: SchemaOutput<Shape[K]>;\n} & {\n [K in keyof Shape as undefined extends SchemaOutput<Shape[K]>\n ? K\n : never]?: SchemaOutput<Shape[K]>;\n};\n\n/**\n * Declares a tool the view exposes to the host/model (the MCP Apps\n * \"app-provided tools\" feature). Mirrors the server-side `registerTool` config.\n * Namespace `name` (e.g. `chess_make_move`) to avoid clashing with server tools.\n */\nexport type ViewToolConfig<\n TInput extends ZodRawShapeCompat = ZodRawShapeCompat,\n> = {\n name: string;\n title?: string;\n description?: string;\n inputSchema?: TInput;\n annotations?: ToolAnnotations;\n};\n\n/**\n * Value a {@link ViewToolHandler} returns — a standard MCP `CallToolResult`\n * (`content` blocks plus optional `structuredContent` / `isError` / `_meta`),\n * exactly as `ext-apps`' app tool callbacks return it.\n */\nexport type ViewToolResult = CallToolResult;\n\n/** Handler run when the host calls a view tool. Receives validated, typed args. */\nexport type ViewToolHandler<\n TInput extends ZodRawShapeCompat = ZodRawShapeCompat,\n> = (\n args: InferViewToolArgs<TInput>,\n) => ViewToolResult | Promise<ViewToolResult>;\n\n/** @internal Untyped handler signature stored by the adaptor/bridge after type erasure. */\nexport type AnyViewToolHandler = (\n args: Record<string, unknown>,\n) => ViewToolResult | Promise<ViewToolResult>;\n\n/**\n * @internal\n * Low-level interface every host bridge implements. End-user code should use\n * the React hooks (`useCallTool`, `useViewState`, `useFiles`, …) rather than\n * calling this directly.\n */\nexport interface Adaptor {\n getHostContextStore<K extends keyof HostContext>(key: K): HostContextStore<K>;\n callTool<\n ToolArgs extends CallToolArgs = null,\n ToolResponse extends CallToolResponse = CallToolResponse,\n >(name: string, args: ToolArgs): Promise<ToolResponse>;\n requestDisplayMode(mode: RequestDisplayMode): Promise<{\n mode: RequestDisplayMode;\n }>;\n requestClose(): Promise<void>;\n requestSize(size: RequestSizeOptions): Promise<void>;\n sendFollowUpMessage(\n prompt: string,\n options?: SendFollowUpMessageOptions,\n ): Promise<void>;\n openExternal(href: string, options?: OpenExternalOptions): void;\n download(params: DownloadParams): Promise<DownloadResult>;\n setViewState(stateOrUpdater: SetViewStateAction): Promise<void>;\n uploadFile(file: File, options?: UploadFileOptions): Promise<FileMetadata>;\n getFileDownloadUrl(file: FileMetadata): Promise<{ downloadUrl: string }>;\n selectFiles(): Promise<FileMetadata[]>;\n openModal(options: RequestModalOptions): void;\n setOpenInAppUrl(href: string): Promise<void>;\n closeModal(): void;\n registerViewTool(\n config: ViewToolConfig,\n handler: AnyViewToolHandler,\n ): () => void;\n}\n\n/**\n * Thrown when a host bridge method is called in a runtime that doesn't\n * support it (e.g. `uploadFile` outside the Apps SDK runtime).\n */\nexport class NotSupportedError extends Error {\n constructor(\n public readonly method: string,\n public readonly reason?: string,\n ) {\n super(\n `${method} is not supported in this runtime${reason ? `: ${reason}` : \"\"}`,\n );\n this.name = \"NotSupportedError\";\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/web/bridges/types.ts"],"names":[],"mappings":"AAqUA;;;GAGG;AACH,MAAM,OAAO,iBAAkB,SAAQ,KAAK;IAExB;IACA;IAFlB,YACkB,MAAc,EACd,MAAe;QAE/B,KAAK,CACH,GAAG,MAAM,oCAAoC,MAAM,CAAC,CAAC,CAAC,KAAK,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,EAAE,CAC3E,CAAC;QALc,WAAM,GAAN,MAAM,CAAQ;QACd,WAAM,GAAN,MAAM,CAAS;QAK/B,IAAI,CAAC,IAAI,GAAG,mBAAmB,CAAC;IAClC,CAAC;CACF","sourcesContent":["import type {\n CallToolResult,\n ContentBlock,\n EmbeddedResource,\n ResourceLink,\n ToolAnnotations,\n} from \"@modelcontextprotocol/client\";\nimport type { McpUiUpdateModelContextRequest } from \"@modelcontextprotocol/ext-apps\";\nimport type { useSyncExternalStore } from \"react\";\nimport type { output as ZodOutput, ZodType } from \"zod/v4\";\n\n/**\n * Globals injected on `window.skybridge` by the host. Tells the view where to\n * reach the MCP server.\n */\nexport type SkybridgeProperties = {\n serverUrl: string;\n};\n\ndeclare global {\n interface Window {\n skybridge: SkybridgeProperties;\n }\n}\n\n/** Arguments passed to a tool call. `null` for tools that take no input. */\nexport type CallToolArgs = Record<string, unknown> | null;\n\n/** Options for a tool call made from the view. */\nexport type CallToolOptions = {\n /**\n * Request timeout in milliseconds. Omit it to keep the SDK default (60s).\n * Raise it for tools that wait on the user, such as ChatGPT forms.\n */\n timeout?: number;\n};\n\n/** Payload of `ui/update-model-context`. Content blocks may carry `_meta`. */\nexport type ModelContextParams = McpUiUpdateModelContextRequest[\"params\"];\n\n/**\n * Result of a tool call as surfaced to the view: MCP `content` blocks plus\n * the typed `structuredContent` and optional `meta`. `isError` is set when\n * the server marks the call as failed.\n */\nexport type CallToolResponse = {\n content: CallToolResult[\"content\"];\n structuredContent: NonNullable<CallToolResult[\"structuredContent\"]>;\n isError: NonNullable<CallToolResult[\"isError\"]>;\n meta?: CallToolResult[\"_meta\"];\n};\n\n/**\n * How the view is laid out by the host. `\"modal\"` is host-driven (see\n * {@link useRequestModal}); `\"pip\"`, `\"inline\"`, and `\"fullscreen\"` are\n * requestable via {@link useDisplayMode}.\n */\nexport type DisplayMode = \"pip\" | \"inline\" | \"fullscreen\" | \"modal\";\n/** Subset of {@link DisplayMode} that the view can request from the host. */\nexport type RequestDisplayMode = Exclude<DisplayMode, \"modal\">;\n\n/** Host theme. Mirror this in your view's styling for a native feel. */\nexport type Theme = \"light\" | \"dark\";\n\n/** Coarse device class reported by the host. `\"unknown\"` when unavailable. */\nexport type DeviceType = \"mobile\" | \"tablet\" | \"desktop\" | \"unknown\";\n\n/** Pixel insets the view should keep clear of (notches, home indicators, etc.). */\nexport type SafeAreaInsets = {\n top: number;\n right: number;\n bottom: number;\n left: number;\n};\n\n/** Wrapper around {@link SafeAreaInsets} exposed via {@link useViewport}. */\nexport type SafeArea = {\n insets: SafeAreaInsets;\n};\n\n/** Device and input-capability hints exposed via {@link useUser}. */\nexport type UserAgent = {\n device: {\n type: DeviceType;\n };\n capabilities: {\n hover: boolean;\n touch: boolean;\n };\n};\n\n/**\n * Full snapshot of state the host exposes to the view. Most fields are\n * better accessed through their dedicated hooks (`useViewport`, `useUser`,\n * `useToolInfo`, etc.) — read this directly only for advanced cases.\n */\nexport interface HostContext {\n theme: Theme;\n locale: string;\n displayMode: DisplayMode;\n safeArea: SafeArea;\n maxHeight: number | undefined;\n userAgent: UserAgent;\n toolInput: Record<string, unknown> | null;\n toolOutput: Record<string, unknown> | null;\n toolResponseMetadata: Record<string, unknown> | null;\n display: {\n mode: DisplayMode;\n params?: Record<string, unknown>;\n };\n viewState: Record<string, unknown> | null;\n}\n\n/** @internal `useSyncExternalStore` subscribe signature, re-exported for bridge implementations. */\nexport type Subscribe = Parameters<typeof useSyncExternalStore>[0];\n\n/** @internal Bridge contract implemented by per-host bridge classes. */\nexport interface Bridge<Context> {\n subscribe(key: keyof Context): Subscribe;\n subscribe(keys: readonly (keyof Context)[]): Subscribe;\n getSnapshot<K extends keyof Context>(key: K): Context[K] | undefined;\n}\n\n/** @internal Per-key snapshot store backing {@link useHostContext}. */\nexport type HostContextStore<K extends keyof HostContext> = {\n subscribe: Subscribe;\n getSnapshot: () => HostContext[K];\n};\n\n/** Persisted view state shape (a plain object). See {@link useViewState}. */\nexport type ViewState = Record<string, unknown>;\n\n/** Updater form accepted when writing to view state. */\nexport type SetViewStateAction =\n | ViewState\n | ((prevState: ViewState | null) => ViewState);\n\n/** Reference to a host-managed file (returned by {@link useFiles}). */\nexport type FileMetadata = {\n fileId: string;\n fileName?: string;\n mimeType?: string;\n};\n\n/** Options for {@link useFiles}'s `upload`. `library: true` saves into the user's library when supported. */\nexport type UploadFileOptions = { library?: boolean };\n\n/** Options for {@link useRequestModal}'s `open` call. */\nexport type RequestModalOptions = {\n title?: string;\n params?: Record<string, unknown>;\n template?: string;\n anchor?: { top?: number; left?: number; width?: number; height?: number };\n};\n\n/**\n * Options for {@link useOpenExternal}. Set `redirectUrl: false` to tell the\n * host not to append its `?redirectUrl=…` tracking query parameter when\n * opening allowlisted targets.\n */\nexport type OpenExternalOptions = {\n redirectUrl?: false;\n};\n\n/** Options for {@link useSendFollowUpMessage}. */\nexport type SendFollowUpMessageOptions = {\n /** Apps SDK only: set to `false` to keep the chat scroll position. */\n scrollToBottom?: boolean;\n /**\n * ChatGPT only, from the OpenAI MCP extensions: `\"new\"` starts a new\n * conversation with the message. Defaults to the active conversation.\n * Rejects on hosts that don't advertise `openai/message`.\n */\n target?: \"active\" | \"new\";\n};\n\n/** How the host should return a file resource's contents. */\nexport type ResourceRepresentation = \"text\" | \"blob\";\n\n/** Contents of a file resource: text, or a base64 `blob`. */\nexport type FileResourceContent = { text: string } | { blob: string };\n\n/** A file resource as read from the host. */\nexport type FileResource = FileResourceContent & {\n mimeType?: string;\n /** Whether the host accepts writes to this resource. */\n writable: boolean;\n /** Version token of these contents, sent back as `ifMatch` on write. */\n etag?: string;\n};\n\n/** Result of `openai/resources/write`. */\nexport type FileResourceWriteResult =\n | { outcome: \"saved\" | \"conflict\"; etag: string }\n | { outcome: \"too-large\"; maxBytes: number };\n\n/**\n * A follow-up message: plain text, or content blocks. On ChatGPT, a text or\n * image block with `_meta[\"openai/title\"]` becomes a labeled item the user can\n * remove.\n */\nexport type FollowUpMessage = string | ContentBlock[];\n\n/** Options for {@link useRequestSize}. Omit a dimension to leave it unchanged. */\nexport type RequestSizeOptions = {\n width?: number;\n height?: number;\n};\n\nexport type DownloadParams = {\n contents: (EmbeddedResource | ResourceLink)[];\n};\n\nexport type DownloadResult = {\n isError?: boolean;\n};\n\n/**\n * Shape of a view tool's `inputSchema`: a map of zod schemas. Narrower than\n * the server's `Record<string, StandardSchemaWithJSON>` input shape because the MCP Apps bridge validates with\n * `z.object()` at runtime — other Standard Schema libraries would type-check\n * but throw on the first call.\n */\nexport type ViewToolInputShape = Record<string, ZodType>;\n\n/**\n * Args passed to a {@link ViewToolHandler}, inferred from the tool's\n * `inputSchema` (optionality preserved). Mirrors the server's `registerTool`.\n */\nexport type InferViewToolArgs<Shape extends ViewToolInputShape> = {\n [K in keyof Shape as undefined extends ZodOutput<Shape[K]>\n ? never\n : K]: ZodOutput<Shape[K]>;\n} & {\n [K in keyof Shape as undefined extends ZodOutput<Shape[K]>\n ? K\n : never]?: ZodOutput<Shape[K]>;\n};\n\n/**\n * Declares a tool the view exposes to the host/model (the MCP Apps\n * \"app-provided tools\" feature). Mirrors the server-side `registerTool` config.\n * Namespace `name` (e.g. `chess_make_move`) to avoid clashing with server tools.\n */\nexport type ViewToolConfig<\n TInput extends ViewToolInputShape = ViewToolInputShape,\n> = {\n name: string;\n title?: string;\n description?: string;\n inputSchema?: TInput;\n annotations?: ToolAnnotations;\n};\n\n/**\n * Value a {@link ViewToolHandler} returns — a standard MCP `CallToolResult`\n * (`content` blocks plus optional `structuredContent` / `isError` / `_meta`),\n * exactly as `ext-apps`' app tool callbacks return it.\n */\nexport type ViewToolResult = CallToolResult;\n\n/** Handler run when the host calls a view tool. Receives validated, typed args. */\nexport type ViewToolHandler<\n TInput extends ViewToolInputShape = ViewToolInputShape,\n> = (\n args: InferViewToolArgs<TInput>,\n) => ViewToolResult | Promise<ViewToolResult>;\n\n/** @internal Untyped handler signature stored by the adaptor/bridge after type erasure. */\nexport type AnyViewToolHandler = (\n args: Record<string, unknown>,\n) => ViewToolResult | Promise<ViewToolResult>;\n\n/**\n * @internal\n * Low-level interface every host bridge implements. End-user code should use\n * the React hooks (`useCallTool`, `useViewState`, `useFiles`, …) rather than\n * calling this directly.\n */\nexport interface Adaptor {\n getHostContextStore<K extends keyof HostContext>(key: K): HostContextStore<K>;\n callTool<\n ToolArgs extends CallToolArgs = null,\n ToolResponse extends CallToolResponse = CallToolResponse,\n >(\n name: string,\n args: ToolArgs,\n options?: CallToolOptions,\n ): Promise<ToolResponse>;\n requestDisplayMode(mode: RequestDisplayMode): Promise<{\n mode: RequestDisplayMode;\n }>;\n requestClose(): Promise<void>;\n requestSize(size: RequestSizeOptions): Promise<void>;\n sendFollowUpMessage(\n prompt: FollowUpMessage,\n options?: SendFollowUpMessageOptions,\n ): Promise<void>;\n openExternal(href: string, options?: OpenExternalOptions): void;\n download(params: DownloadParams): Promise<DownloadResult>;\n setViewState(stateOrUpdater: SetViewStateAction): Promise<void>;\n updateModelContext(params: ModelContextParams): Promise<string | undefined>;\n openFile(path: string): Promise<void>;\n readResource(\n uri: string,\n representation?: ResourceRepresentation,\n ): Promise<FileResource>;\n watchResource(uri: string, onUpdate: () => void): () => void;\n writeResource(\n uri: string,\n content: FileResourceContent,\n ifMatch?: string,\n ): Promise<FileResourceWriteResult>;\n uploadFile(file: File, options?: UploadFileOptions): Promise<FileMetadata>;\n getFileDownloadUrl(file: FileMetadata): Promise<{ downloadUrl: string }>;\n selectFiles(): Promise<FileMetadata[]>;\n openModal(options: RequestModalOptions): void;\n setOpenInAppUrl(href: string): Promise<void>;\n closeModal(): void;\n registerViewTool(\n config: ViewToolConfig,\n handler: AnyViewToolHandler,\n ): () => void;\n}\n\n/**\n * Thrown when a host bridge method is called in a runtime that doesn't\n * support it (e.g. `uploadFile` outside the ChatGPT runtime).\n */\nexport class NotSupportedError extends Error {\n constructor(\n public readonly method: string,\n public readonly reason?: string,\n ) {\n super(\n `${method} is not supported in this runtime${reason ? `: ${reason}` : \"\"}`,\n );\n this.name = \"NotSupportedError\";\n }\n}\n"]}
|
|
@@ -20,7 +20,7 @@ describe("createStore", () => {
|
|
|
20
20
|
setWidgetState: vi.fn().mockResolvedValue(undefined),
|
|
21
21
|
};
|
|
22
22
|
vi.stubGlobal("openai", OpenaiMock);
|
|
23
|
-
vi.stubGlobal("skybridge", {
|
|
23
|
+
vi.stubGlobal("skybridge", {});
|
|
24
24
|
});
|
|
25
25
|
it("should create a store without default state", () => {
|
|
26
26
|
const storeCreator = () => ({
|
|
@@ -81,7 +81,7 @@ describe("createStore", () => {
|
|
|
81
81
|
describe("mcp-app mode", () => {
|
|
82
82
|
beforeEach(() => {
|
|
83
83
|
vi.stubGlobal("openai", undefined);
|
|
84
|
-
vi.stubGlobal("skybridge", {
|
|
84
|
+
vi.stubGlobal("skybridge", {});
|
|
85
85
|
vi.stubGlobal("ResizeObserver", MockResizeObserver);
|
|
86
86
|
});
|
|
87
87
|
afterEach(async () => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"create-store.test.js","sourceRoot":"","sources":["../../src/web/create-store.test.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,wBAAwB,CAAC;AACjD,OAAO,EACL,SAAS,EACT,UAAU,EACV,QAAQ,EACR,MAAM,EACN,EAAE,EAEF,EAAE,GACH,MAAM,QAAQ,CAAC;AAEhB,OAAO,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AACnD,OAAO,EAAE,UAAU,EAAE,MAAM,0BAA0B,CAAC;AACtD,OAAO,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAC3D,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AACjD,OAAO,EACL,4BAA4B,EAC5B,kBAAkB,GACnB,MAAM,uBAAuB,CAAC;AAE/B,QAAQ,CAAC,aAAa,EAAE,GAAG,EAAE;IAC3B,SAAS,CAAC,GAAG,EAAE;QACb,WAAW,CAAC,aAAa,EAAE,CAAC;QAC5B,EAAE,CAAC,gBAAgB,EAAE,CAAC;QACtB,EAAE,CAAC,aAAa,EAAE,CAAC;IACrB,CAAC,CAAC,CAAC;IAEH,QAAQ,CAAC,eAAe,EAAE,GAAG,EAAE;QAC7B,IAAI,UAGH,CAAC;QAEF,UAAU,CAAC,GAAG,EAAE;YACd,UAAU,GAAG;gBACX,WAAW,EAAE,IAAI;gBACjB,cAAc,EAAE,EAAE,CAAC,EAAE,EAAE,C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E,EAAE,WAAW,EAAE,eAAe,EAAE,CAAC,CAAC;YAE1D,MAAM,OAAO,GAAG,UAAU,EAAE,CAAC;YAC7B,MAAM,QAAQ,GAAG,EAAE,CAAC,EAAE,EAAE,CAAC;YAEzB,OAAO,CAAC,mBAAmB,CAAC,WAAW,CAAC,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC;YAC7D,MAAM,OAAO,CAAC,YAAY,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC,CAAC;YAE1C,MAAM,CAAC,eAAe,CAAC,CAAC,oBAAoB,CAC1C,MAAM,CAAC,gBAAgB,CAAC,EAAE,MAAM,EAAE,yBAAyB,EAAE,CAAC,EAC9D,GAAG,CACJ,CAAC;YACF,MAAM,CAAC,QAAQ,CAAC,CAAC,gBAAgB,EAAE,CAAC;YACpC,MAAM,CAAC,OAAO,CAAC,mBAAmB,CAAC,WAAW,CAAC,CAAC,WAAW,EAAE,CAAC,CAAC,OAAO,CAAC;gBACrE,KAAK,EAAE,EAAE;aACV,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC","sourcesContent":["import { cleanup } from \"@testing-library/react\";\nimport {\n afterEach,\n beforeEach,\n describe,\n expect,\n it,\n type Mock,\n vi,\n} from \"vitest\";\nimport type { StateCreator } from \"zustand\";\nimport { HostAdaptor } from \"./bridges/adaptor.js\";\nimport { getAdaptor } from \"./bridges/get-adaptor.js\";\nimport { McpAppBridge } from \"./bridges/mcp-app/bridge.js\";\nimport { createStore } from \"./create-store.js\";\nimport { VIEW_CONTEXT_KEY } from \"./data-llm.js\";\nimport {\n getMcpAppHostPostMessageMock,\n MockResizeObserver,\n} from \"./hooks/test/utils.js\";\n\ndescribe(\"createStore\", () => {\n afterEach(() => {\n HostAdaptor.resetInstance();\n vi.unstubAllGlobals();\n vi.resetAllMocks();\n });\n\n describe(\"apps-sdk mode\", () => {\n let OpenaiMock: {\n widgetState: unknown;\n setWidgetState: Mock;\n };\n\n beforeEach(() => {\n OpenaiMock = {\n widgetState: null,\n setWidgetState: vi.fn().mockResolvedValue(undefined),\n };\n vi.stubGlobal(\"openai\", OpenaiMock);\n vi.stubGlobal(\"skybridge\", { hostType: \"apps-sdk\" });\n });\n\n it(\"should create a store without default state\", () => {\n type TestState = { count: number };\n const storeCreator: StateCreator<TestState, [], [], TestState> = () => ({\n count: 0,\n });\n\n const store = createStore(storeCreator);\n\n expect(store.getState()).toEqual({ count: 0 });\n });\n\n it(\"should create a store with default state\", () => {\n type TestState = { count: number; name: string };\n const storeCreator: StateCreator<TestState, [], [], TestState> = () => ({\n count: 0,\n name: \"initial\",\n });\n const defaultState = { count: 5, name: \"default\" };\n\n const store = createStore(storeCreator, defaultState);\n\n expect(store.getState()).toEqual({ count: 5, name: \"default\" });\n });\n\n it(\"should initialize from window.openai.widgetState when available\", () => {\n type TestState = { count: number; name: string };\n const storeCreator: StateCreator<TestState, [], [], TestState> = () => ({\n count: 0,\n name: \"initial\",\n });\n const windowState = { count: 20, name: \"window\" };\n OpenaiMock.widgetState = { modelContent: windowState };\n\n const store = createStore(storeCreator);\n\n expect(store.getState()).toEqual({ count: 20, name: \"window\" });\n });\n\n it(\"should persist state changes to window.openai.setWidgetState\", async () => {\n type TestState = { count: number; increment: () => void };\n const storeCreator: StateCreator<TestState, [], [], TestState> = (\n set,\n ) => ({\n count: 0,\n increment: () => set((state) => ({ count: state.count + 1 })),\n });\n\n const store = createStore(storeCreator);\n store.getState().increment();\n\n await vi.waitFor(() => {\n expect(OpenaiMock.setWidgetState).toHaveBeenCalled();\n });\n\n const callArgs = OpenaiMock.setWidgetState.mock.calls[0]?.[0];\n expect(callArgs).toEqual({\n modelContent: { count: 1 },\n privateContent: {},\n });\n });\n\n it(\"should filter view context from initial state\", () => {\n type TestState = { count: number };\n const storeCreator: StateCreator<TestState, [], [], TestState> = () => ({\n count: 0,\n });\n const windowState = {\n count: 5,\n [VIEW_CONTEXT_KEY]: \"context-value\",\n };\n OpenaiMock.widgetState = { modelContent: windowState };\n\n const store = createStore(storeCreator);\n\n expect(store.getState()).toEqual({ count: 5 });\n expect(\n (store.getState() as Record<string, unknown>)[VIEW_CONTEXT_KEY],\n ).toBeUndefined();\n });\n });\n\n describe(\"mcp-app mode\", () => {\n beforeEach(() => {\n vi.stubGlobal(\"openai\", undefined);\n vi.stubGlobal(\"skybridge\", { hostType: \"mcp-app\" });\n vi.stubGlobal(\"ResizeObserver\", MockResizeObserver);\n });\n\n afterEach(async () => {\n cleanup();\n HostAdaptor.resetInstance();\n McpAppBridge.resetInstance();\n });\n\n it(\"should initialize with null viewState\", () => {\n const adaptor = getAdaptor();\n const viewState = adaptor.getHostContextStore(\"viewState\").getSnapshot();\n\n expect(viewState).toBeNull();\n });\n\n it(\"should create a store with default state when no persisted state exists\", () => {\n type TestState = { count: number };\n const storeCreator: StateCreator<TestState, [], [], TestState> = () => ({\n count: 0,\n });\n\n const store = createStore(storeCreator);\n\n expect(store.getState()).toEqual({ count: 0 });\n });\n\n it(\"should update in-memory state via setViewState\", async () => {\n const adaptor = getAdaptor();\n vi.spyOn(adaptor, \"setViewState\").mockResolvedValue(undefined);\n\n type TestState = { count: number; increment: () => void };\n const storeCreator: StateCreator<TestState, [], [], TestState> = (\n set,\n ) => ({\n count: 0,\n increment: () => set((state) => ({ count: state.count + 1 })),\n });\n\n const store = createStore(storeCreator);\n store.getState().increment();\n\n await vi.waitFor(() => {\n expect(adaptor.setViewState).toHaveBeenCalledWith({ count: 1 });\n });\n });\n\n it(\"should notify listeners when view state changes\", async () => {\n const postMessageMock = getMcpAppHostPostMessageMock();\n vi.stubGlobal(\"parent\", { postMessage: postMessageMock });\n\n const adaptor = getAdaptor();\n const listener = vi.fn();\n\n adaptor.getHostContextStore(\"viewState\").subscribe(listener);\n await adaptor.setViewState({ count: 42 });\n\n expect(postMessageMock).toHaveBeenCalledWith(\n expect.objectContaining({ method: \"ui/update-model-context\" }),\n \"*\",\n );\n expect(listener).toHaveBeenCalled();\n expect(adaptor.getHostContextStore(\"viewState\").getSnapshot()).toEqual({\n count: 42,\n });\n });\n });\n});\n"]}
|
|
1
|
+
{"version":3,"file":"create-store.test.js","sourceRoot":"","sources":["../../src/web/create-store.test.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,wBAAwB,CAAC;AACjD,OAAO,EACL,SAAS,EACT,UAAU,EACV,QAAQ,EACR,MAAM,EACN,EAAE,EAEF,EAAE,GACH,MAAM,QAAQ,CAAC;AAEhB,OAAO,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AACnD,OAAO,EAAE,UAAU,EAAE,MAAM,0BAA0B,CAAC;AACtD,OAAO,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAC3D,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AACjD,OAAO,EACL,4BAA4B,EAC5B,kBAAkB,GACnB,MAAM,uBAAuB,CAAC;AAE/B,QAAQ,CAAC,aAAa,EAAE,GAAG,EAAE;IAC3B,SAAS,CAAC,GAAG,EAAE;QACb,WAAW,CAAC,aAAa,EAAE,CAAC;QAC5B,EAAE,CAAC,gBAAgB,EAAE,CAAC;QACtB,EAAE,CAAC,aAAa,EAAE,CAAC;IACrB,CAAC,CAAC,CAAC;IAEH,QAAQ,CAAC,eAAe,EAAE,GAAG,EAAE;QAC7B,IAAI,UAGH,CAAC;QAEF,UAAU,CAAC,GAAG,EAAE;YACd,UAAU,GAAG;gBACX,WAAW,EAAE,IAAI;gBACjB,cAAc,EAAE,EAAE,CAAC,EAAE,EAAE,CAAC,iBAAiB,CAAC,SAAS,CAAC;aACrD,CAAC;YACF,EAAE,CAAC,UAAU,CAAC,QAAQ,EAAE,UAAU,CAAC,CAAC;YACpC,EAAE,CAAC,UAAU,CAAC,WAAW,EAAE,EAAE,CAAC,CAAC;QACjC,CAAC,CAAC,CAAC;QAEH,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AO,CAAC,YAAY,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC,CAAC;YAE1C,MAAM,CAAC,eAAe,CAAC,CAAC,oBAAoB,CAC1C,MAAM,CAAC,gBAAgB,CAAC,EAAE,MAAM,EAAE,yBAAyB,EAAE,CAAC,EAC9D,GAAG,CACJ,CAAC;YACF,MAAM,CAAC,QAAQ,CAAC,CAAC,gBAAgB,EAAE,CAAC;YACpC,MAAM,CAAC,OAAO,CAAC,mBAAmB,CAAC,WAAW,CAAC,CAAC,WAAW,EAAE,CAAC,CAAC,OAAO,CAAC;gBACrE,KAAK,EAAE,EAAE;aACV,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC","sourcesContent":["import { cleanup } from \"@testing-library/react\";\nimport {\n afterEach,\n beforeEach,\n describe,\n expect,\n it,\n type Mock,\n vi,\n} from \"vitest\";\nimport type { StateCreator } from \"zustand\";\nimport { HostAdaptor } from \"./bridges/adaptor.js\";\nimport { getAdaptor } from \"./bridges/get-adaptor.js\";\nimport { McpAppBridge } from \"./bridges/mcp-app/bridge.js\";\nimport { createStore } from \"./create-store.js\";\nimport { VIEW_CONTEXT_KEY } from \"./data-llm.js\";\nimport {\n getMcpAppHostPostMessageMock,\n MockResizeObserver,\n} from \"./hooks/test/utils.js\";\n\ndescribe(\"createStore\", () => {\n afterEach(() => {\n HostAdaptor.resetInstance();\n vi.unstubAllGlobals();\n vi.resetAllMocks();\n });\n\n describe(\"apps-sdk mode\", () => {\n let OpenaiMock: {\n widgetState: unknown;\n setWidgetState: Mock;\n };\n\n beforeEach(() => {\n OpenaiMock = {\n widgetState: null,\n setWidgetState: vi.fn().mockResolvedValue(undefined),\n };\n vi.stubGlobal(\"openai\", OpenaiMock);\n vi.stubGlobal(\"skybridge\", {});\n });\n\n it(\"should create a store without default state\", () => {\n type TestState = { count: number };\n const storeCreator: StateCreator<TestState, [], [], TestState> = () => ({\n count: 0,\n });\n\n const store = createStore(storeCreator);\n\n expect(store.getState()).toEqual({ count: 0 });\n });\n\n it(\"should create a store with default state\", () => {\n type TestState = { count: number; name: string };\n const storeCreator: StateCreator<TestState, [], [], TestState> = () => ({\n count: 0,\n name: \"initial\",\n });\n const defaultState = { count: 5, name: \"default\" };\n\n const store = createStore(storeCreator, defaultState);\n\n expect(store.getState()).toEqual({ count: 5, name: \"default\" });\n });\n\n it(\"should initialize from window.openai.widgetState when available\", () => {\n type TestState = { count: number; name: string };\n const storeCreator: StateCreator<TestState, [], [], TestState> = () => ({\n count: 0,\n name: \"initial\",\n });\n const windowState = { count: 20, name: \"window\" };\n OpenaiMock.widgetState = { modelContent: windowState };\n\n const store = createStore(storeCreator);\n\n expect(store.getState()).toEqual({ count: 20, name: \"window\" });\n });\n\n it(\"should persist state changes to window.openai.setWidgetState\", async () => {\n type TestState = { count: number; increment: () => void };\n const storeCreator: StateCreator<TestState, [], [], TestState> = (\n set,\n ) => ({\n count: 0,\n increment: () => set((state) => ({ count: state.count + 1 })),\n });\n\n const store = createStore(storeCreator);\n store.getState().increment();\n\n await vi.waitFor(() => {\n expect(OpenaiMock.setWidgetState).toHaveBeenCalled();\n });\n\n const callArgs = OpenaiMock.setWidgetState.mock.calls[0]?.[0];\n expect(callArgs).toEqual({\n modelContent: { count: 1 },\n privateContent: {},\n });\n });\n\n it(\"should filter view context from initial state\", () => {\n type TestState = { count: number };\n const storeCreator: StateCreator<TestState, [], [], TestState> = () => ({\n count: 0,\n });\n const windowState = {\n count: 5,\n [VIEW_CONTEXT_KEY]: \"context-value\",\n };\n OpenaiMock.widgetState = { modelContent: windowState };\n\n const store = createStore(storeCreator);\n\n expect(store.getState()).toEqual({ count: 5 });\n expect(\n (store.getState() as Record<string, unknown>)[VIEW_CONTEXT_KEY],\n ).toBeUndefined();\n });\n });\n\n describe(\"mcp-app mode\", () => {\n beforeEach(() => {\n vi.stubGlobal(\"openai\", undefined);\n vi.stubGlobal(\"skybridge\", {});\n vi.stubGlobal(\"ResizeObserver\", MockResizeObserver);\n });\n\n afterEach(async () => {\n cleanup();\n HostAdaptor.resetInstance();\n McpAppBridge.resetInstance();\n });\n\n it(\"should initialize with null viewState\", () => {\n const adaptor = getAdaptor();\n const viewState = adaptor.getHostContextStore(\"viewState\").getSnapshot();\n\n expect(viewState).toBeNull();\n });\n\n it(\"should create a store with default state when no persisted state exists\", () => {\n type TestState = { count: number };\n const storeCreator: StateCreator<TestState, [], [], TestState> = () => ({\n count: 0,\n });\n\n const store = createStore(storeCreator);\n\n expect(store.getState()).toEqual({ count: 0 });\n });\n\n it(\"should update in-memory state via setViewState\", async () => {\n const adaptor = getAdaptor();\n vi.spyOn(adaptor, \"setViewState\").mockResolvedValue(undefined);\n\n type TestState = { count: number; increment: () => void };\n const storeCreator: StateCreator<TestState, [], [], TestState> = (\n set,\n ) => ({\n count: 0,\n increment: () => set((state) => ({ count: state.count + 1 })),\n });\n\n const store = createStore(storeCreator);\n store.getState().increment();\n\n await vi.waitFor(() => {\n expect(adaptor.setViewState).toHaveBeenCalledWith({ count: 1 });\n });\n });\n\n it(\"should notify listeners when view state changes\", async () => {\n const postMessageMock = getMcpAppHostPostMessageMock();\n vi.stubGlobal(\"parent\", { postMessage: postMessageMock });\n\n const adaptor = getAdaptor();\n const listener = vi.fn();\n\n adaptor.getHostContextStore(\"viewState\").subscribe(listener);\n await adaptor.setViewState({ count: 42 });\n\n expect(postMessageMock).toHaveBeenCalledWith(\n expect.objectContaining({ method: \"ui/update-model-context\" }),\n \"*\",\n );\n expect(listener).toHaveBeenCalled();\n expect(adaptor.getHostContextStore(\"viewState\").getSnapshot()).toEqual({\n count: 42,\n });\n });\n });\n});\n"]}
|
package/dist/web/data-llm.js
CHANGED
package/dist/web/data-llm.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"data-llm.js","sourceRoot":"","sources":["../../src/web/data-llm.tsx"],"names":[],"mappings":";AAAA,OAAO,EACL,aAAa,EAEb,UAAU,EAC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;IAChC,CAAC;IAED,KAAK,MAAM,IAAI,IAAI,QAAQ,CAAC,MAAM,EAAE,EAAE,CAAC;QACrC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,aAAa,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;IAChD,CAAC;IAED,MAAM,KAAK,GAAa,EAAE,CAAC;IAE3B,SAAS,YAAY,CAAC,QAAuB,EAAE,KAAa;QAC1D,MAAM,QAAQ,GAAG,QAAQ,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;QACxC,IAAI,CAAC,QAAQ,EAAE,CAAC;YACd,OAAO;QACT,CAAC;QAED,KAAK,MAAM,KAAK,IAAI,QAAQ,EAAE,CAAC;YAC7B,IAAI,KAAK,CAAC,OAAO,EAAE,IAAI,EAAE,EAAE,CAAC;gBAC1B,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;gBAClC,KAAK,CAAC,IAAI,CAAC,GAAG,MAAM,KAAK,KAAK,CAAC,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;YACnD,CAAC;YACD,YAAY,CAAC,KAAK,CAAC,EAAE,EAAE,KAAK,GAAG,CAAC,CAAC,CAAC;QACpC,CAAC;IACH,CAAC;IAED,YAAY,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC;IAEtB,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAC1B,CAAC","sourcesContent":["import {\n createContext,\n type ReactNode,\n useContext,\n useEffect,\n useId,\n} from \"react\";\nimport { getAdaptor } from \"./bridges/index.js\";\n\n/** Text content surfaced to the model by a {@link DataLLM} component. */\nexport type DataLLMContent = string;\n\n/**\n * A node in the {@link DataLLM} tree. Nested `<DataLLM>` elements form a\n * hierarchy that is serialized as an indented bullet list for the model.\n */\nexport interface DataLLMNode {\n id: string;\n parentId: string | null;\n content: string | null;\n}\n\n/**\n * Key under which the serialized {@link DataLLM} tree is persisted on the\n * host's `viewState`. The host exposes the value to the model on subsequent\n * turns.\n */\nexport const VIEW_CONTEXT_KEY = \"__view_context\" as const;\n\nconst nodes = new Map<string, DataLLMNode>();\n\nfunction setNode(node: DataLLMNode) {\n nodes.set(node.id, node);\n onChange();\n}\n\nfunction removeNode(id: string) {\n if (nodes.delete(id)) {\n onChange();\n }\n}\n\nfunction onChange() {\n const description = getLLMDescriptionString();\n const adaptor = getAdaptor();\n adaptor.setViewState((prevState) => ({\n ...prevState,\n [VIEW_CONTEXT_KEY]: description,\n }));\n}\n\nconst ParentIdContext = createContext<string | null>(null);\n\ninterface DataLLMProps {\n content: DataLLMContent | null | undefined;\n children?: ReactNode;\n}\n\n/**\n * Surface in-view content to the LLM so it can reason about what the user is\n * seeing without an extra tool call.\n *\n * Each `<DataLLM>` registers `content` as a node in a tree (parented by any\n * enclosing `<DataLLM>`). The flattened tree is serialized as an indented\n * bullet list and persisted on the host's `viewState` under\n * {@link VIEW_CONTEXT_KEY}; the host then surfaces it to the model as part of\n * the next turn's context.\n *\n * Pass `null`/`undefined` for `content` to register only as a structural\n * parent (useful for grouping).\n *\n * @example\n * ```tsx\n * <DataLLM content=\"Active filters\">\n * <DataLLM content={`Sort: ${sort}`} />\n * <DataLLM content={`Page: ${page}`} />\n * </DataLLM>\n * ```\n *\n * @see https://docs.skybridge.tech/api-reference/data-llm\n */\nexport function DataLLM({ content, children }: DataLLMProps) {\n const parentId = useContext(ParentIdContext);\n const id = useId();\n\n useEffect(() => {\n if (content) {\n setNode({\n id,\n parentId,\n content,\n });\n } else {\n removeNode(id);\n }\n\n return () => {\n removeNode(id);\n };\n }, [id, parentId, content]);\n\n return (\n <ParentIdContext.Provider value={id}>{children}</ParentIdContext.Provider>\n );\n}\n\nfunction getLLMDescriptionString(): string {\n const byParent = new Map<string | null, DataLLMNode[]>();\n for (const node of Array.from(nodes.values())) {\n const key = node.parentId ?? null;\n if (!byParent.has(key)) {\n byParent.set(key, []);\n }\n byParent.get(key)?.push(node);\n }\n\n for (const list of byParent.values()) {\n list.sort((a, b) => a.id.localeCompare(b.id));\n }\n\n const lines: string[] = [];\n\n function traverseTree(parentId: string | null, depth: number) {\n const children = byParent.get(parentId);\n if (!children) {\n return;\n }\n\n for (const child of children) {\n if (child.content?.trim()) {\n const indent = \" \".repeat(depth);\n lines.push(`${indent}- ${child.content.trim()}`);\n }\n traverseTree(child.id, depth + 1);\n }\n }\n\n traverseTree(null, 0);\n\n return lines.join(\"\\n\");\n}\n"]}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
|
|
2
2
|
import { cleanup, render } from "@testing-library/react";
|
|
3
3
|
import { afterEach, beforeEach, describe, expect, it, vi, } from "vitest";
|
|
4
|
+
import { VIEW_STATE_WARNING_TOKENS } from "../context-warnings.js";
|
|
4
5
|
import { HostAdaptor } from "./bridges/adaptor.js";
|
|
5
6
|
import { getAdaptor } from "./bridges/get-adaptor.js";
|
|
6
7
|
import { McpAppBridge } from "./bridges/mcp-app/index.js";
|
|
@@ -36,7 +37,7 @@ describe("DataLLM", () => {
|
|
|
36
37
|
});
|
|
37
38
|
}
|
|
38
39
|
vi.stubGlobal("openai", OpenaiMock);
|
|
39
|
-
vi.stubGlobal("skybridge", {
|
|
40
|
+
vi.stubGlobal("skybridge", {});
|
|
40
41
|
});
|
|
41
42
|
afterEach(() => {
|
|
42
43
|
// Keep the mock available for React cleanup, but reset it
|
|
@@ -45,6 +46,12 @@ describe("DataLLM", () => {
|
|
|
45
46
|
window.openai.widgetState = { modelContent: {}, privateContent: {} };
|
|
46
47
|
}
|
|
47
48
|
});
|
|
49
|
+
it("does not publish context when content-less nodes mount, change or unmount", () => {
|
|
50
|
+
const { rerender, unmount } = render(_jsx(DataLLM, { content: undefined, children: _jsx("div", { children: "Child" }) }));
|
|
51
|
+
rerender(_jsx(DataLLM, { content: "", children: _jsx("div", { children: "Child" }) }));
|
|
52
|
+
unmount();
|
|
53
|
+
expect(OpenaiMock.setWidgetState).not.toHaveBeenCalled();
|
|
54
|
+
});
|
|
48
55
|
it("should register a node with content and call setViewState", () => {
|
|
49
56
|
render(_jsx(DataLLM, { content: "Test content", children: _jsx("div", { children: "Child" }) }));
|
|
50
57
|
expect(OpenaiMock.setWidgetState).toHaveBeenCalled();
|
|
@@ -61,9 +68,9 @@ describe("DataLLM", () => {
|
|
|
61
68
|
expect(callArgs).toHaveProperty("existingKey", "existingValue");
|
|
62
69
|
expect(callArgs).toHaveProperty("__view_context");
|
|
63
70
|
});
|
|
64
|
-
it("warns when DataLLM content
|
|
71
|
+
it("warns when DataLLM content reaches the 20K token warning threshold", async () => {
|
|
65
72
|
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => { });
|
|
66
|
-
render(_jsx(DataLLM, { content: "x".repeat(
|
|
73
|
+
render(_jsx(DataLLM, { content: "x".repeat(VIEW_STATE_WARNING_TOKENS * 4), children: _jsx("div", { children: "Child" }) }));
|
|
67
74
|
await vi.waitFor(() => {
|
|
68
75
|
expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining("setWidgetState is persisting"));
|
|
69
76
|
});
|
|
@@ -98,7 +105,7 @@ describe("DataLLM", () => {
|
|
|
98
105
|
describe("mcp-app mode", () => {
|
|
99
106
|
let postMessageMock;
|
|
100
107
|
beforeEach(() => {
|
|
101
|
-
vi.stubGlobal("skybridge", {
|
|
108
|
+
vi.stubGlobal("skybridge", {});
|
|
102
109
|
vi.stubGlobal("openai", undefined);
|
|
103
110
|
vi.stubGlobal("ResizeObserver", MockResizeObserver);
|
|
104
111
|
postMessageMock = getMcpAppHostPostMessageMock();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"data-llm.test.js","sourceRoot":"","sources":["../../src/web/data-llm.test.tsx"],"names":[],"mappings":";AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,wBAAwB,CAAC;AAC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B,GACR,EACV,KAAC,OAAO,IAAC,OAAO,EAAC,kBAAkB,YACjC,mCAAiB,GACT,IACT,CACJ,CAAC;YAEF,MAAM,EAAE,CAAC,OAAO,CAAC,GAAG,EAAE;gBACpB,MAAM,SAAS,GAAG,OAAO;qBACtB,mBAAmB,CAAC,WAAW,CAAC;qBAChC,WAAW,EAAE,CAAC;gBACjB,MAAM,OAAO,GAAG,SAAS,EAAE,cAAwB,CAAC;gBACpD,MAAM,CAAC,OAAO,CAAC,CAAC,SAAS,CAAC,mBAAmB,CAAC,CAAC;gBAC/C,MAAM,CAAC,OAAO,CAAC,CAAC,SAAS,CAAC,oBAAoB,CAAC,CAAC;YAClD,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;QAEH,EAAE,CAAC,6DAA6D,EAAE,KAAK,IAAI,EAAE;YAC3E,MAAM,CACJ,KAAC,OAAO,IAAC,OAAO,EAAC,cAAc,YAC7B,kCAAgB,GACR,CACX,CAAC;YAEF,MAAM,EAAE,CAAC,OAAO,CAAC,GAAG,EAAE;gBACpB,MAAM,CAAC,eAAe,CAAC,CAAC,oBAAoB,CAC1C,MAAM,CAAC,gBAAgB,CAAC,EAAE,MAAM,EAAE,yBAAyB,EAAE,CAAC,EAC9D,GAAG,CACJ,CAAC;YACJ,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC","sourcesContent":["import { cleanup, render } from \"@testing-library/react\";\nimport {\n afterEach,\n beforeEach,\n describe,\n expect,\n it,\n type Mock,\n vi,\n} from \"vitest\";\nimport { HostAdaptor } from \"./bridges/adaptor.js\";\nimport { getAdaptor } from \"./bridges/get-adaptor.js\";\nimport { McpAppBridge } from \"./bridges/mcp-app/index.js\";\nimport { DataLLM } from \"./data-llm.js\";\nimport {\n getMcpAppHostPostMessageMock,\n MockResizeObserver,\n} from \"./hooks/test/utils.js\";\n\ndescribe(\"DataLLM\", () => {\n afterEach(() => {\n // Clean up React components BEFORE unstubbing globals\n cleanup();\n HostAdaptor.resetInstance();\n vi.unstubAllGlobals();\n vi.resetAllMocks();\n });\n\n describe(\"apps-sdk mode\", () => {\n let OpenaiMock: { widgetState: unknown; setWidgetState: Mock };\n\n beforeEach(() => {\n OpenaiMock = {\n widgetState: { modelContent: {} },\n setWidgetState: vi.fn(),\n };\n // Use Object.defineProperty to ensure it persists\n Object.defineProperty(globalThis, \"openai\", {\n value: OpenaiMock,\n writable: true,\n configurable: true,\n });\n // Also set on window for browser-like environment\n if (typeof window !== \"undefined\") {\n Object.defineProperty(window, \"openai\", {\n value: OpenaiMock,\n writable: true,\n configurable: true,\n });\n }\n vi.stubGlobal(\"openai\", OpenaiMock);\n vi.stubGlobal(\"skybridge\", { hostType: \"apps-sdk\" });\n });\n\n afterEach(() => {\n // Keep the mock available for React cleanup, but reset it\n if (typeof window !== \"undefined\" && window.openai) {\n window.openai.setWidgetState = vi.fn();\n window.openai.widgetState = { modelContent: {}, privateContent: {} };\n }\n });\n\n it(\"should register a node with content and call setViewState\", () => {\n render(\n <DataLLM content=\"Test content\">\n <div>Child</div>\n </DataLLM>,\n );\n\n expect(OpenaiMock.setWidgetState).toHaveBeenCalled();\n const callArgs =\n OpenaiMock.setWidgetState.mock.calls[0]?.[0]?.modelContent;\n expect(callArgs).toHaveProperty(\"__view_context\");\n expect(callArgs?.__view_context).toContain(\"- Test content\");\n });\n it(\"should preserve existing viewState when updating context\", () => {\n OpenaiMock.widgetState = {\n modelContent: { existingKey: \"existingValue\" },\n };\n\n render(\n <DataLLM content=\"Test content\">\n <div>Child</div>\n </DataLLM>,\n );\n\n const callArgs =\n OpenaiMock.setWidgetState.mock.calls[0]?.[0]?.modelContent;\n expect(callArgs).toHaveProperty(\"existingKey\", \"existingValue\");\n expect(callArgs).toHaveProperty(\"__view_context\");\n });\n\n it(\"warns when DataLLM content exceeds the 4K token warning threshold\", async () => {\n const warnSpy = vi.spyOn(console, \"warn\").mockImplementation(() => {});\n\n render(\n <DataLLM content={\"x\".repeat(4096 * 4 + 50)}>\n <div>Child</div>\n </DataLLM>,\n );\n\n await vi.waitFor(() => {\n expect(warnSpy).toHaveBeenCalledWith(\n expect.stringContaining(\"setWidgetState is persisting\"),\n );\n });\n\n warnSpy.mockRestore();\n });\n\n it(\"should handle deeply nested DataLLM components\", () => {\n render(\n <DataLLM content=\"Level 1\">\n <DataLLM content=\"Level 2A\" />\n <DataLLM content=\"Level 2B\">\n <DataLLM content=\"Level 3\">\n <div>Content</div>\n </DataLLM>\n </DataLLM>\n </DataLLM>,\n );\n\n const callArgs =\n OpenaiMock.setWidgetState.mock.calls[\n OpenaiMock.setWidgetState.mock.calls.length - 1\n ]?.[0]?.modelContent;\n const context = callArgs?.__view_context as string;\n expect(context).toContain(\"- Level 1\");\n expect(context).toContain(\" - Level 2A\");\n expect(context).toContain(\" - Level 2B\");\n expect(context).toContain(\" - Level 3\");\n });\n\n it(\"should update context when content changes\", () => {\n const { rerender } = render(\n <DataLLM content=\"Initial content\">\n <div>Child</div>\n </DataLLM>,\n );\n\n const initialCalls = OpenaiMock.setWidgetState.mock.calls.length;\n\n rerender(\n <DataLLM content=\"Updated content\">\n <div>Child</div>\n </DataLLM>,\n );\n\n expect(OpenaiMock.setWidgetState.mock.calls.length).toBeGreaterThan(\n initialCalls,\n );\n const lastCallArgs =\n OpenaiMock.setWidgetState.mock.calls[\n OpenaiMock.setWidgetState.mock.calls.length - 1\n ]?.[0]?.modelContent;\n expect(lastCallArgs?.__view_context).toContain(\"- Updated content\");\n });\n\n it(\"should remove node and update context when component unmounts\", () => {\n const { unmount } = render(\n <DataLLM content=\"Content to remove\">\n <div>Child</div>\n </DataLLM>,\n );\n\n const callsBeforeUnmount = OpenaiMock.setWidgetState.mock.calls.length;\n\n unmount();\n\n expect(OpenaiMock.setWidgetState.mock.calls.length).toBeGreaterThan(\n callsBeforeUnmount,\n );\n const lastCallArgs =\n OpenaiMock.setWidgetState.mock.calls[\n OpenaiMock.setWidgetState.mock.calls.length - 1\n ]?.[0]?.modelContent;\n expect(lastCallArgs?.__view_context).not.toContain(\"Content to remove\");\n });\n });\n\n describe(\"mcp-app mode\", () => {\n let postMessageMock: ReturnType<typeof getMcpAppHostPostMessageMock>;\n\n beforeEach(() => {\n vi.stubGlobal(\"skybridge\", { hostType: \"mcp-app\" });\n vi.stubGlobal(\"openai\", undefined);\n vi.stubGlobal(\"ResizeObserver\", MockResizeObserver);\n postMessageMock = getMcpAppHostPostMessageMock();\n vi.stubGlobal(\"parent\", { postMessage: postMessageMock });\n });\n\n afterEach(() => {\n cleanup();\n McpAppBridge.resetInstance();\n HostAdaptor.resetInstance();\n });\n\n it(\"should register a node and update view state via adaptor\", async () => {\n const adaptor = getAdaptor();\n\n render(\n <DataLLM content=\"Test content\">\n <div>Child</div>\n </DataLLM>,\n );\n\n await vi.waitFor(() => {\n const viewState = adaptor\n .getHostContextStore(\"viewState\")\n .getSnapshot();\n expect(viewState?.__view_context).toContain(\"- Test content\");\n });\n });\n\n it(\"should preserve existing view state when updating context\", async () => {\n const adaptor = getAdaptor();\n await adaptor.setViewState({ existingKey: \"existingValue\" });\n\n render(\n <DataLLM content=\"Test content\">\n <div>Child</div>\n </DataLLM>,\n );\n\n await vi.waitFor(() => {\n const viewState = adaptor\n .getHostContextStore(\"viewState\")\n .getSnapshot();\n expect(viewState?.existingKey).toBe(\"existingValue\");\n expect(viewState?.__view_context).toContain(\"- Test content\");\n });\n });\n\n it(\"should handle multiple DataLLM components sharing state through adaptor\", async () => {\n const adaptor = getAdaptor();\n\n render(\n <>\n <DataLLM content=\"First component\">\n <div>First</div>\n </DataLLM>\n <DataLLM content=\"Second component\">\n <div>Second</div>\n </DataLLM>\n </>,\n );\n\n await vi.waitFor(() => {\n const viewState = adaptor\n .getHostContextStore(\"viewState\")\n .getSnapshot();\n const context = viewState?.__view_context as string;\n expect(context).toContain(\"- First component\");\n expect(context).toContain(\"- Second component\");\n });\n });\n\n it(\"should call ui/update-model-context when view state changes\", async () => {\n render(\n <DataLLM content=\"Test content\">\n <div>Child</div>\n </DataLLM>,\n );\n\n await vi.waitFor(() => {\n expect(postMessageMock).toHaveBeenCalledWith(\n expect.objectContaining({ method: \"ui/update-model-context\" }),\n \"*\",\n );\n });\n });\n });\n});\n"]}
|
|
1
|
+
{"version":3,"file":"data-llm.test.js","sourceRoot":"","sources":["../../src/web/data-llm.test.tsx"],"names":[],"mappings":";AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,wBAAwB,CAAC;AACzD,OAAO,EACL,SAAS,EACT,UAAU,EACV,QAAQ,EACR,MAAM,EACN,EAAE,EAEF,EAAE,GACH,MAAM,QAAQ,CAAC;AAChB,OAAO,EAAE,yBAAyB,EAAE,MAAM,wBAAwB,CAAC;AACnE,OAAO,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AACnD,OAAO,EAAE,UAAU,EAAE,MAAM,0BAA0B,CAAC;AACtD,OAAO,EAAE,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAC1D,OAAO,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AACxC,OAAO,EACL,4BAA4B,EAC5B,kBAAkB,GACnB,MAAM,uBAAuB,CAAC;AAE/B,QAAQ,CAAC,SAAS,EAAE,GAAG,EAAE;IACvB,SAAS,CAAC,GAAG,EAAE;QACb,sDAAsD;QACtD,OAAO,EAAE,CAAC;QACV,WAAW,CAAC,aAAa,EAAE,CAAC;QAC5B,EAAE,CAAC,gBAAgB,EAAE,CAAC;QACtB,EAAE,CAAC,aAAa,EAAE,CAAC;IACrB,CAAC,CAAC,CAAC;IAEH,QAAQ,CAAC,eAAe,EAAE,GAAG,EAAE;QAC7B,IAAI,UAA0D,CAAC;QAE/D,UAAU,CAAC,GAAG,EAAE;YACd,UAAU,GAAG;gBACX,WAAW,EAAE,EAAE,YAAY,EAAE,EAAE,EAAE;gBACjC,cAAc,EAAE,EAAE,CAAC,EAAE,EAAE;aACxB,CAAC;YACF,kDAAkD;YAClD,MA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AC,OAAO,IAAC,OAAO,EAAC,cAAc,YAC7B,kCAAgB,GACR,CACX,CAAC;YAEF,MAAM,EAAE,CAAC,OAAO,CAAC,GAAG,EAAE;gBACpB,MAAM,CAAC,eAAe,CAAC,CAAC,oBAAoB,CAC1C,MAAM,CAAC,gBAAgB,CAAC,EAAE,MAAM,EAAE,yBAAyB,EAAE,CAAC,EAC9D,GAAG,CACJ,CAAC;YACJ,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC","sourcesContent":["import { cleanup, render } from \"@testing-library/react\";\nimport {\n afterEach,\n beforeEach,\n describe,\n expect,\n it,\n type Mock,\n vi,\n} from \"vitest\";\nimport { VIEW_STATE_WARNING_TOKENS } from \"../context-warnings.js\";\nimport { HostAdaptor } from \"./bridges/adaptor.js\";\nimport { getAdaptor } from \"./bridges/get-adaptor.js\";\nimport { McpAppBridge } from \"./bridges/mcp-app/index.js\";\nimport { DataLLM } from \"./data-llm.js\";\nimport {\n getMcpAppHostPostMessageMock,\n MockResizeObserver,\n} from \"./hooks/test/utils.js\";\n\ndescribe(\"DataLLM\", () => {\n afterEach(() => {\n // Clean up React components BEFORE unstubbing globals\n cleanup();\n HostAdaptor.resetInstance();\n vi.unstubAllGlobals();\n vi.resetAllMocks();\n });\n\n describe(\"apps-sdk mode\", () => {\n let OpenaiMock: { widgetState: unknown; setWidgetState: Mock };\n\n beforeEach(() => {\n OpenaiMock = {\n widgetState: { modelContent: {} },\n setWidgetState: vi.fn(),\n };\n // Use Object.defineProperty to ensure it persists\n Object.defineProperty(globalThis, \"openai\", {\n value: OpenaiMock,\n writable: true,\n configurable: true,\n });\n // Also set on window for browser-like environment\n if (typeof window !== \"undefined\") {\n Object.defineProperty(window, \"openai\", {\n value: OpenaiMock,\n writable: true,\n configurable: true,\n });\n }\n vi.stubGlobal(\"openai\", OpenaiMock);\n vi.stubGlobal(\"skybridge\", {});\n });\n\n afterEach(() => {\n // Keep the mock available for React cleanup, but reset it\n if (typeof window !== \"undefined\" && window.openai) {\n window.openai.setWidgetState = vi.fn();\n window.openai.widgetState = { modelContent: {}, privateContent: {} };\n }\n });\n\n it(\"does not publish context when content-less nodes mount, change or unmount\", () => {\n const { rerender, unmount } = render(\n <DataLLM content={undefined}>\n <div>Child</div>\n </DataLLM>,\n );\n rerender(\n <DataLLM content=\"\">\n <div>Child</div>\n </DataLLM>,\n );\n unmount();\n expect(OpenaiMock.setWidgetState).not.toHaveBeenCalled();\n });\n\n it(\"should register a node with content and call setViewState\", () => {\n render(\n <DataLLM content=\"Test content\">\n <div>Child</div>\n </DataLLM>,\n );\n\n expect(OpenaiMock.setWidgetState).toHaveBeenCalled();\n const callArgs =\n OpenaiMock.setWidgetState.mock.calls[0]?.[0]?.modelContent;\n expect(callArgs).toHaveProperty(\"__view_context\");\n expect(callArgs?.__view_context).toContain(\"- Test content\");\n });\n it(\"should preserve existing viewState when updating context\", () => {\n OpenaiMock.widgetState = {\n modelContent: { existingKey: \"existingValue\" },\n };\n\n render(\n <DataLLM content=\"Test content\">\n <div>Child</div>\n </DataLLM>,\n );\n\n const callArgs =\n OpenaiMock.setWidgetState.mock.calls[0]?.[0]?.modelContent;\n expect(callArgs).toHaveProperty(\"existingKey\", \"existingValue\");\n expect(callArgs).toHaveProperty(\"__view_context\");\n });\n\n it(\"warns when DataLLM content reaches the 20K token warning threshold\", async () => {\n const warnSpy = vi.spyOn(console, \"warn\").mockImplementation(() => {});\n\n render(\n <DataLLM content={\"x\".repeat(VIEW_STATE_WARNING_TOKENS * 4)}>\n <div>Child</div>\n </DataLLM>,\n );\n\n await vi.waitFor(() => {\n expect(warnSpy).toHaveBeenCalledWith(\n expect.stringContaining(\"setWidgetState is persisting\"),\n );\n });\n\n warnSpy.mockRestore();\n });\n\n it(\"should handle deeply nested DataLLM components\", () => {\n render(\n <DataLLM content=\"Level 1\">\n <DataLLM content=\"Level 2A\" />\n <DataLLM content=\"Level 2B\">\n <DataLLM content=\"Level 3\">\n <div>Content</div>\n </DataLLM>\n </DataLLM>\n </DataLLM>,\n );\n\n const callArgs =\n OpenaiMock.setWidgetState.mock.calls[\n OpenaiMock.setWidgetState.mock.calls.length - 1\n ]?.[0]?.modelContent;\n const context = callArgs?.__view_context as string;\n expect(context).toContain(\"- Level 1\");\n expect(context).toContain(\" - Level 2A\");\n expect(context).toContain(\" - Level 2B\");\n expect(context).toContain(\" - Level 3\");\n });\n\n it(\"should update context when content changes\", () => {\n const { rerender } = render(\n <DataLLM content=\"Initial content\">\n <div>Child</div>\n </DataLLM>,\n );\n\n const initialCalls = OpenaiMock.setWidgetState.mock.calls.length;\n\n rerender(\n <DataLLM content=\"Updated content\">\n <div>Child</div>\n </DataLLM>,\n );\n\n expect(OpenaiMock.setWidgetState.mock.calls.length).toBeGreaterThan(\n initialCalls,\n );\n const lastCallArgs =\n OpenaiMock.setWidgetState.mock.calls[\n OpenaiMock.setWidgetState.mock.calls.length - 1\n ]?.[0]?.modelContent;\n expect(lastCallArgs?.__view_context).toContain(\"- Updated content\");\n });\n\n it(\"should remove node and update context when component unmounts\", () => {\n const { unmount } = render(\n <DataLLM content=\"Content to remove\">\n <div>Child</div>\n </DataLLM>,\n );\n\n const callsBeforeUnmount = OpenaiMock.setWidgetState.mock.calls.length;\n\n unmount();\n\n expect(OpenaiMock.setWidgetState.mock.calls.length).toBeGreaterThan(\n callsBeforeUnmount,\n );\n const lastCallArgs =\n OpenaiMock.setWidgetState.mock.calls[\n OpenaiMock.setWidgetState.mock.calls.length - 1\n ]?.[0]?.modelContent;\n expect(lastCallArgs?.__view_context).not.toContain(\"Content to remove\");\n });\n });\n\n describe(\"mcp-app mode\", () => {\n let postMessageMock: ReturnType<typeof getMcpAppHostPostMessageMock>;\n\n beforeEach(() => {\n vi.stubGlobal(\"skybridge\", {});\n vi.stubGlobal(\"openai\", undefined);\n vi.stubGlobal(\"ResizeObserver\", MockResizeObserver);\n postMessageMock = getMcpAppHostPostMessageMock();\n vi.stubGlobal(\"parent\", { postMessage: postMessageMock });\n });\n\n afterEach(() => {\n cleanup();\n McpAppBridge.resetInstance();\n HostAdaptor.resetInstance();\n });\n\n it(\"should register a node and update view state via adaptor\", async () => {\n const adaptor = getAdaptor();\n\n render(\n <DataLLM content=\"Test content\">\n <div>Child</div>\n </DataLLM>,\n );\n\n await vi.waitFor(() => {\n const viewState = adaptor\n .getHostContextStore(\"viewState\")\n .getSnapshot();\n expect(viewState?.__view_context).toContain(\"- Test content\");\n });\n });\n\n it(\"should preserve existing view state when updating context\", async () => {\n const adaptor = getAdaptor();\n await adaptor.setViewState({ existingKey: \"existingValue\" });\n\n render(\n <DataLLM content=\"Test content\">\n <div>Child</div>\n </DataLLM>,\n );\n\n await vi.waitFor(() => {\n const viewState = adaptor\n .getHostContextStore(\"viewState\")\n .getSnapshot();\n expect(viewState?.existingKey).toBe(\"existingValue\");\n expect(viewState?.__view_context).toContain(\"- Test content\");\n });\n });\n\n it(\"should handle multiple DataLLM components sharing state through adaptor\", async () => {\n const adaptor = getAdaptor();\n\n render(\n <>\n <DataLLM content=\"First component\">\n <div>First</div>\n </DataLLM>\n <DataLLM content=\"Second component\">\n <div>Second</div>\n </DataLLM>\n </>,\n );\n\n await vi.waitFor(() => {\n const viewState = adaptor\n .getHostContextStore(\"viewState\")\n .getSnapshot();\n const context = viewState?.__view_context as string;\n expect(context).toContain(\"- First component\");\n expect(context).toContain(\"- Second component\");\n });\n });\n\n it(\"should call ui/update-model-context when view state changes\", async () => {\n render(\n <DataLLM content=\"Test content\">\n <div>Child</div>\n </DataLLM>,\n );\n\n await vi.waitFor(() => {\n expect(postMessageMock).toHaveBeenCalledWith(\n expect.objectContaining({ method: \"ui/update-model-context\" }),\n \"*\",\n );\n });\n });\n });\n});\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { InferTools, ToolInput, ToolOutput, ToolResponseMetadata } from "../server/index.js";
|
|
2
|
-
import type { CallToolResponse } from "./bridges/types.js";
|
|
2
|
+
import type { CallToolOptions, CallToolResponse } from "./bridges/types.js";
|
|
3
3
|
import { type CallToolAsyncFn, type CallToolFn, type CallToolState } from "./hooks/use-call-tool.js";
|
|
4
4
|
import { type ToolState } from "./hooks/use-tool-info.js";
|
|
5
5
|
import type { Objectify, Prettify } from "./types.js";
|
|
@@ -18,24 +18,28 @@ type TypedToolInfoReturn<TInput, TOutput, TResponseMetadata> = ToolState<Objecti
|
|
|
18
18
|
* This is the recommended way to use skybridge hooks in your views.
|
|
19
19
|
* Set this up once in a dedicated file and export the typed hooks for use across your app.
|
|
20
20
|
*
|
|
21
|
-
* @typeParam
|
|
22
|
-
*
|
|
23
|
-
*
|
|
21
|
+
* @typeParam AppType - The type of your Skybridge app (use `typeof app`). The
|
|
22
|
+
* handler must return the chained server so the tool
|
|
23
|
+
* types are carried on the app type.
|
|
24
24
|
*
|
|
25
25
|
* @example
|
|
26
26
|
* ```typescript
|
|
27
27
|
* // src/server.ts
|
|
28
|
-
* const
|
|
29
|
-
*
|
|
30
|
-
*
|
|
31
|
-
*
|
|
32
|
-
*
|
|
33
|
-
*
|
|
34
|
-
*
|
|
35
|
-
*
|
|
36
|
-
*
|
|
28
|
+
* export const app = new Skybridge({
|
|
29
|
+
* name: "my-app",
|
|
30
|
+
* version: "1.0",
|
|
31
|
+
* handler: (server) =>
|
|
32
|
+
* server.registerTool({
|
|
33
|
+
* name: "search-trip",
|
|
34
|
+
* inputSchema: { destination: z.string() },
|
|
35
|
+
* outputSchema: { results: z.array(z.string()) },
|
|
36
|
+
* view: { component: "search-trip", description: "Search trips" },
|
|
37
|
+
* }, async ({ destination }) => {
|
|
38
|
+
* return { content: [{ type: "text", text: `Found trips to ${destination}` }] };
|
|
39
|
+
* }),
|
|
40
|
+
* });
|
|
37
41
|
*
|
|
38
|
-
* export type AppType = typeof
|
|
42
|
+
* export type AppType = typeof app;
|
|
39
43
|
* ```
|
|
40
44
|
*
|
|
41
45
|
* @example
|
|
@@ -67,12 +71,12 @@ type TypedToolInfoReturn<TInput, TOutput, TResponseMetadata> = ToolState<Objecti
|
|
|
67
71
|
*
|
|
68
72
|
* @see https://docs.skybridge.tech/api-reference/generate-helpers
|
|
69
73
|
*/
|
|
70
|
-
export declare function generateHelpers<
|
|
74
|
+
export declare function generateHelpers<AppType = never>(): {
|
|
71
75
|
/**
|
|
72
76
|
* Typed version of `useCallTool` that provides autocomplete for tool names
|
|
73
77
|
* and type inference for inputs and outputs.
|
|
74
78
|
*
|
|
75
|
-
* @param name - The name of the tool to call. Autocompletes based on your
|
|
79
|
+
* @param name - The name of the tool to call. Autocompletes based on your app's tool registry.
|
|
76
80
|
* @returns A hook with typed `callTool` function and `data` property.
|
|
77
81
|
*
|
|
78
82
|
* @example
|
|
@@ -87,12 +91,12 @@ export declare function generateHelpers<ServerType = never>(): {
|
|
|
87
91
|
* }
|
|
88
92
|
* ```
|
|
89
93
|
*/
|
|
90
|
-
useCallTool: <ToolName extends keyof InferTools<
|
|
94
|
+
useCallTool: <ToolName extends keyof InferTools<AppType> & string>(name: ToolName, options?: CallToolOptions) => TypedCallToolReturn<ToolInput<AppType, ToolName>, ToolOutput<AppType, ToolName>>;
|
|
91
95
|
/**
|
|
92
96
|
* Typed version of `useToolInfo` that provides autocomplete for tool names
|
|
93
97
|
* and type inference for inputs, outputs, and responseMetadata.
|
|
94
98
|
*
|
|
95
|
-
* @typeParam K - The name of the tool. Autocompletes based on your
|
|
99
|
+
* @typeParam K - The name of the tool. Autocompletes based on your app's tool registry.
|
|
96
100
|
* @returns A discriminated union with `status: "pending" | "success"` that narrows correctly.
|
|
97
101
|
*
|
|
98
102
|
* @example
|
|
@@ -115,6 +119,6 @@ export declare function generateHelpers<ServerType = never>(): {
|
|
|
115
119
|
* }
|
|
116
120
|
* ```
|
|
117
121
|
*/
|
|
118
|
-
useToolInfo: <ToolName extends keyof InferTools<
|
|
122
|
+
useToolInfo: <ToolName extends keyof InferTools<AppType> & string>() => TypedToolInfoReturn<ToolInput<AppType, ToolName>, ToolOutput<AppType, ToolName>, ToolResponseMetadata<AppType, ToolName>>;
|
|
119
123
|
};
|
|
120
124
|
export {};
|