@backmatter/studio 0.0.19 → 0.0.21

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.
Files changed (57) hide show
  1. package/dist/chunks/{UiKitApp-B1ANqCac.js → UiKitApp-CMMcsaX4.js} +2 -2
  2. package/dist/chunks/{WorkspaceRoutes-BHNGrf-j.js → WorkspaceRoutes-DW0sLdpJ.js} +27141 -26236
  3. package/dist/chunks/dashboard-By0P4Yny.js +1879 -0
  4. package/dist/chunks/{index-HYioDjux.js → index-DTPUqaHE.js} +1 -1
  5. package/dist/dashboard.js +2 -2
  6. package/dist/index.js +205 -194
  7. package/dist/site-widget.css +208 -0
  8. package/dist/site-widget.js +10495 -9947
  9. package/dist/studio.css +280 -24
  10. package/package.json +2 -2
  11. package/src/App.tsx +7 -1
  12. package/src/api.ts +113 -13
  13. package/src/chat/ChatFiles.tsx +261 -0
  14. package/src/chat/ChatMessage.tsx +5 -0
  15. package/src/chat/ChatPanel.tsx +218 -14
  16. package/src/chat/ChatProvider.tsx +72 -22
  17. package/src/chat/Composer.tsx +83 -6
  18. package/src/chat/PendingFileRow.tsx +188 -0
  19. package/src/chat/chat-context.ts +7 -1
  20. package/src/chat/chat-helpers.ts +49 -0
  21. package/src/chat/chat-state.ts +17 -6
  22. package/src/chat/icons.tsx +28 -0
  23. package/src/chat/model-copy.ts +41 -0
  24. package/src/chat/pending-files.ts +236 -0
  25. package/src/chat/side-width.ts +48 -0
  26. package/src/chrome/AppShell.tsx +9 -1
  27. package/src/chrome/CommandPalette.tsx +7 -0
  28. package/src/chrome/ContentExplorerSidebar.tsx +43 -74
  29. package/src/chrome/folder-create-context.ts +56 -11
  30. package/src/chrome/hotkeys.ts +8 -0
  31. package/src/fields/FieldControl.tsx +331 -115
  32. package/src/fields/LinkFieldInput.tsx +13 -6
  33. package/src/fields/array-item-title.ts +28 -0
  34. package/src/fields/field-label.ts +8 -0
  35. package/src/host-pointer.ts +2 -0
  36. package/src/install-preview-pointer.ts +1 -0
  37. package/src/pages/BlockPicker.tsx +362 -0
  38. package/src/pages/BlocksList.tsx +57 -50
  39. package/src/pages/CliAuthorizePage.tsx +138 -25
  40. package/src/pages/DocEditorPage.tsx +95 -18
  41. package/src/pages/EmbedPublishPage.tsx +40 -2
  42. package/src/pages/LoginPage.tsx +118 -31
  43. package/src/pages/SettingsSchemaPage.tsx +19 -3
  44. package/src/pages/WorkspaceLayout.tsx +16 -1
  45. package/src/pages/block-picker.ts +116 -0
  46. package/src/pages/editor-grab.ts +61 -13
  47. package/src/pages/preview-split.ts +24 -0
  48. package/src/pages/session-preview.ts +1 -0
  49. package/src/replica/types.ts +2 -0
  50. package/src/sign-in-link.ts +45 -0
  51. package/src/site-pointer.ts +14 -1
  52. package/src/site-widget.tsx +12 -1
  53. package/src/ui/Field.tsx +26 -0
  54. package/src/workspace/schema-source.tsx +126 -0
  55. package/dist/chunks/dashboard-b-W6dGm5.js +0 -1779
  56. package/src/site-devbar-overlay-inject.ts +0 -15
  57. package/src/site-publish-menu.tsx +0 -33
package/src/api.ts CHANGED
@@ -369,11 +369,20 @@ export type SchemaField = {
369
369
  max?: number;
370
370
  step?: number;
371
371
  where?: Record<string, string | number | boolean>;
372
+ /** Guidance from the site developer: what goes here. */
373
+ description?: string;
372
374
  };
373
375
 
374
376
  export type BlockSnapshot = {
375
377
  name: string;
376
378
  fields: Record<string, SchemaField>;
379
+ /** Guidance from the site developer: when to use this block. */
380
+ description?: string;
381
+ group?: string;
382
+ placement?: "first" | "last" | "any";
383
+ maxPerPage?: number;
384
+ /** Picker thumbnail: an http(s) URL or a site path like "/block-previews/hero.png". */
385
+ preview?: string;
377
386
  };
378
387
 
379
388
  export type SchemaPayload = {
@@ -393,14 +402,21 @@ export type SchemaPayload = {
393
402
  /** In-content blocks from the client `richtext/` directory. */
394
403
  richtext?: BlockSnapshot[];
395
404
  objects?: Array<{ name: string; fields: Record<string, SchemaField> }>;
405
+ /** Source files the last import could not evaluate. */
406
+ failures?: SchemaFailure[];
396
407
  };
397
408
 
409
+ /** A model, object, or block file the import could not evaluate. */
410
+ export type SchemaFailure = { path: string; message: string };
411
+
398
412
  export function fetchSchema(workspaceId: string) {
399
413
  return api<{
400
414
  schema: {
401
415
  id: string;
402
416
  version: number;
403
417
  branch?: string;
418
+ /** ISO time the snapshot was written. */
419
+ createdAt?: string;
404
420
  payload: SchemaPayload;
405
421
  } | null;
406
422
  branch?: string;
@@ -611,7 +627,10 @@ export type ImportResult = {
611
627
  imported: number;
612
628
  deleted: number;
613
629
  skipped: number;
630
+ /** Everything that went wrong, including a `path: message` line per file in `failedFiles`. */
614
631
  errors: string[];
632
+ /** Schema files that failed to load. The pull still worked; the block picker and schema settings name them. */
633
+ failedFiles?: string[];
615
634
  headSha: string | null;
616
635
  };
617
636
 
@@ -621,8 +640,12 @@ export async function importContent(workspaceId: string) {
621
640
  `/workspaces/${workspaceId}/content/import`,
622
641
  { method: "POST", signal: AbortSignal.timeout(90_000) },
623
642
  );
624
- if (body.result.errors.length > 0) {
625
- const err = new Error(body.result.errors.join("; ")) as ApiError;
643
+ const failed = body.result.failedFiles ?? [];
644
+ const failures = body.result.errors.filter(
645
+ (error) => !failed.some((path) => error.startsWith(`${path}: `)),
646
+ );
647
+ if (failures.length > 0) {
648
+ const err = new Error(failures.join("; ")) as ApiError;
626
649
  err.status = 502;
627
650
  err.code = "github_import_failed";
628
651
  throw err;
@@ -1030,9 +1053,71 @@ export function uploadMedia(
1030
1053
  file: File,
1031
1054
  onProgress?: (fraction: number) => void,
1032
1055
  ) {
1033
- return new Promise<{ media: CatalogMedia }>((resolve, reject) => {
1056
+ const body = new FormData();
1057
+ body.set("file", file);
1058
+ return postFormWithProgress<{ media: CatalogMedia }>(
1059
+ `/workspaces/${workspaceId}/media`,
1060
+ body,
1061
+ "media",
1062
+ onProgress,
1063
+ );
1064
+ }
1065
+
1066
+ /** A chat file as the server stored it. Its bytes stay out of the media catalog. */
1067
+ export type ChatFileUpload = {
1068
+ id: string;
1069
+ filename: string;
1070
+ kind: "image" | "pdf" | "text";
1071
+ mediaType: string;
1072
+ byteSize: number;
1073
+ };
1074
+
1075
+ /** The thread file list, as the agent sees it. */
1076
+ export type ThreadChatFile = {
1077
+ id: string;
1078
+ filename: string;
1079
+ kind: "image" | "pdf" | "text";
1080
+ byteSize: number;
1081
+ mediaUrl: string | null;
1082
+ };
1083
+
1084
+ export function uploadChatFile(
1085
+ workspaceId: string,
1086
+ file: File,
1087
+ modelCopy: Blob | null,
1088
+ onProgress?: (fraction: number) => void,
1089
+ ) {
1090
+ const body = new FormData();
1091
+ body.set("file", file);
1092
+ if (modelCopy) body.set("model", modelCopy, modelCopy.type === "image/jpeg" ? "model.jpg" : "model.webp");
1093
+ return postFormWithProgress<{ file: ChatFileUpload }>(
1094
+ `/workspaces/${workspaceId}/ai/chat-files`,
1095
+ body,
1096
+ "file",
1097
+ onProgress,
1098
+ );
1099
+ }
1100
+
1101
+ /** The original bytes of a chat file, as a blob the browser can show. */
1102
+ export async function fetchChatFileBlob(workspaceId: string, fileId: string): Promise<Blob> {
1103
+ const res = await fetch(apiUrl(`/workspaces/${workspaceId}/ai/chat-files/${encodeURIComponent(fileId)}`), {
1104
+ credentials: apiCredentials(),
1105
+ headers: apiHeaders(),
1106
+ });
1107
+ if (res.status === 401 || res.status === 426) reportUnauthorized(res.status, undefined);
1108
+ if (!res.ok) throw new Error(`chat file ${res.status}`);
1109
+ return res.blob();
1110
+ }
1111
+
1112
+ function postFormWithProgress<T extends object>(
1113
+ path: string,
1114
+ body: FormData,
1115
+ resultKey: keyof T & string,
1116
+ onProgress?: (fraction: number) => void,
1117
+ ): Promise<T> {
1118
+ return new Promise<T>((resolve, reject) => {
1034
1119
  const xhr = new XMLHttpRequest();
1035
- xhr.open("POST", apiUrl(`/workspaces/${workspaceId}/media`));
1120
+ xhr.open("POST", apiUrl(path));
1036
1121
  xhr.withCredentials = apiCredentials() === "include";
1037
1122
  for (const [name, value] of Object.entries(apiHeaders())) {
1038
1123
  xhr.setRequestHeader(name, value);
@@ -1045,15 +1130,15 @@ export function uploadMedia(
1045
1130
  xhr.onload = () => {
1046
1131
  const payload = (() => {
1047
1132
  try {
1048
- return JSON.parse(xhr.responseText) as { media?: CatalogMedia; error?: string };
1133
+ return JSON.parse(xhr.responseText) as Partial<T> & { error?: string };
1049
1134
  } catch {
1050
- return {};
1135
+ return {} as Partial<T> & { error?: string };
1051
1136
  }
1052
1137
  })();
1053
1138
  if (xhr.status === 401 || xhr.status === 426) {
1054
1139
  reportUnauthorized(xhr.status, payload.error);
1055
1140
  }
1056
- if (xhr.status < 200 || xhr.status >= 300 || !payload.media) {
1141
+ if (xhr.status < 200 || xhr.status >= 300 || !payload[resultKey]) {
1057
1142
  const err = new Error(payload.error ?? `upload failed: ${xhr.status}`) as ApiError;
1058
1143
  err.status = xhr.status;
1059
1144
  err.code = payload.error;
@@ -1061,10 +1146,8 @@ export function uploadMedia(
1061
1146
  return;
1062
1147
  }
1063
1148
  onProgress?.(1);
1064
- resolve({ media: payload.media });
1149
+ resolve(payload as T);
1065
1150
  };
1066
- const body = new FormData();
1067
- body.set("file", file);
1068
1151
  xhr.send(body);
1069
1152
  });
1070
1153
  }
@@ -1084,8 +1167,22 @@ export function deleteMedia(workspaceId: string, mediaId: string) {
1084
1167
  return api<{ ok: true }>(`/workspaces/${workspaceId}/media/${mediaId}`, { method: "DELETE" });
1085
1168
  }
1086
1169
 
1087
- export function approveCliLogin(id: string) {
1088
- return api<{ ok: true }>(`/cli/login/${id}/approve`, { method: "POST" });
1170
+ export type CliLoginRequest = {
1171
+ userCode: string;
1172
+ client: string | null;
1173
+ /** The workspace the CLI asked for, when the signed-in person is a member of it. */
1174
+ workspace: { id: string; name: string; slug: string } | null;
1175
+ };
1176
+
1177
+ export function fetchCliLoginRequest(id: string) {
1178
+ return api<CliLoginRequest>(`/cli/login/${encodeURIComponent(id)}/request`);
1179
+ }
1180
+
1181
+ export function approveCliLogin(id: string, workspaceId: string) {
1182
+ return api<{ ok: true }>(`/cli/login/${encodeURIComponent(id)}/approve`, {
1183
+ method: "POST",
1184
+ body: JSON.stringify({ workspaceId }),
1185
+ });
1089
1186
  }
1090
1187
 
1091
1188
  export function testWorkspaceMcp(workspaceId: string, id: string) {
@@ -1093,4 +1190,7 @@ export function testWorkspaceMcp(workspaceId: string, id: string) {
1093
1190
  `/workspaces/${workspaceId}/mcp/${id}/test`,
1094
1191
  { method: "POST" },
1095
1192
  );
1096
- }
1193
+ }
1194
+ export function fetchThreadFiles(workspaceId: string, threadId: string) {
1195
+ return api<{ files: ThreadChatFile[] }>(`/workspaces/${workspaceId}/ai/threads/${threadId}/files`);
1196
+ }
@@ -0,0 +1,261 @@
1
+ // packages/studio/src/chat/ChatFiles.tsx
2
+ //
3
+ // Chat files after they are sent: the squares on a user message, and the thread's
4
+ // Files list in the panel header. Their bytes come from the chat-file route with the
5
+ // normal API credentials; a part's `chat-file:` url is an id, never an <img src>.
6
+ import { useEffect, useRef, useState } from "react";
7
+ import * as stylex from "@stylexjs/stylex";
8
+ import { fetchChatFileBlob, type ThreadChatFile } from "../api";
9
+ import { colors, radius, space, type } from "../styles/tokens.stylex";
10
+ import { Tooltip } from "../ui/Tooltip";
11
+ import { FileIcon, PaperclipIcon } from "./icons";
12
+
13
+ export const CHAT_INSERT_EVENT = "backmatter:chat-insert";
14
+
15
+ type FilePart = { type: "file"; mediaType: string; filename?: string; url: string };
16
+
17
+ export function chatFileIdOf(url: string): string | null {
18
+ return url.startsWith("chat-file:") ? url.slice("chat-file:".length) : null;
19
+ }
20
+
21
+ function useChatFileUrl(workspaceId: string, id: string | null, enabled: boolean): string | null {
22
+ const [url, setUrl] = useState<string | null>(null);
23
+ useEffect(() => {
24
+ if (!id || !enabled) return;
25
+ let cancelled = false;
26
+ let made: string | null = null;
27
+ fetchChatFileBlob(workspaceId, id)
28
+ .then((blob) => {
29
+ if (cancelled || typeof URL.createObjectURL !== "function") return;
30
+ made = URL.createObjectURL(blob);
31
+ setUrl(made);
32
+ })
33
+ .catch(() => {
34
+ // A missing file shows as a plain tile.
35
+ });
36
+ return () => {
37
+ cancelled = true;
38
+ if (made) URL.revokeObjectURL(made);
39
+ };
40
+ }, [workspaceId, id, enabled]);
41
+ return url;
42
+ }
43
+
44
+ /** The chat files a sent user message carries. */
45
+ export function SentFiles({ workspaceId, parts }: { workspaceId: string; parts: FilePart[] }) {
46
+ if (parts.length === 0) return null;
47
+ return (
48
+ <div {...stylex.props(styles.sent)} aria-label="Files">
49
+ {parts.map((part, index) => (
50
+ <SentFile key={`${part.url}-${index}`} workspaceId={workspaceId} part={part} />
51
+ ))}
52
+ </div>
53
+ );
54
+ }
55
+
56
+ function SentFile({ workspaceId, part }: { workspaceId: string; part: FilePart }) {
57
+ const id = chatFileIdOf(part.url);
58
+ const image = part.mediaType.startsWith("image/");
59
+ const src = useChatFileUrl(workspaceId, id, image);
60
+ const name = part.filename || "file";
61
+ if (image) {
62
+ return (
63
+ <span title={name} {...stylex.props(styles.sentTile)}>
64
+ {src ? <img src={src} alt={name} {...stylex.props(styles.thumb)} /> : null}
65
+ </span>
66
+ );
67
+ }
68
+ return (
69
+ <span title={name} {...stylex.props(styles.sentDoc)}>
70
+ <FileIcon size={13} />
71
+ <span {...stylex.props(styles.sentName)}>{name}</span>
72
+ </span>
73
+ );
74
+ }
75
+
76
+ function formatBytes(bytes: number): string {
77
+ if (bytes < 1024 * 1024) return `${Math.max(1, Math.round(bytes / 1024))} KB`;
78
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
79
+ }
80
+
81
+ /** Header button listing the thread's chat files. Hidden while the thread has none. */
82
+ export function ThreadFilesButton({ files }: { files: ThreadChatFile[] }) {
83
+ const [open, setOpen] = useState(false);
84
+ const wrapRef = useRef<HTMLDivElement>(null);
85
+
86
+ useEffect(() => {
87
+ if (!open) return;
88
+ function onPointer(e: PointerEvent) {
89
+ if (!wrapRef.current?.contains(e.target as Node)) setOpen(false);
90
+ }
91
+ function onKey(e: KeyboardEvent) {
92
+ if (e.key === "Escape") setOpen(false);
93
+ }
94
+ document.addEventListener("pointerdown", onPointer);
95
+ document.addEventListener("keydown", onKey);
96
+ return () => {
97
+ document.removeEventListener("pointerdown", onPointer);
98
+ document.removeEventListener("keydown", onKey);
99
+ };
100
+ }, [open]);
101
+
102
+ if (files.length === 0) return null;
103
+ const newest = [...files].reverse();
104
+
105
+ return (
106
+ <div ref={wrapRef} {...stylex.props(styles.menuWrap)}>
107
+ <Tooltip label="Files in this chat">
108
+ <button
109
+ type="button"
110
+ aria-label={`Files in this chat (${files.length})`}
111
+ aria-expanded={open}
112
+ onClick={() => setOpen((v) => !v)}
113
+ {...stylex.props(styles.countBtn)}
114
+ >
115
+ <PaperclipIcon />
116
+ <span>{files.length}</span>
117
+ </button>
118
+ </Tooltip>
119
+ {open ? (
120
+ <ul role="list" aria-label="Files in this chat" {...stylex.props(styles.menu)}>
121
+ {newest.map((file) => (
122
+ <li key={file.id}>
123
+ <button
124
+ type="button"
125
+ onClick={() => {
126
+ window.dispatchEvent(
127
+ new CustomEvent(CHAT_INSERT_EVENT, { detail: { text: `"${file.filename}" (${file.id})` } }),
128
+ );
129
+ setOpen(false);
130
+ }}
131
+ {...stylex.props(styles.menuRow)}
132
+ >
133
+ <FileIcon size={13} />
134
+ <span {...stylex.props(styles.menuName)}>{file.filename}</span>
135
+ <span {...stylex.props(styles.menuMeta)}>{formatBytes(file.byteSize)}</span>
136
+ </button>
137
+ {file.mediaUrl ? (
138
+ <a href={file.mediaUrl} target="_blank" rel="noreferrer" {...stylex.props(styles.saved)}>
139
+ Saved to media
140
+ </a>
141
+ ) : null}
142
+ </li>
143
+ ))}
144
+ </ul>
145
+ ) : null}
146
+ </div>
147
+ );
148
+ }
149
+
150
+ const styles = stylex.create({
151
+ sent: {
152
+ display: "flex",
153
+ flexWrap: "wrap",
154
+ justifyContent: "flex-end",
155
+ gap: space.xs,
156
+ },
157
+ sentTile: {
158
+ display: "block",
159
+ width: 64,
160
+ height: 64,
161
+ overflow: "hidden",
162
+ borderRadius: radius.md,
163
+ backgroundColor: colors.bgPanelInset,
164
+ },
165
+ thumb: {
166
+ display: "block",
167
+ width: "100%",
168
+ height: "100%",
169
+ objectFit: "cover",
170
+ },
171
+ sentDoc: {
172
+ display: "inline-flex",
173
+ alignItems: "center",
174
+ gap: space.xs,
175
+ maxWidth: 220,
176
+ height: 28,
177
+ paddingInline: space.sm,
178
+ borderRadius: radius.md,
179
+ backgroundColor: colors.bgPanelInset,
180
+ color: colors.textMuted,
181
+ fontSize: type.xs,
182
+ },
183
+ sentName: {
184
+ overflow: "hidden",
185
+ textOverflow: "ellipsis",
186
+ whiteSpace: "nowrap",
187
+ color: colors.text,
188
+ },
189
+ // Static, so the menu anchors to the panel header rather than the button.
190
+ menuWrap: {
191
+ position: "static",
192
+ },
193
+ countBtn: {
194
+ display: "inline-flex",
195
+ alignItems: "center",
196
+ gap: 4,
197
+ height: 28,
198
+ paddingInline: space.sm,
199
+ borderWidth: 0,
200
+ borderRadius: 999,
201
+ backgroundColor: "transparent",
202
+ color: colors.textMuted,
203
+ fontSize: type.xs,
204
+ cursor: "pointer",
205
+ ":hover": { backgroundColor: colors.bgHover, color: colors.text },
206
+ },
207
+ menu: {
208
+ position: "absolute",
209
+ top: "calc(100% - 4px)",
210
+ right: space.md,
211
+ zIndex: 5,
212
+ width: 280,
213
+ maxWidth: `calc(100% - 2 * ${space.md})`,
214
+ maxHeight: 320,
215
+ overflowY: "auto",
216
+ margin: 0,
217
+ padding: space.xs,
218
+ listStyle: "none",
219
+ borderWidth: 1,
220
+ borderStyle: "solid",
221
+ borderColor: colors.border,
222
+ borderRadius: 10,
223
+ backgroundColor: colors.bgSurface,
224
+ boxShadow: "0 8px 24px rgba(0,0,0,0.12)",
225
+ },
226
+ menuRow: {
227
+ display: "flex",
228
+ alignItems: "center",
229
+ gap: space.sm,
230
+ width: "100%",
231
+ height: 30,
232
+ paddingInline: space.sm,
233
+ borderWidth: 0,
234
+ borderRadius: radius.md,
235
+ backgroundColor: "transparent",
236
+ color: colors.textMuted,
237
+ fontSize: type.sm,
238
+ textAlign: "left",
239
+ cursor: "pointer",
240
+ ":hover": { backgroundColor: colors.bgHover },
241
+ },
242
+ menuName: {
243
+ flex: 1,
244
+ minWidth: 0,
245
+ overflow: "hidden",
246
+ textOverflow: "ellipsis",
247
+ whiteSpace: "nowrap",
248
+ color: colors.text,
249
+ },
250
+ menuMeta: {
251
+ flexShrink: 0,
252
+ fontSize: type.xs,
253
+ },
254
+ saved: {
255
+ display: "block",
256
+ paddingInline: `calc(${space.sm} + 13px + ${space.sm})`,
257
+ paddingBottom: space.xs,
258
+ fontSize: type.xs,
259
+ color: colors.textMuted,
260
+ },
261
+ });
@@ -26,6 +26,7 @@ import { CheckIcon, ChevronDownIcon, EyeIcon, FileIcon, SearchIcon, UndoIcon } f
26
26
  import { pointersFromMetadata } from "./chat-context";
27
27
  import { PointerChip, pointerKey } from "./PointerChip";
28
28
  import { Reveal } from "./Reveal";
29
+ import { SentFiles } from "./ChatFiles";
29
30
 
30
31
  const hover = "@media (hover: hover)";
31
32
 
@@ -180,6 +181,9 @@ export function ChatMessage({
180
181
  .map((p) => p.text)
181
182
  .join("\n");
182
183
  const pointers = pointersFromMetadata(message.metadata);
184
+ const fileParts = message.parts.filter(
185
+ (p): p is { type: "file"; mediaType: string; filename?: string; url: string } => p.type === "file",
186
+ );
183
187
  return (
184
188
  // The anchor is outside the entrance transform. Measuring the rising
185
189
  // bubble would place the slot too high, and the thread would snap back
@@ -195,6 +199,7 @@ export function ChatMessage({
195
199
  ))}
196
200
  </div>
197
201
  ) : null}
202
+ <SentFiles workspaceId={workspaceId} parts={fileParts} />
198
203
  {text ? <div {...stylex.props(styles.userBubble)}>{text}</div> : null}
199
204
  </div>
200
205
  </div>