@rebasepro/cms 0.29.2 → 0.29.3
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/dist/components/CollectionTableBinding/fields/TableStorageUpload.js +1 -1
- package/dist/components/CollectionTableBinding/fields/TableStorageUpload.js.map +1 -1
- package/dist/components/EntityPreviewBinding.d.ts +20 -0
- package/dist/components/EntityPreviewBinding.js +121 -18
- package/dist/components/EntityPreviewBinding.js.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.js +3 -1
- package/dist/mcp_view/bridge.d.ts +21 -1
- package/dist/mcp_view/bridge.js.map +1 -1
- package/dist/mcp_view/index.d.ts +7 -7
- package/dist/mcp_view/index.js +6 -1
- package/dist/mcp_view/index.js.map +1 -1
- package/dist/mcp_view/screen.d.ts +6 -4
- package/dist/mcp_view/screen.js +14 -42
- package/dist/mcp_view/screen.js.map +1 -1
- package/dist/mcp_view/tool_driver.d.ts +33 -0
- package/dist/mcp_view/tool_driver.js +186 -85
- package/dist/mcp_view/tool_driver.js.map +1 -1
- package/dist/mcp_view/write_review.d.ts +35 -0
- package/dist/mcp_view/write_review.js +144 -0
- package/dist/mcp_view/write_review.js.map +1 -0
- package/dist/preview/components/RelationPreview.js +7 -2
- package/dist/preview/components/RelationPreview.js.map +1 -1
- package/dist/saved_apps/SavedAppsView.d.ts +17 -0
- package/dist/saved_apps/SavedAppsView.js +167 -0
- package/dist/saved_apps/SavedAppsView.js.map +1 -0
- package/dist/saved_apps/admin_apps_client.d.ts +24 -0
- package/dist/saved_apps/admin_apps_client.js +46 -0
- package/dist/saved_apps/admin_apps_client.js.map +1 -0
- package/dist/saved_apps/saved_app_frame.d.ts +20 -0
- package/dist/saved_apps/saved_app_frame.js +143 -0
- package/dist/saved_apps/saved_app_frame.js.map +1 -0
- package/package.json +9 -9
package/dist/mcp_view/index.d.ts
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import type { AdminCollection } from "@rebasepro/cms-types";
|
|
2
|
-
import {
|
|
2
|
+
import { type ViewBridge } from "./bridge.js";
|
|
3
3
|
import { type Screen } from "./payload.js";
|
|
4
4
|
export { APPS_PROTOCOL_VERSION, McpAppBridge, isRecord } from "./bridge.js";
|
|
5
|
-
export type { HostContext, ToolResult, DisplayMode } from "./bridge.js";
|
|
6
|
-
export { createToolDriver, DEFAULT_ACTIONS, SaveCancelledError, describeChanges, describeFailedWrite, describeRefusal } from "./tool_driver.js";
|
|
7
|
-
export type { CallTool, SeedPage, ToolDriver, ViewActions, WritePlan, ViewChange, WriteFailure } from "./tool_driver.js";
|
|
5
|
+
export type { HostContext, ToolResult, DisplayMode, ViewBridge } from "./bridge.js";
|
|
6
|
+
export { createToolDriver, DEFAULT_ACTIONS, SaveCancelledError, describeChanges, describeFailedWrite, describeRefusal, needsConfirmation } from "./tool_driver.js";
|
|
7
|
+
export type { CallTool, SeedPage, ToolDriver, ViewActions, WritePlan, WriteIntent, ViewChange, WriteFailure } from "./tool_driver.js";
|
|
8
8
|
export { parseResult, actionsOf, filterOf } from "./payload.js";
|
|
9
9
|
export type { Screen, Block } from "./payload.js";
|
|
10
10
|
export interface McpViewOptions {
|
|
@@ -19,20 +19,20 @@ export interface McpViewOptions {
|
|
|
19
19
|
* Draw a result from a server that predates the admin panel's views
|
|
20
20
|
* (show_collection's columns only): the old table, where the view has it.
|
|
21
21
|
*/
|
|
22
|
-
mountTable?: (bridge:
|
|
22
|
+
mountTable?: (bridge: ViewBridge, container: HTMLElement) => void;
|
|
23
23
|
/** Name and version the view gives the host. */
|
|
24
24
|
appInfo?: {
|
|
25
25
|
name: string;
|
|
26
26
|
version: string;
|
|
27
27
|
};
|
|
28
28
|
/** The channel to the host; a new one on this window's parent by default. */
|
|
29
|
-
bridge?:
|
|
29
|
+
bridge?: ViewBridge;
|
|
30
30
|
}
|
|
31
31
|
/**
|
|
32
32
|
* Connect to the host, wait for the tool's result, set the embed host from
|
|
33
33
|
* it, and mount the app.
|
|
34
34
|
*/
|
|
35
|
-
export declare function startMcpView(options: McpViewOptions):
|
|
35
|
+
export declare function startMcpView(options: McpViewOptions): ViewBridge;
|
|
36
36
|
/**
|
|
37
37
|
* The app's collections as this person may see them here: the project's own
|
|
38
38
|
* configs — with their components — narrowed as the server narrowed the ones
|
package/dist/mcp_view/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { McpAppBridge, isRecord } from "./bridge.js";
|
|
2
|
-
import { createToolDriver, describeChanges, describeRefusal } from "./tool_driver.js";
|
|
2
|
+
import { createToolDriver, describeChanges, describeRefusal, needsConfirmation } from "./tool_driver.js";
|
|
3
3
|
import { findCollection, parseResult } from "./payload.js";
|
|
4
4
|
import { describeAppError } from "./code_app.js";
|
|
5
5
|
import { createViewStore } from "./store.js";
|
|
@@ -49,6 +49,7 @@ function startMcpView(options) {
|
|
|
49
49
|
function embedHost(bridge, screen) {
|
|
50
50
|
const pending = createViewStore(void 0);
|
|
51
51
|
const refused = createViewStore(void 0);
|
|
52
|
+
const saved = createViewStore(void 0);
|
|
52
53
|
const context = createViewStore(bridge.hostContext);
|
|
53
54
|
bridge.watchHostContext((next) => context.set(next));
|
|
54
55
|
const told = modelContext(bridge);
|
|
@@ -65,6 +66,9 @@ function embedHost(bridge, screen) {
|
|
|
65
66
|
resolve(confirmed);
|
|
66
67
|
}
|
|
67
68
|
})),
|
|
69
|
+
onWritten: (intent) => {
|
|
70
|
+
if (!needsConfirmation(intent)) saved.set(intent);
|
|
71
|
+
},
|
|
68
72
|
onChange: told.changes,
|
|
69
73
|
rowLabel: (name, id, row) => rowTitle(findCollection(screen.collections, name), id, row),
|
|
70
74
|
onWriteFailed: (failure) => {
|
|
@@ -84,6 +88,7 @@ function embedHost(bridge, screen) {
|
|
|
84
88
|
screen,
|
|
85
89
|
hostContext: context,
|
|
86
90
|
pendingPlan: pending,
|
|
91
|
+
savedWrite: saved,
|
|
87
92
|
writeFailure: refused,
|
|
88
93
|
onAppError: told.appError
|
|
89
94
|
})
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../src/mcp_view/index.tsx"],"sourcesContent":["/**\n * `@rebasepro/cms/mcp-view`: a project's admin app, inside an MCP App view.\n *\n * A client like Claude shows what the show_* tools open (a collection, a\n * record, an app the model wrote) in a sandboxed frame next to the\n * conversation. This is what runs in that frame: it speaks the host's\n * protocol, reads and writes through the server's tools as the person, and\n * draws with the admin panel's own components — inside the project's own\n * admin app, so its custom views, entity views, fields, previews, actions,\n * plugins and slots are the ones drawn.\n *\n * ```ts\n * // the project's view entry (the Vite plugin generates it)\n * import { startMcpView } from \"@rebasepro/cms/mcp-view\";\n * startMcpView({ mountApp: () => import(\"./main\") });\n * ```\n *\n * The app mounts as it does on its own page; `<Rebase>`, `<RebaseCMS>`,\n * `<RebaseStudio>` and `<RebaseShell>` find the embed host this sets\n * (`setRebaseEmbedHost` in `@rebasepro/app`) and stand in what the frame\n * cannot give them: data through the tools, the person already signed in,\n * no routes, no network.\n *\n * @module\n */\nimport React from \"react\";\nimport { createRoot } from \"react-dom/client\";\nimport { getTitlePropertyKeyForValues, looksLikeIdentifierValue, setRebaseEmbedHost, type RebaseEmbedHost } from \"@rebasepro/app\";\nimport type { AdminCollection, AuthController } from \"@rebasepro/cms-types\";\nimport type { SecurityRule, User } from \"@rebasepro/types\";\nimport { Alert } from \"@rebasepro/ui\";\nimport { McpAppBridge, type HostContext, type ToolResult } from \"./bridge\";\nimport { createToolDriver, describeChanges, describeRefusal, type ToolDriver, type ViewChange, type WriteFailure } from \"./tool_driver\";\nimport { findCollection, parseResult, type Screen } from \"./payload\";\nimport { describeAppError, type AppError } from \"./code_app\";\nimport { McpScreen, type PendingPlan } from \"./screen\";\nimport { VIEW_STORAGE_SOURCE } from \"./storage_source\";\nimport { createViewStore } from \"./store\";\n\nexport { APPS_PROTOCOL_VERSION, McpAppBridge, isRecord } from \"./bridge\";\nimport { isRecord } from \"./bridge\";\nexport type { HostContext, ToolResult, DisplayMode } from \"./bridge\";\nexport { createToolDriver, DEFAULT_ACTIONS, SaveCancelledError, describeChanges, describeFailedWrite, describeRefusal } from \"./tool_driver\";\nexport type { CallTool, SeedPage, ToolDriver, ViewActions, WritePlan, ViewChange, WriteFailure } from \"./tool_driver\";\nexport { parseResult, actionsOf, filterOf } from \"./payload\";\nexport type { Screen, Block } from \"./payload\";\n\nexport interface McpViewOptions {\n /**\n * Mount the app, once the host is set: import the project's entry (which\n * renders its app as it would on its page), or render a default one into\n * `#root`. Given the screen the tool opened, for an app with no\n * collections of its own.\n */\n mountApp: (screen: Screen) => void | Promise<unknown>;\n /**\n * Draw a result from a server that predates the admin panel's views\n * (show_collection's columns only): the old table, where the view has it.\n */\n mountTable?: (bridge: McpAppBridge, container: HTMLElement) => void;\n /** Name and version the view gives the host. */\n appInfo?: { name: string; version: string };\n /** The channel to the host; a new one on this window's parent by default. */\n bridge?: McpAppBridge;\n}\n\n/**\n * Connect to the host, wait for the tool's result, set the embed host from\n * it, and mount the app.\n */\nexport function startMcpView(options: McpViewOptions): McpAppBridge {\n installSubmitFix();\n const bridge = options.bridge ?? new McpAppBridge();\n let started = false;\n\n bridge.ontoolresult = (result: ToolResult) => {\n if (started) return;\n started = true;\n const parsed = parseResult(result);\n if (parsed.kind === \"table\") {\n const container = document.getElementById(\"root\");\n if (container && options.mountTable) options.mountTable(bridge, container);\n else showError(\"This view cannot draw this result.\");\n return;\n }\n if (parsed.kind === \"error\") {\n showError(parsed.message);\n return;\n }\n setRebaseEmbedHost(embedHost(bridge, parsed.screen));\n Promise.resolve(options.mountApp(parsed.screen))\n .catch(error => showError(`The view could not start: ${error instanceof Error ? error.message : String(error)}`));\n };\n\n // The host's light or dark, on the class the UI kit's `dark:` variant reads.\n bridge.watchHostContext(context => {\n if (context.theme) document.documentElement.classList.toggle(\"dark\", context.theme === \"dark\");\n });\n\n void bridge.connect(options.appInfo ?? { name: \"rebase\", version: \"0.3.0\" });\n return bridge;\n}\n\n/** What the app runs on, here: the tools, the person, the frame's storage and theme, and the screen to draw. */\nfunction embedHost(bridge: McpAppBridge, screen: Screen): RebaseEmbedHost {\n const pending = createViewStore<PendingPlan | undefined>(undefined);\n const refused = createViewStore<WriteFailure | undefined>(undefined);\n const context = createViewStore<HostContext>(bridge.hostContext);\n bridge.watchHostContext(next => context.set(next));\n\n const told = modelContext(bridge);\n const tools: ToolDriver = createToolDriver({\n callTool: (name, args) => bridge.callTool(name, args),\n actions: screen.actions,\n ...(screen.firstPage && { seed: screen.firstPage }),\n ...(screen.seeds && { seeds: screen.seeds }),\n // A collection by whichever name it was read or written under: its\n // data path (the tools' name, the model's) or its slug (the admin's).\n collection: name => findCollection(screen.collections, name),\n confirm: plan => new Promise<boolean>(resolve => pending.set({\n plan,\n answer: confirmed => {\n pending.set(undefined);\n resolve(confirmed);\n }\n })),\n onChange: told.changes,\n rowLabel: (name, id, row) => rowTitle(findCollection(screen.collections, name), id, row),\n onWriteFailed: failure => {\n refused.set(failure);\n told.writeFailed(failure);\n }\n });\n\n const host: RebaseEmbedHost = {\n dataDriver: tools.driver,\n // Code can write without a click, so the row hooks ask the person\n // before each write; a save made with the admin's own controls goes\n // as on any screen. A courtesy, not the boundary: every call is the\n // server's tool as the person, under their RLS and granted scopes.\n rowHooksDriver: tools.confirmingDriver,\n authController: viewerAuth(screen.viewer),\n storageSource: VIEW_STORAGE_SOURCE,\n mode: bridge.hostContext.theme === \"dark\" ? \"dark\" : \"light\",\n narrowCollections: collections => narrowCollections(collections, screen.collections),\n renderCms: () => (\n <McpScreen\n bridge={bridge}\n screen={screen}\n hostContext={context}\n pendingPlan={pending}\n writeFailure={refused}\n onAppError={told.appError}\n />\n )\n };\n // The theme follows the host's.\n bridge.watchHostContext(next => {\n const mode = next.theme === \"dark\" ? \"dark\" : \"light\";\n if (mode !== host.mode) {\n host.mode = mode;\n setRebaseEmbedHost({ ...host });\n }\n });\n return host;\n}\n\n/**\n * The app's collections as this person may see them here: the project's own\n * configs — with their components — narrowed as the server narrowed the ones\n * it sent (`McpViewPayload` in the server's `mcp/mcp-view.ts`). A field the\n * server left out is left out; one it made read-only is read-only; its\n * security rules (the project's, and the one closing what the connection was\n * not granted) are the ones checked. A collection the server sent nothing\n * for is shown with every change closed: this screen did not ask for it.\n *\n * Where the app has no collections of its own (the view without a project),\n * the server's configs are the collections.\n */\nexport function narrowCollections(own: AdminCollection[], sent: readonly AdminCollection[]): AdminCollection[] {\n if (own.length === 0) return [...sent];\n const bySlug = new Map(sent.map(collection => [collection.slug, collection]));\n return own.map((collection): AdminCollection => {\n const narrowed = bySlug.get(collection.slug);\n if (!narrowed) {\n return { ...collection, securityRules: [...(collection.securityRules ?? []), CLOSED] };\n }\n const copy = { ...collection };\n return Object.assign(copy, {\n properties: narrowProperties(collection.properties, narrowed.properties),\n securityRules: narrowed.securityRules ?? collection.securityRules\n });\n });\n}\n\n/** The fields the server sent, with its read-only marks; the project's own config for each. */\nfunction narrowProperties<P extends Record<string, unknown>>(own: P, sent: Record<string, unknown>): P {\n const narrowed = { ...own };\n for (const key of Object.keys(narrowed)) {\n const sentProperty = sent[key];\n if (!sentProperty) {\n delete narrowed[key];\n continue;\n }\n const property = narrowed[key];\n if (isRecord(sentProperty) && isRecord(sentProperty.admin) && sentProperty.admin.readOnly === true && isRecord(property)) {\n Object.assign(narrowed, { [key]: { ...property, admin: { ...(isRecord(property.admin) ? property.admin : {}), readOnly: true } } });\n }\n }\n return narrowed;\n}\n\n/** A restrictive rule no account passes, closing every change. */\nconst CLOSED: SecurityRule = {\n name: \"mcp_view_not_opened\",\n mode: \"restrictive\",\n operations: [\"insert\", \"update\", \"delete\"],\n roles: [\"__mcp_view_not_opened__\"]\n};\n\n/**\n * The person the server drew the screen for, as the admin panel asks about\n * them: the security rules it evaluates before offering an action read\n * `uid` and `roles`. Signing out means nothing here — the host holds the\n * connection.\n */\nfunction viewerAuth(viewer: Screen[\"viewer\"]): AuthController {\n const user: User = {\n uid: viewer.uid,\n displayName: null,\n email: null,\n photoURL: null,\n providerId: \"mcp\",\n isAnonymous: false,\n roles: viewer.roles\n };\n return {\n user,\n initialLoading: false,\n authLoading: false,\n loginSkipped: true,\n storageEnabled: false,\n signOut: async () => undefined,\n getAuthToken: async () => \"\",\n extra: undefined,\n setExtra: () => undefined\n };\n}\n\n/**\n * What the model is told, sent with the person's next message: the changes\n * they made here, and an app's failure. Each update replaces the last, so\n * both go every time.\n */\nfunction modelContext(bridge: McpAppBridge) {\n const state: { changes?: string; refused?: string; error?: string } = {};\n const send = () => {\n const text = [state.changes, state.refused, state.error].filter(Boolean).join(\"\\n\");\n if (text) void bridge.updateModelContext(text).catch(() => undefined);\n };\n return {\n changes: (changes: readonly ViewChange[]) => {\n state.changes = describeChanges(changes);\n send();\n },\n writeFailed: (failure: WriteFailure) => {\n state.refused = describeRefusal(failure);\n send();\n },\n appError: (error: AppError) => {\n state.error = describeAppError(error);\n send();\n }\n };\n}\n\n/**\n * A row's title, as the admin names the record: the collection's title\n * property where the row carries a readable value for it. Nothing where it\n * does not — an opaque id says no more than the caller's fallback.\n */\nexport function rowTitle(collection: AdminCollection | undefined, id: string, row: Record<string, unknown> | undefined): string | undefined {\n if (!collection || !row) return undefined;\n const key = getTitlePropertyKeyForValues(collection, row, id);\n const value = key ? row[key] : undefined;\n if (typeof value === \"number\") return String(value);\n return typeof value === \"string\" && value.trim() !== \"\" && !looksLikeIdentifierValue(value) ? value : undefined;\n}\n\n/** An error where the app would be, before it could start. */\nfunction showError(message: string): void {\n const container = document.getElementById(\"root\") ?? document.body.appendChild(document.createElement(\"div\"));\n createRoot(container).render(<div className=\"p-4\"><Alert color=\"error\" size=\"small\">{message}</Alert></div>);\n}\n\n/**\n * A host may sandbox the view without `allow-forms`, and then a form's submit\n * button submits nothing: the browser drops the submission before the form's\n * `submit` event — the admin panel's record form saves on that event. The\n * click still happens, so it is turned into the event itself, after the click\n * has finished (a button's own handler may say which save it was).\n */\nfunction installSubmitFix(): void {\n document.addEventListener(\"click\", (event) => {\n const button = event.target instanceof Element ? event.target.closest(\"button[type=submit]\") : null;\n if (!(button instanceof HTMLButtonElement) || !button.form || button.disabled) return;\n event.preventDefault();\n const form = button.form;\n setTimeout(() => form.dispatchEvent(new SubmitEvent(\"submit\", { bubbles: true, cancelable: true, submitter: button })));\n }, true);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAsEA,SAAgB,aAAa,SAAuC;CAChE,iBAAiB;CACjB,MAAM,SAAS,QAAQ,UAAU,IAAI,aAAa;CAClD,IAAI,UAAU;CAEd,OAAO,gBAAgB,WAAuB;EAC1C,IAAI,SAAS;EACb,UAAU;EACV,MAAM,SAAS,YAAY,MAAM;EACjC,IAAI,OAAO,SAAS,SAAS;GACzB,MAAM,YAAY,SAAS,eAAe,MAAM;GAChD,IAAI,aAAa,QAAQ,YAAY,QAAQ,WAAW,QAAQ,SAAS;QACpE,UAAU,oCAAoC;GACnD;EACJ;EACA,IAAI,OAAO,SAAS,SAAS;GACzB,UAAU,OAAO,OAAO;GACxB;EACJ;EACA,mBAAmB,UAAU,QAAQ,OAAO,MAAM,CAAC;EACnD,QAAQ,QAAQ,QAAQ,SAAS,OAAO,MAAM,CAAC,CAAC,CAC3C,OAAM,UAAS,UAAU,6BAA6B,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GAAG,CAAC;CACxH;CAGA,OAAO,kBAAiB,YAAW;EAC/B,IAAI,QAAQ,OAAO,SAAS,gBAAgB,UAAU,OAAO,QAAQ,QAAQ,UAAU,MAAM;CACjG,CAAC;CAED,OAAY,QAAQ,QAAQ,WAAW;EAAE,MAAM;EAAU,SAAS;CAAQ,CAAC;CAC3E,OAAO;AACX;;AAGA,SAAS,UAAU,QAAsB,QAAiC;CACtE,MAAM,UAAU,gBAAyC,KAAA,CAAS;CAClE,MAAM,UAAU,gBAA0C,KAAA,CAAS;CACnE,MAAM,UAAU,gBAA6B,OAAO,WAAW;CAC/D,OAAO,kBAAiB,SAAQ,QAAQ,IAAI,IAAI,CAAC;CAEjD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QAAQ,qBAAqB,IAAI;EAC/F,IAAI,EAAE,kBAAkB,sBAAsB,CAAC,OAAO,QAAQ,OAAO,UAAU;EAC/E,MAAM,eAAe;EACrB,MAAM,OAAO,OAAO;EACpB,iBAAiB,KAAK,cAAc,IAAI,YAAY,UAAU;GAAE,SAAS;GAAM,YAAY;GAAM,WAAW;EAAO,CAAC,CAAC,CAAC;CAC1H,GAAG,IAAI;AACX"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../src/mcp_view/index.tsx"],"sourcesContent":["/**\n * `@rebasepro/cms/mcp-view`: a project's admin app, inside an MCP App view.\n *\n * A client like Claude shows what the show_* tools open (a collection, a\n * record, an app the model wrote) in a sandboxed frame next to the\n * conversation. This is what runs in that frame: it speaks the host's\n * protocol, reads and writes through the server's tools as the person, and\n * draws with the admin panel's own components — inside the project's own\n * admin app, so its custom views, entity views, fields, previews, actions,\n * plugins and slots are the ones drawn.\n *\n * ```ts\n * // the project's view entry (the Vite plugin generates it)\n * import { startMcpView } from \"@rebasepro/cms/mcp-view\";\n * startMcpView({ mountApp: () => import(\"./main\") });\n * ```\n *\n * The app mounts as it does on its own page; `<Rebase>`, `<RebaseCMS>`,\n * `<RebaseStudio>` and `<RebaseShell>` find the embed host this sets\n * (`setRebaseEmbedHost` in `@rebasepro/app`) and stand in what the frame\n * cannot give them: data through the tools, the person already signed in,\n * no routes, no network.\n *\n * @module\n */\nimport React from \"react\";\nimport { createRoot } from \"react-dom/client\";\nimport { getTitlePropertyKeyForValues, looksLikeIdentifierValue, setRebaseEmbedHost, type RebaseEmbedHost } from \"@rebasepro/app\";\nimport type { AdminCollection, AuthController } from \"@rebasepro/cms-types\";\nimport type { SecurityRule, User } from \"@rebasepro/types\";\nimport { Alert } from \"@rebasepro/ui\";\nimport { McpAppBridge, type HostContext, type ToolResult, type ViewBridge } from \"./bridge\";\nimport { createToolDriver, describeChanges, describeRefusal, needsConfirmation, type ToolDriver, type ViewChange, type WriteFailure, type WriteIntent } from \"./tool_driver\";\nimport { findCollection, parseResult, type Screen } from \"./payload\";\nimport { describeAppError, type AppError } from \"./code_app\";\nimport { McpScreen, type PendingPlan } from \"./screen\";\nimport { VIEW_STORAGE_SOURCE } from \"./storage_source\";\nimport { createViewStore } from \"./store\";\n\nexport { APPS_PROTOCOL_VERSION, McpAppBridge, isRecord } from \"./bridge\";\nimport { isRecord } from \"./bridge\";\nexport type { HostContext, ToolResult, DisplayMode, ViewBridge } from \"./bridge\";\nexport { createToolDriver, DEFAULT_ACTIONS, SaveCancelledError, describeChanges, describeFailedWrite, describeRefusal, needsConfirmation } from \"./tool_driver\";\nexport type { CallTool, SeedPage, ToolDriver, ViewActions, WritePlan, WriteIntent, ViewChange, WriteFailure } from \"./tool_driver\";\nexport { parseResult, actionsOf, filterOf } from \"./payload\";\nexport type { Screen, Block } from \"./payload\";\n\nexport interface McpViewOptions {\n /**\n * Mount the app, once the host is set: import the project's entry (which\n * renders its app as it would on its page), or render a default one into\n * `#root`. Given the screen the tool opened, for an app with no\n * collections of its own.\n */\n mountApp: (screen: Screen) => void | Promise<unknown>;\n /**\n * Draw a result from a server that predates the admin panel's views\n * (show_collection's columns only): the old table, where the view has it.\n */\n mountTable?: (bridge: ViewBridge, container: HTMLElement) => void;\n /** Name and version the view gives the host. */\n appInfo?: { name: string; version: string };\n /** The channel to the host; a new one on this window's parent by default. */\n bridge?: ViewBridge;\n}\n\n/**\n * Connect to the host, wait for the tool's result, set the embed host from\n * it, and mount the app.\n */\nexport function startMcpView(options: McpViewOptions): ViewBridge {\n installSubmitFix();\n const bridge = options.bridge ?? new McpAppBridge();\n let started = false;\n\n bridge.ontoolresult = (result: ToolResult) => {\n if (started) return;\n started = true;\n const parsed = parseResult(result);\n if (parsed.kind === \"table\") {\n const container = document.getElementById(\"root\");\n if (container && options.mountTable) options.mountTable(bridge, container);\n else showError(\"This view cannot draw this result.\");\n return;\n }\n if (parsed.kind === \"error\") {\n showError(parsed.message);\n return;\n }\n setRebaseEmbedHost(embedHost(bridge, parsed.screen));\n Promise.resolve(options.mountApp(parsed.screen))\n .catch(error => showError(`The view could not start: ${error instanceof Error ? error.message : String(error)}`));\n };\n\n // The host's light or dark, on the class the UI kit's `dark:` variant reads.\n bridge.watchHostContext(context => {\n if (context.theme) document.documentElement.classList.toggle(\"dark\", context.theme === \"dark\");\n });\n\n void bridge.connect(options.appInfo ?? { name: \"rebase\", version: \"0.3.0\" });\n return bridge;\n}\n\n/** What the app runs on, here: the tools, the person, the frame's storage and theme, and the screen to draw. */\nfunction embedHost(bridge: ViewBridge, screen: Screen): RebaseEmbedHost {\n const pending = createViewStore<PendingPlan | undefined>(undefined);\n const refused = createViewStore<WriteFailure | undefined>(undefined);\n const saved = createViewStore<WriteIntent | undefined>(undefined);\n const context = createViewStore<HostContext>(bridge.hostContext);\n bridge.watchHostContext(next => context.set(next));\n\n const told = modelContext(bridge);\n const tools: ToolDriver = createToolDriver({\n callTool: (name, args) => bridge.callTool(name, args),\n actions: screen.actions,\n ...(screen.firstPage && { seed: screen.firstPage }),\n ...(screen.seeds && { seeds: screen.seeds }),\n // A collection by whichever name it was read or written under: its\n // data path (the tools' name, the model's) or its slug (the admin's).\n collection: name => findCollection(screen.collections, name),\n confirm: plan => new Promise<boolean>(resolve => pending.set({\n plan,\n answer: confirmed => {\n pending.set(undefined);\n resolve(confirmed);\n }\n })),\n onWritten: intent => {\n if (!needsConfirmation(intent)) saved.set(intent);\n },\n onChange: told.changes,\n rowLabel: (name, id, row) => rowTitle(findCollection(screen.collections, name), id, row),\n onWriteFailed: failure => {\n refused.set(failure);\n told.writeFailed(failure);\n }\n });\n\n const host: RebaseEmbedHost = {\n dataDriver: tools.driver,\n // Code can write without a click, so the row hooks ask the person\n // before each write; a save made with the admin's own controls goes\n // as on any screen. A courtesy, not the boundary: every call is the\n // server's tool as the person, under their RLS and granted scopes.\n rowHooksDriver: tools.confirmingDriver,\n authController: viewerAuth(screen.viewer),\n storageSource: VIEW_STORAGE_SOURCE,\n mode: bridge.hostContext.theme === \"dark\" ? \"dark\" : \"light\",\n narrowCollections: collections => narrowCollections(collections, screen.collections),\n renderCms: () => (\n <McpScreen\n bridge={bridge}\n screen={screen}\n hostContext={context}\n pendingPlan={pending}\n savedWrite={saved}\n writeFailure={refused}\n onAppError={told.appError}\n />\n )\n };\n // The theme follows the host's.\n bridge.watchHostContext(next => {\n const mode = next.theme === \"dark\" ? \"dark\" : \"light\";\n if (mode !== host.mode) {\n host.mode = mode;\n setRebaseEmbedHost({ ...host });\n }\n });\n return host;\n}\n\n/**\n * The app's collections as this person may see them here: the project's own\n * configs — with their components — narrowed as the server narrowed the ones\n * it sent (`McpViewPayload` in the server's `mcp/mcp-view.ts`). A field the\n * server left out is left out; one it made read-only is read-only; its\n * security rules (the project's, and the one closing what the connection was\n * not granted) are the ones checked. A collection the server sent nothing\n * for is shown with every change closed: this screen did not ask for it.\n *\n * Where the app has no collections of its own (the view without a project),\n * the server's configs are the collections.\n */\nexport function narrowCollections(own: AdminCollection[], sent: readonly AdminCollection[]): AdminCollection[] {\n if (own.length === 0) return [...sent];\n const bySlug = new Map(sent.map(collection => [collection.slug, collection]));\n return own.map((collection): AdminCollection => {\n const narrowed = bySlug.get(collection.slug);\n if (!narrowed) {\n return { ...collection, securityRules: [...(collection.securityRules ?? []), CLOSED] };\n }\n const copy = { ...collection };\n return Object.assign(copy, {\n properties: narrowProperties(collection.properties, narrowed.properties),\n securityRules: narrowed.securityRules ?? collection.securityRules\n });\n });\n}\n\n/** The fields the server sent, with its read-only marks; the project's own config for each. */\nfunction narrowProperties<P extends Record<string, unknown>>(own: P, sent: Record<string, unknown>): P {\n const narrowed = { ...own };\n for (const key of Object.keys(narrowed)) {\n const sentProperty = sent[key];\n if (!sentProperty) {\n delete narrowed[key];\n continue;\n }\n const property = narrowed[key];\n if (isRecord(sentProperty) && isRecord(sentProperty.admin) && sentProperty.admin.readOnly === true && isRecord(property)) {\n Object.assign(narrowed, { [key]: { ...property, admin: { ...(isRecord(property.admin) ? property.admin : {}), readOnly: true } } });\n }\n }\n return narrowed;\n}\n\n/** A restrictive rule no account passes, closing every change. */\nconst CLOSED: SecurityRule = {\n name: \"mcp_view_not_opened\",\n mode: \"restrictive\",\n operations: [\"insert\", \"update\", \"delete\"],\n roles: [\"__mcp_view_not_opened__\"]\n};\n\n/**\n * The person the server drew the screen for, as the admin panel asks about\n * them: the security rules it evaluates before offering an action read\n * `uid` and `roles`. Signing out means nothing here — the host holds the\n * connection.\n */\nfunction viewerAuth(viewer: Screen[\"viewer\"]): AuthController {\n const user: User = {\n uid: viewer.uid,\n displayName: null,\n email: null,\n photoURL: null,\n providerId: \"mcp\",\n isAnonymous: false,\n roles: viewer.roles\n };\n return {\n user,\n initialLoading: false,\n authLoading: false,\n loginSkipped: true,\n storageEnabled: false,\n signOut: async () => undefined,\n getAuthToken: async () => \"\",\n extra: undefined,\n setExtra: () => undefined\n };\n}\n\n/**\n * What the model is told, sent with the person's next message: the changes\n * they made here, and an app's failure. Each update replaces the last, so\n * both go every time.\n */\nfunction modelContext(bridge: ViewBridge) {\n const state: { changes?: string; refused?: string; error?: string } = {};\n const send = () => {\n const text = [state.changes, state.refused, state.error].filter(Boolean).join(\"\\n\");\n if (text) void bridge.updateModelContext(text).catch(() => undefined);\n };\n return {\n changes: (changes: readonly ViewChange[]) => {\n state.changes = describeChanges(changes);\n send();\n },\n writeFailed: (failure: WriteFailure) => {\n state.refused = describeRefusal(failure);\n send();\n },\n appError: (error: AppError) => {\n state.error = describeAppError(error);\n send();\n }\n };\n}\n\n/**\n * A row's title, as the admin names the record: the collection's title\n * property where the row carries a readable value for it. Nothing where it\n * does not — an opaque id says no more than the caller's fallback.\n */\nexport function rowTitle(collection: AdminCollection | undefined, id: string, row: Record<string, unknown> | undefined): string | undefined {\n if (!collection || !row) return undefined;\n const key = getTitlePropertyKeyForValues(collection, row, id);\n const value = key ? row[key] : undefined;\n if (typeof value === \"number\") return String(value);\n return typeof value === \"string\" && value.trim() !== \"\" && !looksLikeIdentifierValue(value) ? value : undefined;\n}\n\n/** An error where the app would be, before it could start. */\nfunction showError(message: string): void {\n const container = document.getElementById(\"root\") ?? document.body.appendChild(document.createElement(\"div\"));\n createRoot(container).render(<div className=\"p-4\"><Alert color=\"error\" size=\"small\">{message}</Alert></div>);\n}\n\n/**\n * A host may sandbox the view without `allow-forms`, and then a form's submit\n * button submits nothing: the browser drops the submission before the form's\n * `submit` event — the admin panel's record form saves on that event. The\n * click still happens, so it is turned into the event itself, after the click\n * has finished (a button's own handler may say which save it was).\n */\nfunction installSubmitFix(): void {\n document.addEventListener(\"click\", (event) => {\n const button = event.target instanceof Element ? event.target.closest(\"button[type=submit]\") : null;\n if (!(button instanceof HTMLButtonElement) || !button.form || button.disabled) return;\n event.preventDefault();\n const form = button.form;\n setTimeout(() => form.dispatchEvent(new SubmitEvent(\"submit\", { bubbles: true, cancelable: true, submitter: button })));\n }, true);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAsEA,SAAgB,aAAa,SAAqC;CAC9D,iBAAiB;CACjB,MAAM,SAAS,QAAQ,UAAU,IAAI,aAAa;CAClD,IAAI,UAAU;CAEd,OAAO,gBAAgB,WAAuB;EAC1C,IAAI,SAAS;EACb,UAAU;EACV,MAAM,SAAS,YAAY,MAAM;EACjC,IAAI,OAAO,SAAS,SAAS;GACzB,MAAM,YAAY,SAAS,eAAe,MAAM;GAChD,IAAI,aAAa,QAAQ,YAAY,QAAQ,WAAW,QAAQ,SAAS;QACpE,UAAU,oCAAoC;GACnD;EACJ;EACA,IAAI,OAAO,SAAS,SAAS;GACzB,UAAU,OAAO,OAAO;GACxB;EACJ;EACA,mBAAmB,UAAU,QAAQ,OAAO,MAAM,CAAC;EACnD,QAAQ,QAAQ,QAAQ,SAAS,OAAO,MAAM,CAAC,CAAC,CAC3C,OAAM,UAAS,UAAU,6BAA6B,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GAAG,CAAC;CACxH;CAGA,OAAO,kBAAiB,YAAW;EAC/B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KAAA;CAC/B,IAAI,OAAO,UAAU,UAAU,OAAO,OAAO,KAAK;CAClD,OAAO,OAAO,UAAU,YAAY,MAAM,KAAK,MAAM,MAAM,CAAC,yBAAyB,KAAK,IAAI,QAAQ,KAAA;AAC1G;;AAGA,SAAS,UAAU,SAAuB;CAEtC,WADkB,SAAS,eAAe,MAAM,KAAK,SAAS,KAAK,YAAY,SAAS,cAAc,KAAK,CAAC,CACxF,CAAC,CAAC,OAAO,oBAAC,OAAD;EAAK,WAAU;YAAM,oBAAC,OAAD;GAAO,OAAM;GAAQ,MAAK;aAAS;EAAe,CAAA;CAAM,CAAA,CAAC;AAC/G;;;;;;;;AASA,SAAS,mBAAyB;CAC9B,SAAS,iBAAiB,UAAU,UAAU;EAC1C,MAAM,SAAS,MAAM,kBAAkB,UAAU,MAAM,OAAO,QAAQ,qBAAqB,IAAI;EAC/F,IAAI,EAAE,kBAAkB,sBAAsB,CAAC,OAAO,QAAQ,OAAO,UAAU;EAC/E,MAAM,eAAe;EACrB,MAAM,OAAO,OAAO;EACpB,iBAAiB,KAAK,cAAc,IAAI,YAAY,UAAU;GAAE,SAAS;GAAM,YAAY;GAAM,WAAW;EAAO,CAAC,CAAC,CAAC;CAC1H,GAAG,IAAI;AACX"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import React from "react";
|
|
2
|
-
import type { HostContext,
|
|
3
|
-
import { type WriteFailure, type WritePlan } from "./tool_driver.js";
|
|
2
|
+
import type { HostContext, ViewBridge } from "./bridge.js";
|
|
3
|
+
import { type WriteFailure, type WriteIntent, type WritePlan } from "./tool_driver.js";
|
|
4
4
|
import { type Screen } from "./payload.js";
|
|
5
5
|
import { type AppError } from "./code_app.js";
|
|
6
6
|
import { type ViewStore } from "./store.js";
|
|
@@ -10,12 +10,14 @@ export interface PendingPlan {
|
|
|
10
10
|
answer: (confirmed: boolean) => void;
|
|
11
11
|
}
|
|
12
12
|
export interface McpScreenProps {
|
|
13
|
-
bridge:
|
|
13
|
+
bridge: ViewBridge;
|
|
14
14
|
screen: Screen;
|
|
15
15
|
/** The host's context, as it changes. */
|
|
16
16
|
hostContext: ViewStore<HostContext>;
|
|
17
17
|
/** The write plan to confirm, as it changes. */
|
|
18
18
|
pendingPlan: ViewStore<PendingPlan | undefined>;
|
|
19
|
+
/** A write that went through without asking, to say what it changed. */
|
|
20
|
+
savedWrite: ViewStore<WriteIntent | undefined>;
|
|
19
21
|
/** The last write the server refused, as it changes: shown to the person, once each. */
|
|
20
22
|
writeFailure?: ViewStore<WriteFailure | undefined>;
|
|
21
23
|
onAppError: (error: AppError) => void;
|
|
@@ -27,4 +29,4 @@ export interface McpScreenProps {
|
|
|
27
29
|
* collections, custom views, entity views, fields and actions are the ones
|
|
28
30
|
* drawn.
|
|
29
31
|
*/
|
|
30
|
-
export declare function McpScreen({ bridge, screen, hostContext, pendingPlan, writeFailure, onAppError }: McpScreenProps): React.JSX.Element;
|
|
32
|
+
export declare function McpScreen({ bridge, screen, hostContext, pendingPlan, writeFailure, savedWrite, onAppError }: McpScreenProps): React.JSX.Element;
|
package/dist/mcp_view/screen.js
CHANGED
|
@@ -5,10 +5,11 @@ import { describeFailedWrite } from "./tool_driver.js";
|
|
|
5
5
|
import { filterOf, orderOf } from "./payload.js";
|
|
6
6
|
import { AppCollections } from "./app_modules.js";
|
|
7
7
|
import { AppErrorBoundary, loadApp } from "./code_app.js";
|
|
8
|
+
import { SavedNotice, WriteConfirmDialog } from "./write_review.js";
|
|
8
9
|
import { createViewStore, useViewStore } from "./store.js";
|
|
9
10
|
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
|
10
11
|
import { jsx, jsxs } from "react/jsx-runtime";
|
|
11
|
-
import { Alert,
|
|
12
|
+
import { Alert, Card, CircularProgress, IconButton, Maximize2Icon, Tooltip, Typography, cls, iconSize } from "@rebasepro/ui";
|
|
12
13
|
//#region src/mcp_view/screen.tsx
|
|
13
14
|
/**
|
|
14
15
|
* The tallest the screen is in the conversation; past it, a collection
|
|
@@ -25,10 +26,12 @@ var INLINE_MAX_HEIGHT = 640;
|
|
|
25
26
|
* collections, custom views, entity views, fields and actions are the ones
|
|
26
27
|
* drawn.
|
|
27
28
|
*/
|
|
28
|
-
function McpScreen({ bridge, screen, hostContext, pendingPlan, writeFailure, onAppError }) {
|
|
29
|
+
function McpScreen({ bridge, screen, hostContext, pendingPlan, writeFailure, savedWrite, onAppError }) {
|
|
29
30
|
const rootRef = useRef(null);
|
|
30
31
|
const context = useViewStore(hostContext);
|
|
31
32
|
const pending = useViewStore(pendingPlan);
|
|
33
|
+
const saved = useViewStore(savedWrite);
|
|
34
|
+
const dismissSaved = useCallback(() => savedWrite.set(void 0), [savedWrite]);
|
|
32
35
|
const [refused, dismissRefused] = useRefusedWrite(writeFailure);
|
|
33
36
|
const registry = useCollectionRegistryController();
|
|
34
37
|
const fullscreen = context.displayMode === "fullscreen";
|
|
@@ -103,47 +106,16 @@ function McpScreen({ bridge, screen, hostContext, pendingPlan, writeFailure, onA
|
|
|
103
106
|
onDismiss: dismissRefused,
|
|
104
107
|
children: `Could not ${describeFailedWrite(refused)}: ${refused.message}`
|
|
105
108
|
}),
|
|
109
|
+
/* @__PURE__ */ jsx(SavedNotice, {
|
|
110
|
+
intent: saved,
|
|
111
|
+
collectionOf,
|
|
112
|
+
onDismiss: dismissSaved
|
|
113
|
+
}),
|
|
106
114
|
body,
|
|
107
|
-
/* @__PURE__ */
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
children: [
|
|
112
|
-
/* @__PURE__ */ jsx(DialogTitle, {
|
|
113
|
-
variant: "subtitle1",
|
|
114
|
-
children: "Confirm this change"
|
|
115
|
-
}),
|
|
116
|
-
/* @__PURE__ */ jsxs(DialogContent, {
|
|
117
|
-
className: "flex flex-col gap-2",
|
|
118
|
-
children: [
|
|
119
|
-
/* @__PURE__ */ jsx(Typography, {
|
|
120
|
-
variant: "body2",
|
|
121
|
-
children: pending?.plan.summary
|
|
122
|
-
}),
|
|
123
|
-
pending?.plan.effects?.map((effect) => /* @__PURE__ */ jsx(Typography, {
|
|
124
|
-
variant: "body2",
|
|
125
|
-
color: "secondary",
|
|
126
|
-
children: effect
|
|
127
|
-
}, effect)),
|
|
128
|
-
pending?.plan.reversible && /* @__PURE__ */ jsxs(Typography, {
|
|
129
|
-
variant: "caption",
|
|
130
|
-
color: "secondary",
|
|
131
|
-
children: ["Undo: ", pending.plan.reversible]
|
|
132
|
-
})
|
|
133
|
-
]
|
|
134
|
-
}),
|
|
135
|
-
/* @__PURE__ */ jsxs(DialogActions, { children: [/* @__PURE__ */ jsx(Button, {
|
|
136
|
-
variant: "text",
|
|
137
|
-
color: "neutral",
|
|
138
|
-
onClick: () => pending?.answer(false),
|
|
139
|
-
children: "Cancel"
|
|
140
|
-
}), /* @__PURE__ */ jsx(Button, {
|
|
141
|
-
variant: "filled",
|
|
142
|
-
color: "primary",
|
|
143
|
-
onClick: () => pending?.answer(true),
|
|
144
|
-
children: "Save"
|
|
145
|
-
})] })
|
|
146
|
-
]
|
|
115
|
+
/* @__PURE__ */ jsx(WriteConfirmDialog, {
|
|
116
|
+
plan: pending?.plan,
|
|
117
|
+
collectionOf,
|
|
118
|
+
onAnswer: (confirmed) => pending?.answer(confirmed)
|
|
147
119
|
})
|
|
148
120
|
]
|
|
149
121
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"screen.js","names":[],"sources":["../../src/mcp_view/screen.tsx"],"sourcesContent":["import React, { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport type { AdminCollection } from \"@rebasepro/cms-types\";\nimport {\n Alert,\n Button,\n Card,\n CircularProgress,\n Dialog,\n DialogActions,\n DialogContent,\n DialogTitle,\n IconButton,\n Maximize2Icon,\n Tooltip,\n Typography,\n cls,\n iconSize\n} from \"@rebasepro/ui\";\nimport { CollectionPanel } from \"../components/CollectionPanel\";\nimport { RecordForm } from \"../components/RecordForm\";\nimport { useCollectionRegistryController } from \"../hooks/navigation/contexts/CollectionRegistryContext\";\nimport type { HostContext, McpAppBridge } from \"./bridge\";\nimport { describeFailedWrite, type WriteFailure, type WritePlan } from \"./tool_driver\";\nimport { filterOf, orderOf, type AppBlock, type CollectionBlock, type RecordBlock, type Screen } from \"./payload\";\nimport { AppErrorBoundary, loadApp, type AppError } from \"./code_app\";\nimport { AppCollections } from \"./app_modules\";\nimport { createViewStore, useViewStore, type ViewStore } from \"./store\";\n\n/**\n * The tallest the screen is in the conversation; past it, a collection\n * scrolls inside its own block, and anything else inside the screen. A\n * record's form and the confirmation of a save open over the frame, centred\n * in it: in a frame as tall as everything on the screen they would open where\n * the person is not looking.\n */\nconst INLINE_MAX_HEIGHT = 640;\n\n/** A write's plan waiting for the person's answer. */\nexport interface PendingPlan {\n plan: WritePlan;\n answer: (confirmed: boolean) => void;\n}\n\nexport interface McpScreenProps {\n bridge: McpAppBridge;\n screen: Screen;\n /** The host's context, as it changes. */\n hostContext: ViewStore<HostContext>;\n /** The write plan to confirm, as it changes. */\n pendingPlan: ViewStore<PendingPlan | undefined>;\n /** The last write the server refused, as it changes: shown to the person, once each. */\n writeFailure?: ViewStore<WriteFailure | undefined>;\n onAppError: (error: AppError) => void;\n}\n\n/**\n * What the embedded app's shell draws (`renderCms` of the embed host): the\n * one block the tool opened — a collection, a record, or an app the model\n * wrote — inside the providers the app's own `<RebaseShell>` set up, so its\n * collections, custom views, entity views, fields and actions are the ones\n * drawn.\n */\nexport function McpScreen({ bridge, screen, hostContext, pendingPlan, writeFailure, onAppError }: McpScreenProps) {\n const rootRef = useRef<HTMLDivElement>(null);\n const context = useViewStore(hostContext);\n const pending = useViewStore(pendingPlan);\n const [refused, dismissRefused] = useRefusedWrite(writeFailure);\n const registry = useCollectionRegistryController();\n const fullscreen = context.displayMode === \"fullscreen\";\n const canExpand = !fullscreen && context.availableDisplayModes?.includes(\"fullscreen\") === true;\n const block = screen.blocks[0];\n\n // The host sizes the frame to the document, which it cannot measure\n // across the sandbox.\n useEffect(() => {\n const root = rootRef.current;\n if (!root) return;\n const measure = () => {\n const html = document.documentElement;\n const previous = html.style.height;\n html.style.height = \"max-content\";\n bridge.sizeChanged(Math.ceil(html.getBoundingClientRect().height));\n html.style.height = previous;\n };\n const observer = new ResizeObserver(measure);\n observer.observe(root);\n measure();\n return () => observer.disconnect();\n }, [bridge]);\n\n const collectionOf = (name: string): AdminCollection | undefined => registry.getCollection(name);\n const heading = screen.title ?? (block.type === \"app\" ? undefined : blockTitle(block, collectionOf(block.collection)));\n\n let body: React.ReactNode;\n if (!registry.initialised && !registry.collections?.length) {\n body = <CircularProgress size=\"smallest\"/>;\n } else if (block.type === \"app\") {\n body = <AppView block={block} onError={onAppError}/>;\n } else {\n const collection = collectionOf(block.collection);\n body = !collection\n ? <Alert color=\"error\" size=\"small\">The collection "{block.collection}" is not in this view.</Alert>\n : block.type === \"collection\"\n ? <CollectionView block={block} collection={collection}/>\n : <RecordView block={block} collection={collection}/>;\n }\n\n return (\n <div ref={rootRef}\n className={cls(\"flex flex-col gap-4 p-4 w-full min-w-0 bg-surface-sheet text-text-primary dark:text-text-primary-dark overflow-y-auto\", fullscreen && \"h-screen\")}\n style={fullscreen ? undefined : { maxHeight: INLINE_MAX_HEIGHT }}>\n {(heading || canExpand) && (\n <div className=\"flex items-center justify-between gap-3 min-h-8\">\n <Typography variant=\"subtitle2\" noWrap>{heading}</Typography>\n {canExpand && (\n <Tooltip title=\"Expand\">\n <IconButton\n size=\"small\"\n aria-label=\"Expand\"\n onClick={() => void bridge.requestDisplayMode(\"fullscreen\").catch(() => undefined)}\n >\n <Maximize2Icon size={iconSize.smallest}/>\n </IconButton>\n </Tooltip>\n )}\n </div>\n )}\n {refused && (\n // Sticky: the inline frame scrolls inside, and the button that\n // wrote may be far below its top.\n <Alert color=\"error\" size=\"small\" outerClassName=\"sticky top-0 z-10\" onDismiss={dismissRefused}>\n {`Could not ${describeFailedWrite(refused)}: ${refused.message}`}\n </Alert>\n )}\n {body}\n <Dialog open={pending !== undefined} onOpenChange={open => !open && pending?.answer(false)} maxWidth=\"sm\">\n <DialogTitle variant=\"subtitle1\">Confirm this change</DialogTitle>\n <DialogContent className=\"flex flex-col gap-2\">\n <Typography variant=\"body2\">{pending?.plan.summary}</Typography>\n {pending?.plan.effects?.map(effect => (\n <Typography key={effect} variant=\"body2\" color=\"secondary\">{effect}</Typography>\n ))}\n {pending?.plan.reversible && (\n <Typography variant=\"caption\" color=\"secondary\">Undo: {pending.plan.reversible}</Typography>\n )}\n </DialogContent>\n <DialogActions>\n <Button variant=\"text\" color=\"neutral\" onClick={() => pending?.answer(false)}>Cancel</Button>\n <Button variant=\"filled\" color=\"primary\" onClick={() => pending?.answer(true)}>Save</Button>\n </DialogActions>\n </Dialog>\n </div>\n );\n}\n\nfunction blockTitle(block: CollectionBlock | RecordBlock, collection: AdminCollection | undefined): string {\n if (block.type === \"record\") {\n const name = collection?.singularName ?? collection?.name ?? block.collection;\n return block.id === undefined ? `New ${name.toLowerCase()}` : name;\n }\n return collection?.name ?? block.collection;\n}\n\n/**\n * show_collection: the admin panel's collection view, where a row opens its\n * form over the screen. It sizes to its rows, up to what the screen leaves\n * it — inline, the screen's height cap; full screen, the window — and then\n * scrolls inside.\n */\nfunction CollectionView({ block, collection }: {\n block: CollectionBlock;\n collection: AdminCollection;\n}) {\n const overrides = useMemo<Partial<AdminCollection>>(() => {\n // The model's filter, as one the person can clear.\n const where = filterOf(block.where);\n return {\n ...(where && { defaultFilter: where }),\n ...(block.limit !== undefined && { pagination: block.limit })\n };\n }, [block.where, block.limit]);\n const sort = orderOf(block.orderBy);\n\n return (\n <CollectionPanel\n collection={collection.slug}\n title={false}\n className=\"flex-1 rounded-xl overflow-hidden\"\n {...(block.view && { viewMode: block.view })}\n {...(sort && { orderBy: sort })}\n collectionOverrides={overrides}\n />\n );\n}\n\n/** show_record: the admin panel's form, for a row or a new one. */\nfunction RecordView({ block, collection }: { block: RecordBlock; collection: AdminCollection }) {\n // A new row's form becomes that row's once it is saved.\n const [created, setCreated] = useState<string | number>();\n const id = block.id ?? created;\n return (\n <Card className=\"min-w-0 overflow-hidden\">\n <RecordForm\n key={String(id ?? \"new\")}\n collection={collection}\n id={id}\n {...(id === undefined && block.values && { defaultValues: block.values })}\n onSaved={params => {\n if (id === undefined) setCreated(params.id);\n }}\n />\n </Card>\n );\n}\n\n/**\n * show_app: the app the model wrote, held to the collections it was opened\n * with, and its failure shown in its place.\n */\nfunction AppView({ block, onError }: {\n block: AppBlock;\n onError: (error: AppError) => void;\n}) {\n const loaded = useMemo(() => loadApp(block.code), [block.code]);\n\n // A module that failed as it loaded is told once.\n useEffect(() => {\n if (loaded.error) onError(loaded.error);\n }, [loaded, onError]);\n\n const failure = (error: AppError) => (\n <Alert color=\"error\" size=\"small\">\n The app failed{error.line ? ` at line ${error.line}` : \"\"}: {error.message}\n </Alert>\n );\n if (!loaded.Component) return failure(loaded.error ?? { message: \"The app did not load.\" });\n const { Component } = loaded;\n return (\n <AppErrorBoundary lineOffset={loaded.lineOffset} onError={onError} fallback={failure}>\n <AppCollections names={block.collections}>\n <Component/>\n </AppCollections>\n </AppErrorBoundary>\n );\n}\n\n/**\n * The last write the server refused, until the person dismisses it: an app's\n * code can drop the rejection, and a button the app drew shows nothing of its\n * own (the admin's own controls show theirs). Shown in the screen, not as a\n * snackbar, which the sandboxed frame left off its edge.\n */\nfunction useRefusedWrite(store: ViewStore<WriteFailure | undefined> | undefined): [WriteFailure | undefined, () => void] {\n const failure = useViewStore(store ?? NO_FAILURES);\n const [dismissed, setDismissed] = useState<WriteFailure | undefined>(undefined);\n const dismiss = useCallback(() => setDismissed(failure), [failure]);\n return [failure !== dismissed ? failure : undefined, dismiss];\n}\n\nconst NO_FAILURES = createViewStore<WriteFailure | undefined>(undefined);\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAmCA,IAAM,oBAAoB;;;;;;;;AA2B1B,SAAgB,UAAU,EAAE,QAAQ,QAAQ,aAAa,aAAa,cAAc,cAA8B;CAC9G,MAAM,UAAU,OAA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Ed;;;;;AAMA,SAAS,QAAQ,EAAE,OAAO,WAGvB;CACC,MAAM,SAAS,cAAc,QAAQ,MAAM,IAAI,GAAG,CAAC,MAAM,IAAI,CAAC;CAG9D,gBAAgB;EACZ,IAAI,OAAO,OAAO,QAAQ,OAAO,KAAK;CAC1C,GAAG,CAAC,QAAQ,OAAO,CAAC;CAEpB,MAAM,WAAW,UACb,qBAAC,OAAD;EAAO,OAAM;EAAQ,MAAK;YAA1B;GAAkC;GACf,MAAM,OAAO,YAAY,MAAM,SAAS;GAAG;GAAG,MAAM;EAChE;;CAEX,IAAI,CAAC,OAAO,WAAW,OAAO,QAAQ,OAAO,SAAS,EAAE,SAAS,wBAAwB,CAAC;CAC1F,MAAM,EAAE,cAAc;CACtB,OACI,oBAAC,kBAAD;EAAkB,YAAY,OAAO;EAAqB;EAAS,UAAU;YACzE,oBAAC,gBAAD;GAAgB,OAAO,MAAM;aACzB,oBAAC,WAAD,CAAW,CAAA;EACC,CAAA;CACF,CAAA;AAE1B;;;;;;;AAQA,SAAS,gBAAgB,OAAgG;CACrH,MAAM,UAAU,aAAa,SAAS,WAAW;CACjD,MAAM,CAAC,WAAW,gBAAgB,SAAmC,KAAA,CAAS;CAC9E,MAAM,UAAU,kBAAkB,aAAa,OAAO,GAAG,CAAC,OAAO,CAAC;CAClE,OAAO,CAAC,YAAY,YAAY,UAAU,KAAA,GAAW,OAAO;AAChE;AAEA,IAAM,cAAc,gBAA0C,KAAA,CAAS"}
|
|
1
|
+
{"version":3,"file":"screen.js","names":[],"sources":["../../src/mcp_view/screen.tsx"],"sourcesContent":["import React, { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport type { AdminCollection } from \"@rebasepro/cms-types\";\nimport {\n Alert,\n Card,\n CircularProgress,\n IconButton,\n Maximize2Icon,\n Tooltip,\n Typography,\n cls,\n iconSize\n} from \"@rebasepro/ui\";\nimport { CollectionPanel } from \"../components/CollectionPanel\";\nimport { RecordForm } from \"../components/RecordForm\";\nimport { useCollectionRegistryController } from \"../hooks/navigation/contexts/CollectionRegistryContext\";\nimport type { HostContext, ViewBridge } from \"./bridge\";\nimport { describeFailedWrite, type WriteFailure, type WriteIntent, type WritePlan } from \"./tool_driver\";\nimport { SavedNotice, WriteConfirmDialog } from \"./write_review\";\nimport { filterOf, orderOf, type AppBlock, type CollectionBlock, type RecordBlock, type Screen } from \"./payload\";\nimport { AppErrorBoundary, loadApp, type AppError } from \"./code_app\";\nimport { AppCollections } from \"./app_modules\";\nimport { createViewStore, useViewStore, type ViewStore } from \"./store\";\n\n/**\n * The tallest the screen is in the conversation; past it, a collection\n * scrolls inside its own block, and anything else inside the screen. A\n * record's form and the confirmation of a save open over the frame, centred\n * in it: in a frame as tall as everything on the screen they would open where\n * the person is not looking.\n */\nconst INLINE_MAX_HEIGHT = 640;\n\n/** A write's plan waiting for the person's answer. */\nexport interface PendingPlan {\n plan: WritePlan;\n answer: (confirmed: boolean) => void;\n}\n\nexport interface McpScreenProps {\n bridge: ViewBridge;\n screen: Screen;\n /** The host's context, as it changes. */\n hostContext: ViewStore<HostContext>;\n /** The write plan to confirm, as it changes. */\n pendingPlan: ViewStore<PendingPlan | undefined>;\n /** A write that went through without asking, to say what it changed. */\n savedWrite: ViewStore<WriteIntent | undefined>;\n /** The last write the server refused, as it changes: shown to the person, once each. */\n writeFailure?: ViewStore<WriteFailure | undefined>;\n onAppError: (error: AppError) => void;\n}\n\n/**\n * What the embedded app's shell draws (`renderCms` of the embed host): the\n * one block the tool opened — a collection, a record, or an app the model\n * wrote — inside the providers the app's own `<RebaseShell>` set up, so its\n * collections, custom views, entity views, fields and actions are the ones\n * drawn.\n */\nexport function McpScreen({ bridge, screen, hostContext, pendingPlan, writeFailure, savedWrite, onAppError }: McpScreenProps) {\n const rootRef = useRef<HTMLDivElement>(null);\n const context = useViewStore(hostContext);\n const pending = useViewStore(pendingPlan);\n const saved = useViewStore(savedWrite);\n const dismissSaved = useCallback(() => savedWrite.set(undefined), [savedWrite]);\n const [refused, dismissRefused] = useRefusedWrite(writeFailure);\n const registry = useCollectionRegistryController();\n const fullscreen = context.displayMode === \"fullscreen\";\n const canExpand = !fullscreen && context.availableDisplayModes?.includes(\"fullscreen\") === true;\n const block = screen.blocks[0];\n\n // The host sizes the frame to the document, which it cannot measure\n // across the sandbox.\n useEffect(() => {\n const root = rootRef.current;\n if (!root) return;\n const measure = () => {\n const html = document.documentElement;\n const previous = html.style.height;\n html.style.height = \"max-content\";\n bridge.sizeChanged(Math.ceil(html.getBoundingClientRect().height));\n html.style.height = previous;\n };\n const observer = new ResizeObserver(measure);\n observer.observe(root);\n measure();\n return () => observer.disconnect();\n }, [bridge]);\n\n const collectionOf = (name: string): AdminCollection | undefined => registry.getCollection(name);\n const heading = screen.title ?? (block.type === \"app\" ? undefined : blockTitle(block, collectionOf(block.collection)));\n\n let body: React.ReactNode;\n if (!registry.initialised && !registry.collections?.length) {\n body = <CircularProgress size=\"smallest\"/>;\n } else if (block.type === \"app\") {\n body = <AppView block={block} onError={onAppError}/>;\n } else {\n const collection = collectionOf(block.collection);\n body = !collection\n ? <Alert color=\"error\" size=\"small\">The collection "{block.collection}" is not in this view.</Alert>\n : block.type === \"collection\"\n ? <CollectionView block={block} collection={collection}/>\n : <RecordView block={block} collection={collection}/>;\n }\n\n return (\n <div ref={rootRef}\n className={cls(\"flex flex-col gap-4 p-4 w-full min-w-0 bg-surface-sheet text-text-primary dark:text-text-primary-dark overflow-y-auto\", fullscreen && \"h-screen\")}\n style={fullscreen ? undefined : { maxHeight: INLINE_MAX_HEIGHT }}>\n {(heading || canExpand) && (\n <div className=\"flex items-center justify-between gap-3 min-h-8\">\n <Typography variant=\"subtitle2\" noWrap>{heading}</Typography>\n {canExpand && (\n <Tooltip title=\"Expand\">\n <IconButton\n size=\"small\"\n aria-label=\"Expand\"\n onClick={() => void bridge.requestDisplayMode(\"fullscreen\").catch(() => undefined)}\n >\n <Maximize2Icon size={iconSize.smallest}/>\n </IconButton>\n </Tooltip>\n )}\n </div>\n )}\n {refused && (\n // Sticky: the inline frame scrolls inside, and the button that\n // wrote may be far below its top.\n <Alert color=\"error\" size=\"small\" outerClassName=\"sticky top-0 z-10\" onDismiss={dismissRefused}>\n {`Could not ${describeFailedWrite(refused)}: ${refused.message}`}\n </Alert>\n )}\n <SavedNotice intent={saved} collectionOf={collectionOf} onDismiss={dismissSaved}/>\n {body}\n <WriteConfirmDialog plan={pending?.plan}\n collectionOf={collectionOf}\n onAnswer={confirmed => pending?.answer(confirmed)}/>\n </div>\n );\n}\n\nfunction blockTitle(block: CollectionBlock | RecordBlock, collection: AdminCollection | undefined): string {\n if (block.type === \"record\") {\n const name = collection?.singularName ?? collection?.name ?? block.collection;\n return block.id === undefined ? `New ${name.toLowerCase()}` : name;\n }\n return collection?.name ?? block.collection;\n}\n\n/**\n * show_collection: the admin panel's collection view, where a row opens its\n * form over the screen. It sizes to its rows, up to what the screen leaves\n * it — inline, the screen's height cap; full screen, the window — and then\n * scrolls inside.\n */\nfunction CollectionView({ block, collection }: {\n block: CollectionBlock;\n collection: AdminCollection;\n}) {\n const overrides = useMemo<Partial<AdminCollection>>(() => {\n // The model's filter, as one the person can clear.\n const where = filterOf(block.where);\n return {\n ...(where && { defaultFilter: where }),\n ...(block.limit !== undefined && { pagination: block.limit })\n };\n }, [block.where, block.limit]);\n const sort = orderOf(block.orderBy);\n\n return (\n <CollectionPanel\n collection={collection.slug}\n title={false}\n className=\"flex-1 rounded-xl overflow-hidden\"\n {...(block.view && { viewMode: block.view })}\n {...(sort && { orderBy: sort })}\n collectionOverrides={overrides}\n />\n );\n}\n\n/** show_record: the admin panel's form, for a row or a new one. */\nfunction RecordView({ block, collection }: { block: RecordBlock; collection: AdminCollection }) {\n // A new row's form becomes that row's once it is saved.\n const [created, setCreated] = useState<string | number>();\n const id = block.id ?? created;\n return (\n <Card className=\"min-w-0 overflow-hidden\">\n <RecordForm\n key={String(id ?? \"new\")}\n collection={collection}\n id={id}\n {...(id === undefined && block.values && { defaultValues: block.values })}\n onSaved={params => {\n if (id === undefined) setCreated(params.id);\n }}\n />\n </Card>\n );\n}\n\n/**\n * show_app: the app the model wrote, held to the collections it was opened\n * with, and its failure shown in its place.\n */\nfunction AppView({ block, onError }: {\n block: AppBlock;\n onError: (error: AppError) => void;\n}) {\n const loaded = useMemo(() => loadApp(block.code), [block.code]);\n\n // A module that failed as it loaded is told once.\n useEffect(() => {\n if (loaded.error) onError(loaded.error);\n }, [loaded, onError]);\n\n const failure = (error: AppError) => (\n <Alert color=\"error\" size=\"small\">\n The app failed{error.line ? ` at line ${error.line}` : \"\"}: {error.message}\n </Alert>\n );\n if (!loaded.Component) return failure(loaded.error ?? { message: \"The app did not load.\" });\n const { Component } = loaded;\n return (\n <AppErrorBoundary lineOffset={loaded.lineOffset} onError={onError} fallback={failure}>\n <AppCollections names={block.collections}>\n <Component/>\n </AppCollections>\n </AppErrorBoundary>\n );\n}\n\n/**\n * The last write the server refused, until the person dismisses it: an app's\n * code can drop the rejection, and a button the app drew shows nothing of its\n * own (the admin's own controls show theirs). Shown in the screen, not as a\n * snackbar, which the sandboxed frame left off its edge.\n */\nfunction useRefusedWrite(store: ViewStore<WriteFailure | undefined> | undefined): [WriteFailure | undefined, () => void] {\n const failure = useViewStore(store ?? NO_FAILURES);\n const [dismissed, setDismissed] = useState<WriteFailure | undefined>(undefined);\n const dismiss = useCallback(() => setDismissed(failure), [failure]);\n return [failure !== dismissed ? failure : undefined, dismiss];\n}\n\nconst NO_FAILURES = createViewStore<WriteFailure | undefined>(undefined);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AA+BA,IAAM,oBAAoB;;;;;;;;AA6B1B,SAAgB,UAAU,EAAE,QAAQ,QAAQ,aAAa,aAAa,cAAc,YAAY,cAA8B;CAC1H,MAAM,UAAU,OAAuB,IAAI;CAC3C,MAAM,UAAU,aAAa,WAAW;CACxC,MAAM,UAAU,aAAa,WAAW;CACxC,MAAM,QAAQ,aAAa,UAAU;CACrC,MAAM,eAAe,kBAAkB,W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AAA;CACF,CAAA;AAE1B;;;;;;;AAQA,SAAS,gBAAgB,OAAgG;CACrH,MAAM,UAAU,aAAa,SAAS,WAAW;CACjD,MAAM,CAAC,WAAW,gBAAgB,SAAmC,KAAA,CAAS;CAC9E,MAAM,UAAU,kBAAkB,aAAa,OAAO,GAAG,CAAC,OAAO,CAAC;CAClE,OAAO,CAAC,YAAY,YAAY,UAAU,KAAA,GAAW,OAAO;AAChE;AAEA,IAAM,cAAc,gBAA0C,KAAA,CAAS"}
|
|
@@ -63,7 +63,38 @@ export interface WritePlan {
|
|
|
63
63
|
summary: string;
|
|
64
64
|
effects?: string[];
|
|
65
65
|
reversible?: string;
|
|
66
|
+
/** The write itself, as the person sees it: the dialog is drawn from this, the summary is for the model. */
|
|
67
|
+
write?: WriteIntent;
|
|
66
68
|
}
|
|
69
|
+
/**
|
|
70
|
+
* One write, described for the person rather than the model: which row, by
|
|
71
|
+
* its title, and its fields' new and old values.
|
|
72
|
+
*/
|
|
73
|
+
export interface WriteIntent {
|
|
74
|
+
action: "create" | "update" | "delete";
|
|
75
|
+
collection: string;
|
|
76
|
+
id?: string;
|
|
77
|
+
title?: string;
|
|
78
|
+
/** The values written. */
|
|
79
|
+
values?: Record<string, unknown>;
|
|
80
|
+
/** The row before the write, where the server or the driver's reads knew it. */
|
|
81
|
+
previous?: Record<string, unknown>;
|
|
82
|
+
/**
|
|
83
|
+
* The write began inside the person's click (the browser's transient user
|
|
84
|
+
* activation was live when it started): a Save, a row action, a button
|
|
85
|
+
* the app drew. Code writing on its own has none.
|
|
86
|
+
*/
|
|
87
|
+
gesture: boolean;
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Whether the write needs the person's yes before it is sent.
|
|
91
|
+
*
|
|
92
|
+
* A change to one row made by their own click does not: the click was the
|
|
93
|
+
* yes, and asking again turns every "Mark as done" into two clicks. What the
|
|
94
|
+
* view tells them afterwards says what changed. A new row, a delete, and any
|
|
95
|
+
* write code made without a click still ask.
|
|
96
|
+
*/
|
|
97
|
+
export declare function needsConfirmation(intent: WriteIntent | undefined): boolean;
|
|
67
98
|
/** One change the person made here, as the model is told about it. */
|
|
68
99
|
export interface ViewChange {
|
|
69
100
|
action: "created" | "updated" | "deleted";
|
|
@@ -113,6 +144,8 @@ export interface ToolDriverOptions {
|
|
|
113
144
|
actions: ViewActions;
|
|
114
145
|
/** Show the person a write's plan; true when they confirm it. */
|
|
115
146
|
confirm: (plan: WritePlan) => Promise<boolean>;
|
|
147
|
+
/** A write went through: the view says what changed when it did not ask first. */
|
|
148
|
+
onWritten?: (intent: WriteIntent) => void;
|
|
116
149
|
/**
|
|
117
150
|
* A page already read: served once in place of the read tool's call, to
|
|
118
151
|
* a read asking for exactly it, and dropped by any write or once it is
|