@bevel-software/platform-core-frontend 0.8.0 → 0.9.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 (35) hide show
  1. package/package.json +2 -2
  2. package/src/core/registry.ts +16 -4
  3. package/src/modules/admin/state/admin.context.tsx +15 -0
  4. package/src/modules/library/__tests__/PluginPage.test.tsx +97 -6
  5. package/src/modules/library/__tests__/PluginsIndexPage.test.tsx +90 -10
  6. package/src/modules/library/__tests__/PluginsSidebar.contextmenu.test.tsx +1 -0
  7. package/src/modules/library/__tests__/PluginsSidebar.locked.test.tsx +1 -0
  8. package/src/modules/library/__tests__/PluginsSidebar.test.tsx +29 -0
  9. package/src/modules/library/__tests__/library-data.test.ts +82 -0
  10. package/src/modules/library/components/LibraryLayout.tsx +11 -2
  11. package/src/modules/library/components/NewSkillPanel.tsx +18 -0
  12. package/src/modules/library/components/PageActions.tsx +31 -8
  13. package/src/modules/library/components/PersonalPluginPage.tsx +14 -4
  14. package/src/modules/library/components/PluginJoinRequests.tsx +22 -1
  15. package/src/modules/library/components/PluginPage.tsx +42 -5
  16. package/src/modules/library/components/PluginsIndexPage.tsx +46 -3
  17. package/src/modules/library/components/PluginsSidebar.tsx +50 -0
  18. package/src/modules/library/components/plugin-page-parts.tsx +183 -3
  19. package/src/modules/library/routes/LibraryRoutes.tsx +2 -2
  20. package/src/modules/library/state/library-data.tsx +21 -0
  21. package/src/modules/onboarding/__tests__/creator-welcome.test.tsx +318 -0
  22. package/src/modules/onboarding/components/CreatorWelcomePage.tsx +143 -0
  23. package/src/modules/onboarding/components/WelcomePage.tsx +11 -14
  24. package/src/modules/onboarding/components/WelcomeRoute.tsx +57 -0
  25. package/src/modules/onboarding/welcome-state.ts +36 -0
  26. package/src/modules/setup/__tests__/setup.test.tsx +203 -0
  27. package/src/modules/setup/components/SetupScreen.tsx +235 -68
  28. package/src/modules/workspace/components/FileRoute.tsx +8 -1
  29. package/src/modules/workspace/components/FileViewer.tsx +95 -38
  30. package/src/modules/workspace/components/__tests__/FileRoute.test.tsx +20 -0
  31. package/src/modules/workspace/components/__tests__/FileViewer.test.tsx +227 -18
  32. package/src/modules/workspace/routing/__tests__/kb-routes.test.tsx +25 -0
  33. package/src/modules/workspace/routing/kb-routes.ts +23 -1
  34. package/src/modules/workspace/utils/fileTree.ts +51 -0
  35. package/src/shared/components/Surface.tsx +15 -0
@@ -1,5 +1,5 @@
1
1
  import { useMemo, useCallback, useContext, useEffect, useRef, useState } from 'react';
2
- import { Check, XCircle, Lock, AlertTriangle, ArrowLeft } from 'lucide-react';
2
+ import { Check, XCircle, Lock, AlertTriangle, ArrowLeft, FileText } from 'lucide-react';
3
3
  import type { FileTreeEntry, PullRequestSummary } from '@bevel-software/platform-shared';
4
4
  import { useWorkspace } from '../state/workspace.context';
5
5
  import { EditorTabs } from './EditorTabs';
@@ -9,7 +9,8 @@ import { Banner, Button, Surface } from '../../../shared/components';
9
9
  import { ManageAccessDialog } from '../../access/components/ManageAccessDialog';
10
10
  import { useGit } from '../../git/state/git.context';
11
11
  import { LayoutContext } from '../../layout/state/layout.context';
12
- import { useCanonicalFileUrl } from '../routing/kb-routes';
12
+ import { useParams } from 'react-router-dom';
13
+ import { useCanonicalFileUrl, useFileNav } from '../routing/kb-routes';
13
14
  import { PullNeededBanner } from '../../git/components/PullNeededBanner';
14
15
  import { useFileAccess } from '../../access/hooks/useFileAccess';
15
16
  import { FileHistoryPanel } from '../../git/components/FileHistoryPanel';
@@ -18,10 +19,7 @@ import {
18
19
  OPEN_COMPARISON_EVENT,
19
20
  type OpenComparisonDetail,
20
21
  } from '../../../core/events';
21
- import {
22
- useAppRegistry,
23
- useSuggestedPromptSeed,
24
- } from '../../../core/registry';
22
+ import { useAppRegistry } from '../../../core/registry';
25
23
  import { useFileLock } from '../../workflow/hooks/useFileLock';
26
24
  import { LockApiError } from '../../workflow/services/lock.api';
27
25
  import { useAuth } from '../../auth/state/auth.context';
@@ -37,21 +35,34 @@ import { FileChangeBoxes } from '../../change-requests/components/FileChangeBoxe
37
35
  import { ChangeRequestDialog } from '../../change-requests/components/ChangeRequestDialog';
38
36
  import { formatEligible } from '../../access/hooks/useFileAccess';
39
37
  import { PR_STALE_EVENT } from '../../../core/events';
38
+ import { suggestedPages } from '../utils/fileTree';
40
39
  import { getFileRenderer, getRendererLayout } from './renderers';
41
40
  import type { RendererSaveState } from './renderers';
42
41
  import { KbDocumentShell } from './KbDocumentShell';
43
42
  import { FilePaneCard } from './FilePaneCard';
44
43
 
45
- const SUGGESTED_PROMPTS = [
46
- 'Give me an overview of the process landscape.',
47
- 'What are the main process modules?',
48
- 'Show me the Registration & Onboarding processes.',
49
- ];
44
+ /**
45
+ * How many pages the empty viewer offers. Enough to look like a starting
46
+ * point, few enough to read at a glance — a longer list is the file tree,
47
+ * which is already on screen and better at being one.
48
+ */
49
+ const SUGGESTION_LIMIT = 4;
50
+
51
+ /** What a page is called, without the extension the reader did not choose. */
52
+ function pageTitle(fileName: string): string {
53
+ return fileName.replace(/\.(md|markdown)$/i, '');
54
+ }
55
+
56
+ /** The folder a page sits in, or '' for one that sits at a root. */
57
+ function parentFolder(relativePath: string): string {
58
+ return relativePath.split('/').slice(-2, -1)[0] ?? '';
59
+ }
50
60
 
51
61
  export function FileViewer() {
52
62
  const {
53
63
  workspaceId,
54
64
  kbDirName,
65
+ fileTree,
55
66
  openFilePath,
56
67
  openFileContent,
57
68
  openFileSavedContent,
@@ -65,9 +76,6 @@ export function FileViewer() {
65
76
  addTab,
66
77
  reloadTabFromDisk,
67
78
  } = useWorkspace();
68
- // Chat decoupling: the suggested-prompt seed is an optional registry port
69
- // (null when no chat surface is registered → the prompt buttons hide).
70
- const seedSuggestedPrompt = useSuggestedPromptSeed();
71
79
  const { fileViewerPanels, renderers } = useAppRegistry();
72
80
  const git = useGit();
73
81
  // Hiding the tree buys margin, not line length (proto:709), and the pane
@@ -788,6 +796,33 @@ export function FileViewer() {
788
796
  });
789
797
  }, [openFilePath]);
790
798
 
799
+ // Where to start, for a viewer with nothing open. Computed here rather than
800
+ // in the empty branch below because that branch is a `return` and this is a
801
+ // hook — and it costs nothing while a file IS open, which is the common case.
802
+ const suggestions = useMemo(
803
+ () => suggestedPages(fileTree, SUGGESTION_LIMIT),
804
+ [fileTree],
805
+ );
806
+ // Opening a suggestion is NAVIGATION, the same as clicking the file in the
807
+ // explorer or a tab: the URL is the canonical record of what is open, and a
808
+ // refresh, share or back-press must land on the page — not on the empty
809
+ // state this button was clicked from. `openWorkspacePath`, not `openFile`:
810
+ // these are real tree paths, and a `#` in a filename is a character, not an
811
+ // anchor. Navigation needs the branch, so the buttons wait for it rather
812
+ // than rendering a click that silently does nothing while git status loads.
813
+ const { openWorkspacePath } = useFileNav();
814
+ // "Ready" is the same predicate `FileRoute` uses to decide the workspace is
815
+ // actually backing this route: the branch is known AND it is the branch the
816
+ // URL names. Mid-switch the status still reports the branch being left, and
817
+ // navigating on that would send the reader back to the branch they just
818
+ // left — a worse outcome than a button that waits a moment.
819
+ // The param arrives ALREADY decoded — the router percent-decodes path params
820
+ // — so it is compared as-is. Decoding again would turn a branch named
821
+ // `my%20branch` into `my branch`, which matches nothing and would leave the
822
+ // offers disabled for good on that deployment.
823
+ const routeBranch = useParams<{ branch: string }>().branch;
824
+ const navReady = !!git.status?.branch && (!routeBranch || git.status.branch === routeBranch);
825
+
791
826
  // ALL open requests, not just the ones scoped to you — a colleague's request
792
827
  // on a file you can read but not write still belongs on this page.
793
828
  const openChangeRequests = useOpenChangeRequests();
@@ -802,32 +837,54 @@ export function FileViewer() {
802
837
  <PullNeededBanner />
803
838
  <EditorTabs />
804
839
  <div className="flex-1 flex items-center justify-center px-6">
805
- <div className="max-w-md text-center">
806
- <h2 className="mb-2 text-head text-ink">
807
- Open a file, or ask the process assistant a question.
808
- </h2>
840
+ <div className="w-full max-w-md text-center">
841
+ <h2 className="mb-2 text-head text-ink">Open a page to start reading.</h2>
809
842
  <p className="mb-6 text-ui text-ink-muted">
810
- Pick anything from the file tree, or start with a suggestion.
843
+ {suggestions.length > 0
844
+ ? 'Pick anything from the file tree, or start with one of these.'
845
+ : 'Pick anything from the file tree.'}
811
846
  </p>
812
- {/* Suggested prompts seed the chat composer — only rendered when a
813
- chat surface registered the seed port. */}
814
- {seedSuggestedPrompt && (
815
- <div className="flex flex-col gap-2">
816
- {SUGGESTED_PROMPTS.map((prompt) => (
817
- <Surface
818
- key={prompt}
819
- as="button"
820
- tone="sunken"
821
- radius="lg"
822
- elevation="none"
823
- interactive
824
- type="button"
825
- onClick={() => seedSuggestedPrompt(prompt)}
826
- className="px-3 py-2 text-left text-ui text-ink"
827
- >
828
- {prompt}
829
- </Surface>
830
- ))}
847
+ {/* Real pages, not prompts. Whoever lands here has a file tree and
848
+ a blank pane, and "browse until something looks right" is the
849
+ one instruction the tree already gives — so the suggestions are
850
+ documents that open, drawn from the top of the knowledge the
851
+ deployment actually holds. */}
852
+ {suggestions.length > 0 && (
853
+ <div className="flex flex-col gap-2 text-left">
854
+ {suggestions.map((page) => {
855
+ const folder = parentFolder(page.relativePath);
856
+ return (
857
+ <Surface
858
+ key={page.relativePath}
859
+ as="button"
860
+ tone="sunken"
861
+ radius="lg"
862
+ elevation="none"
863
+ interactive
864
+ type="button"
865
+ onClick={() => openWorkspacePath(page.relativePath)}
866
+ disabled={!navReady}
867
+ className="flex items-center gap-2.5 px-3 py-2"
868
+ >
869
+ <FileText size={15} className="shrink-0 text-ink-faint" aria-hidden />
870
+ <span className="min-w-0 flex-1 truncate text-ui text-ink">
871
+ {pageTitle(page.name)}
872
+ </span>
873
+ {/* The folder it sits in — two pages can share a name,
874
+ and the one thing that tells them apart is where they
875
+ live. */}
876
+ {/* Capped so a long folder name truncates instead of
877
+ squeezing out the page title it is there to
878
+ disambiguate — same contract as the comparison
879
+ panel's path label. */}
880
+ {folder && (
881
+ <span className="max-w-[40%] shrink-0 truncate text-meta text-ink-faint">
882
+ {folder}
883
+ </span>
884
+ )}
885
+ </Surface>
886
+ );
887
+ })}
831
888
  </div>
832
889
  )}
833
890
  </div>
@@ -152,6 +152,26 @@ describe('FileRoute', () => {
152
152
  expect(setPersistenceBranch).toHaveBeenCalledWith('alice/draft');
153
153
  });
154
154
 
155
+ /**
156
+ * A branch name may legitimately contain a percent sign. The router already
157
+ * percent-decodes path params, so decoding again read `my%20branch` as
158
+ * `my branch` and bootstrapped the workspace under a branch nobody has.
159
+ */
160
+ it('takes the branch as the router decoded it, percent sign and all', async () => {
161
+ const setPersistenceBranch = vi.fn();
162
+ const workspace = makeWorkspace({
163
+ hydrateTabs: vi.fn<WorkspaceContextValue['hydrateTabs']>(async () =>
164
+ makeHydrateResult({ surviving: ['Knowledge/Foo.md'] }),
165
+ ),
166
+ setPersistenceBranch,
167
+ });
168
+ const git = makeGit({ status: makeStatus('my%20branch') });
169
+
170
+ renderAt('/workspace/my%2520branch/Knowledge/Foo.md', { git, workspace });
171
+
172
+ await waitFor(() => expect(setPersistenceBranch).toHaveBeenCalledWith('my%20branch'));
173
+ });
174
+
155
175
  it('redirects to the new branch via setPersistenceBranch when URL points elsewhere (no git checkout)', async () => {
156
176
  // Under the per-branch workspace model, "switching branches" in
157
177
  // FileRoute is just calling setPersistenceBranch — useWorkspaceState
@@ -1,9 +1,13 @@
1
1
  import { describe, it, expect, vi, afterEach } from 'vitest';
2
2
  import { render, screen, waitFor, act, within } from '@testing-library/react';
3
3
  import userEvent from '@testing-library/user-event';
4
- import { MemoryRouter } from 'react-router-dom';
4
+ import { MemoryRouter, Routes, Route, useLocation } from 'react-router-dom';
5
5
  import { useEffect, useState } from 'react';
6
- import type { BranchInfo, WorkingTreeStatus } from '@bevel-software/platform-shared';
6
+ import type {
7
+ BranchInfo,
8
+ FileTreeEntry,
9
+ WorkingTreeStatus,
10
+ } from '@bevel-software/platform-shared';
7
11
 
8
12
  // Mock the access API before importing the component tree — useFileAccess
9
13
  // fires a fetch in an effect on mount, and we don't want real network in tests.
@@ -148,7 +152,7 @@ const fetchFileHistoryMock = vi.fn(async () => [
148
152
  },
149
153
  ]);
150
154
 
151
- function makeGit(status: WorkingTreeStatus): GitContextValue {
155
+ function makeGit(status: WorkingTreeStatus | null): GitContextValue {
152
156
  const branches: BranchInfo[] = [];
153
157
  return {
154
158
  status,
@@ -168,12 +172,24 @@ function makeGit(status: WorkingTreeStatus): GitContextValue {
168
172
  };
169
173
  }
170
174
 
175
+ /**
176
+ * Where the router currently stands. Opening a page from the empty state is
177
+ * navigation — the URL is the observable contract, and this makes it
178
+ * assertable without a route tree.
179
+ */
180
+ function LocationEcho() {
181
+ const location = useLocation();
182
+ return <div data-testid="location">{location.pathname}</div>;
183
+ }
184
+
171
185
  function ViewerHarness({
172
186
  initialContent = 'Base content',
173
187
  pendingValue = 'Agent version',
174
188
  branch = 'alice/draft',
189
+ routeBranch,
175
190
  filePath = 'knowledge-base/Knowledge/Foo.md',
176
191
  kbDirName = 'knowledge-base',
192
+ fileTree = null,
177
193
  addTab,
178
194
  changeRequests = [],
179
195
  authUser = null,
@@ -181,9 +197,18 @@ function ViewerHarness({
181
197
  }: {
182
198
  initialContent?: string;
183
199
  pendingValue?: string;
184
- branch?: string;
185
- filePath?: string;
200
+ /** `null` = git status has not loaded (or failed) — there is no branch yet. */
201
+ branch?: string | null;
202
+ /**
203
+ * The branch the URL names, when it differs from the one git status reports
204
+ * — i.e. mid-switch, before the workspace has caught up.
205
+ */
206
+ routeBranch?: string;
207
+ /** `null` means nothing is open — the viewer's empty state. */
208
+ filePath?: string | null;
186
209
  kbDirName?: string | null;
210
+ /** What the explorer holds; the empty state draws its suggestions from it. */
211
+ fileTree?: FileTreeEntry | null;
187
212
  addTab?: WorkspaceContextValue['addTab'];
188
213
  /** Open change requests touching `filePath`. */
189
214
  changeRequests?: { number: number; title: string; who: string }[];
@@ -210,18 +235,20 @@ function ViewerHarness({
210
235
  }, [pendingValue]);
211
236
 
212
237
  const effectiveSaved = captureTyped ? savedContent : openFileContent;
213
- const tab = {
214
- path: filePath,
215
- content: openFileContent,
216
- savedContent: effectiveSaved,
217
- isDirty: false,
218
- pendingFileContent,
219
- };
238
+ const tab = filePath
239
+ ? {
240
+ path: filePath,
241
+ content: openFileContent,
242
+ savedContent: effectiveSaved,
243
+ isDirty: false,
244
+ pendingFileContent,
245
+ }
246
+ : null;
220
247
  const workspace: WorkspaceContextValue = {
221
248
  workspaceId: 'ws-1',
222
249
  kbDirName,
223
- fileTree: null,
224
- openTabs: [tab],
250
+ fileTree,
251
+ openTabs: tab ? [tab] : [],
225
252
  activeTab: tab,
226
253
  dirtyTabFilenames: [],
227
254
  openFilePath: filePath,
@@ -292,15 +319,18 @@ function ViewerHarness({
292
319
  login: async () => {},
293
320
  logout: () => {},
294
321
  };
295
- return (
296
- <MemoryRouter>
322
+ // Rendered UNDER the real route shape, so `:branch` resolves the way it does
323
+ // in the app — the empty state's suggestions compare it against git status
324
+ // before offering to navigate.
325
+ const urlBranch = routeBranch ?? branch ?? 'alice/draft';
326
+ const tree = (
297
327
  <AuthContext.Provider value={auth}>
298
328
  <WorkspaceContext.Provider value={workspace}>
299
- <GitContext.Provider value={makeGit(makeStatus(branch))}>
329
+ <GitContext.Provider value={makeGit(branch ? makeStatus(branch) : null)}>
300
330
  <ReviewContext.Provider value={review}>
301
331
  <OpenChangeRequestsContext.Provider
302
332
  value={{
303
- paths: new Set(changeRequests.length ? [filePath] : []),
333
+ paths: new Set(changeRequests.length && filePath ? [filePath] : []),
304
334
  minePaths: new Map(),
305
335
  mineNumbers: new Set<number>(),
306
336
  forPath: (p) =>
@@ -321,11 +351,18 @@ function ViewerHarness({
321
351
  Inject pending
322
352
  </button>
323
353
  <FileViewer />
354
+ <LocationEcho />
324
355
  </OpenChangeRequestsContext.Provider>
325
356
  </ReviewContext.Provider>
326
357
  </GitContext.Provider>
327
358
  </WorkspaceContext.Provider>
328
359
  </AuthContext.Provider>
360
+ );
361
+ return (
362
+ <MemoryRouter initialEntries={[`/workspace/${encodeURIComponent(urlBranch)}`]}>
363
+ <Routes>
364
+ <Route path="/workspace/:branch/*" element={tree} />
365
+ </Routes>
329
366
  </MemoryRouter>
330
367
  );
331
368
  }
@@ -908,3 +945,175 @@ describe('FileViewer: proposing a change without write access', () => {
908
945
  expect(screen.queryByText(/You don't have permission to edit/i)).not.toBeInTheDocument();
909
946
  });
910
947
  });
948
+
949
+ /**
950
+ * NOTHING OPEN. The first thing most people see in Knowledge, and for a long
951
+ * time it told them to go and ask an assistant a question — three canned ones
952
+ * about a "process landscape" that only rendered at all on a deployment with a
953
+ * chat surface registered, and that sent someone looking at a knowledge base
954
+ * away from the pages it holds. It offers those pages now.
955
+ */
956
+ describe('FileViewer: nothing open', () => {
957
+ const TREE: FileTreeEntry = {
958
+ name: 'knowledge-base',
959
+ relativePath: 'knowledge-base',
960
+ type: 'directory',
961
+ children: [
962
+ {
963
+ name: 'KnowledgeBase',
964
+ relativePath: 'knowledge-base/KnowledgeBase',
965
+ type: 'directory',
966
+ children: [
967
+ {
968
+ name: 'Onboarding',
969
+ relativePath: 'knowledge-base/KnowledgeBase/Onboarding',
970
+ type: 'directory',
971
+ children: [
972
+ {
973
+ name: 'Day one.md',
974
+ relativePath: 'knowledge-base/KnowledgeBase/Onboarding/Day one.md',
975
+ type: 'file',
976
+ },
977
+ ],
978
+ },
979
+ {
980
+ name: 'Handbook.md',
981
+ relativePath: 'knowledge-base/KnowledgeBase/Handbook.md',
982
+ type: 'file',
983
+ },
984
+ {
985
+ name: 'logo.png',
986
+ relativePath: 'knowledge-base/KnowledgeBase/logo.png',
987
+ type: 'file',
988
+ },
989
+ ],
990
+ },
991
+ {
992
+ name: 'Plugins',
993
+ relativePath: 'knowledge-base/Plugins',
994
+ type: 'directory',
995
+ children: [
996
+ {
997
+ name: 'SKILL.md',
998
+ relativePath: 'knowledge-base/Plugins/team-a/SKILL.md',
999
+ type: 'file',
1000
+ },
1001
+ ],
1002
+ },
1003
+ { name: 'access.md', relativePath: 'knowledge-base/access.md', type: 'file' },
1004
+ ],
1005
+ };
1006
+
1007
+ it('does not send the reader off to an assistant', async () => {
1008
+ render(<ViewerHarness filePath={null} fileTree={TREE} />);
1009
+ await screen.findByRole('heading', { name: /Open a page/ });
1010
+ expect(document.body.textContent).not.toMatch(/assistant/i);
1011
+ });
1012
+
1013
+ it('offers the pages nearest the top of the knowledge tree', async () => {
1014
+ render(<ViewerHarness filePath={null} fileTree={TREE} />);
1015
+ // Shallowest first, and the extension is not part of the name.
1016
+ const shallow = await screen.findByRole('button', { name: /Handbook/ });
1017
+ // One level down, labelled with the folder that tells two like-named
1018
+ // pages apart.
1019
+ const deeper = screen.getByRole('button', { name: /Day one/ });
1020
+ expect(deeper).toHaveTextContent('Onboarding');
1021
+ // "Nearest the top" is an ORDER, not just a membership: the top-level page
1022
+ // renders before the one a folder down, and a regression to depth-first
1023
+ // would flip exactly this.
1024
+ expect(
1025
+ shallow.compareDocumentPosition(deeper) & Node.DOCUMENT_POSITION_FOLLOWING,
1026
+ ).toBeTruthy();
1027
+ });
1028
+
1029
+ it('offers nothing that is not a document', async () => {
1030
+ render(<ViewerHarness filePath={null} fileTree={TREE} />);
1031
+ await screen.findByRole('button', { name: /Handbook/ });
1032
+ // An image is not a page; `Plugins/` belongs to Skills & Tools and is not a
1033
+ // browsing destination here; the loose root files configure the
1034
+ // deployment rather than saying anything.
1035
+ expect(screen.queryByRole('button', { name: /logo/ })).toBeNull();
1036
+ expect(screen.queryByRole('button', { name: /SKILL/ })).toBeNull();
1037
+ expect(screen.queryByRole('button', { name: /access/ })).toBeNull();
1038
+ });
1039
+
1040
+ /**
1041
+ * NAVIGATES, the same as clicking the file in the explorer — the URL is the
1042
+ * canonical record of what is open, so refresh/share/back land on the page
1043
+ * rather than on the empty state, and a failed load surfaces where every
1044
+ * other open's does.
1045
+ */
1046
+ it('navigates to the page it suggested', async () => {
1047
+ const addTab = vi.fn(async () => true);
1048
+ render(<ViewerHarness filePath={null} fileTree={TREE} addTab={addTab} />);
1049
+ await userEvent.click(await screen.findByRole('button', { name: /Handbook/ }));
1050
+ expect(screen.getByTestId('location')).toHaveTextContent(
1051
+ /\/workspace\/.*\/knowledge-base\/KnowledgeBase\/Handbook\.md$/,
1052
+ );
1053
+ // Through the route, not around it.
1054
+ expect(addTab).not.toHaveBeenCalled();
1055
+ });
1056
+
1057
+ /**
1058
+ * Navigation needs a branch, and git status arrives asynchronously. Until it
1059
+ * does, a suggestion click would silently do nothing — so the buttons wait,
1060
+ * visibly, instead of pretending to work.
1061
+ */
1062
+ it('waits for the branch before offering to open anything', async () => {
1063
+ render(<ViewerHarness filePath={null} fileTree={TREE} branch={null} />);
1064
+ expect(await screen.findByRole('button', { name: /Handbook/ })).toBeDisabled();
1065
+ });
1066
+
1067
+ /**
1068
+ * Mid-switch, git status still reports the branch being LEFT while the URL
1069
+ * already names the new one. Navigating on the stale value would send the
1070
+ * reader back to the branch they just left, so the offer waits — the same
1071
+ * "branch matches the route" test `FileRoute` makes before acting.
1072
+ */
1073
+ it('does not offer to open on the branch it is switching away from', async () => {
1074
+ render(
1075
+ <ViewerHarness filePath={null} fileTree={TREE} branch="alice/draft" routeBranch="main" />,
1076
+ );
1077
+ expect(await screen.findByRole('button', { name: /Handbook/ })).toBeDisabled();
1078
+ });
1079
+
1080
+ /**
1081
+ * A branch name may legitimately contain a percent sign. The router hands
1082
+ * path params over already decoded, so decoding again would read this branch
1083
+ * as `my branch`, match nothing, and disable the offers permanently for a
1084
+ * deployment on it.
1085
+ */
1086
+ it('offers pages on a branch whose name contains a percent sign', async () => {
1087
+ render(<ViewerHarness filePath={null} fileTree={TREE} branch="my%20branch" />);
1088
+ expect(await screen.findByRole('button', { name: /Handbook/ })).toBeEnabled();
1089
+ });
1090
+
1091
+ /** A knowledge base with nothing in it has nothing to suggest, and says so. */
1092
+ it('promises nothing when there is nothing to open', async () => {
1093
+ render(<ViewerHarness filePath={null} fileTree={null} />);
1094
+ await screen.findByRole('heading', { name: /Open a page/ });
1095
+ expect(screen.getByText('Pick anything from the file tree.')).toBeInTheDocument();
1096
+ });
1097
+
1098
+ /**
1099
+ * A clone that predates the `KnowledgeBase/` split has no named roots to
1100
+ * scope to — the whole tree is the knowledge, and reading none of it because
1101
+ * a folder is missing would be the wrong answer.
1102
+ */
1103
+ it('reads the whole tree when there are no named roots', async () => {
1104
+ render(
1105
+ <ViewerHarness
1106
+ filePath={null}
1107
+ fileTree={{
1108
+ name: 'knowledge-base',
1109
+ relativePath: 'knowledge-base',
1110
+ type: 'directory',
1111
+ children: [
1112
+ { name: 'Charter.md', relativePath: 'knowledge-base/Charter.md', type: 'file' },
1113
+ ],
1114
+ }}
1115
+ />,
1116
+ );
1117
+ expect(await screen.findByRole('button', { name: /Charter/ })).toBeInTheDocument();
1118
+ });
1119
+ });
@@ -86,6 +86,31 @@ describe('useFileNav.openFile', () => {
86
86
  );
87
87
  });
88
88
 
89
+ it('treats # in a filename as part of the path when told it IS a path', () => {
90
+ navigateMock.mockClear();
91
+ const { result } = renderNav('alice/draft');
92
+ // `openFile` parses link-shaped input, so `#` means "anchor" there.
93
+ // `openWorkspacePath` is for real tree paths, where `#` is a character in
94
+ // a filename and must be encoded, not split off.
95
+ result.current.openWorkspacePath('knowledge-base/Knowledge/Q#A.md');
96
+ expect(navigateMock).toHaveBeenCalledWith(
97
+ '/workspace/alice%2Fdraft/knowledge-base/Knowledge/Q%23A.md',
98
+ );
99
+ });
100
+
101
+ it('opens a tree path verbatim even when a folder inside it is named like the kbDirName', () => {
102
+ navigateMock.mockClear();
103
+ const { result } = renderNav('alice/draft');
104
+ // A tree whose root is not the KB dir, holding a folder that happens to be
105
+ // named like it. The junk-segment repair drops everything before that
106
+ // segment, rewriting this to `knowledge-base/notes.md` — a different file.
107
+ // A path that came from the tree is already correct and needs no repair.
108
+ result.current.openWorkspacePath('Knowledge/knowledge-base/notes.md');
109
+ expect(navigateMock).toHaveBeenCalledWith(
110
+ '/workspace/alice%2Fdraft/Knowledge/knowledge-base/notes.md',
111
+ );
112
+ });
113
+
89
114
  it('leaves a well-formed path untouched and ignores a kbDirName substring match', () => {
90
115
  navigateMock.mockClear();
91
116
  const { result } = renderNav('alice/draft');
@@ -218,12 +218,34 @@ export function useFileNav() {
218
218
  [branch, kbDirName, navigate],
219
219
  );
220
220
 
221
+ /**
222
+ * Navigate to a KNOWN workspace-relative path, verbatim. `openFile` parses
223
+ * link-shaped input — it splits off `#heading` anchors and unwraps absolute
224
+ * workspace URLs — which is right for hrefs and wrong for a path that came
225
+ * from the file tree, where `#` is just a character in a filename. Callers
226
+ * holding a real path (suggestions, explorers) use this; callers holding a
227
+ * link destination keep `openFile`.
228
+ *
229
+ * VERBATIM means verbatim: no `stripJunkBeforeKbDir` either. That repair
230
+ * exists for paths an LLM may have mangled, and it rewrites any path whose
231
+ * later segment happens to equal `kbDirName` — which a real folder inside
232
+ * the tree is allowed to be. A path that came from the tree needs no
233
+ * repair, so applying one could only ever open the wrong file.
234
+ */
235
+ const openWorkspacePath = useCallback(
236
+ (path: string) => {
237
+ if (!branch) return;
238
+ navigate(kbFileUrl(branch, path));
239
+ },
240
+ [branch, navigate],
241
+ );
242
+
221
243
  const closeFile = useCallback(() => {
222
244
  if (!branch) return;
223
245
  navigate(kbFileUrl(branch));
224
246
  }, [branch, navigate]);
225
247
 
226
- return { openFile, closeFile };
248
+ return { openFile, openWorkspacePath, closeFile };
227
249
  }
228
250
 
229
251
  /**
@@ -42,6 +42,57 @@ export function findKbRoot(node: FileTreeEntry | null): FileTreeEntry | null {
42
42
  return null;
43
43
  }
44
44
 
45
+ /** Documents, as opposed to the data, config and archives beside them. */
46
+ const READABLE_PAGE = /\.(md|markdown)$/i;
47
+
48
+ /**
49
+ * Pages worth offering to someone who has nothing open: the documents nearest
50
+ * the top of the knowledge tree, breadth-first, so the opening suggestion is a
51
+ * section heading rather than the fifth file inside the first folder.
52
+ *
53
+ * Scoped to exactly what the explorer browses under "Knowledge" —
54
+ * `KnowledgeBase/` plus any stray content folder. `Plugins/` is the Skills &
55
+ * Tools app's storage and is not a browsing destination here, and the loose
56
+ * files at the root (`access.md`, `roles.yaml`) are how the deployment is
57
+ * configured, not something to read. A clone that predates the split has no
58
+ * named roots to scope to, so its whole tree is the knowledge.
59
+ *
60
+ * Fewer than `limit` — including none at all — is a legitimate answer for a
61
+ * knowledge base that is still empty; the caller says so rather than padding.
62
+ */
63
+ export function suggestedPages(tree: FileTreeEntry | null, limit: number): FileTreeEntry[] {
64
+ const kbRoot = findKbRoot(tree);
65
+ const roots = kbRoot?.children
66
+ ? [
67
+ ...kbRoot.children.filter((c) => c.type === 'directory' && c.name === KNOWLEDGE_BASE_DIR),
68
+ ...kbRoot.children.filter((c) => c.type === 'directory' && !KB_ROOT_DIRS.has(c.name)),
69
+ ]
70
+ : tree
71
+ ? [tree]
72
+ : [];
73
+
74
+ const pages: FileTreeEntry[] = [];
75
+ let level = roots;
76
+ while (level.length > 0 && pages.length < limit) {
77
+ const next: FileTreeEntry[] = [];
78
+ for (const entry of level) {
79
+ // Enough pages is enough work: without this, the last level scanned is
80
+ // walked to its end — every remaining sibling tested and pushed — for
81
+ // pages the final slice would throw away.
82
+ if (pages.length >= limit) break;
83
+ // Dot-prefixed entries are the repository's own bookkeeping.
84
+ if (entry.name.startsWith('.')) continue;
85
+ if (entry.type === 'file') {
86
+ if (READABLE_PAGE.test(entry.name)) pages.push(entry);
87
+ } else if (entry.name !== PLUGINS_DIR) {
88
+ next.push(...(entry.children ?? []));
89
+ }
90
+ }
91
+ level = next;
92
+ }
93
+ return pages.slice(0, limit);
94
+ }
95
+
45
96
  function findEntryByPath(tree: FileTreeEntry | null, relativePath: string): FileTreeEntry | null {
46
97
  if (!tree) return null;
47
98
  if (tree.relativePath === relativePath) return tree;