@bevel-software/platform-core-frontend 0.14.0 → 0.15.1

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 (89) hide show
  1. package/package.json +2 -2
  2. package/src/core/CoreAppShell.tsx +18 -17
  3. package/src/core/__tests__/bootstrap.test.ts +33 -1
  4. package/src/core/bootstrap.ts +30 -1
  5. package/src/lib/__tests__/api.test.ts +38 -0
  6. package/src/lib/api.ts +19 -2
  7. package/src/lib/utils.ts +2 -0
  8. package/src/modules/access/__tests__/ManageAccessDialog.test.tsx +111 -1
  9. package/src/modules/access/__tests__/plugin-token.test.ts +21 -0
  10. package/src/modules/access/api.ts +52 -4
  11. package/src/modules/access/components/ManageAccessDialog.tsx +112 -83
  12. package/src/modules/git/__tests__/GitSyncFailedBanner.test.tsx +65 -1
  13. package/src/modules/git/components/GitSyncFailedBanner.tsx +68 -5
  14. package/src/modules/layout/components/SidebarFrame.tsx +1 -1
  15. package/src/modules/library/__tests__/LibraryRoutes.test.tsx +1 -1
  16. package/src/modules/library/__tests__/LibrarySidebarMenu.test.tsx +1 -1
  17. package/src/modules/library/__tests__/LinkSkillPanel.test.tsx +121 -0
  18. package/src/modules/library/__tests__/LockedPluginView.test.tsx +6 -0
  19. package/src/modules/library/__tests__/NewPluginDialog.test.tsx +5 -4
  20. package/src/modules/library/__tests__/PluginExtras.test.tsx +15 -0
  21. package/src/modules/library/__tests__/PluginPage.test.tsx +195 -1
  22. package/src/modules/library/__tests__/PluginsSidebar.contextmenu.test.tsx +1 -1
  23. package/src/modules/library/__tests__/PluginsSidebar.locked.test.tsx +1 -1
  24. package/src/modules/library/__tests__/PluginsSidebar.test.tsx +64 -3
  25. package/src/modules/library/__tests__/SkillPage.test.tsx +9 -2
  26. package/src/modules/library/__tests__/SkillsTree.test.tsx +172 -0
  27. package/src/modules/library/__tests__/ToolPage.test.tsx +7 -0
  28. package/src/modules/library/__tests__/WorkspaceItemRoute.test.tsx +115 -4
  29. package/src/modules/library/__tests__/library-data.stale.test.tsx +90 -0
  30. package/src/modules/library/__tests__/library-paths.test.ts +32 -0
  31. package/src/modules/library/__tests__/link-membership.test.ts +120 -0
  32. package/src/modules/library/__tests__/plugin-summary.test.ts +32 -0
  33. package/src/modules/library/__tests__/useJoinRequests.test.tsx +46 -0
  34. package/src/modules/library/components/AddToPluginDialog.tsx +33 -0
  35. package/src/modules/library/components/LibraryCard.tsx +14 -0
  36. package/src/modules/library/components/LibraryLayout.tsx +24 -14
  37. package/src/modules/library/components/LinkSkillPanel.tsx +171 -0
  38. package/src/modules/library/components/LockedPluginView.tsx +2 -2
  39. package/src/modules/library/components/NewPluginDialog.tsx +4 -4
  40. package/src/modules/library/components/PageActions.tsx +21 -1
  41. package/src/modules/library/components/PersonalPluginPage.tsx +2 -1
  42. package/src/modules/library/components/PluginExtras.tsx +3 -1
  43. package/src/modules/library/components/PluginPage.tsx +92 -12
  44. package/src/modules/library/components/PluginsIndexPage.tsx +11 -6
  45. package/src/modules/library/components/PluginsSidebar.tsx +110 -53
  46. package/src/modules/library/components/RenamePluginDialog.tsx +136 -0
  47. package/src/modules/library/components/SkillsTree.tsx +91 -0
  48. package/src/modules/library/components/StatusDot.tsx +1 -0
  49. package/src/modules/library/components/plugin-page-parts.tsx +32 -9
  50. package/src/modules/library/components/skill-page/SharedViaPlugins.tsx +218 -0
  51. package/src/modules/library/components/skill-page/SkillPage.tsx +70 -6
  52. package/src/modules/library/components/tool-page/ToolPage.tsx +11 -2
  53. package/src/modules/library/hooks/useJoinRequests.ts +48 -18
  54. package/src/modules/library/routes/WorkspaceItemRoute.tsx +180 -83
  55. package/src/modules/library/routes/library-paths.ts +21 -8
  56. package/src/modules/library/services/library.api.ts +55 -1
  57. package/src/modules/library/services/plugins.api.ts +94 -3
  58. package/src/modules/library/state/library-data.tsx +115 -22
  59. package/src/modules/library/utils/plugin-summary.ts +36 -0
  60. package/src/modules/library/utils/status.ts +74 -7
  61. package/src/modules/onboarding/__tests__/creator-welcome.test.tsx +3 -2
  62. package/src/modules/settings/components/ClaudeConnectionCard.tsx +169 -0
  63. package/src/modules/settings/components/DeploymentPage.tsx +15 -1
  64. package/src/modules/settings/components/__tests__/ClaudeConnectionCard.test.tsx +63 -0
  65. package/src/modules/settings/components/__tests__/DeploymentPage.test.tsx +10 -0
  66. package/src/modules/settings/services/github-facade.api.ts +43 -0
  67. package/src/modules/setup/__tests__/setup.test.tsx +118 -0
  68. package/src/modules/setup/components/SetupGate.tsx +1 -1
  69. package/src/modules/setup/components/SetupScreen.tsx +195 -2
  70. package/src/modules/setup/services/setup.api.ts +78 -0
  71. package/src/modules/toolbar/components/ExternalAgentAccessPage.tsx +295 -83
  72. package/src/modules/toolbar/components/__tests__/ExternalAgentAccessPage.test.tsx +129 -6
  73. package/src/modules/toolbar/services/external-api-keys.api.ts +2 -0
  74. package/src/modules/workspace/__tests__/testFixtures.ts +1 -0
  75. package/src/modules/workspace/components/FileExplorer.tsx +292 -236
  76. package/src/modules/workspace/components/FileRoute.tsx +37 -0
  77. package/src/modules/workspace/components/__tests__/FileRoute.test.tsx +39 -0
  78. package/src/modules/workspace/components/__tests__/FileViewer.test.tsx +1 -0
  79. package/src/modules/workspace/hooks/useMergedWorkspaceTree.ts +70 -0
  80. package/src/modules/workspace/hooks/useWorkspaceState.ts +17 -3
  81. package/src/modules/workspace/routing/kb-routes.ts +1 -1
  82. package/src/modules/workspace/state/workspace.context.ts +8 -0
  83. package/src/modules/workspace/utils/__tests__/fileTree.test.ts +15 -0
  84. package/src/modules/workspace/utils/fileTree.ts +14 -16
  85. package/src/shared/__tests__/marketplace-url.test.ts +54 -0
  86. package/src/shared/components/Badge.tsx +3 -1
  87. package/src/shared/components/Banner.tsx +5 -1
  88. package/src/shared/marketplace-url.ts +90 -0
  89. package/src/shared/theme/tokens.css +9 -0
@@ -11,6 +11,16 @@ import { AdminContext, type AdminContextValue } from '../../../admin/state/admin
11
11
  */
12
12
 
13
13
  const apiMock = vi.hoisted(() => ({ fetchSetupStatus: vi.fn(), saveSettings: vi.fn() }));
14
+ // The Claude connection card fetches its credentials on mount; answer it so
15
+ // its retry button never stands beside the page's own.
16
+ vi.mock('../../services/github-facade.api', () => ({
17
+ fetchGitHubFacade: vi.fn(async () => ({
18
+ host: 'kb.test', appId: '123456', clientId: 'Iv1.x', clientSecret: 's', webhookSecret: 'w',
19
+ privateKeyPem: 'p', marketplaceUrl: 'https://kb.test/git/marketplace.git', createdAt: 0, rotatedAt: null,
20
+ })),
21
+ rotateGitHubFacade: vi.fn(),
22
+ }));
23
+
14
24
  vi.mock('../../../setup/services/setup.api', async (importOriginal) => ({
15
25
  ...(await importOriginal<object>()),
16
26
  fetchSetupStatus: apiMock.fetchSetupStatus,
@@ -0,0 +1,43 @@
1
+ import { authFetch } from '../../../lib/api';
2
+
3
+ /**
4
+ * What an Owner pastes into Claude's admin settings to register this
5
+ * deployment as a GitHub Enterprise Server — the credentials hexis generated
6
+ * for that purpose. Admins only; every field is shown so it can be copied.
7
+ */
8
+ export interface GitHubFacadeCredentials {
9
+ /** The hostname to register. */
10
+ host: string;
11
+ appId: string;
12
+ clientId: string;
13
+ clientSecret: string;
14
+ webhookSecret: string;
15
+ privateKeyPem: string;
16
+ /** The marketplace URL people paste in Cowork and claude.ai — the same one Claude Code clones. */
17
+ marketplaceUrl: string;
18
+ createdAt: number;
19
+ rotatedAt: number | null;
20
+ }
21
+
22
+ async function unwrap(res: Response, fallback: string): Promise<never> {
23
+ let serverError: string | undefined;
24
+ try {
25
+ const body = (await res.json()) as { error?: string };
26
+ if (typeof body.error === 'string' && body.error.length > 0) serverError = body.error;
27
+ } catch {
28
+ // Non-JSON error body — fall through.
29
+ }
30
+ throw new Error(serverError ?? fallback);
31
+ }
32
+
33
+ export async function fetchGitHubFacade(): Promise<GitHubFacadeCredentials> {
34
+ const res = await authFetch('/api/admin/github-facade');
35
+ if (!res.ok) await unwrap(res, "Couldn't load the Claude connection.");
36
+ return res.json() as Promise<GitHubFacadeCredentials>;
37
+ }
38
+
39
+ export async function rotateGitHubFacade(): Promise<GitHubFacadeCredentials> {
40
+ const res = await authFetch('/api/admin/github-facade/rotate', { method: 'POST' });
41
+ if (!res.ok) await unwrap(res, "Couldn't rotate the Claude connection.");
42
+ return res.json() as Promise<GitHubFacadeCredentials>;
43
+ }
@@ -6,6 +6,7 @@ const api = vi.hoisted(() => ({
6
6
  fetchSetupStatus: vi.fn(),
7
7
  saveSettings: vi.fn(),
8
8
  testConnection: vi.fn(),
9
+ syncNow: vi.fn(),
9
10
  }));
10
11
  vi.mock('../services/setup.api', async () => {
11
12
  // The error class is real — the screen distinguishes field problems from a
@@ -43,6 +44,7 @@ beforeEach(() => {
43
44
  api.fetchSetupStatus.mockReset();
44
45
  api.saveSettings.mockReset();
45
46
  api.testConnection.mockReset();
47
+ api.syncNow.mockReset();
46
48
  reload = vi.fn();
47
49
  Object.defineProperty(window, 'location', {
48
50
  configurable: true,
@@ -741,3 +743,119 @@ describe('SetupScreen', () => {
741
743
  expect(await screen.findByText(/restart it when convenient/)).toBeInTheDocument();
742
744
  });
743
745
  });
746
+
747
+ describe('SetupScreen — remote sync panel', () => {
748
+ const SYNC_SETTING: SettingStatus = {
749
+ key: 'kbSyncSecret', envVar: 'KB_SYNC_SECRET', section: KB, source: 'unset', configured: false, secret: true, restartToApply: false,
750
+ };
751
+ const SYNC = {
752
+ url: 'https://hexis.example.test/api/sync',
753
+ last: {
754
+ at: Date.UTC(2026, 8, 4, 12, 0, 0),
755
+ by: 'github-signature',
756
+ status: 'synced' as const,
757
+ results: [{ branch: 'main', outcome: 'updated' as const, from: 'aaa', to: 'bbb' }],
758
+ },
759
+ };
760
+
761
+ it('shows the address a hook calls on first run, without a Sync now button', () => {
762
+ render(<SetupScreen settings={[...SETTINGS, SYNC_SETTING]} sync={SYNC} onSaved={() => {}} />);
763
+ expect(screen.getByText('https://hexis.example.test/api/sync/<branch>')).toBeTruthy();
764
+ expect(screen.getByRole('button', { name: 'Copy the sync address' })).toBeTruthy();
765
+ // The 'setup' variant never offers the button or the history, whatever the
766
+ // record says: on first run the repository behind them is not connected yet.
767
+ expect(screen.queryByRole('button', { name: 'Sync now' })).toBeNull();
768
+ });
769
+
770
+ it('shows the address on the Deployment page too', () => {
771
+ render(
772
+ <SetupScreen settings={[...SETTINGS, SYNC_SETTING]} sync={SYNC} onSaved={() => {}} variant="settings" />,
773
+ );
774
+ expect(screen.getByText('https://hexis.example.test/api/sync/<branch>')).toBeTruthy();
775
+ expect(screen.getByRole('button', { name: 'Sync now' })).toBeTruthy();
776
+ });
777
+
778
+ it('keeps the panel when the secret is set by the environment', () => {
779
+ const fromEnv: SettingStatus = { ...SYNC_SETTING, source: 'env', configured: true };
780
+ render(
781
+ <SetupScreen settings={[...SETTINGS, fromEnv]} sync={SYNC} onSaved={() => {}} variant="settings" />,
782
+ );
783
+ // The secret itself is locked, listed under the environment…
784
+ expect(screen.getByText('KB_SYNC_SECRET')).toBeTruthy();
785
+ // …but the address, the history and Sync now are still there.
786
+ expect(screen.getByText('https://hexis.example.test/api/sync/<branch>')).toBeTruthy();
787
+ expect(screen.getByRole('button', { name: 'Sync now' })).toBeTruthy();
788
+ });
789
+
790
+ it('on the Deployment page: says what the last sync did, and Sync now reports the result', async () => {
791
+ api.syncNow.mockResolvedValue({
792
+ ok: true,
793
+ status: 'synced',
794
+ results: [
795
+ { branch: 'main', outcome: 'updated' },
796
+ { branch: 'ali/x', outcome: 'up-to-date' },
797
+ ],
798
+ });
799
+ const onSaved = vi.fn();
800
+ render(
801
+ <SetupScreen
802
+ settings={[...SETTINGS, SYNC_SETTING]}
803
+ sync={SYNC}
804
+ onSaved={onSaved}
805
+ variant="settings"
806
+ />,
807
+ );
808
+ expect(screen.getByText(/Last sync .* by github-signature: main updated\./)).toBeTruthy();
809
+
810
+ await userEvent.click(screen.getByRole('button', { name: 'Sync now' }));
811
+ await waitFor(() => expect(screen.getByText('Synced: main updated, ali/x up to date.')).toBeTruthy());
812
+ expect(api.syncNow).toHaveBeenCalledTimes(1);
813
+ // The status carries the last-sync record, so the page refetches it.
814
+ expect(onSaved).toHaveBeenCalled();
815
+ });
816
+
817
+ it('a conflict comes back as the branch’s own message', async () => {
818
+ api.syncNow.mockResolvedValue({
819
+ ok: false,
820
+ status: 'partial',
821
+ results: [
822
+ { branch: 'main', outcome: 'conflict', error: 'main is not in sync yet: a.md changed both in Hexis and on the git host.' },
823
+ ],
824
+ });
825
+ render(
826
+ <SetupScreen
827
+ settings={[...SETTINGS, SYNC_SETTING]}
828
+ sync={{ ...SYNC, last: null }}
829
+ onSaved={() => {}}
830
+ variant="settings"
831
+ />,
832
+ );
833
+ expect(screen.getByText('No sync since this server started.')).toBeTruthy();
834
+ await userEvent.click(screen.getByRole('button', { name: 'Sync now' }));
835
+ await waitFor(() =>
836
+ expect(screen.getByText(/main is not in sync yet: a\.md changed both/)).toBeTruthy(),
837
+ );
838
+ });
839
+ });
840
+
841
+ describe('SetupScreen — sync panel when the whole knowledge base is env-set', () => {
842
+ it('still renders the address and Sync now, in a section of its own', () => {
843
+ const KB_FROM_ENV: SettingStatus[] = SETTINGS.map((s) =>
844
+ s.section === 'knowledge-base' ? { ...s, source: 'env', configured: true } : s,
845
+ );
846
+ const syncFromEnv: SettingStatus = {
847
+ key: 'kbSyncSecret', envVar: 'KB_SYNC_SECRET', section: 'knowledge-base', source: 'env', configured: true, secret: true, restartToApply: false,
848
+ };
849
+ render(
850
+ <SetupScreen
851
+ settings={[...KB_FROM_ENV, syncFromEnv]}
852
+ sync={{ url: 'https://hexis.example.test/api/sync', last: null }}
853
+ onSaved={() => {}}
854
+ variant="settings"
855
+ />,
856
+ );
857
+ expect(screen.getByText('https://hexis.example.test/api/sync/<branch>')).toBeTruthy();
858
+ expect(screen.getByRole('button', { name: 'Sync now' })).toBeTruthy();
859
+ expect(screen.getByRole('heading', { name: 'Repository sync' })).toBeTruthy();
860
+ });
861
+ });
@@ -63,5 +63,5 @@ export function SetupGate({ children }: { children: ReactNode }) {
63
63
  );
64
64
  }
65
65
 
66
- return <SetupScreen settings={status.settings} onSaved={refresh} />;
66
+ return <SetupScreen settings={status.settings} sync={status.sync} onSaved={refresh} />;
67
67
  }
@@ -1,14 +1,66 @@
1
- import { useRef, useState, type FormEvent } from 'react';
1
+ import { useEffect, useRef, useState, type FormEvent } from 'react';
2
2
  import { Banner, Button, Surface, TextField } from '../../../shared/components';
3
3
  import { tokenUsernameForHost } from '../utils/git-host';
4
+ import { copyToClipboard } from '../../../lib/clipboard';
4
5
  import {
5
6
  saveSettings,
7
+ syncNow,
8
+ syncOutcomeError,
6
9
  testConnection,
7
10
  SettingsProblems,
8
11
  type ConnectionTest,
12
+ type LastSync,
9
13
  type SettingStatus,
14
+ type SyncNowResult,
15
+ type SyncStatus,
10
16
  } from '../services/setup.api';
11
17
 
18
+ /** A value to paste elsewhere, with the one button such a value needs. */
19
+ function CopyValue({ value, label }: { value: string; label: string }) {
20
+ const [state, setState] = useState<'idle' | 'copied' | 'failed'>('idle');
21
+ const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
22
+ useEffect(() => () => {
23
+ if (timer.current) clearTimeout(timer.current);
24
+ }, []);
25
+ const copy = async () => {
26
+ // `copyToClipboard` answers false for every ordinary reason a copy does
27
+ // not land (no secure context, no focus, no clipboard at all); the button
28
+ // says so rather than pretending.
29
+ const landed = await copyToClipboard(value);
30
+ setState(landed ? 'copied' : 'failed');
31
+ if (timer.current) clearTimeout(timer.current);
32
+ timer.current = setTimeout(() => setState('idle'), 1500);
33
+ };
34
+ return (
35
+ <div className="flex flex-wrap items-center gap-2">
36
+ <code className="min-w-0 break-all rounded bg-surface px-2 py-1 font-mono text-meta text-ink">
37
+ {value}
38
+ </code>
39
+ <Button type="button" variant="outline" size="sm" onClick={() => void copy()} aria-label={label}>
40
+ {state === 'copied' ? 'Copied' : state === 'failed' ? 'Couldn’t copy' : 'Copy'}
41
+ </Button>
42
+ </div>
43
+ );
44
+ }
45
+
46
+ /** "main updated, ali/x up to date" — the per-branch outcomes as one phrase. */
47
+ function describeOutcomes(results: LastSync['results']): string {
48
+ if (results.length === 0) return 'nothing to sync yet';
49
+ const word = (r: LastSync['results'][number]): string => {
50
+ switch (r.outcome) {
51
+ case 'up-to-date':
52
+ return 'up to date';
53
+ case 'not-cloned':
54
+ return 'not cloned';
55
+ case 'remote-gone':
56
+ return 'deleted on the host';
57
+ default:
58
+ return r.outcome;
59
+ }
60
+ };
61
+ return results.map((r) => `${r.branch} ${word(r)}`).join(', ');
62
+ }
63
+
12
64
  /** Copy for each setting: what it is, in the words of someone who has to fill it in. */
13
65
  const FIELDS: Record<
14
66
  string,
@@ -40,6 +92,30 @@ const FIELDS: Record<
40
92
  placeholder: 'knowledge-base',
41
93
  advanced: true,
42
94
  },
95
+ kbSyncSecret: {
96
+ label: 'Sync secret',
97
+ help: 'Lets your git host tell this deployment when the repository changes, so pushes and merged pull requests show up right away. Add a webhook, action or pipeline step that calls POST /api/sync/<branch> with this value as a bearer token. Optional: without it, only an administrator can trigger a sync. Stored encrypted, and never shown again.',
98
+ placeholder: 'A long random string',
99
+ advanced: true,
100
+ },
101
+ knowledgeBaseDir: {
102
+ label: 'Knowledge folder',
103
+ help: 'The top-level folder in the repository that holds the knowledge. Change it only to read a repository laid out by someone else.',
104
+ placeholder: 'KnowledgeBase',
105
+ advanced: true,
106
+ },
107
+ skillsDir: {
108
+ label: 'Skills folder',
109
+ help: 'The top-level folder that holds shared skills. The three folder names must differ.',
110
+ placeholder: 'Skills',
111
+ advanced: true,
112
+ },
113
+ pluginsDir: {
114
+ label: 'Plugins folder',
115
+ help: 'The top-level folder that holds plugins. The three folder names must differ.',
116
+ placeholder: 'Plugins',
117
+ advanced: true,
118
+ },
43
119
  defaultBranch: {
44
120
  label: 'Main branch',
45
121
  help: 'The version everyone sees. Filled in from your repository when you test the connection.',
@@ -132,6 +208,11 @@ interface Props {
132
208
  * and the restart banners must never drift between first run and later.
133
209
  */
134
210
  variant?: 'setup' | 'settings';
211
+ /**
212
+ * The remote-sync facts to show beside the sync secret: the address a hook
213
+ * calls, and what the last call did. Absent on a build without the module.
214
+ */
215
+ sync?: SyncStatus;
135
216
  }
136
217
 
137
218
  /**
@@ -150,8 +231,11 @@ interface Props {
150
231
  * silently outranking the infrastructure config someone is reviewing in a
151
232
  * repo, which is the same rule the server enforces.
152
233
  */
153
- export function SetupScreen({ settings, onSaved, variant = 'setup' }: Props) {
234
+ export function SetupScreen({ settings, onSaved, variant = 'setup', sync }: Props) {
154
235
  const [draft, setDraft] = useState<Record<string, string>>({});
236
+ const [syncing, setSyncing] = useState(false);
237
+ /** What the last "Sync now" from THIS page came back with (a failure to ask is `error`). */
238
+ const [syncResult, setSyncResult] = useState<SyncNowResult | null>(null);
155
239
  const [problems, setProblems] = useState<Record<string, string>>({});
156
240
  const [error, setError] = useState<string | null>(null);
157
241
  const [test, setTest] = useState<ConnectionTest | null>(null);
@@ -349,6 +433,88 @@ export function SetupScreen({ settings, onSaved, variant = 'setup' }: Props) {
349
433
  }
350
434
  }
351
435
 
436
+ async function runSync() {
437
+ setSyncing(true);
438
+ setSyncResult(null);
439
+ try {
440
+ setSyncResult(await syncNow());
441
+ // The status carries the last-sync record; refetch so it shows this one.
442
+ onSaved();
443
+ } catch (err) {
444
+ setSyncResult({
445
+ ok: false,
446
+ results: [],
447
+ error: err instanceof Error ? err.message : 'Could not sync.',
448
+ });
449
+ } finally {
450
+ setSyncing(false);
451
+ }
452
+ }
453
+
454
+ /**
455
+ * Beside the sync secret: the address a hook calls (in both variants — an
456
+ * admin wiring a hook needs it before first run too), and once the
457
+ * deployment is live, what the last call did plus a button to make one.
458
+ */
459
+ function renderSyncPanel() {
460
+ if (!sync) return null;
461
+ const last = sync.last;
462
+ return (
463
+ <Surface tone="surface" radius="md" className="mt-3 space-y-3 border border-line p-3">
464
+ <div className="space-y-1.5">
465
+ <span className="text-meta font-medium text-ink">Address for the hook</span>
466
+ <CopyValue value={`${sync.url}/<branch>`} label="Copy the sync address" />
467
+ <p className="text-meta text-ink-faint">
468
+ Replace <code className="font-mono">&lt;branch&gt;</code> with the branch that changed;
469
+ send the secret as a bearer token.
470
+ </p>
471
+ </div>
472
+ {variant === 'settings' && (
473
+ <div className="space-y-2">
474
+ <p role="status" className="text-meta text-ink-muted">
475
+ {last
476
+ ? `Last sync ${new Date(last.at).toLocaleString()} by ${last.by}: ${describeOutcomes(last.results)}.`
477
+ : 'No sync since this server started.'}
478
+ </p>
479
+ <div className="flex flex-wrap items-center gap-3">
480
+ <Button
481
+ type="button"
482
+ variant="outline"
483
+ size="sm"
484
+ onClick={() => void runSync()}
485
+ disabled={syncing}
486
+ >
487
+ {syncing ? 'Syncing…' : 'Sync now'}
488
+ </Button>
489
+ <span className="text-meta text-ink-faint">
490
+ Pulls every branch from the repository with your own session — the same thing the
491
+ hook does.
492
+ </span>
493
+ </div>
494
+ {syncResult && (
495
+ <p
496
+ role="status"
497
+ // One line per failed branch: the server's sentences are
498
+ // joined with newlines and rendered as such.
499
+ className={`whitespace-pre-line text-detail ${syncResult.ok ? 'text-ok' : 'text-danger'}`}
500
+ >
501
+ {syncResult.error
502
+ ? syncResult.error
503
+ : syncResult.ok
504
+ ? `Synced: ${describeOutcomes(syncResult.results)}.`
505
+ : (syncResult.results
506
+ .map(syncOutcomeError)
507
+ .filter((e): e is string => !!e)
508
+ .join('\n') ||
509
+ `Not fully synced: ${describeOutcomes(syncResult.results)}.`)}
510
+ </p>
511
+ )}
512
+ </div>
513
+ )}
514
+ </Surface>
515
+ );
516
+ }
517
+
352
518
  async function submit(e: FormEvent) {
353
519
  e.preventDefault();
354
520
  if (saving) return;
@@ -497,6 +663,7 @@ export function SetupScreen({ settings, onSaved, variant = 'setup' }: Props) {
497
663
  </datalist>
498
664
  )}
499
665
  <p className="mt-1 text-meta text-ink-faint">{copy.help}</p>
666
+ {setting.key === 'kbSyncSecret' && renderSyncPanel()}
500
667
  {/* Only AFTER setup: on first run there is nothing yet to lose, so
501
668
  the caution would be noise. Once a deployment is live, this field
502
669
  is the one whose careless edit strands everything. */}
@@ -684,11 +851,37 @@ export function SetupScreen({ settings, onSaved, variant = 'setup' }: Props) {
684
851
  </div>
685
852
  </details>
686
853
  )}
854
+
855
+ {/* The sync panel normally hangs off the secret's field. When
856
+ the secret comes from the environment that field is in the
857
+ locked list below, not here — but the address, the last
858
+ sync and Sync now are about the deployment, not the secret,
859
+ and an admin with an env-set secret needs them just as much. */}
860
+ {section.id === 'knowledge-base' &&
861
+ sync &&
862
+ !fields.some((f) => f.key === 'kbSyncSecret') &&
863
+ renderSyncPanel()}
687
864
  </Surface>
688
865
  );
689
866
  })}
690
867
 
691
868
 
869
+ {/* When EVERY knowledge-base setting comes from the environment the
870
+ section above does not render at all, and the sync panel that
871
+ normally lives inside it would vanish with it. The panel is
872
+ about the deployment, not about any one editable field, so it
873
+ gets its own place here in that case. */}
874
+ {sync && editable.every((s) => s.section !== 'knowledge-base') && (
875
+ <Surface as="section" tone="surface" radius="lg" elevation="card" className="p-6">
876
+ <h2 className="text-title font-semibold text-ink">Repository sync</h2>
877
+ <p className="mt-1 max-w-[60ch] text-detail text-ink-muted">
878
+ The knowledge-base connection is set by the environment. The sync hook is still
879
+ yours to wire up and check on here.
880
+ </p>
881
+ {renderSyncPanel()}
882
+ </Surface>
883
+ )}
884
+
692
885
  {/* A rejected connection stops here rather than at the far side of
693
886
  it. Saving these answers would finish setup — the server checks
694
887
  that they are present, not that they work — and open the app onto
@@ -1,3 +1,4 @@
1
+ import type { BranchSyncOutcome } from '@bevel-software/platform-shared';
1
2
  import { authFetch } from '../../../lib/api';
2
3
 
3
4
  /** One configurable setting, as the server describes it. */
@@ -15,6 +16,31 @@ export interface SettingStatus {
15
16
  restartToApply: boolean;
16
17
  }
17
18
 
19
+ /** One branch's part in a remote sync, as `POST /api/sync` reports it — the shared union, so this cannot drift from the server. */
20
+ export type SyncBranchOutcome = BranchSyncOutcome;
21
+
22
+ /** The message a failed branch carries, if its outcome has one. */
23
+ export function syncOutcomeError(r: SyncBranchOutcome): string | undefined {
24
+ return r.outcome === 'conflict' || r.outcome === 'error' ? r.error : undefined;
25
+ }
26
+
27
+ /** What the most recent remote sync did — from the server's memory, so "none yet" after a restart. */
28
+ export interface LastSync {
29
+ /** Epoch ms. */
30
+ at: number;
31
+ /** A credential kind (`bearer`, `github-signature`, …) or an admin's email. */
32
+ by: string;
33
+ status: 'synced' | 'partial';
34
+ results: SyncBranchOutcome[];
35
+ }
36
+
37
+ /** The remote-sync facts shown beside the sync secret. Admins only. */
38
+ export interface SyncStatus {
39
+ /** `<backend>/api/sync` — a hook appends `/<branch>`. */
40
+ url: string;
41
+ last: LastSync | null;
42
+ }
43
+
18
44
  export interface SetupStatus {
19
45
  /** Reachable knowledge base AND a process that can serve it. */
20
46
  complete: boolean;
@@ -26,6 +52,8 @@ export interface SetupStatus {
26
52
  isAdmin: boolean;
27
53
  /** Admins only — nobody else is told what is missing. */
28
54
  settings?: SettingStatus[];
55
+ /** Admins only. Absent on a build without the sync module. */
56
+ sync?: SyncStatus;
29
57
  }
30
58
 
31
59
  export interface SaveResult {
@@ -60,6 +88,56 @@ async function readError(res: Response): Promise<never> {
60
88
  throw new Error(data.error || `Request failed (${res.status})`);
61
89
  }
62
90
 
91
+ /**
92
+ * The header the sync endpoint stamps on every response it writes, so the
93
+ * client can tell its 503 ("a branch could not be pulled") from a reverse
94
+ * proxy's 503 ("the backend is down"). Mirrors `SYNC_RESPONSE_HEADER` in the
95
+ * backend's `kb-sync.routes.ts`.
96
+ */
97
+ const SYNC_RESPONSE_HEADER = 'x-hexis-sync';
98
+ const SYNC_RESPONSE_MARKER = 'result';
99
+
100
+ /** What "Sync now" came back with. A 409 or 503 still carries per-branch results. */
101
+ export interface SyncNowResult {
102
+ /** True for 200 — every branch current. */
103
+ ok: boolean;
104
+ status?: 'synced' | 'partial';
105
+ results: SyncBranchOutcome[];
106
+ /** Set when the server answered with an error body instead of results. */
107
+ error?: string;
108
+ }
109
+
110
+ /**
111
+ * Run a sync of every cloned branch with the admin's own session — the same
112
+ * thing a hook does, from the page where the hook is being wired up, so an
113
+ * admin can prove the deployment reaches the repository before trusting the
114
+ * hook to.
115
+ */
116
+ export async function syncNow(): Promise<SyncNowResult> {
117
+ // The endpoint answers 503 when a branch could not be pulled — an ordinary
118
+ // result here, not the backend being down. It marks every response it
119
+ // writes with `X-Hexis-Sync: result`, which a reverse proxy answering for a
120
+ // dead backend never sets, so only a 503 carrying that marker is exempted
121
+ // from the maintenance-overlay signal. A proxy 503, a 502/504 or a network
122
+ // failure still signals, as for every other call.
123
+ const res = await authFetch(
124
+ '/api/sync',
125
+ { method: 'POST' },
126
+ { isApplicationResponse: (r) => r.headers.get(SYNC_RESPONSE_HEADER) === SYNC_RESPONSE_MARKER },
127
+ );
128
+ let body: unknown;
129
+ try {
130
+ body = await res.json();
131
+ } catch {
132
+ throw new Error(`Sync failed (${res.status})`);
133
+ }
134
+ const data = body as { status?: 'synced' | 'partial'; results?: SyncBranchOutcome[]; error?: string };
135
+ if (!Array.isArray(data.results)) {
136
+ return { ok: false, results: [], error: data.error || `Sync failed (${res.status})` };
137
+ }
138
+ return { ok: res.status === 200, status: data.status, results: data.results };
139
+ }
140
+
63
141
  export async function fetchSetupStatus(): Promise<SetupStatus> {
64
142
  const res = await authFetch('/api/setup/status');
65
143
  if (!res.ok) await readError(res);