@rebasepro/cms 0.29.1 → 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/collection_editor/serializable_types.d.ts +2 -0
- package/dist/collection_editor/ui/collection_editor/CollectionRelationsTab.d.ts +1 -1
- package/dist/components/CollectionPanel.js +22 -13
- package/dist/components/CollectionPanel.js.map +1 -1
- package/dist/components/CollectionTableBinding/fields/TableStorageUpload.js +1 -1
- package/dist/components/CollectionTableBinding/fields/TableStorageUpload.js.map +1 -1
- package/dist/components/CollectionTableBinding/internal/popup_field/PopupFormField.d.ts +1 -1
- package/dist/components/CollectionTableBinding/internal/popup_field/PopupFormField.js.map +1 -1
- package/dist/components/CollectionViewBinding/CollectionCardViewBinding.js.map +1 -1
- package/dist/components/CollectionViewBinding/CollectionListViewBinding.js +39 -14
- package/dist/components/CollectionViewBinding/CollectionListViewBinding.js.map +1 -1
- package/dist/components/CollectionViewBinding/CollectionViewContent.d.ts +11 -0
- package/dist/components/CollectionViewBinding/CollectionViewContent.js +19 -2
- package/dist/components/CollectionViewBinding/CollectionViewContent.js.map +1 -1
- package/dist/components/CollectionViewBinding/EntityCardBinding.d.ts +1 -1
- package/dist/components/CollectionViewBinding/EntityCardBinding.js +1 -1
- package/dist/components/CollectionViewBinding/EntityCardBinding.js.map +1 -1
- package/dist/components/CollectionViewBinding/SlotValue.js.map +1 -1
- package/dist/components/CollectionViewBinding/usePreviewSlots.d.ts +19 -1
- package/dist/components/CollectionViewBinding/usePreviewSlots.js +18 -7
- package/dist/components/CollectionViewBinding/usePreviewSlots.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/components/HomePage/ContentHomePage.js +2 -3
- package/dist/components/HomePage/ContentHomePage.js.map +1 -1
- package/dist/components/RecordForm.d.ts +25 -4
- package/dist/components/RecordForm.js +21 -3
- package/dist/components/RecordForm.js.map +1 -1
- package/dist/components/RelationSelector.js.map +1 -1
- package/dist/components/SelectableTable/filters/FilterFieldBinding.d.ts +13 -1
- package/dist/components/SelectableTable/filters/FilterFieldBinding.js +19 -3
- package/dist/components/SelectableTable/filters/FilterFieldBinding.js.map +1 -1
- package/dist/components/SelectableTable/filters/RelationFilterField.d.ts +1 -1
- package/dist/components/SelectableTable/filters/RelationFilterField.js.map +1 -1
- package/dist/components/history/EntityHistoryEntry.js.map +1 -1
- package/dist/data_import/utils/save_entities.d.ts +10 -2
- package/dist/data_import/utils/save_entities.js.map +1 -1
- package/dist/editor/markdown.d.ts +10 -0
- package/dist/editor/markdown.js.map +1 -1
- package/dist/form/PropertyFieldBinding.js +4 -2
- package/dist/form/PropertyFieldBinding.js.map +1 -1
- package/dist/form/field_bindings/BinaryFieldBinding.js.map +1 -1
- package/dist/form/field_bindings/GeopointFieldBinding.js.map +1 -1
- package/dist/hooks/useBuildSidePanel.d.ts +10 -0
- package/dist/hooks/useBuildSidePanel.js +43 -4
- package/dist/hooks/useBuildSidePanel.js.map +1 -1
- package/dist/hooks/useResolvedNavigationFrom.d.ts +14 -2
- package/dist/hooks/useResolvedNavigationFrom.js.map +1 -1
- package/dist/index.d.ts +3 -1
- package/dist/index.js +4 -2
- package/dist/mcp_view/app_modules.js +4 -2
- package/dist/mcp_view/app_modules.js.map +1 -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 +7 -2
- package/dist/mcp_view/index.js.map +1 -1
- package/dist/mcp_view/payload.js +7 -2
- package/dist/mcp_view/payload.js.map +1 -1
- package/dist/mcp_view/screen.d.ts +6 -4
- package/dist/mcp_view/screen.js +15 -43
- package/dist/mcp_view/screen.js.map +1 -1
- package/dist/mcp_view/tool_driver.d.ts +58 -6
- package/dist/mcp_view/tool_driver.js +256 -117
- 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/compact_text.d.ts +1 -1
- package/dist/preview/compact_text.js.map +1 -1
- 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/dist/selection/resolve_selection.d.ts +10 -2
- package/dist/selection/resolve_selection.js.map +1 -1
- package/dist/util/property_utils.d.ts +2 -2
- package/dist/util/property_utils.js.map +1 -1
- 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 } 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,
|
|
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
|
})
|
|
@@ -204,7 +209,7 @@ function modelContext(bridge) {
|
|
|
204
209
|
send();
|
|
205
210
|
},
|
|
206
211
|
writeFailed: (failure) => {
|
|
207
|
-
state.refused =
|
|
212
|
+
state.refused = describeRefusal(failure);
|
|
208
213
|
send();
|
|
209
214
|
},
|
|
210
215
|
appError: (error) => {
|
|
@@ -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, describeFailedWrite, 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 } 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 = `The app tried to ${describeFailedWrite(failure)}, and the server refused: ${failure.message}`;\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,IA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X"}
|
|
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,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,QAAoB,QAAiC;CACpE,MAAM,UAAU,gBAAyC,KAAA,CAAS;CAClE,MAAM,UA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AC,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"}
|
package/dist/mcp_view/payload.js
CHANGED
|
@@ -36,8 +36,13 @@ function parseResult(result) {
|
|
|
36
36
|
message: "The screen has no blocks."
|
|
37
37
|
};
|
|
38
38
|
const viewer = isRecord(view.viewer) ? view.viewer : {};
|
|
39
|
+
const readAt = typeof view.readAt === "number" && Number.isFinite(view.readAt) ? view.readAt : void 0;
|
|
40
|
+
const stamped = (page) => readAt === void 0 ? page : {
|
|
41
|
+
...page,
|
|
42
|
+
readAt
|
|
43
|
+
};
|
|
39
44
|
const firstPage = firstPageOf(blocks[0], content);
|
|
40
|
-
const seeds = Array.isArray(view.seeds) ? view.seeds.flatMap(seedOf) : [];
|
|
45
|
+
const seeds = Array.isArray(view.seeds) ? view.seeds.flatMap(seedOf).map(stamped) : [];
|
|
41
46
|
return {
|
|
42
47
|
kind: "screen",
|
|
43
48
|
screen: {
|
|
@@ -49,7 +54,7 @@ function parseResult(result) {
|
|
|
49
54
|
roles: Array.isArray(viewer.roles) ? viewer.roles.filter((role) => typeof role === "string") : []
|
|
50
55
|
},
|
|
51
56
|
actions: actionsOf(content.actions),
|
|
52
|
-
...firstPage && { firstPage },
|
|
57
|
+
...firstPage && { firstPage: stamped(firstPage) },
|
|
53
58
|
...seeds.length > 0 && { seeds }
|
|
54
59
|
}
|
|
55
60
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"payload.js","names":[],"sources":["../../src/mcp_view/payload.ts"],"sourcesContent":["/**\n * The screen a show_* tool asked for, read from its result\n * (`McpViewPayload` in the server's `mcp/mcp-view.ts`).\n *\n * A result with no payload is one from a server that only knew the table\n * (show_collection before 0.29): the view draws that table.\n */\nimport {\n ALL_WHERE_FILTER_OPS,\n deserializeCollections,\n getCollectionDataPath,\n type CollectionConfig,\n type FilterValues,\n type WhereFilterOp\n} from \"@rebasepro/types\";\nimport type { AdminCollection } from \"@rebasepro/cms-types\";\nimport { isRecord, type ToolResult } from \"./bridge\";\nimport { DEFAULT_ACTIONS, textOf, type SeedPage, type ToolAction, type ViewActions } from \"./tool_driver\";\n\nexport type ViewMode = \"table\" | \"list\" | \"cards\" | \"kanban\";\n\nexport interface CollectionBlock {\n key: string;\n type: \"collection\";\n collection: string;\n view?: ViewMode;\n where?: Record<string, unknown>;\n orderBy?: unknown;\n searchString?: string;\n limit?: number;\n}\n\nexport interface RecordBlock {\n key: string;\n type: \"record\";\n collection: string;\n id?: string;\n values?: Record<string, unknown>;\n}\n\n/** An app the model wrote: compiled CommonJS, and the collections it reads. */\nexport interface AppBlock {\n key: string;\n type: \"app\";\n code: string;\n collections: string[];\n}\n\nexport type Block = CollectionBlock | RecordBlock | AppBlock;\n\nexport interface Screen {\n title?: string;\n blocks: Block[];\n collections: AdminCollection[];\n viewer: { uid: string; roles: string[] };\n actions: ViewActions;\n /** The page show_collection read for the model: what the collection block reads first. */\n firstPage?: SeedPage;\n /** The pages show_app read ahead of the app's first render, one per collection it names. */\n seeds?: SeedPage[];\n}\n\nexport type Parsed =\n | { kind: \"screen\"; screen: Screen }\n /** A result from before the admin panel's views: the table's own columns. */\n | { kind: \"table\" }\n | { kind: \"error\"; message: string };\n\nconst PAYLOAD_VERSION = 1;\n\nexport function parseResult(result: ToolResult): Parsed {\n if (result.isError) return { kind: \"error\", message: textOf(result) ?? \"The view could not be opened.\" };\n const content = result.structuredContent;\n if (!isRecord(content)) {\n return { kind: \"error\", message: \"This view needs the tool's structured result, and the host did not pass it.\" };\n }\n const view = content.view;\n if (!isRecord(view)) {\n return Array.isArray(content.columns)\n ? { kind: \"table\" }\n : { kind: \"error\", message: \"The result carries nothing this view can draw.\" };\n }\n if (view.version !== PAYLOAD_VERSION) {\n return { kind: \"error\", message: \"This view is older than the server that answered; it cannot draw this screen.\" };\n }\n const collections = Array.isArray(view.collections)\n ? deserializeCollections(view.collections) as AdminCollection[]\n : [];\n const blocks = Array.isArray(view.blocks) ? view.blocks.filter(isBlock) : [];\n if (blocks.length === 0) return { kind: \"error\", message: \"The screen has no blocks.\" };\n const viewer = isRecord(view.viewer) ? view.viewer : {};\n const firstPage = firstPageOf(blocks[0], content);\n const seeds = Array.isArray(view.seeds) ? view.seeds.flatMap(seedOf) : [];\n return {\n kind: \"screen\",\n screen: {\n ...(typeof view.title === \"string\" && { title: view.title }),\n blocks,\n collections,\n viewer: {\n uid: typeof viewer.uid === \"string\" ? viewer.uid : \"\",\n roles: Array.isArray(viewer.roles) ? viewer.roles.filter((role): role is string => typeof role === \"string\") : []\n },\n actions: actionsOf(content.actions),\n ...(firstPage && { firstPage }),\n ...(seeds.length > 0 && { seeds })\n }\n };\n}\n\n/**\n * The rows a show_collection result carries beside its screen — the page the\n * server read for the model — and the arguments that read them: the block's,\n * with the window the server says it read.\n */\nfunction firstPageOf(block: Block, content: Record<string, unknown>): SeedPage | undefined {\n if (block.type !== \"collection\" || !Array.isArray(content.data)) return undefined;\n const meta = isRecord(content.meta) ? content.meta : {};\n const limit = typeof meta.limit === \"number\" ? meta.limit : block.limit;\n return {\n collection: block.collection,\n args: {\n ...(block.where && { where: block.where }),\n ...(block.orderBy !== undefined && { orderBy: block.orderBy }),\n ...(block.searchString && { searchString: block.searchString }),\n ...(limit !== undefined && { limit }),\n ...(typeof meta.offset === \"number\" && { offset: meta.offset })\n },\n rows: content.data.filter(isRecord)\n };\n}\n\n/** One page show_app read ahead, as the server sent it; nothing for one malformed. */\nfunction seedOf(value: unknown): SeedPage[] {\n if (!isRecord(value) || typeof value.collection !== \"string\" || !isRecord(value.args) || !Array.isArray(value.rows)) return [];\n return [{\n collection: value.collection,\n args: value.args,\n rows: value.rows.filter(isRecord),\n ...(typeof value.total === \"number\" && { total: value.total })\n }];\n}\n\nfunction isBlock(value: unknown): value is Block {\n if (!isRecord(value) || typeof value.key !== \"string\") return false;\n if (value.type === \"app\") return typeof value.code === \"string\" && Array.isArray(value.collections);\n return typeof value.collection === \"string\" && (value.type === \"collection\" || value.type === \"record\");\n}\n\n/**\n * The tools a result says to read and write with, over the defaults. The\n * hosted connector's table named `edit` for what is `update` here.\n */\nexport function actionsOf(raw: unknown): ViewActions {\n if (!isRecord(raw)) return DEFAULT_ACTIONS;\n const action = (value: unknown, fallback: ToolAction): ToolAction => isRecord(value) && typeof value.tool === \"string\"\n ? { tool: value.tool, arguments: isRecord(value.arguments) ? value.arguments : {}, ...(value.plans === true && { plans: true }) }\n : fallback;\n return {\n page: action(raw.page, DEFAULT_ACTIONS.page),\n get: action(raw.get, DEFAULT_ACTIONS.get),\n count: action(raw.count, DEFAULT_ACTIONS.count),\n create: action(raw.create, DEFAULT_ACTIONS.create),\n update: action(raw.update ?? raw.edit, DEFAULT_ACTIONS.update),\n delete: action(raw.delete, DEFAULT_ACTIONS.delete),\n aggregate: action(raw.aggregate, DEFAULT_ACTIONS.aggregate)\n };\n}\n\n/** The collection a block names: by the name the tools take, which is its data path, or by slug. */\nexport function findCollection(collections: readonly AdminCollection[], name: string): AdminCollection | undefined {\n return collections.find(collection => getCollectionDataPath(collection as CollectionConfig) === name)\n ?? collections.find(collection => collection.slug === name);\n}\n\n/**\n * A block's `where` as the admin panel's filter: each field's condition, or\n * list of conditions, kept where it is one the read tools take. The server\n * checked it before it opened the screen.\n */\nexport function filterOf(where: Record<string, unknown> | undefined): FilterValues<string> | undefined {\n if (!where) return undefined;\n const filter: FilterValues<string> = {};\n for (const [key, raw] of Object.entries(where)) {\n const single = conditionOf(raw);\n if (single) {\n filter[key] = single;\n } else if (Array.isArray(raw)) {\n const conditions = raw.map(conditionOf).filter((entry): entry is [WhereFilterOp, unknown] => entry !== undefined);\n if (conditions.length > 0 && conditions.length === raw.length) filter[key] = conditions;\n }\n }\n return filter;\n}\n\nfunction conditionOf(raw: unknown): [WhereFilterOp, unknown] | undefined {\n if (!Array.isArray(raw) || raw.length !== 2) return undefined;\n const op = ALL_WHERE_FILTER_OPS.find(candidate => candidate === raw[0]);\n return op ? [op, raw[1]] : undefined;\n}\n\n/** A sort as the collection view takes it: its first key. */\nexport function orderOf(raw: unknown): [string, \"asc\" | \"desc\"] | undefined {\n if (typeof raw === \"string\" && raw !== \"\") {\n const [field, direction] = raw.split(\":\");\n return [field, direction === \"desc\" ? \"desc\" : \"asc\"];\n }\n if (Array.isArray(raw) && raw.length > 0) {\n const first: unknown[] = Array.isArray(raw[0]) ? raw[0] : raw;\n if (typeof first[0] === \"string\") return [first[0], first[1] === \"desc\" ? \"desc\" : \"asc\"];\n }\n return undefined;\n}\n"],"mappings":";;;;;;;;;;;AAoEA,IAAM,kBAAkB;AAExB,SAAgB,YAAY,QAA4B;CACpD,IAAI,OAAO,SAAS,OAAO;EAAE,MAAM;EAAS,SAAS,OAAO,MAAM,KAAK;CAAgC;CACvG,MAAM,UAAU,OAAO;CACvB,IAAI,CAAC,SAAS,OAAO,GACjB,OAAO;EAAE,MAAM;EAAS,SAAS;CAA8E;CAEnH,MAAM,OAAO,QAAQ;CACrB,IAAI,CAAC,SAAS,IAAI,GACd,OAAO,MAAM,QAAQ,QAAQ,OAAO,IAC9B,EAAE,MAAM,QAAQ,IAChB;EAAE,MAAM;EAAS,SAAS;CAAiD;CAErF,IAAI,KAAK,YAAY,iBACjB,OAAO;EAAE,MAAM;EAAS,SAAS;CAAgF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AAmB,MAAM,QAAQ,IAAI,EAAE,IAAI,IAAI,KAAK;EAC1D,IAAI,OAAO,MAAM,OAAO,UAAU,OAAO,CAAC,MAAM,IAAI,MAAM,OAAO,SAAS,SAAS,KAAK;CAC5F;AAEJ"}
|
|
1
|
+
{"version":3,"file":"payload.js","names":[],"sources":["../../src/mcp_view/payload.ts"],"sourcesContent":["/**\n * The screen a show_* tool asked for, read from its result\n * (`McpViewPayload` in the server's `mcp/mcp-view.ts`).\n *\n * A result with no payload is one from a server that only knew the table\n * (show_collection before 0.29): the view draws that table.\n */\nimport {\n ALL_WHERE_FILTER_OPS,\n deserializeCollections,\n getCollectionDataPath,\n type CollectionConfig,\n type FilterValues,\n type WhereFilterOp\n} from \"@rebasepro/types\";\nimport type { AdminCollection } from \"@rebasepro/cms-types\";\nimport { isRecord, type ToolResult } from \"./bridge\";\nimport { DEFAULT_ACTIONS, textOf, type SeedPage, type ToolAction, type ViewActions } from \"./tool_driver\";\n\nexport type ViewMode = \"table\" | \"list\" | \"cards\" | \"kanban\";\n\nexport interface CollectionBlock {\n key: string;\n type: \"collection\";\n collection: string;\n view?: ViewMode;\n where?: Record<string, unknown>;\n orderBy?: unknown;\n searchString?: string;\n limit?: number;\n}\n\nexport interface RecordBlock {\n key: string;\n type: \"record\";\n collection: string;\n id?: string;\n values?: Record<string, unknown>;\n}\n\n/** An app the model wrote: compiled CommonJS, and the collections it reads. */\nexport interface AppBlock {\n key: string;\n type: \"app\";\n code: string;\n collections: string[];\n}\n\nexport type Block = CollectionBlock | RecordBlock | AppBlock;\n\nexport interface Screen {\n title?: string;\n blocks: Block[];\n collections: AdminCollection[];\n viewer: { uid: string; roles: string[] };\n actions: ViewActions;\n /** The page show_collection read for the model: what the collection block reads first. */\n firstPage?: SeedPage;\n /** The pages show_app read ahead of the app's first render, one per collection it names. */\n seeds?: SeedPage[];\n}\n\nexport type Parsed =\n | { kind: \"screen\"; screen: Screen }\n /** A result from before the admin panel's views: the table's own columns. */\n | { kind: \"table\" }\n | { kind: \"error\"; message: string };\n\nconst PAYLOAD_VERSION = 1;\n\nexport function parseResult(result: ToolResult): Parsed {\n if (result.isError) return { kind: \"error\", message: textOf(result) ?? \"The view could not be opened.\" };\n const content = result.structuredContent;\n if (!isRecord(content)) {\n return { kind: \"error\", message: \"This view needs the tool's structured result, and the host did not pass it.\" };\n }\n const view = content.view;\n if (!isRecord(view)) {\n return Array.isArray(content.columns)\n ? { kind: \"table\" }\n : { kind: \"error\", message: \"The result carries nothing this view can draw.\" };\n }\n if (view.version !== PAYLOAD_VERSION) {\n return { kind: \"error\", message: \"This view is older than the server that answered; it cannot draw this screen.\" };\n }\n const collections = Array.isArray(view.collections)\n ? deserializeCollections(view.collections) as AdminCollection[]\n : [];\n const blocks = Array.isArray(view.blocks) ? view.blocks.filter(isBlock) : [];\n if (blocks.length === 0) return { kind: \"error\", message: \"The screen has no blocks.\" };\n const viewer = isRecord(view.viewer) ? view.viewer : {};\n // When the server read the rows the result carries: they are that old\n // however late the host draws it. A server from before the stamp sends none.\n const readAt = typeof view.readAt === \"number\" && Number.isFinite(view.readAt) ? view.readAt : undefined;\n const stamped = (page: SeedPage): SeedPage => readAt === undefined ? page : { ...page, readAt };\n const firstPage = firstPageOf(blocks[0], content);\n const seeds = Array.isArray(view.seeds) ? view.seeds.flatMap(seedOf).map(stamped) : [];\n return {\n kind: \"screen\",\n screen: {\n ...(typeof view.title === \"string\" && { title: view.title }),\n blocks,\n collections,\n viewer: {\n uid: typeof viewer.uid === \"string\" ? viewer.uid : \"\",\n roles: Array.isArray(viewer.roles) ? viewer.roles.filter((role): role is string => typeof role === \"string\") : []\n },\n actions: actionsOf(content.actions),\n ...(firstPage && { firstPage: stamped(firstPage) }),\n ...(seeds.length > 0 && { seeds })\n }\n };\n}\n\n/**\n * The rows a show_collection result carries beside its screen — the page the\n * server read for the model — and the arguments that read them: the block's,\n * with the window the server says it read.\n */\nfunction firstPageOf(block: Block, content: Record<string, unknown>): SeedPage | undefined {\n if (block.type !== \"collection\" || !Array.isArray(content.data)) return undefined;\n const meta = isRecord(content.meta) ? content.meta : {};\n const limit = typeof meta.limit === \"number\" ? meta.limit : block.limit;\n return {\n collection: block.collection,\n args: {\n ...(block.where && { where: block.where }),\n ...(block.orderBy !== undefined && { orderBy: block.orderBy }),\n ...(block.searchString && { searchString: block.searchString }),\n ...(limit !== undefined && { limit }),\n ...(typeof meta.offset === \"number\" && { offset: meta.offset })\n },\n rows: content.data.filter(isRecord)\n };\n}\n\n/** One page show_app read ahead, as the server sent it; nothing for one malformed. */\nfunction seedOf(value: unknown): SeedPage[] {\n if (!isRecord(value) || typeof value.collection !== \"string\" || !isRecord(value.args) || !Array.isArray(value.rows)) return [];\n return [{\n collection: value.collection,\n args: value.args,\n rows: value.rows.filter(isRecord),\n ...(typeof value.total === \"number\" && { total: value.total })\n }];\n}\n\nfunction isBlock(value: unknown): value is Block {\n if (!isRecord(value) || typeof value.key !== \"string\") return false;\n if (value.type === \"app\") return typeof value.code === \"string\" && Array.isArray(value.collections);\n return typeof value.collection === \"string\" && (value.type === \"collection\" || value.type === \"record\");\n}\n\n/**\n * The tools a result says to read and write with, over the defaults. The\n * hosted connector's table named `edit` for what is `update` here.\n */\nexport function actionsOf(raw: unknown): ViewActions {\n if (!isRecord(raw)) return DEFAULT_ACTIONS;\n const action = (value: unknown, fallback: ToolAction): ToolAction => isRecord(value) && typeof value.tool === \"string\"\n ? { tool: value.tool, arguments: isRecord(value.arguments) ? value.arguments : {}, ...(value.plans === true && { plans: true }) }\n : fallback;\n return {\n page: action(raw.page, DEFAULT_ACTIONS.page),\n get: action(raw.get, DEFAULT_ACTIONS.get),\n count: action(raw.count, DEFAULT_ACTIONS.count),\n create: action(raw.create, DEFAULT_ACTIONS.create),\n update: action(raw.update ?? raw.edit, DEFAULT_ACTIONS.update),\n delete: action(raw.delete, DEFAULT_ACTIONS.delete),\n aggregate: action(raw.aggregate, DEFAULT_ACTIONS.aggregate)\n };\n}\n\n/** The collection a block names: by the name the tools take, which is its data path, or by slug. */\nexport function findCollection(collections: readonly AdminCollection[], name: string): AdminCollection | undefined {\n return collections.find(collection => getCollectionDataPath(collection as CollectionConfig) === name)\n ?? collections.find(collection => collection.slug === name);\n}\n\n/**\n * A block's `where` as the admin panel's filter: each field's condition, or\n * list of conditions, kept where it is one the read tools take. The server\n * checked it before it opened the screen.\n */\nexport function filterOf(where: Record<string, unknown> | undefined): FilterValues<string> | undefined {\n if (!where) return undefined;\n const filter: FilterValues<string> = {};\n for (const [key, raw] of Object.entries(where)) {\n const single = conditionOf(raw);\n if (single) {\n filter[key] = single;\n } else if (Array.isArray(raw)) {\n const conditions = raw.map(conditionOf).filter((entry): entry is [WhereFilterOp, unknown] => entry !== undefined);\n if (conditions.length > 0 && conditions.length === raw.length) filter[key] = conditions;\n }\n }\n return filter;\n}\n\nfunction conditionOf(raw: unknown): [WhereFilterOp, unknown] | undefined {\n if (!Array.isArray(raw) || raw.length !== 2) return undefined;\n const op = ALL_WHERE_FILTER_OPS.find(candidate => candidate === raw[0]);\n return op ? [op, raw[1]] : undefined;\n}\n\n/** A sort as the collection view takes it: its first key. */\nexport function orderOf(raw: unknown): [string, \"asc\" | \"desc\"] | undefined {\n if (typeof raw === \"string\" && raw !== \"\") {\n const [field, direction] = raw.split(\":\");\n return [field, direction === \"desc\" ? \"desc\" : \"asc\"];\n }\n if (Array.isArray(raw) && raw.length > 0) {\n const first: unknown[] = Array.isArray(raw[0]) ? raw[0] : raw;\n if (typeof first[0] === \"string\") return [first[0], first[1] === \"desc\" ? \"desc\" : \"asc\"];\n }\n return undefined;\n}\n"],"mappings":";;;;;;;;;;;AAoEA,IAAM,kBAAkB;AAExB,SAAgB,YAAY,QAA4B;CACpD,IAAI,OAAO,SAAS,OAAO;EAAE,MAAM;EAAS,SAAS,OAAO,MAAM,KAAK;CAAgC;CACvG,MAAM,UAAU,OAAO;CACvB,IAAI,CAAC,SAAS,OAAO,GACjB,OAAO;EAAE,MAAM;EAAS,SAAS;CAA8E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;CACrE,IAAI,CAAC,MAAM,QAAQ,GAAG,KAAK,IAAI,WAAW,GAAG,OAAO,KAAA;CACpD,MAAM,KAAK,qBAAqB,MAAK,cAAa,cAAc,IAAI,EAAE;CACtE,OAAO,KAAK,CAAC,IAAI,IAAI,EAAE,IAAI,KAAA;AAC/B;;AAGA,SAAgB,QAAQ,KAAoD;CACxE,IAAI,OAAO,QAAQ,YAAY,QAAQ,IAAI;EACvC,MAAM,CAAC,OAAO,aAAa,IAAI,MAAM,GAAG;EACxC,OAAO,CAAC,OAAO,cAAc,SAAS,SAAS,KAAK;CACxD;CACA,IAAI,MAAM,QAAQ,GAAG,KAAK,IAAI,SAAS,GAAG;EACtC,MAAM,QAAmB,MAAM,QAAQ,IAAI,EAAE,IAAI,IAAI,KAAK;EAC1D,IAAI,OAAO,MAAM,OAAO,UAAU,OAAO,CAAC,MAAM,IAAI,MAAM,OAAO,SAAS,SAAS,KAAK;CAC5F;AAEJ"}
|
|
@@ -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";
|
|
@@ -77,7 +80,7 @@ function McpScreen({ bridge, screen, hostContext, pendingPlan, writeFailure, onA
|
|
|
77
80
|
}
|
|
78
81
|
return /* @__PURE__ */ jsxs("div", {
|
|
79
82
|
ref: rootRef,
|
|
80
|
-
className: cls("flex flex-col gap-4 p-4 w-full min-w-0 bg-surface-sheet overflow-y-auto", fullscreen && "h-screen"),
|
|
83
|
+
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"),
|
|
81
84
|
style: fullscreen ? void 0 : { maxHeight: INLINE_MAX_HEIGHT },
|
|
82
85
|
children: [
|
|
83
86
|
(heading || canExpand) && /* @__PURE__ */ jsxs("div", {
|
|
@@ -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 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,OAAuB,IAAI;CAC3C,MAAM,UAAU,aAAa,WAAW;CACxC,MAAM,UAAU,aAAa,WAAW;CACxC,MAAM,CAAC,SAAS,kBAAkB,gBAAgB,YAAY;CAC9D,MAAM,WAAW,gCAAgC;CACjD,MAAM,aAAa,QAAQ,gBAAgB;CAC3C,MAAM,YAAY,CAAC,cAAc,QAAQ,uBAAuB,SAAS,YAAY,MAAM;CAC3F,MAAM,QAAQ,OAAO,OAAO;CAI5B,gBAAgB;EACZ,MAAM,OAAO,QAAQ;EACrB,IAAI,CAAC,MAAM;EACX,MAAM,gBAAgB;GAClB,MAAM,OAAO,SAAS;GACtB,MAAM,WAAW,KAAK,MAAM;GAC5B,KAAK,MAAM,SAAS;GACpB,OAAO,YAAY,KAAK,KAAK,KAAK,sBAAsB,CAAC,CAAC,MAAM,CAAC;GACjE,KAAK,MAAM,SAAS;EACxB;EACA,MAAM,WAAW,IAAI,eAAe,OAAO;EAC3C,SAAS,QAAQ,IAAI;EACrB,QAAQ;EACR,aAAa,SAAS,WAAW;CACrC,GAAG,CAAC,MAAM,CAAC;CAEX,MAAM,gBAAgB,SAA8C,SAAS,cAAc,IAAI;CAC/F,MAAM,UAAU,OAAO,UAAU,MAAM,SAAS,QAAQ,KAAA,IAAY,WAAW,OAAO,aAAa,MAAM,UAAU,CAAC;CAEpH,IAAI;CACJ,IAAI,CAAC,SAAS,eAAe,CAAC,SAAS,aAAa,QAChD,OAAO,oBAAC,kBAAD,EAAkB,MAAK,WAAW,CAAA;MACtC,IAAI,MAAM,SAAS,OACtB,OAAO,oBAAC,SAAD;EAA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ourcesContent":["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":";;;;;;;;;;;;;;;;;;;;A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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"}
|
|
@@ -63,13 +63,48 @@ 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";
|
|
70
101
|
collection: string;
|
|
71
102
|
id: string;
|
|
72
|
-
/**
|
|
103
|
+
/**
|
|
104
|
+
* The row as the person knows it — its title — where the driver can tell;
|
|
105
|
+
* see {@link ToolDriverOptions.rowLabel}. The model is told it only as
|
|
106
|
+
* quoted, capped data ({@link describeChanges}).
|
|
107
|
+
*/
|
|
73
108
|
label?: string;
|
|
74
109
|
fields?: string[];
|
|
75
110
|
}
|
|
@@ -77,8 +112,10 @@ export interface ViewChange {
|
|
|
77
112
|
export interface WriteFailure {
|
|
78
113
|
action: "create" | "update" | "delete";
|
|
79
114
|
collection: string;
|
|
80
|
-
/** The row
|
|
81
|
-
|
|
115
|
+
/** The row's id; absent for a create. */
|
|
116
|
+
id?: string;
|
|
117
|
+
/** The row's title, as {@link ToolDriverOptions.rowLabel} names it, where the view has read it. */
|
|
118
|
+
title?: string;
|
|
82
119
|
message: string;
|
|
83
120
|
}
|
|
84
121
|
/** The calls the driver makes: the bridge's `callTool`, as a function so a test can stand in for the host. */
|
|
@@ -95,16 +132,25 @@ export interface SeedPage {
|
|
|
95
132
|
rows: Record<string, unknown>[];
|
|
96
133
|
/** How many rows the read's filter matches, where the server counted them: answers that count, once. */
|
|
97
134
|
total?: number;
|
|
135
|
+
/**
|
|
136
|
+
* When the server read it, in epoch milliseconds: it is as old as that,
|
|
137
|
+
* however late the host draws the result. Absent (a server from before
|
|
138
|
+
* the stamp), as old as the driver.
|
|
139
|
+
*/
|
|
140
|
+
readAt?: number;
|
|
98
141
|
}
|
|
99
142
|
export interface ToolDriverOptions {
|
|
100
143
|
callTool: CallTool;
|
|
101
144
|
actions: ViewActions;
|
|
102
145
|
/** Show the person a write's plan; true when they confirm it. */
|
|
103
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;
|
|
104
149
|
/**
|
|
105
150
|
* A page already read: served once in place of the read tool's call, to
|
|
106
151
|
* a read asking for exactly it, and dropped by any write or once it is
|
|
107
|
-
* older than the driver's read cache keeps a row
|
|
152
|
+
* older than the driver's read cache keeps a row — counted from its
|
|
153
|
+
* `readAt`.
|
|
108
154
|
*/
|
|
109
155
|
seed?: SeedPage;
|
|
110
156
|
/**
|
|
@@ -154,7 +200,13 @@ export declare class SaveCancelledError extends Error {
|
|
|
154
200
|
}
|
|
155
201
|
export declare function createToolDriver(options: ToolDriverOptions): ToolDriver;
|
|
156
202
|
export declare function textOf(result: ToolResult): string | undefined;
|
|
157
|
-
/**
|
|
158
|
-
|
|
203
|
+
/**
|
|
204
|
+
* A refused write as the person is shown it: "update ORD-2026-0081 in
|
|
205
|
+
* orders", "create a row in orders". Not for the model: a title is text a
|
|
206
|
+
* user wrote ({@link describeRefusal}).
|
|
207
|
+
*/
|
|
159
208
|
export declare function describeFailedWrite(failure: WriteFailure): string;
|
|
209
|
+
/** What the model is told of a write the server refused, sent with the person's next message. */
|
|
210
|
+
export declare function describeRefusal(failure: WriteFailure): string;
|
|
211
|
+
/** What the model is told the person changed here, sent with their next message. */
|
|
160
212
|
export declare function describeChanges(changes: readonly ViewChange[]): string;
|