@bevel-software/platform-core-frontend 0.1.0

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 (203) hide show
  1. package/LICENSE +202 -0
  2. package/package.json +70 -0
  3. package/src/core/CoreAppShell.tsx +444 -0
  4. package/src/core/__tests__/ShellRoutes.test.tsx +95 -0
  5. package/src/core/events.ts +29 -0
  6. package/src/core/registry.ts +336 -0
  7. package/src/css-side-effect-imports.d.ts +7 -0
  8. package/src/html-extensions.ts +12 -0
  9. package/src/index.css +49 -0
  10. package/src/index.ts +23 -0
  11. package/src/lib/api.ts +57 -0
  12. package/src/lib/utils.ts +138 -0
  13. package/src/modules/access/__tests__/ManageAccessDialog.test.tsx +130 -0
  14. package/src/modules/access/__tests__/useFileAccess.test.tsx +253 -0
  15. package/src/modules/access/api.ts +205 -0
  16. package/src/modules/access/components/AccessRestrictedBanner.tsx +31 -0
  17. package/src/modules/access/components/ManageAccessDialog.tsx +1232 -0
  18. package/src/modules/access/components/NodeOwnersBanner.tsx +30 -0
  19. package/src/modules/access/hooks/useFileAccess.ts +151 -0
  20. package/src/modules/admin/components/AdminRolesPage.tsx +943 -0
  21. package/src/modules/admin/components/RolesCorruptedBanner.tsx +74 -0
  22. package/src/modules/admin/services/admin.api.ts +92 -0
  23. package/src/modules/admin/services/roles.api.ts +136 -0
  24. package/src/modules/admin/state/admin.context.tsx +223 -0
  25. package/src/modules/auth/components/LoginScreen.tsx +135 -0
  26. package/src/modules/auth/hooks/useAuthState.ts +59 -0
  27. package/src/modules/auth/services/auth.api.ts +24 -0
  28. package/src/modules/auth/services/microsoft-oauth.ts +57 -0
  29. package/src/modules/auth/state/auth.context.ts +18 -0
  30. package/src/modules/git/__tests__/BranchSwitcher.test.tsx +347 -0
  31. package/src/modules/git/__tests__/FileHistoryPanel.test.tsx +201 -0
  32. package/src/modules/git/__tests__/ProtectedBranchBanner.test.tsx +82 -0
  33. package/src/modules/git/__tests__/PullNeededBanner.test.tsx +441 -0
  34. package/src/modules/git/__tests__/git.api.test.ts +113 -0
  35. package/src/modules/git/__tests__/pr.api.test.ts +44 -0
  36. package/src/modules/git/__tests__/useAutoPullUpdates.test.tsx +212 -0
  37. package/src/modules/git/components/BranchSwitcher.tsx +527 -0
  38. package/src/modules/git/components/DiffView.tsx +30 -0
  39. package/src/modules/git/components/FileComparisonPanel.tsx +377 -0
  40. package/src/modules/git/components/FileHistoryPanel.tsx +320 -0
  41. package/src/modules/git/components/ProtectedBranchBanner.tsx +42 -0
  42. package/src/modules/git/components/PullNeededBanner.tsx +204 -0
  43. package/src/modules/git/components/PullRequestsForMe.tsx +244 -0
  44. package/src/modules/git/components/UnifiedDiffView.tsx +37 -0
  45. package/src/modules/git/hooks/__tests__/useGitState.deleteBranch.test.tsx +99 -0
  46. package/src/modules/git/hooks/useAutoPullUpdates.ts +121 -0
  47. package/src/modules/git/hooks/useGitState.ts +335 -0
  48. package/src/modules/git/services/__tests__/error-messages.test.ts +134 -0
  49. package/src/modules/git/services/error-messages.ts +257 -0
  50. package/src/modules/git/services/git.api.ts +163 -0
  51. package/src/modules/git/services/pr-prompts.ts +159 -0
  52. package/src/modules/git/services/pr.api.ts +39 -0
  53. package/src/modules/git/state/auto-update.context.ts +21 -0
  54. package/src/modules/git/state/git.context.ts +82 -0
  55. package/src/modules/layout/components/AppLayout.tsx +40 -0
  56. package/src/modules/layout/components/DemoBanner.tsx +57 -0
  57. package/src/modules/layout/components/MaintenanceOverlay.tsx +104 -0
  58. package/src/modules/layout/components/MobileChatLayout.tsx +153 -0
  59. package/src/modules/layout/components/ResizableThreePaneLayout.tsx +203 -0
  60. package/src/modules/layout/components/SlideOverlay.tsx +224 -0
  61. package/src/modules/layout/components/__tests__/MobileChatLayout.test.tsx +77 -0
  62. package/src/modules/layout/components/__tests__/ResizableThreePaneLayout.test.tsx +57 -0
  63. package/src/modules/layout/hooks/useMediaQuery.ts +23 -0
  64. package/src/modules/layout/state/__tests__/layout.context.test.tsx +39 -0
  65. package/src/modules/layout/state/layout.context.ts +46 -0
  66. package/src/modules/library/__tests__/DetailDialog.test.tsx +200 -0
  67. package/src/modules/library/__tests__/diff.test.ts +62 -0
  68. package/src/modules/library/__tests__/loadout.test.tsx +72 -0
  69. package/src/modules/library/__tests__/status.test.ts +117 -0
  70. package/src/modules/library/components/ChangeRequestDock.tsx +47 -0
  71. package/src/modules/library/components/CompareView.tsx +357 -0
  72. package/src/modules/library/components/DetailDialog.tsx +566 -0
  73. package/src/modules/library/components/GearIcon.tsx +12 -0
  74. package/src/modules/library/components/LibraryCard.tsx +132 -0
  75. package/src/modules/library/components/LibraryPage.tsx +254 -0
  76. package/src/modules/library/components/LoadoutSidebar.tsx +156 -0
  77. package/src/modules/library/components/StatusGem.tsx +21 -0
  78. package/src/modules/library/components/SuggestChange.tsx +171 -0
  79. package/src/modules/library/components/particles.ts +50 -0
  80. package/src/modules/library/hooks/useLibraryData.ts +119 -0
  81. package/src/modules/library/hooks/useSkillDetail.ts +74 -0
  82. package/src/modules/library/library.css +320 -0
  83. package/src/modules/library/services/library.api.ts +164 -0
  84. package/src/modules/library/state/loadout.tsx +129 -0
  85. package/src/modules/library/state/toast.tsx +42 -0
  86. package/src/modules/library/utils/diff.ts +102 -0
  87. package/src/modules/library/utils/status.ts +116 -0
  88. package/src/modules/pr/__tests__/PrApprovalBadge.test.tsx +93 -0
  89. package/src/modules/pr/__tests__/PrCancelButton.test.tsx +158 -0
  90. package/src/modules/pr/__tests__/PrCancelConfirmDialog.test.tsx +44 -0
  91. package/src/modules/pr/__tests__/PrMergeButton.test.tsx +360 -0
  92. package/src/modules/pr/__tests__/bucketize-comments.test.ts +85 -0
  93. package/src/modules/pr/__tests__/parsePatch.test.ts +104 -0
  94. package/src/modules/pr/__tests__/usePrViewerState.test.ts +72 -0
  95. package/src/modules/pr/components/OpenChangeRequestDialog.tsx +193 -0
  96. package/src/modules/pr/components/PrApprovalBadge.tsx +80 -0
  97. package/src/modules/pr/components/PrCancelButton.tsx +99 -0
  98. package/src/modules/pr/components/PrCancelConfirmDialog.tsx +119 -0
  99. package/src/modules/pr/components/PrCommentComposer.tsx +92 -0
  100. package/src/modules/pr/components/PrCommentThread.tsx +168 -0
  101. package/src/modules/pr/components/PrCommentsPanel.tsx +143 -0
  102. package/src/modules/pr/components/PrDiffPane.tsx +425 -0
  103. package/src/modules/pr/components/PrFileRow.tsx +164 -0
  104. package/src/modules/pr/components/PrFilesList.tsx +53 -0
  105. package/src/modules/pr/components/PrHeader.tsx +45 -0
  106. package/src/modules/pr/components/PrHeaderOverflowMenu.tsx +58 -0
  107. package/src/modules/pr/components/PrMergeButton.tsx +268 -0
  108. package/src/modules/pr/components/PrMergeConfirmDialog.tsx +112 -0
  109. package/src/modules/pr/components/PrRefreshFromTargetButton.tsx +110 -0
  110. package/src/modules/pr/components/PrViewer.tsx +364 -0
  111. package/src/modules/pr/hooks/usePrViewerState.ts +150 -0
  112. package/src/modules/pr/services/pr-approvals.api.ts +31 -0
  113. package/src/modules/pr/services/pr-cancel.api.ts +19 -0
  114. package/src/modules/pr/services/pr-comments.api.ts +45 -0
  115. package/src/modules/pr/services/pr-detail.api.ts +17 -0
  116. package/src/modules/pr/services/pr-merge.api.ts +53 -0
  117. package/src/modules/pr/services/pr-open.api.ts +30 -0
  118. package/src/modules/pr/state/pr-viewer.context.ts +34 -0
  119. package/src/modules/pr/utils/bucketize-comments.ts +55 -0
  120. package/src/modules/pr/utils/parsePatch.ts +57 -0
  121. package/src/modules/review/__tests__/review.api.test.ts +121 -0
  122. package/src/modules/review/components/BinaryChangePlaceholder.tsx +15 -0
  123. package/src/modules/review/components/DiffViewer.tsx +78 -0
  124. package/src/modules/review/components/MarkdownDiffViewer.tsx +263 -0
  125. package/src/modules/review/components/ReviewFileRow.tsx +114 -0
  126. package/src/modules/review/components/ReviewPanel.tsx +260 -0
  127. package/src/modules/review/components/ReviewPanelSurface.tsx +52 -0
  128. package/src/modules/review/components/__tests__/ReviewPanel.test.tsx +106 -0
  129. package/src/modules/review/hooks/__tests__/useReviewState.test.ts +88 -0
  130. package/src/modules/review/hooks/useReviewState.ts +256 -0
  131. package/src/modules/review/services/review.api.ts +72 -0
  132. package/src/modules/review/state/ReviewProvider.tsx +28 -0
  133. package/src/modules/review/state/review.context.ts +29 -0
  134. package/src/modules/secrets-vault/components/ConnectToolsPage.tsx +488 -0
  135. package/src/modules/secrets-vault/components/SecretsPage.tsx +276 -0
  136. package/src/modules/secrets-vault/components/ToolSecretsPanel.tsx +362 -0
  137. package/src/modules/secrets-vault/components/__tests__/SecretsPage.test.tsx +51 -0
  138. package/src/modules/secrets-vault/services/connect.api.ts +113 -0
  139. package/src/modules/secrets-vault/services/secrets.api.ts +82 -0
  140. package/src/modules/secrets-vault/services/tool-secrets.api.ts +116 -0
  141. package/src/modules/toolbar/components/AdminMenu.tsx +250 -0
  142. package/src/modules/toolbar/components/AppSwitcher.tsx +108 -0
  143. package/src/modules/toolbar/components/ExternalAgentAccessPage.tsx +548 -0
  144. package/src/modules/toolbar/components/Toolbar.tsx +123 -0
  145. package/src/modules/toolbar/components/__tests__/AppSwitcher.test.tsx +122 -0
  146. package/src/modules/toolbar/components/__tests__/Toolbar.test.tsx +353 -0
  147. package/src/modules/toolbar/services/external-api-keys.api.ts +65 -0
  148. package/src/modules/tools/ToolsExplorerPage.tsx +380 -0
  149. package/src/modules/workflow/hooks/useEventBusSubscription.ts +24 -0
  150. package/src/modules/workflow/hooks/useFileLock.ts +430 -0
  151. package/src/modules/workflow/services/lock.api.ts +139 -0
  152. package/src/modules/workflow/state/EventBusFocusBinder.tsx +25 -0
  153. package/src/modules/workflow/state/EventBusProvider.tsx +232 -0
  154. package/src/modules/workflow/state/event-bus.context.ts +75 -0
  155. package/src/modules/workspace/__tests__/testFixtures.ts +54 -0
  156. package/src/modules/workspace/__tests__/useWorkspaceState.test.ts +91 -0
  157. package/src/modules/workspace/components/EditorTabs.tsx +384 -0
  158. package/src/modules/workspace/components/FileExplorer.tsx +1068 -0
  159. package/src/modules/workspace/components/FileRoute.tsx +392 -0
  160. package/src/modules/workspace/components/FileViewer.tsx +906 -0
  161. package/src/modules/workspace/components/__tests__/EditorTabs.test.tsx +241 -0
  162. package/src/modules/workspace/components/__tests__/FileExplorer.test.tsx +666 -0
  163. package/src/modules/workspace/components/__tests__/FileRoute.test.tsx +330 -0
  164. package/src/modules/workspace/components/__tests__/FileViewer.test.tsx +492 -0
  165. package/src/modules/workspace/components/renderers/CsvRenderer.tsx +174 -0
  166. package/src/modules/workspace/components/renderers/DocxRenderer.tsx +87 -0
  167. package/src/modules/workspace/components/renderers/HtmlRenderer.tsx +231 -0
  168. package/src/modules/workspace/components/renderers/ImageRenderer.tsx +50 -0
  169. package/src/modules/workspace/components/renderers/KbMarkdownView.tsx +287 -0
  170. package/src/modules/workspace/components/renderers/MarkdownRenderer.tsx +252 -0
  171. package/src/modules/workspace/components/renderers/MermaidDiagram.tsx +268 -0
  172. package/src/modules/workspace/components/renderers/PdfRenderer.tsx +81 -0
  173. package/src/modules/workspace/components/renderers/TextRenderer.tsx +86 -0
  174. package/src/modules/workspace/components/renderers/ToolForm.tsx +404 -0
  175. package/src/modules/workspace/components/renderers/ToolRenderer.tsx +417 -0
  176. package/src/modules/workspace/components/renderers/XlsxRenderer.tsx +157 -0
  177. package/src/modules/workspace/components/renderers/__tests__/CsvRenderer.test.ts +57 -0
  178. package/src/modules/workspace/components/renderers/__tests__/KbMarkdownView.test.tsx +95 -0
  179. package/src/modules/workspace/components/renderers/__tests__/MarkdownRenderer.test.tsx +328 -0
  180. package/src/modules/workspace/components/renderers/__tests__/PdfRenderer.test.tsx +167 -0
  181. package/src/modules/workspace/components/renderers/__tests__/htmlSandbox.test.ts +318 -0
  182. package/src/modules/workspace/components/renderers/csvUtils.ts +76 -0
  183. package/src/modules/workspace/components/renderers/htmlSandbox.ts +332 -0
  184. package/src/modules/workspace/components/renderers/index.ts +39 -0
  185. package/src/modules/workspace/components/renderers/types.ts +27 -0
  186. package/src/modules/workspace/hooks/__tests__/useWorkspaceState.test.tsx +298 -0
  187. package/src/modules/workspace/hooks/useWorkspaceState.ts +1315 -0
  188. package/src/modules/workspace/routing/__tests__/kb-routes.test.tsx +99 -0
  189. package/src/modules/workspace/routing/kb-routes.ts +266 -0
  190. package/src/modules/workspace/services/__tests__/workspace.api.test.ts +72 -0
  191. package/src/modules/workspace/services/workspace.api.ts +185 -0
  192. package/src/modules/workspace/state/workspace.context.ts +235 -0
  193. package/src/modules/workspace/utils/__tests__/frontmatter.test.ts +107 -0
  194. package/src/modules/workspace/utils/diff.ts +53 -0
  195. package/src/modules/workspace/utils/fileTree.ts +179 -0
  196. package/src/modules/workspace/utils/frontmatter.ts +80 -0
  197. package/src/modules/workspace/utils/readDroppedEntries.ts +119 -0
  198. package/src/modules/workspace/utils/tab-persistence.ts +23 -0
  199. package/src/shared/components/Dialog.tsx +198 -0
  200. package/src/shared/components/PageShell.tsx +51 -0
  201. package/src/shared/components/useModalLayer.ts +35 -0
  202. package/src/shared/markdown/Markdown.tsx +62 -0
  203. package/src/test-setup.ts +59 -0
@@ -0,0 +1,417 @@
1
+ import { useCallback, useEffect, useRef, useState } from 'react';
2
+ import { parse as parseYaml } from 'yaml';
3
+ import { extractFrontmatter } from '@bevel-software/platform-shared';
4
+ import type { FileRendererProps, RendererSaveState } from './types';
5
+ import { authFetch } from '../../../../lib/api';
6
+ import { Markdown } from '../../../../shared/markdown/Markdown';
7
+ import { ToolForm } from './ToolForm';
8
+ import { ToolSecretsPanel } from '../../../secrets-vault/components/ToolSecretsPanel';
9
+ import { listToolSecrets, type ToolSecrets } from '../../../secrets-vault/services/tool-secrets.api';
10
+
11
+ /**
12
+ * Whether the Form view can render this file: THE TOOL IS THE FRONTMATTER, so
13
+ * a fenced file's `---` block must parse to an object (anything after the
14
+ * closing fence is free-form notes the Form shows below the fields); a
15
+ * fence-less legacy file is the object itself.
16
+ */
17
+ function parsesToObject(text: string): boolean {
18
+ if (!text.trim()) return true; // empty file → start in Form
19
+ const fm = extractFrontmatter(text);
20
+ const source = (fm ? fm.frontmatter : text).trim();
21
+ if (!source) return true;
22
+ try {
23
+ const p = parseYaml(source);
24
+ return !!p && typeof p === 'object' && !Array.isArray(p);
25
+ } catch {
26
+ return false;
27
+ }
28
+ }
29
+
30
+ /** The free-form notes after the closing `---` fence (empty for fence-less files). */
31
+ function notesOf(text: string): string {
32
+ return extractFrontmatter(text)?.body.trim() ?? '';
33
+ }
34
+
35
+ /**
36
+ * Config UI for a `.tool` file — a UTCP manual (inline / http / mcp) that the
37
+ * MCP/UTCP endpoint loads for anyone who can read it. The file's JSON is the
38
+ * source of truth (edited in the pane), with helpers alongside: scaffolds for
39
+ * each manual type, a palette of Secrets Vault keys that inserts `${KEY}` at the
40
+ * cursor, and a live Preview that resolves/validates the manual's tools.
41
+ *
42
+ * Save/dirty plumbing mirrors the other text-backed renderers; the parent
43
+ * (`FileViewer`) owns the commit/push.
44
+ */
45
+
46
+ interface PreviewResult {
47
+ ok: boolean;
48
+ tools?: { name: string; description?: string }[];
49
+ errors?: string[];
50
+ }
51
+
52
+ // THE TOOL IS THE FRONTMATTER: id + access + config all live in ONE `---` YAML
53
+ // block. The id is the tool's stable name / secret namespace (snake_case).
54
+ const SCAFFOLDS: Record<string, string> = {
55
+ inline: [
56
+ '---',
57
+ 'id: my_tool',
58
+ 'type: inline',
59
+ 'tools:',
60
+ ' - name: example',
61
+ ' description: What this tool does.',
62
+ ' inputs: { type: object, properties: {} }',
63
+ ' outputs: { type: object, properties: {} }',
64
+ ' tool_call_template:',
65
+ ' call_template_type: http',
66
+ ' http_method: POST',
67
+ ' url: https://api.example.com/do',
68
+ ' headers: { Authorization: "Bearer ${EXAMPLE_TOKEN}" }',
69
+ '---',
70
+ '',
71
+ ].join('\n'),
72
+ http: [
73
+ '---',
74
+ 'id: my_tool',
75
+ 'type: http',
76
+ 'remote: true',
77
+ 'url: https://api.example.com/utcp',
78
+ 'headers: { Authorization: "Bearer ${EXAMPLE_TOKEN}" }',
79
+ '---',
80
+ '',
81
+ ].join('\n'),
82
+ mcp: [
83
+ '---',
84
+ 'id: my_tool',
85
+ 'type: mcp',
86
+ 'remote: true',
87
+ 'url: https://mcp.example.com',
88
+ 'headers: { Authorization: "Bearer ${EXAMPLE_TOKEN}" }',
89
+ '---',
90
+ '',
91
+ ].join('\n'),
92
+ };
93
+
94
+ export function ToolRenderer({
95
+ content,
96
+ savedContent,
97
+ filePath,
98
+ onSave,
99
+ onDirtyChange,
100
+ onValueChange,
101
+ onSaveStateChange,
102
+ readOnly = false,
103
+ }: FileRendererProps) {
104
+ const [value, setValue] = useState(content);
105
+ const [savedValue, setSavedValue] = useState(savedContent ?? content);
106
+ const [saveState, setSaveState] = useState<RendererSaveState>('idle');
107
+ const [saveError, setSaveError] = useState<string | null>(null);
108
+ const [secretKeys, setSecretKeys] = useState<string[]>([]);
109
+ const [toolSecrets, setToolSecrets] = useState<ToolSecrets | null>(null);
110
+ const [mode, setMode] = useState<'form' | 'code'>(() => (parsesToObject(content) ? 'form' : 'code'));
111
+ const [preview, setPreview] = useState<PreviewResult | null>(null);
112
+ const [previewing, setPreviewing] = useState(false);
113
+ const savingRef = useRef(false);
114
+ const textareaRef = useRef<HTMLTextAreaElement>(null);
115
+ // Monotonic id so a slow `loadToolSecrets` can't apply a result for a prior file.
116
+ const toolSecretsReqRef = useRef(0);
117
+
118
+ const dirty = !readOnly && value !== savedValue;
119
+
120
+ useEffect(() => {
121
+ setValue(content);
122
+ setSavedValue(savedContent ?? content);
123
+ setSaveState('idle');
124
+ setSaveError(null);
125
+ setPreview(null);
126
+ }, [content, savedContent, filePath]);
127
+
128
+ // Re-pick the default view (Form when parseable, else Code) when the file changes.
129
+ useEffect(() => {
130
+ setMode(parsesToObject(content) ? 'form' : 'code');
131
+ // Only on file switch — not on every keystroke, or Code edits would flip to Form.
132
+ // eslint-disable-next-line react-hooks/exhaustive-deps
133
+ }, [filePath]);
134
+
135
+ useEffect(() => {
136
+ onDirtyChange?.(dirty);
137
+ }, [dirty, onDirtyChange]);
138
+
139
+ useEffect(() => {
140
+ onSaveStateChange?.(saveState);
141
+ }, [saveState, onSaveStateChange]);
142
+
143
+ // Load the caller's Secrets Vault keys for the insert palette.
144
+ useEffect(() => {
145
+ let cancelled = false;
146
+ (async () => {
147
+ try {
148
+ const res = await authFetch('/api/secrets');
149
+ if (!res.ok) return;
150
+ const body = (await res.json()) as { secrets?: { key: string }[] };
151
+ if (!cancelled) setSecretKeys((body.secrets ?? []).map((s) => s.key));
152
+ } catch {
153
+ /* palette is best-effort */
154
+ }
155
+ })();
156
+ return () => {
157
+ cancelled = true;
158
+ };
159
+ }, []);
160
+
161
+ // Load THIS tool's declared variables + their config status (for the per-tool
162
+ // secrets panel). Matched from the default-branch catalog by file path (with a
163
+ // basename fallback, since the editor's path may be prefixed differently).
164
+ const loadToolSecrets = useCallback(async () => {
165
+ // Guard against a stale response landing after `filePath` changed: only the
166
+ // newest request may call setToolSecrets.
167
+ const reqId = ++toolSecretsReqRef.current;
168
+ try {
169
+ const tools = await listToolSecrets();
170
+ if (reqId !== toolSecretsReqRef.current) return;
171
+ const base = filePath.split('/').pop();
172
+ // Prefer the strongest match so an exact path never loses to a weaker suffix
173
+ // / basename match (which could expose a different tool's secrets).
174
+ const match =
175
+ tools.find((t) => t.path === filePath) ??
176
+ tools.find((t) => t.path.endsWith(filePath) || filePath.endsWith(t.path)) ??
177
+ tools.find((t) => t.path.split('/').pop() === base) ??
178
+ null;
179
+ setToolSecrets(match);
180
+ } catch {
181
+ if (reqId === toolSecretsReqRef.current) setToolSecrets(null);
182
+ }
183
+ }, [filePath]);
184
+
185
+ useEffect(() => {
186
+ void loadToolSecrets();
187
+ }, [loadToolSecrets]);
188
+
189
+ const save = useCallback(async (): Promise<boolean> => {
190
+ if (readOnly || value === savedValue) return true;
191
+ if (savingRef.current) return false;
192
+ savingRef.current = true;
193
+ setSaveState('saving');
194
+ setSaveError(null);
195
+ try {
196
+ await onSave(value);
197
+ setSavedValue(value);
198
+ setSaveState('idle');
199
+ return true;
200
+ } catch (err) {
201
+ setSaveState('error');
202
+ setSaveError(err instanceof Error ? err.message : String(err));
203
+ return false;
204
+ } finally {
205
+ savingRef.current = false;
206
+ }
207
+ }, [readOnly, value, savedValue, onSave]);
208
+
209
+ const updateValue = useCallback(
210
+ (next: string) => {
211
+ setValue(next);
212
+ onValueChange?.(next);
213
+ },
214
+ [onValueChange],
215
+ );
216
+
217
+ const insertAtCursor = useCallback(
218
+ (text: string) => {
219
+ const ta = textareaRef.current;
220
+ if (!ta) return;
221
+ const start = ta.selectionStart ?? value.length;
222
+ const end = ta.selectionEnd ?? value.length;
223
+ const next = value.slice(0, start) + text + value.slice(end);
224
+ updateValue(next);
225
+ requestAnimationFrame(() => {
226
+ ta.focus();
227
+ const pos = start + text.length;
228
+ ta.setSelectionRange(pos, pos);
229
+ });
230
+ },
231
+ [value, updateValue],
232
+ );
233
+
234
+ const runPreview = useCallback(async () => {
235
+ setPreviewing(true);
236
+ try {
237
+ const res = await authFetch('/api/tools/preview', {
238
+ method: 'POST',
239
+ headers: { 'Content-Type': 'application/json' },
240
+ body: JSON.stringify({ content: value }),
241
+ });
242
+ if (!res.ok) {
243
+ // A 401/500 body isn't a PreviewResult — surface it as an error rather
244
+ // than letting it fall through to the "No tools." branch.
245
+ const msg = await res
246
+ .json()
247
+ .then((b) => (b as { error?: string })?.error)
248
+ .catch(() => null);
249
+ setPreview({ ok: false, errors: [msg || `Preview failed (HTTP ${res.status})`] });
250
+ return;
251
+ }
252
+ setPreview((await res.json()) as PreviewResult);
253
+ } catch (err) {
254
+ setPreview({ ok: false, errors: [err instanceof Error ? err.message : String(err)] });
255
+ } finally {
256
+ setPreviewing(false);
257
+ }
258
+ }, [value]);
259
+
260
+ const handleKeyDown = useCallback(
261
+ (e: React.KeyboardEvent) => {
262
+ if ((e.ctrlKey || e.metaKey) && e.key === 's') {
263
+ e.preventDefault();
264
+ void save();
265
+ }
266
+ },
267
+ [save],
268
+ );
269
+
270
+ return (
271
+ <div className="flex h-full min-h-0">
272
+ <div className="flex min-h-0 flex-1 flex-col border-r border-slate-200">
273
+ <div className="flex shrink-0 items-center gap-2 border-b border-slate-100 px-3 py-1.5">
274
+ <span className="text-xs font-medium text-slate-600">{filePath.split('/').pop()}</span>
275
+ {dirty && <span className="text-[10px] text-amber-600">● unsaved</span>}
276
+ {saveState === 'error' && <span className="text-[10px] text-red-600">{saveError}</span>}
277
+ {/* No Save button here — like the other renderers, the FileViewer's Save
278
+ persists edits (tracked via onValueChange). We only own the view toggle. */}
279
+ <div className="ml-auto flex overflow-hidden rounded border border-slate-200">
280
+ {(['form', 'code'] as const).map((m) => (
281
+ <button
282
+ key={m}
283
+ type="button"
284
+ onClick={() => setMode(m)}
285
+ className={`px-2 py-0.5 text-[11px] capitalize ${
286
+ mode === m ? 'bg-slate-800 text-white' : 'bg-white text-slate-600 hover:bg-slate-100'
287
+ }`}
288
+ >
289
+ {m}
290
+ </button>
291
+ ))}
292
+ </div>
293
+ </div>
294
+ {mode === 'form' ? (
295
+ <div className="min-h-0 flex-1 overflow-y-auto p-3">
296
+ <ToolForm value={value} onChange={updateValue} readOnly={readOnly} />
297
+ {notesOf(value) && (
298
+ <section className="mt-4 border-t border-slate-200 pt-3">
299
+ <h3 className="mb-1 text-[11px] font-semibold uppercase tracking-wide text-slate-400">Notes</h3>
300
+ {/* The free-form markdown after the frontmatter fence — where a
301
+ tool's setup instructions live. Edited in the Code view. */}
302
+ <Markdown className="text-xs">{notesOf(value)}</Markdown>
303
+ </section>
304
+ )}
305
+ </div>
306
+ ) : (
307
+ <textarea
308
+ ref={textareaRef}
309
+ value={value}
310
+ readOnly={readOnly}
311
+ onChange={(e) => updateValue(e.target.value)}
312
+ onKeyDown={handleKeyDown}
313
+ spellCheck={false}
314
+ className="min-h-0 flex-1 resize-none bg-slate-50 p-3 font-mono text-xs text-slate-800 focus:outline-none"
315
+ placeholder="A .tool file is a UTCP manual. Use a scaffold →"
316
+ />
317
+ )}
318
+ </div>
319
+
320
+ <aside className="flex w-72 shrink-0 flex-col gap-4 overflow-y-auto p-3">
321
+ {!readOnly && (
322
+ <section>
323
+ <h3 className="mb-1 text-[11px] font-semibold uppercase tracking-wide text-slate-400">Scaffold</h3>
324
+ <div className="flex gap-1">
325
+ {(['inline', 'http', 'mcp'] as const).map((t) => (
326
+ <button
327
+ key={t}
328
+ onClick={() => {
329
+ if (!value.trim() || window.confirm('Replace the file contents with this scaffold?')) {
330
+ updateValue(SCAFFOLDS[t]);
331
+ }
332
+ }}
333
+ className="rounded bg-slate-100 px-2 py-1 text-[11px] text-slate-600 hover:bg-slate-200"
334
+ >
335
+ {t}
336
+ </button>
337
+ ))}
338
+ </div>
339
+ </section>
340
+ )}
341
+
342
+ {!readOnly && (
343
+ <section>
344
+ <h3 className="mb-1 text-[11px] font-semibold uppercase tracking-wide text-slate-400">Secret variables</h3>
345
+ {secretKeys.length === 0 ? (
346
+ <p className="text-[11px] text-slate-400">
347
+ No secrets yet. Add them on the Secrets page, then reference them here.
348
+ </p>
349
+ ) : (
350
+ <div className="flex flex-wrap gap-1">
351
+ {secretKeys.map((k) => (
352
+ <button
353
+ key={k}
354
+ onClick={() => insertAtCursor(`\${${k}}`)}
355
+ className="rounded bg-blue-50 px-1.5 py-0.5 font-mono text-[10px] text-blue-700 hover:bg-blue-100"
356
+ title={`Insert \${${k}}`}
357
+ >
358
+ {`\${${k}}`}
359
+ </button>
360
+ ))}
361
+ </div>
362
+ )}
363
+ </section>
364
+ )}
365
+
366
+ <section>
367
+ <h3 className="mb-1 text-[11px] font-semibold uppercase tracking-wide text-slate-400">Secrets for this tool</h3>
368
+ {toolSecrets ? (
369
+ <ToolSecretsPanel tool={toolSecrets} onChanged={() => void loadToolSecrets()} />
370
+ ) : (
371
+ <p className="text-[11px] text-slate-400">
372
+ Declare a <code className="rounded bg-slate-100 px-1">variables</code> block and save this tool to the
373
+ default branch to configure its secrets here.
374
+ </p>
375
+ )}
376
+ </section>
377
+
378
+ <section>
379
+ <div className="mb-1 flex items-center gap-2">
380
+ <h3 className="text-[11px] font-semibold uppercase tracking-wide text-slate-400">Preview</h3>
381
+ <button
382
+ onClick={() => void runPreview()}
383
+ disabled={previewing}
384
+ className="ml-auto rounded bg-slate-100 px-2 py-0.5 text-[11px] text-slate-600 hover:bg-slate-200 disabled:opacity-40"
385
+ >
386
+ {previewing ? '…' : 'Run'}
387
+ </button>
388
+ </div>
389
+ {preview && (
390
+ <div className="text-[11px]">
391
+ {preview.errors?.length ? (
392
+ <ul className="space-y-1 text-red-600">
393
+ {preview.errors.map((e, i) => (
394
+ <li key={i}>{e}</li>
395
+ ))}
396
+ </ul>
397
+ ) : preview.tools && preview.tools.length > 0 ? (
398
+ <ul className="space-y-1">
399
+ {preview.tools.map((t) => (
400
+ <li key={t.name} className="rounded bg-slate-50 px-1.5 py-1">
401
+ <code className="text-slate-700">{t.name}</code>
402
+ {t.description && <div className="text-slate-400">{t.description}</div>}
403
+ </li>
404
+ ))}
405
+ </ul>
406
+ ) : (
407
+ <p className="text-slate-400">
408
+ {preview.ok ? 'Valid. Tools resolve at runtime (http/mcp).' : 'No tools.'}
409
+ </p>
410
+ )}
411
+ </div>
412
+ )}
413
+ </section>
414
+ </aside>
415
+ </div>
416
+ );
417
+ }
@@ -0,0 +1,157 @@
1
+ import { useEffect, useState } from 'react';
2
+ import * as XLSX from 'xlsx';
3
+ import { useWorkspace } from '../../state/workspace.context';
4
+ import { authFetch } from '../../../../lib/api';
5
+ import type { FileRendererProps } from './types';
6
+
7
+ interface SheetView {
8
+ name: string;
9
+ rows: string[][];
10
+ }
11
+
12
+ /**
13
+ * Inline .xlsx viewer. Fetches the binary from `/api/workspace/:id/file/raw`,
14
+ * parses it with SheetJS, and renders each sheet as an HTML table with a
15
+ * tab strip across the top. Multi-sheet workbooks show one tab per sheet;
16
+ * single-sheet workbooks hide the tab strip.
17
+ *
18
+ * View-only: there is no edit mode for binary office formats. The renderer
19
+ * ignores `onSave` / `onValueChange` / `readOnly`.
20
+ *
21
+ * Cells are rendered as their formatted string value (`raw: false`) so dates
22
+ * and percentages match what the user sees in Excel rather than coming out
23
+ * as raw serial numbers / decimals.
24
+ */
25
+ export function XlsxRenderer({ filePath }: FileRendererProps) {
26
+ const { workspaceId } = useWorkspace();
27
+ const [sheets, setSheets] = useState<SheetView[] | null>(null);
28
+ const [activeSheet, setActiveSheet] = useState(0);
29
+ const [error, setError] = useState<string | null>(null);
30
+
31
+ useEffect(() => {
32
+ setSheets(null);
33
+ setActiveSheet(0);
34
+ setError(null);
35
+ if (!workspaceId) return;
36
+
37
+ let cancelled = false;
38
+ (async () => {
39
+ try {
40
+ const res = await authFetch(
41
+ `/api/workspace/${workspaceId}/file/raw?path=${encodeURIComponent(filePath)}`,
42
+ );
43
+ if (cancelled) return;
44
+ if (!res.ok) {
45
+ setError(`Failed to load spreadsheet (HTTP ${res.status})`);
46
+ return;
47
+ }
48
+ const buffer = await res.arrayBuffer();
49
+ if (cancelled) return;
50
+ const workbook = XLSX.read(new Uint8Array(buffer), { type: 'array' });
51
+ const parsed: SheetView[] = workbook.SheetNames.map((name) => {
52
+ const sheet = workbook.Sheets[name];
53
+ const rows = sheet
54
+ ? (XLSX.utils.sheet_to_json(sheet, {
55
+ header: 1,
56
+ raw: false,
57
+ defval: '',
58
+ }) as unknown[][])
59
+ : [];
60
+ return {
61
+ name,
62
+ rows: rows.map((row) => row.map((cell) => (cell == null ? '' : String(cell)))),
63
+ };
64
+ });
65
+ if (cancelled) return;
66
+ setSheets(parsed);
67
+ } catch (e) {
68
+ if (cancelled) return;
69
+ setError(e instanceof Error ? e.message : String(e));
70
+ }
71
+ })();
72
+
73
+ return () => {
74
+ cancelled = true;
75
+ };
76
+ }, [workspaceId, filePath]);
77
+
78
+ if (error) {
79
+ return (
80
+ <div className="flex items-center justify-center h-full text-red-600 text-sm">
81
+ {error}
82
+ </div>
83
+ );
84
+ }
85
+
86
+ if (sheets === null) {
87
+ return (
88
+ <div className="flex items-center justify-center h-full text-slate-600 text-sm">
89
+ Loading spreadsheet...
90
+ </div>
91
+ );
92
+ }
93
+
94
+ if (sheets.length === 0) {
95
+ return (
96
+ <div className="flex items-center justify-center h-full text-slate-600 text-sm">
97
+ The workbook has no sheets.
98
+ </div>
99
+ );
100
+ }
101
+
102
+ const sheet = sheets[Math.min(activeSheet, sheets.length - 1)]!;
103
+
104
+ return (
105
+ <div className="flex flex-col h-full">
106
+ {sheets.length > 1 && (
107
+ <div className="flex items-center gap-1 border-b border-slate-200 px-1 pb-1 overflow-x-auto shrink-0">
108
+ {sheets.map((s, i) => (
109
+ <button
110
+ key={s.name}
111
+ type="button"
112
+ onClick={() => setActiveSheet(i)}
113
+ className={`px-2 py-1 rounded text-xs font-medium whitespace-nowrap transition-colors ${
114
+ i === activeSheet
115
+ ? 'bg-slate-100 text-slate-900'
116
+ : 'text-slate-600 hover:text-slate-900 hover:bg-slate-100/80'
117
+ }`}
118
+ >
119
+ {s.name}
120
+ </button>
121
+ ))}
122
+ </div>
123
+ )}
124
+ <div className="flex-1 overflow-auto">
125
+ {sheet.rows.length === 0 ? (
126
+ <div className="flex items-center justify-center h-full text-slate-600 text-sm">
127
+ This sheet is empty.
128
+ </div>
129
+ ) : (
130
+ <table className="border-collapse text-sm">
131
+ <tbody>
132
+ {sheet.rows.map((row, rIdx) => (
133
+ <tr key={rIdx}>
134
+ {row.map((cell, cIdx) => {
135
+ const Tag = rIdx === 0 ? 'th' : 'td';
136
+ return (
137
+ <Tag
138
+ key={cIdx}
139
+ className={`border border-slate-200 px-2 py-1 align-top whitespace-pre-wrap ${
140
+ rIdx === 0
141
+ ? 'bg-slate-50 text-slate-900 font-medium text-left'
142
+ : 'text-slate-700'
143
+ }`}
144
+ >
145
+ {cell}
146
+ </Tag>
147
+ );
148
+ })}
149
+ </tr>
150
+ ))}
151
+ </tbody>
152
+ </table>
153
+ )}
154
+ </div>
155
+ </div>
156
+ );
157
+ }
@@ -0,0 +1,57 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { parseCsv } from '../csvUtils';
3
+
4
+ describe('parseCsv', () => {
5
+ it('parses a simple comma-separated grid', () => {
6
+ expect(parseCsv('a,b,c\n1,2,3')).toEqual([
7
+ ['a', 'b', 'c'],
8
+ ['1', '2', '3'],
9
+ ]);
10
+ });
11
+
12
+ it('does not emit a trailing empty row for a terminating newline', () => {
13
+ expect(parseCsv('a,b\n1,2\n')).toEqual([
14
+ ['a', 'b'],
15
+ ['1', '2'],
16
+ ]);
17
+ });
18
+
19
+ it('handles CRLF line endings', () => {
20
+ expect(parseCsv('a,b\r\n1,2')).toEqual([
21
+ ['a', 'b'],
22
+ ['1', '2'],
23
+ ]);
24
+ });
25
+
26
+ it('keeps commas inside quoted fields', () => {
27
+ expect(parseCsv('"Smith, John",42')).toEqual([['Smith, John', '42']]);
28
+ });
29
+
30
+ it('unescapes doubled quotes inside a quoted field', () => {
31
+ expect(parseCsv('"She said ""hi""",ok')).toEqual([['She said "hi"', 'ok']]);
32
+ });
33
+
34
+ it('preserves newlines embedded in quoted fields', () => {
35
+ expect(parseCsv('"line1\nline2",b')).toEqual([['line1\nline2', 'b']]);
36
+ });
37
+
38
+ it('preserves empty fields', () => {
39
+ expect(parseCsv('a,,c')).toEqual([['a', '', 'c']]);
40
+ });
41
+
42
+ it('returns no rows for empty input', () => {
43
+ expect(parseCsv('')).toEqual([]);
44
+ });
45
+
46
+ it('keeps a single quoted empty field at EOF', () => {
47
+ expect(parseCsv('""')).toEqual([['']]);
48
+ });
49
+
50
+ it('keeps a trailing row that is a single quoted empty field', () => {
51
+ expect(parseCsv('a\n""')).toEqual([['a'], ['']]);
52
+ });
53
+
54
+ it('keeps a trailing empty field after a comma at EOF', () => {
55
+ expect(parseCsv('a,')).toEqual([['a', '']]);
56
+ });
57
+ });