@bevel-software/platform-core-frontend 0.33.0 → 0.34.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 (59) hide show
  1. package/package.json +2 -2
  2. package/src/lib/__tests__/api.test.ts +28 -1
  3. package/src/lib/api.ts +4 -2
  4. package/src/modules/access/__tests__/ManageAccessDialog.add-row-picking.test.tsx +53 -1
  5. package/src/modules/access/api.ts +3 -4
  6. package/src/modules/access/components/ManageAccessDialog.tsx +7 -7
  7. package/src/modules/admin/__tests__/DirectoryGroupsPage.test.tsx +51 -0
  8. package/src/modules/admin/components/DirectoryGroupsPage.tsx +42 -5
  9. package/src/modules/admin/services/groups.api.ts +11 -1
  10. package/src/modules/agents/__tests__/useConnectAsChoice.test.ts +56 -0
  11. package/src/modules/agents/components/ConnectAsChoice.tsx +81 -0
  12. package/src/modules/agents/connect-as.ts +15 -0
  13. package/src/modules/agents/index.ts +5 -0
  14. package/src/modules/agents/services/agent-choices.api.ts +39 -0
  15. package/src/modules/agents/useConnectAsChoice.ts +66 -0
  16. package/src/modules/audit/__tests__/AuditLogPage.test.tsx +13 -0
  17. package/src/modules/audit/components/AuditLogPage.tsx +9 -0
  18. package/src/modules/audit/services/audit.api.ts +5 -0
  19. package/src/modules/auth/__tests__/AccountPage.test.tsx +21 -0
  20. package/src/modules/auth/__tests__/account.api.test.ts +69 -0
  21. package/src/modules/auth/components/AccountPage.tsx +8 -2
  22. package/src/modules/auth/services/account.api.ts +18 -2
  23. package/src/modules/git/__tests__/BranchSwitcher.test.tsx +0 -14
  24. package/src/modules/git/__tests__/git.api.test.ts +2 -2
  25. package/src/modules/git/hooks/__tests__/useGitState.deleteBranch.test.tsx +1 -1
  26. package/src/modules/library/__tests__/SkillPage.test.tsx +229 -24
  27. package/src/modules/library/components/skill-page/SkillFilePane.tsx +57 -9
  28. package/src/modules/library/components/skill-page/SkillPage.tsx +65 -25
  29. package/src/modules/review/components/MarkdownDiffViewer.tsx +23 -1
  30. package/src/modules/review/components/ReviewPanel.tsx +8 -2
  31. package/src/modules/review/components/__tests__/MarkdownDiffViewer.test.tsx +31 -0
  32. package/src/modules/secrets-vault/components/ConnectToolsPage.tsx +79 -16
  33. package/src/modules/secrets-vault/components/__tests__/ConnectToolsPage.test.tsx +112 -2
  34. package/src/modules/secrets-vault/services/connect.api.ts +20 -5
  35. package/src/modules/toolbar/components/ExternalAgentAccessPage.tsx +38 -4
  36. package/src/modules/toolbar/components/__tests__/ExternalAgentAccessPage.test.tsx +91 -2
  37. package/src/modules/toolbar/services/external-api-keys.api.ts +5 -2
  38. package/src/modules/workspace/components/__tests__/FileExplorer.test.tsx +26 -0
  39. package/src/modules/workspace/components/renderers/HtmlRenderer.tsx +40 -7
  40. package/src/modules/workspace/components/renderers/KbAppLink.tsx +56 -0
  41. package/src/modules/workspace/components/renderers/KbMarkdownView.tsx +30 -10
  42. package/src/modules/workspace/components/renderers/MarkdownRenderer.tsx +37 -40
  43. package/src/modules/workspace/components/renderers/__tests__/HtmlRenderer.links.test.tsx +185 -0
  44. package/src/modules/workspace/components/renderers/__tests__/MarkdownRenderer.sectionReclick.test.tsx +88 -0
  45. package/src/modules/workspace/components/renderers/__tests__/MarkdownRenderer.test.tsx +199 -29
  46. package/src/modules/workspace/components/renderers/__tests__/bridgeHarness.ts +37 -4
  47. package/src/modules/workspace/components/renderers/__tests__/htmlSandbox.test.ts +59 -0
  48. package/src/modules/workspace/components/renderers/__tests__/htmlViewsGuide.test.ts +15 -1
  49. package/src/modules/workspace/components/renderers/__tests__/liveDataReferencePage.test.ts +397 -0
  50. package/src/modules/workspace/components/renderers/htmlSandbox.ts +48 -15
  51. package/src/modules/workspace/components/renderers/htmlToolBridge.ts +19 -0
  52. package/src/modules/workspace/components/renderers/kbMarkdownPipeline.tsx +35 -28
  53. package/src/modules/workspace/components/renderers/scrollToHeading.ts +35 -0
  54. package/src/modules/workspace/hooks/__tests__/useLinksOut.test.ts +6 -0
  55. package/src/modules/workspace/hooks/useLinksOut.ts +12 -6
  56. package/src/modules/workspace/index.ts +21 -2
  57. package/src/modules/workspace/routing/__tests__/kb-routes.test.tsx +262 -25
  58. package/src/modules/workspace/routing/kb-routes.ts +221 -53
  59. package/src/modules/workspace/utils/fileTree.ts +1 -1
@@ -177,6 +177,19 @@ describe('AuditLogPage', () => {
177
177
  expect(screen.queryByRole('button', { name: /Revoke key for Old script/ })).not.toBeInTheDocument();
178
178
  });
179
179
 
180
+ it('shows what each connection and key connects as: Everything, or the agent file it was made as', async () => {
181
+ vi.mocked(listPrincipals).mockResolvedValue([
182
+ { ...ALICE_CLAUDE, agentPath: 'Agents/delivery-mechanic.agent' },
183
+ { ...ALICE_CI, agentPath: null },
184
+ ]);
185
+ renderPage({ isAdmin: true });
186
+ await waitFor(() => expect(screen.getByText('CI pipeline')).toBeInTheDocument());
187
+ const rowOf = (label: string) => screen.getByText(label).closest('li') as HTMLElement;
188
+ expect(rowOf('Claude')).toHaveTextContent('As delivery-mechanic');
189
+ expect(within(rowOf('Claude')).getByTitle('Agents/delivery-mechanic.agent')).toBeInTheDocument();
190
+ expect(rowOf('CI pipeline')).toHaveTextContent('As Everything');
191
+ });
192
+
180
193
  it('shows an admin a key its owner deleted for good, marked as such, with its history intact', async () => {
181
194
  vi.mocked(listPrincipals).mockResolvedValue([{ ...BOB_OLD, deletedAt: NOW - 10 * DAY, eventCount: 18 }]);
182
195
  renderPage({ isAdmin: true });
@@ -8,6 +8,7 @@ import { GITHUB_LINK_KIND } from '../../../shared/marketplace-url';
8
8
  import { useAdmin } from '../../admin';
9
9
  import { useAuth } from '../../auth';
10
10
  import { listPrincipals, revokeAgent, revokeKey, type AuditPrincipal } from '../services/audit.api';
11
+ import { connectedAsLabel } from '../../agents';
11
12
  import { groupByAccount, principalKey } from './principal-grouping';
12
13
  import { AuditEventsPanel } from './AuditEventsPanel';
13
14
 
@@ -276,6 +277,14 @@ export function AuditLogPage() {
276
277
  {p.deletedAt != null && <Badge tone="outline">Deleted by owner</Badge>}
277
278
  </span>
278
279
  <span className="block text-meta text-ink-muted">
280
+ {/* What the connection loads: Everything, or the agent configuration it
281
+ was made as. A page acts as its viewer, so it has none. */}
282
+ {p.kind !== 'page' && (
283
+ <>
284
+ <span title={p.agentPath ?? undefined}>As {connectedAsLabel(p.agentPath)}</span>
285
+ {' · '}
286
+ </>
287
+ )}
279
288
  <span title={formatAbsolute(p.createdAt)}>
280
289
  {p.kind === 'agent' ? 'Connected' : p.kind === 'page' ? 'First call' : 'Created'}{' '}
281
290
  {formatRelative(p.createdAt)}
@@ -29,6 +29,11 @@ export interface AuditPrincipal {
29
29
  /** Events on record for it. */
30
30
  eventCount: number;
31
31
  user: { id: string; email: string; name: string };
32
+ /**
33
+ * For a key or an agent: the agent configuration it connects as (a knowledge-base
34
+ * path), or null for Everything. Absent for a page.
35
+ */
36
+ agentPath?: string | null;
32
37
  }
33
38
 
34
39
  export type AgentEventKind = 'capability' | 'tool' | 'skill';
@@ -75,6 +75,27 @@ describe('AccountPage', () => {
75
75
  await userEvent.click(screen.getByRole('button', { name: 'Change password' }));
76
76
  expect(await screen.findByRole('alert')).toHaveTextContent('Current password is incorrect');
77
77
  });
78
+
79
+ it('disables the submit while a change is in flight, and sends one change for a double click', async () => {
80
+ let finish!: () => void;
81
+ vi.mocked(changePassword).mockImplementation(
82
+ () => new Promise<void>((resolve) => (finish = resolve)),
83
+ );
84
+ renderPage();
85
+ await userEvent.type(screen.getByLabelText(/Current password/), 'old-password');
86
+ await userEvent.type(screen.getByLabelText(/New password/), 'new-password-1');
87
+ await userEvent.type(screen.getByLabelText(/Confirm new password/), 'new-password-1');
88
+ await userEvent.dblClick(screen.getByRole('button', { name: 'Change password' }));
89
+ // A second submit straight from the form, as a click landing before the
90
+ // disabled button rendered would be.
91
+ screen.getByRole('button', { name: 'Saving…' }).closest('form')!.requestSubmit();
92
+ expect(screen.getByRole('button', { name: 'Saving…' })).toBeDisabled();
93
+ expect(changePassword).toHaveBeenCalledTimes(1);
94
+
95
+ finish();
96
+ expect(await screen.findByRole('status')).toHaveTextContent('Password changed.');
97
+ expect(screen.getByRole('button', { name: 'Change password' })).toBeEnabled();
98
+ });
78
99
  });
79
100
 
80
101
  /**
@@ -0,0 +1,69 @@
1
+ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
2
+ import { changePassword } from '../services/account.api';
3
+ import { authFetch, getToken, setToken } from '../../../lib/api';
4
+
5
+ /**
6
+ * A password change ends every session opened before it, the changer's old
7
+ * token included, so the page keeps working only if the token the change
8
+ * hands back is what the NEXT request carries. Only `fetch` is stubbed: the
9
+ * real `changePassword` and `authFetch` read and write the stored token.
10
+ */
11
+ describe('changePassword and the token it hands back', () => {
12
+ beforeEach(() => {
13
+ localStorage.clear();
14
+ });
15
+
16
+ afterEach(() => {
17
+ vi.restoreAllMocks();
18
+ localStorage.clear();
19
+ });
20
+
21
+ it('authenticates the next request with the replacement token', async () => {
22
+ setToken('token-before-the-change');
23
+ const fetchMock = vi
24
+ .spyOn(globalThis, 'fetch')
25
+ .mockResolvedValueOnce(new Response(JSON.stringify({ ok: true, token: 'token-after-the-change' }), { status: 200 }))
26
+ .mockResolvedValueOnce(new Response(JSON.stringify({ user: {} }), { status: 200 }));
27
+
28
+ await changePassword('old-password-1', 'new-password-1');
29
+ await authFetch('/api/auth/me');
30
+
31
+ const authorization = (call: number) =>
32
+ new Headers((fetchMock.mock.calls[call][1] as RequestInit).headers).get('Authorization');
33
+ expect(authorization(0)).toBe('Bearer token-before-the-change');
34
+ expect(authorization(1)).toBe('Bearer token-after-the-change');
35
+ expect(getToken()).toBe('token-after-the-change');
36
+ });
37
+
38
+ it('keeps a sign-in another tab made while the change was in flight, rather than overwriting it', async () => {
39
+ setToken('token-before-the-change');
40
+ vi.spyOn(globalThis, 'fetch').mockImplementationOnce(async () => {
41
+ // The other tab signs in as someone else before this response arrives.
42
+ setToken('other-account-token');
43
+ return new Response(JSON.stringify({ ok: true, token: 'token-after-the-change' }), { status: 200 });
44
+ });
45
+
46
+ await changePassword('old-password-1', 'new-password-1');
47
+ expect(getToken()).toBe('other-account-token');
48
+ });
49
+
50
+ it('keeps the stored token when a success answer carries no token, rather than storing "undefined"', async () => {
51
+ setToken('token-before-the-change');
52
+ vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(new Response(JSON.stringify({ ok: true }), { status: 200 }));
53
+
54
+ await changePassword('old-password-1', 'new-password-1');
55
+ expect(getToken()).toBe('token-before-the-change');
56
+ });
57
+
58
+ it('keeps the stored token when the change is refused', async () => {
59
+ setToken('token-before-the-change');
60
+ vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(
61
+ new Response(JSON.stringify({ error: 'Your password was changed from another session; nothing was changed.' }), {
62
+ status: 409,
63
+ }),
64
+ );
65
+
66
+ await expect(changePassword('old-password-1', 'new-password-1')).rejects.toThrow(/another session/);
67
+ expect(getToken()).toBe('token-before-the-change');
68
+ });
69
+ });
@@ -1,4 +1,4 @@
1
- import { useState, type FormEvent } from 'react';
1
+ import { useRef, useState, type FormEvent } from 'react';
2
2
  import { PageShell } from '../../../shared/components/PageShell';
3
3
  import { useAuth } from '../state/auth.context';
4
4
  import { changePassword } from '../services/account.api';
@@ -25,15 +25,20 @@ export function AccountPage() {
25
25
  const [error, setError] = useState<string | null>(null);
26
26
  const [saved, setSaved] = useState(false);
27
27
  const [submitting, setSubmitting] = useState(false);
28
+ // Set synchronously, so a second click landing before the disabled button
29
+ // renders is dropped too: one change at a time, never two racing.
30
+ const inFlight = useRef(false);
28
31
 
29
32
  async function handleSubmit(e: FormEvent<HTMLFormElement>) {
30
33
  e.preventDefault();
34
+ if (inFlight.current) return;
31
35
  setError(null);
32
36
  setSaved(false);
33
37
  if (newPassword !== confirmPassword) {
34
38
  setError('New passwords do not match');
35
39
  return;
36
40
  }
41
+ inFlight.current = true;
37
42
  setSubmitting(true);
38
43
  try {
39
44
  await changePassword(currentPassword || undefined, newPassword);
@@ -44,6 +49,7 @@ export function AccountPage() {
44
49
  } catch (err) {
45
50
  setError(err instanceof Error ? err.message : 'Could not change password');
46
51
  } finally {
52
+ inFlight.current = false;
47
53
  setSubmitting(false);
48
54
  }
49
55
  }
@@ -113,7 +119,7 @@ export function AccountPage() {
113
119
  )}
114
120
  {saved && (
115
121
  <div className="text-sm text-emerald-700" role="status">
116
- Password changed.
122
+ Password changed. Every other session has been signed out.
117
123
  </div>
118
124
  )}
119
125
 
@@ -1,4 +1,4 @@
1
- import { authFetch } from '../../../lib/api';
1
+ import { authFetch, getToken, setToken } from '../../../lib/api';
2
2
 
3
3
  /** One row of the admin Accounts list (`GET /api/admin/accounts`). */
4
4
  export interface AccountSummary {
@@ -48,17 +48,33 @@ async function readError(res: Response, fallback: string): Promise<string> {
48
48
  return (body as { error?: string }).error || fallback;
49
49
  }
50
50
 
51
- /** Self-service password change. `currentPassword` is required once one is set. */
51
+ /**
52
+ * Self-service password change. `currentPassword` is required once one is set.
53
+ * The change ends every session opened before it, this one's included, so the
54
+ * fresh token the server hands back replaces the stored one — but only the
55
+ * one this request sent: the stored token is one key shared by every tab, and
56
+ * a tab that signed in as someone else while this request was in flight has
57
+ * replaced it already. That sign-in is kept; this change's token belongs to
58
+ * a session that tab no longer has.
59
+ */
52
60
  export async function changePassword(
53
61
  currentPassword: string | undefined,
54
62
  newPassword: string,
55
63
  ): Promise<void> {
64
+ const sent = getToken();
56
65
  const res = await authFetch('/api/auth/change-password', {
57
66
  method: 'POST',
58
67
  headers: { 'Content-Type': 'application/json' },
59
68
  body: JSON.stringify({ currentPassword, newPassword }),
60
69
  });
61
70
  if (!res.ok) throw new Error(await readError(res, 'Could not change password'));
71
+ const body = (await res.json().catch(() => ({}))) as { token?: unknown };
72
+ // The change is written by now. Only a token the server actually handed
73
+ // back replaces the stored one: an answer without one (a replica from
74
+ // before the change handed tokens back, mid-deploy) must not turn the
75
+ // stored token into the string "undefined" and sign the person out.
76
+ const token = typeof body.token === 'string' && body.token ? body.token : null;
77
+ if (token && getToken() === sent) setToken(token);
62
78
  }
63
79
 
64
80
  export async function listAccounts(): Promise<AccountSummary[]> {
@@ -219,8 +219,6 @@ describe('BranchSwitcher: author-can-delete affordance', () => {
219
219
  {
220
220
  name: 'alice/my-draft',
221
221
  isProtected: false,
222
- ahead: 0,
223
- behind: 0,
224
222
  hasRemote: true,
225
223
  },
226
224
  ]));
@@ -239,8 +237,6 @@ describe('BranchSwitcher: author-can-delete affordance', () => {
239
237
  {
240
238
  name: 'bob/other-draft',
241
239
  isProtected: false,
242
- ahead: 0,
243
- behind: 0,
244
240
  hasRemote: true,
245
241
  },
246
242
  ]));
@@ -260,8 +256,6 @@ describe('BranchSwitcher: author-can-delete affordance', () => {
260
256
  {
261
257
  name: 'bob/merged-and-pruned',
262
258
  isProtected: false,
263
- ahead: 0,
264
- behind: 0,
265
259
  hasRemote: false,
266
260
  },
267
261
  ]));
@@ -307,8 +301,6 @@ describe('BranchSwitcher: admin-can-delete affordance', () => {
307
301
  {
308
302
  name: 'bob/other-draft',
309
303
  isProtected: false,
310
- ahead: 0,
311
- behind: 0,
312
304
  hasRemote: true,
313
305
  },
314
306
  ]));
@@ -326,8 +318,6 @@ describe('BranchSwitcher: admin-can-delete affordance', () => {
326
318
  {
327
319
  name: 'fix/some-cli-branch',
328
320
  isProtected: false,
329
- ahead: 0,
330
- behind: 0,
331
321
  hasRemote: true,
332
322
  },
333
323
  ]));
@@ -344,8 +334,6 @@ describe('BranchSwitcher: admin-can-delete affordance', () => {
344
334
  {
345
335
  name: 'current-company-state',
346
336
  isProtected: true,
347
- ahead: 0,
348
- behind: 0,
349
337
  hasRemote: true,
350
338
  },
351
339
  ]));
@@ -369,8 +357,6 @@ describe('BranchSwitcher: deleting a shared branch asks in the app', () => {
369
357
  const shared = (name: string): BranchInfo => ({
370
358
  name,
371
359
  isProtected: false,
372
- ahead: 0,
373
- behind: 0,
374
360
  hasRemote: true,
375
361
  });
376
362
 
@@ -46,7 +46,7 @@ describe('git.api', () => {
46
46
  it('fetchBranches returns the array body', async () => {
47
47
  fetchMock.mockResolvedValueOnce(
48
48
  ok([
49
- { name: 'current-company-state', isCurrent: true, isProtected: true, ahead: 0, behind: 0 },
49
+ { name: 'current-company-state', isCurrent: true, isProtected: true },
50
50
  ]),
51
51
  );
52
52
  const bs = await fetchBranches('ws-1');
@@ -56,7 +56,7 @@ describe('git.api', () => {
56
56
 
57
57
  it('createBranch POSTs JSON body', async () => {
58
58
  fetchMock.mockResolvedValueOnce(
59
- ok({ name: 'feature/x', isCurrent: false, isProtected: false, ahead: null, behind: null }),
59
+ ok({ name: 'feature/x', isCurrent: false, isProtected: false }),
60
60
  );
61
61
  await createBranch('ws-1', 'feature/x');
62
62
  const [, init] = fetchMock.mock.calls[0];
@@ -34,7 +34,7 @@ const mockFetchStatus = vi.mocked(fetchStatus);
34
34
  const mockDeleteBranch = vi.mocked(apiDeleteBranch);
35
35
 
36
36
  function mkBranch(name: string): BranchInfo {
37
- return { name, isProtected: false, ahead: 0, behind: 0, hasRemote: true };
37
+ return { name, isProtected: false, hasRemote: true };
38
38
  }
39
39
 
40
40
  describe('useGitState: optimistic deleteBranch', () => {
@@ -1,4 +1,4 @@
1
- import { describe, it, expect, vi, beforeEach } from 'vitest';
1
+ import { describe, it, expect, vi, beforeEach, afterEach, type MockInstance } from 'vitest';
2
2
  import { useContext } from 'react';
3
3
  import { render, screen, fireEvent, waitFor, act, within } from '@testing-library/react';
4
4
  import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom';
@@ -34,7 +34,9 @@ const apiMock = vi.hoisted(() => ({
34
34
  * callback the pane only reaches through an HTML page's frame (Open in the
35
35
  * platform). The pane itself renders as it always does.
36
36
  */
37
- const paneProps = vi.hoisted(() => ({ last: null as null | { onOpenInPlatform?: () => void } }));
37
+ const paneProps = vi.hoisted(() => ({
38
+ last: null as null | { onOpenInPlatform?: () => void; linkHome?: { path: string; branch: string } },
39
+ }));
38
40
  vi.mock('../components/skill-page/SkillFilePane', async (importOriginal) => {
39
41
  const real = await importOriginal<typeof import('../components/skill-page/SkillFilePane')>();
40
42
  return {
@@ -88,24 +90,53 @@ vi.mock('../../pr/services/pr-detail.api', () => ({ fetchPrDetail: apiMock.fetch
88
90
  vi.mock('../../pr/services/pr-approvals.api', () => ({ approvePrFile: apiMock.approvePrFile }));
89
91
 
90
92
  // Keep the markdown pipeline (mermaid etc.) out of this test — the stub renders
91
- // the raw source so assertions can see the body text, plus two probes for the
92
- // wiring the page hands the view: a click on a percent-encoded link, and what
93
+ // the raw source so assertions can see the body text, plus probes for the
94
+ // wiring the page hands the view: a click on a link (another file, and a
95
+ // section of this one), where the page says such a link leads, and what
93
96
  // the image resolver answers for a picture beside the file.
94
97
  vi.mock('../../workspace/components/renderers/KbMarkdownView', () => ({
95
98
  KbMarkdownView: ({
96
99
  source,
97
100
  onOpenFile,
101
+ fileLinkTarget,
102
+ onOpenNodeId,
103
+ nodeIdLinkTarget,
98
104
  resolveImage,
99
105
  }: {
100
106
  source: string;
101
107
  onOpenFile: (href: string) => void;
108
+ fileLinkTarget?: (href: string) => unknown;
109
+ onOpenNodeId?: (id: string) => void;
110
+ nodeIdLinkTarget?: (id: string) => unknown;
102
111
  resolveImage?: (src: string) => unknown;
103
112
  }) => (
104
113
  <div data-testid="md-view">
105
114
  {source}
115
+ <h2 id="steps">Steps</h2>
106
116
  <button type="button" onClick={() => onOpenFile('Some%20File.md')}>
107
117
  link-probe
108
118
  </button>
119
+ <button type="button" onClick={() => onOpenFile('SKILL.md#steps')}>
120
+ section-probe
121
+ </button>
122
+ <button type="button" onClick={() => onOpenNodeId?.('newsletter#steps')}>
123
+ self-id-probe
124
+ </button>
125
+ <button type="button" onClick={() => onOpenNodeId?.('plan-node#goal')}>
126
+ other-id-probe
127
+ </button>
128
+ <span data-testid="other-id-target-probe">
129
+ {JSON.stringify(nodeIdLinkTarget ? nodeIdLinkTarget('plan-node#goal') : 'no-target')}
130
+ </span>
131
+ <span data-testid="self-id-target-probe">
132
+ {JSON.stringify(nodeIdLinkTarget ? nodeIdLinkTarget('newsletter#steps') : 'no-target')}
133
+ </span>
134
+ <span data-testid="link-target-probe">
135
+ {JSON.stringify(fileLinkTarget ? fileLinkTarget('Some%20File.md') : 'no-target')}
136
+ </span>
137
+ <span data-testid="section-target-probe">
138
+ {JSON.stringify(fileLinkTarget ? fileLinkTarget('SKILL.md#steps') : 'no-target')}
139
+ </span>
109
140
  <span data-testid="image-probe">
110
141
  {JSON.stringify(resolveImage ? resolveImage('./assets/shot.png') : 'no-resolver')}
111
142
  </span>
@@ -385,11 +416,13 @@ function harness(
385
416
  routerState?: Record<string, unknown>,
386
417
  pageProps?: { provisional?: boolean },
387
418
  workspaceValue: WorkspaceContextValue = workspace,
419
+ /** The fragment the page's address arrives with, e.g. `#steps`. */
420
+ hash = '',
388
421
  ) {
389
422
  return (
390
423
  <MemoryRouter
391
424
  initialEntries={[
392
- { pathname: '/skills-and-tools/skills/newsletter', state: routerState ?? null },
425
+ { pathname: '/skills-and-tools/skills/newsletter', hash, state: routerState ?? null },
393
426
  ]}
394
427
  >
395
428
  <AuthContext.Provider value={auth}>
@@ -430,6 +463,27 @@ allowed-tools: [slack_post_message]
430
463
  Collect the news and draft the letter.`;
431
464
  const RAW_BRANCH = RAW_MAIN.replace('draft the letter', 'ship the letter');
432
465
 
466
+ /**
467
+ * The node id of the file in the pane, as the backend answers it for the
468
+ * default branch (`resolve-path`): SKILL.md is the node `newsletter`, and
469
+ * no other file of the skill is a node. Every other request goes to the real
470
+ * fetch, as it always has.
471
+ */
472
+ let resolvePathSpy: MockInstance<typeof fetch>;
473
+ beforeEach(() => {
474
+ const realFetch = globalThis.fetch;
475
+ resolvePathSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => {
476
+ const url = String(input);
477
+ if (!url.includes('/resolve-path?')) return realFetch(input, init);
478
+ return url.includes(encodeURIComponent('knowledge-base/Skills/newsletter/SKILL.md'))
479
+ ? new Response(JSON.stringify({ id: 'newsletter' }), { status: 200 })
480
+ : new Response('{}', { status: 404 });
481
+ });
482
+ });
483
+ afterEach(() => {
484
+ resolvePathSpy.mockRestore();
485
+ });
486
+
433
487
  beforeEach(() => {
434
488
  apiMock.getSkill.mockReset().mockResolvedValue(skillDetail);
435
489
  apiMock.getSkillFile.mockReset().mockResolvedValue('watchlist:\n - topic: AI');
@@ -476,15 +530,29 @@ describe('SkillPage', () => {
476
530
  expect(await screen.findByTestId('navigated-to')).toHaveTextContent(/^\/skills-and-tools\/connect$/);
477
531
  });
478
532
 
479
- it("opens a page of the skill on the Knowledge file page, not back on this page, for Open in the platform", async () => {
480
- renderPage(true);
481
- await settled();
482
- expect(paneProps.last?.onOpenInPlatform).toBeTypeOf('function');
483
- act(() => paneProps.last!.onOpenInPlatform!());
484
- // The file's own address, with the state that makes the item route show
485
- // the file route rather than this skill page again.
486
- expect(await screen.findByTestId('navigated-to')).toHaveTextContent(/^\/workspace\/[^/]+\/knowledge-base\/Skills\/newsletter\/SKILL\.md$/);
487
- expect(screen.getByTestId('navigated-raw-file')).toHaveTextContent('true');
533
+ it("opens a page of the skill on the Knowledge file page in a new tab, not back on this page, for Open in the platform", async () => {
534
+ const open = vi
535
+ .spyOn(window, 'open')
536
+ .mockImplementation(() => ({ opener: window }) as unknown as Window);
537
+ try {
538
+ renderPage(true);
539
+ await settled();
540
+ expect(paneProps.last?.onOpenInPlatform).toBeTypeOf('function');
541
+ act(() => paneProps.last!.onOpenInPlatform!());
542
+ // The file page's own address on the default branch — the query is what
543
+ // makes the item route show the file route rather than this skill page
544
+ // again, since a new tab carries no router state.
545
+ expect(open).toHaveBeenCalledTimes(1);
546
+ expect(open).toHaveBeenCalledWith(
547
+ `/workspace/${encodeURIComponent(DEFAULT_BRANCH)}/knowledge-base/Skills/newsletter/SKILL.md?as=file`,
548
+ '_blank',
549
+ );
550
+ // And this tab stayed on the skill page.
551
+ expect(screen.queryByTestId('navigated-to')).toBeNull();
552
+ expect(screen.getByRole('heading', { name: 'newsletter' })).toBeInTheDocument();
553
+ } finally {
554
+ open.mockRestore();
555
+ }
488
556
  });
489
557
 
490
558
  /**
@@ -1574,18 +1642,155 @@ describe('SkillPage: deciding on a change', () => {
1574
1642
  * is under test is what the PAGE hands the view.
1575
1643
  */
1576
1644
  describe('SkillPage: links and images in the file', () => {
1577
- it('opens a percent-encoded link as the file it names, on the default branch', async () => {
1578
- // The drift this fixes: the page used to resolve the href undecoded, so a
1579
- // link written `Some File.md` opened `Some%20File.md`, a file that is not there.
1645
+ const SOME_FILE_URL = `/workspace/${encodeURIComponent(DEFAULT_BRANCH)}/knowledge-base/Skills/newsletter/Some%20File.md`;
1646
+
1647
+ it('opens a link to another file in a new tab, as the file it names, on the default branch', async () => {
1648
+ // Decoded: the page used to resolve the href undecoded, so a link written
1649
+ // `Some File.md` opened `Some%20File.md`, a file that is not there. And a
1650
+ // NEW TAB: a link inside a file never navigates away from it. The git
1651
+ // status names another branch, so the default branch is the page's doing.
1652
+ const open = vi
1653
+ .spyOn(window, 'open')
1654
+ .mockImplementation(() => ({ opener: window }) as unknown as Window);
1655
+ try {
1656
+ renderPage(false, [], [], makeFakeBus(), undefined, undefined, undefined, {
1657
+ ...git,
1658
+ status: { ...git.status!, branch: 'alice/draft' },
1659
+ });
1660
+ await settled();
1661
+ fireEvent.click(screen.getByRole('button', { name: 'link-probe' }));
1662
+ expect(open).toHaveBeenCalledTimes(1);
1663
+ expect(open).toHaveBeenCalledWith(SOME_FILE_URL, '_blank');
1664
+ expect(screen.queryByTestId('navigated-to')).toBeNull();
1665
+ expect(screen.getByRole('heading', { name: 'newsletter' })).toBeInTheDocument();
1666
+ } finally {
1667
+ open.mockRestore();
1668
+ }
1669
+ });
1670
+
1671
+ it("hands the view each link's target: another file a new tab, this file's section this tab", async () => {
1580
1672
  renderPage(false);
1581
1673
  await settled();
1582
- fireEvent.click(screen.getByRole('button', { name: 'link-probe' }));
1583
- const target = await screen.findByTestId('navigated-to');
1584
- expect(target.textContent).toMatch(
1585
- new RegExp(
1586
- `^/workspace/${encodeURIComponent(DEFAULT_BRANCH)}/knowledge-base/Skills/newsletter/Some(%20| )File\\.md$`,
1587
- ),
1588
- );
1674
+ // The same answer the click follows, so the anchor's href, target and rel
1675
+ // agree with it (a middle-click goes where the click goes).
1676
+ expect(JSON.parse(screen.getByTestId('link-target-probe').textContent ?? 'null')).toEqual({
1677
+ href: SOME_FILE_URL,
1678
+ newTab: true,
1679
+ });
1680
+ expect(JSON.parse(screen.getByTestId('section-target-probe').textContent ?? 'null')).toEqual({
1681
+ href: '/skills-and-tools/skills/newsletter#steps',
1682
+ newTab: false,
1683
+ });
1684
+ });
1685
+
1686
+ it('follows a link to a section of the file on screen by scrolling to its heading, in this tab', async () => {
1687
+ const open = vi.spyOn(window, 'open');
1688
+ // The page's address has no heading scroll of its own, so the click is
1689
+ // what scrolls: the heading the fragment names comes into view, and the
1690
+ // page neither opens a tab nor navigates.
1691
+ const original = Element.prototype.scrollIntoView;
1692
+ const scrolled: string[] = [];
1693
+ Element.prototype.scrollIntoView = function (this: Element) {
1694
+ scrolled.push(this.id);
1695
+ };
1696
+ try {
1697
+ renderPage(false);
1698
+ await settled();
1699
+ fireEvent.click(screen.getByRole('button', { name: 'section-probe' }));
1700
+ expect(scrolled).toEqual(['steps']);
1701
+ expect(open).not.toHaveBeenCalled();
1702
+ expect(screen.queryByTestId('navigated-to')).toBeNull();
1703
+ expect(screen.getByRole('heading', { name: 'newsletter' })).toBeInTheDocument();
1704
+ } finally {
1705
+ open.mockRestore();
1706
+ Element.prototype.scrollIntoView = original;
1707
+ }
1708
+ });
1709
+
1710
+ it("follows an id-link to this skill's own heading by scrolling the pane, in this tab", async () => {
1711
+ const open = vi.spyOn(window, 'open').mockImplementation(() => ({ opener: window }) as unknown as Window);
1712
+ const original = Element.prototype.scrollIntoView;
1713
+ const scrolled: string[] = [];
1714
+ Element.prototype.scrollIntoView = function (this: Element) {
1715
+ scrolled.push(this.id);
1716
+ };
1717
+ try {
1718
+ renderPage(false);
1719
+ await settled();
1720
+ // The anchor's own answer agrees: a section of this page, not a new tab.
1721
+ await waitFor(() =>
1722
+ expect(JSON.parse(screen.getByTestId('self-id-target-probe').textContent ?? 'null')).toEqual({
1723
+ href: '/skills-and-tools/skills/newsletter#steps',
1724
+ newTab: false,
1725
+ }),
1726
+ );
1727
+ fireEvent.click(screen.getByRole('button', { name: 'self-id-probe' }));
1728
+ expect(scrolled).toEqual(['steps']);
1729
+ expect(open).not.toHaveBeenCalled();
1730
+ expect(screen.queryByTestId('navigated-to')).toBeNull();
1731
+ // Another node is still a new tab.
1732
+ fireEvent.click(screen.getByRole('button', { name: 'other-id-probe' }));
1733
+ expect(open).toHaveBeenCalledWith(`/workspace/${encodeURIComponent(DEFAULT_BRANCH)}/plan-node#goal`, '_blank');
1734
+ expect(screen.getByRole('heading', { name: 'newsletter' })).toBeInTheDocument();
1735
+ } finally {
1736
+ open.mockRestore();
1737
+ Element.prototype.scrollIntoView = original;
1738
+ }
1739
+ });
1740
+
1741
+ // The pane renders the default branch's file whatever is checked out, so
1742
+ // an id in it names a node there: with a draft checked out, the click and
1743
+ // the anchor both open the default branch's node, not the draft's.
1744
+ it("opens another node on the default branch, where the file was read, while a draft is checked out", async () => {
1745
+ const open = vi.spyOn(window, 'open').mockImplementation(() => ({ opener: window }) as unknown as Window);
1746
+ try {
1747
+ renderPage(false, [], [], makeFakeBus(), undefined, undefined, undefined, {
1748
+ ...git,
1749
+ status: { ...git.status!, branch: 'alice/draft' },
1750
+ });
1751
+ await settled();
1752
+ fireEvent.click(screen.getByRole('button', { name: 'other-id-probe' }));
1753
+ expect(open).toHaveBeenCalledTimes(1);
1754
+ expect(open).toHaveBeenCalledWith(`/workspace/${encodeURIComponent(DEFAULT_BRANCH)}/plan-node#goal`, '_blank');
1755
+ expect(JSON.parse(screen.getByTestId('other-id-target-probe').textContent ?? 'null')).toEqual({
1756
+ href: `/workspace/${encodeURIComponent(DEFAULT_BRANCH)}/plan-node#goal`,
1757
+ newTab: true,
1758
+ });
1759
+ expect(screen.queryByTestId('navigated-to')).toBeNull();
1760
+ } finally {
1761
+ open.mockRestore();
1762
+ }
1763
+ });
1764
+
1765
+ // A section link's own address — where a middle-click or a modified click
1766
+ // on it goes — is this page plus the heading. Arriving there scrolls to it,
1767
+ // so the new tab lands where the plain click does.
1768
+ it('scrolls to the heading its address names when it arrives with a fragment', async () => {
1769
+ const original = Element.prototype.scrollIntoView;
1770
+ const scrolled: string[] = [];
1771
+ Element.prototype.scrollIntoView = function (this: Element) {
1772
+ scrolled.push(this.id);
1773
+ };
1774
+ try {
1775
+ libraryMock.value = libraryValue(false, [], []);
1776
+ render(harness(makeFakeBus(), git, undefined, undefined, workspace, '#steps'));
1777
+ await settled();
1778
+ await waitFor(() => expect(scrolled).toContain('steps'));
1779
+ } finally {
1780
+ Element.prototype.scrollIntoView = original;
1781
+ }
1782
+ });
1783
+
1784
+ it("names the file's real home for an HTML page's links: its workspace path, on the default branch", async () => {
1785
+ renderPage(false, [], [], makeFakeBus(), undefined, undefined, undefined, {
1786
+ ...git,
1787
+ status: { ...git.status!, branch: 'alice/draft' },
1788
+ });
1789
+ await settled();
1790
+ expect(paneProps.last?.linkHome).toEqual({
1791
+ path: 'knowledge-base/Skills/newsletter/SKILL.md',
1792
+ branch: DEFAULT_BRANCH,
1793
+ });
1589
1794
  });
1590
1795
 
1591
1796
  it("serves a relative image from the default branch's workspace, under the skill folder", async () => {