@kelpie/ui 0.16.0 → 0.17.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 (180) hide show
  1. package/dist/api/client.d.ts +1 -1
  2. package/dist/api/resources/ai.d.ts +16 -0
  3. package/dist/api/resources/ai.d.ts.map +1 -0
  4. package/dist/api/resources/ai.js +93 -0
  5. package/dist/api/resources/ai.js.map +1 -0
  6. package/dist/api/resources/conversions.js +1 -1
  7. package/dist/api/resources/conversions.js.map +1 -1
  8. package/dist/api/resources/session.d.ts.map +1 -1
  9. package/dist/api/resources/session.js +3 -1
  10. package/dist/api/resources/session.js.map +1 -1
  11. package/dist/api/resources/workspace.d.ts +2 -2
  12. package/dist/api/resources/workspace.js +2 -2
  13. package/dist/components/ActivitiesPanel.d.ts +7 -4
  14. package/dist/components/ActivitiesPanel.d.ts.map +1 -1
  15. package/dist/components/ActivitiesPanel.js +12 -2
  16. package/dist/components/ActivitiesPanel.js.map +1 -1
  17. package/dist/components/ActivityAction.d.ts +15 -0
  18. package/dist/components/ActivityAction.d.ts.map +1 -0
  19. package/dist/components/ActivityAction.js +20 -0
  20. package/dist/components/ActivityAction.js.map +1 -0
  21. package/dist/components/AgentTasks.d.ts +5 -0
  22. package/dist/components/AgentTasks.d.ts.map +1 -1
  23. package/dist/components/AgentTasks.js +88 -10
  24. package/dist/components/AgentTasks.js.map +1 -1
  25. package/dist/components/DecisionsPanel.d.ts.map +1 -1
  26. package/dist/components/DecisionsPanel.js +3 -1
  27. package/dist/components/DecisionsPanel.js.map +1 -1
  28. package/dist/components/LinkedText.d.ts +12 -0
  29. package/dist/components/LinkedText.d.ts.map +1 -0
  30. package/dist/components/LinkedText.js +25 -0
  31. package/dist/components/LinkedText.js.map +1 -0
  32. package/dist/components/MarkdownView.d.ts +3 -1
  33. package/dist/components/MarkdownView.d.ts.map +1 -1
  34. package/dist/components/MarkdownView.js +17 -3
  35. package/dist/components/MarkdownView.js.map +1 -1
  36. package/dist/components/NotesPanel.d.ts +2 -1
  37. package/dist/components/NotesPanel.d.ts.map +1 -1
  38. package/dist/components/NotesPanel.js +6 -7
  39. package/dist/components/NotesPanel.js.map +1 -1
  40. package/dist/components/PlanPanel.d.ts.map +1 -1
  41. package/dist/components/PlanPanel.js +3 -1
  42. package/dist/components/PlanPanel.js.map +1 -1
  43. package/dist/components/RecordLinkTextarea.d.ts +12 -0
  44. package/dist/components/RecordLinkTextarea.d.ts.map +1 -0
  45. package/dist/components/RecordLinkTextarea.js +142 -0
  46. package/dist/components/RecordLinkTextarea.js.map +1 -0
  47. package/dist/components/WorkspaceSwitcher.d.ts +2 -1
  48. package/dist/components/WorkspaceSwitcher.d.ts.map +1 -1
  49. package/dist/components/WorkspaceSwitcher.js +7 -2
  50. package/dist/components/WorkspaceSwitcher.js.map +1 -1
  51. package/dist/index.d.ts +5 -2
  52. package/dist/index.d.ts.map +1 -1
  53. package/dist/index.js +6 -1
  54. package/dist/index.js.map +1 -1
  55. package/dist/lib/fragmentTarget.d.ts +18 -0
  56. package/dist/lib/fragmentTarget.d.ts.map +1 -0
  57. package/dist/lib/fragmentTarget.js +73 -0
  58. package/dist/lib/fragmentTarget.js.map +1 -0
  59. package/dist/lib/recordLinks.d.ts +17 -0
  60. package/dist/lib/recordLinks.d.ts.map +1 -0
  61. package/dist/lib/recordLinks.js +48 -0
  62. package/dist/lib/recordLinks.js.map +1 -0
  63. package/dist/lib/recordReferences.d.ts +41 -0
  64. package/dist/lib/recordReferences.d.ts.map +1 -0
  65. package/dist/lib/recordReferences.js +92 -0
  66. package/dist/lib/recordReferences.js.map +1 -0
  67. package/dist/modules/ai.d.ts +13 -0
  68. package/dist/modules/ai.d.ts.map +1 -0
  69. package/dist/modules/ai.js +22 -0
  70. package/dist/modules/ai.js.map +1 -0
  71. package/dist/modules/aiRunner.d.ts +3 -0
  72. package/dist/modules/aiRunner.d.ts.map +1 -0
  73. package/dist/modules/aiRunner.js +66 -0
  74. package/dist/modules/aiRunner.js.map +1 -0
  75. package/dist/pages/CompanyDetail.d.ts.map +1 -1
  76. package/dist/pages/CompanyDetail.js +2 -1
  77. package/dist/pages/CompanyDetail.js.map +1 -1
  78. package/dist/pages/DealDetail.d.ts.map +1 -1
  79. package/dist/pages/DealDetail.js +2 -1
  80. package/dist/pages/DealDetail.js.map +1 -1
  81. package/dist/pages/EnquiryDetail.d.ts.map +1 -1
  82. package/dist/pages/EnquiryDetail.js +2 -1
  83. package/dist/pages/EnquiryDetail.js.map +1 -1
  84. package/dist/pages/EventDetail.d.ts.map +1 -1
  85. package/dist/pages/EventDetail.js +2 -1
  86. package/dist/pages/EventDetail.js.map +1 -1
  87. package/dist/pages/OpportunityDetail.d.ts.map +1 -1
  88. package/dist/pages/OpportunityDetail.js +2 -1
  89. package/dist/pages/OpportunityDetail.js.map +1 -1
  90. package/dist/pages/PartnershipDetail.d.ts.map +1 -1
  91. package/dist/pages/PartnershipDetail.js +2 -1
  92. package/dist/pages/PartnershipDetail.js.map +1 -1
  93. package/dist/pages/PersonDetail.d.ts.map +1 -1
  94. package/dist/pages/PersonDetail.js +2 -1
  95. package/dist/pages/PersonDetail.js.map +1 -1
  96. package/dist/pages/RaiseDetail.d.ts.map +1 -1
  97. package/dist/pages/RaiseDetail.js +2 -1
  98. package/dist/pages/RaiseDetail.js.map +1 -1
  99. package/dist/pages/SearchPage.d.ts.map +1 -1
  100. package/dist/pages/SearchPage.js +26 -14
  101. package/dist/pages/SearchPage.js.map +1 -1
  102. package/dist/pages/admin/AiPage.d.ts +2 -0
  103. package/dist/pages/admin/AiPage.d.ts.map +1 -0
  104. package/dist/pages/admin/AiPage.js +134 -0
  105. package/dist/pages/admin/AiPage.js.map +1 -0
  106. package/dist/pages/admin/McpPage.js +2 -2
  107. package/dist/pages/admin/McpPage.js.map +1 -1
  108. package/dist/pages/admin/WorkspaceSettingsPage.d.ts +5 -6
  109. package/dist/pages/admin/WorkspaceSettingsPage.d.ts.map +1 -1
  110. package/dist/pages/admin/WorkspaceSettingsPage.js +12 -17
  111. package/dist/pages/admin/WorkspaceSettingsPage.js.map +1 -1
  112. package/dist/pages/dashboard/attention.d.ts +0 -5
  113. package/dist/pages/dashboard/attention.d.ts.map +1 -1
  114. package/dist/pages/dashboard/attention.js +1 -21
  115. package/dist/pages/dashboard/attention.js.map +1 -1
  116. package/dist/pages/dashboard/sections.d.ts.map +1 -1
  117. package/dist/pages/dashboard/sections.js +6 -3
  118. package/dist/pages/dashboard/sections.js.map +1 -1
  119. package/dist/pages/handbook/HandbookPage.d.ts.map +1 -1
  120. package/dist/pages/handbook/HandbookPage.js +2 -3
  121. package/dist/pages/handbook/HandbookPage.js.map +1 -1
  122. package/dist/pages/onboarding/WorkspaceStepPage.d.ts.map +1 -1
  123. package/dist/pages/onboarding/WorkspaceStepPage.js +9 -27
  124. package/dist/pages/onboarding/WorkspaceStepPage.js.map +1 -1
  125. package/dist/pages/onboarding/onboardingRerun.d.ts +9 -0
  126. package/dist/pages/onboarding/onboardingRerun.d.ts.map +1 -1
  127. package/dist/pages/onboarding/onboardingRerun.js +11 -0
  128. package/dist/pages/onboarding/onboardingRerun.js.map +1 -1
  129. package/dist/registry/context.d.ts +3 -1
  130. package/dist/registry/context.d.ts.map +1 -1
  131. package/dist/registry/context.js +4 -0
  132. package/dist/registry/context.js.map +1 -1
  133. package/dist/registry/contributions.d.ts +38 -0
  134. package/dist/registry/contributions.d.ts.map +1 -1
  135. package/dist/registry/registry.d.ts +5 -1
  136. package/dist/registry/registry.d.ts.map +1 -1
  137. package/dist/registry/registry.js +8 -0
  138. package/dist/registry/registry.js.map +1 -1
  139. package/package.json +2 -2
  140. package/src/api/client.ts +1 -1
  141. package/src/api/resources/ai.ts +110 -0
  142. package/src/api/resources/conversions.ts +1 -1
  143. package/src/api/resources/session.ts +3 -1
  144. package/src/api/resources/workspace.ts +4 -4
  145. package/src/components/ActivitiesPanel.tsx +39 -10
  146. package/src/components/ActivityAction.tsx +33 -0
  147. package/src/components/AgentTasks.tsx +138 -10
  148. package/src/components/DecisionsPanel.tsx +9 -1
  149. package/src/components/LinkedText.tsx +51 -0
  150. package/src/components/MarkdownView.tsx +37 -7
  151. package/src/components/NotesPanel.tsx +18 -12
  152. package/src/components/PlanPanel.tsx +9 -1
  153. package/src/components/RecordLinkTextarea.tsx +257 -0
  154. package/src/components/WorkspaceSwitcher.tsx +15 -1
  155. package/src/index.ts +10 -0
  156. package/src/lib/fragmentTarget.ts +96 -0
  157. package/src/lib/recordLinks.ts +57 -0
  158. package/src/lib/recordReferences.ts +139 -0
  159. package/src/modules/ai.tsx +23 -0
  160. package/src/modules/aiRunner.ts +80 -0
  161. package/src/pages/CompanyDetail.tsx +2 -1
  162. package/src/pages/DealDetail.tsx +2 -1
  163. package/src/pages/EnquiryDetail.tsx +2 -1
  164. package/src/pages/EventDetail.tsx +2 -1
  165. package/src/pages/OpportunityDetail.tsx +2 -1
  166. package/src/pages/PartnershipDetail.tsx +2 -1
  167. package/src/pages/PersonDetail.tsx +2 -1
  168. package/src/pages/RaiseDetail.tsx +2 -1
  169. package/src/pages/SearchPage.tsx +30 -15
  170. package/src/pages/admin/AiPage.tsx +353 -0
  171. package/src/pages/admin/McpPage.tsx +11 -5
  172. package/src/pages/admin/WorkspaceSettingsPage.tsx +13 -28
  173. package/src/pages/dashboard/attention.ts +1 -24
  174. package/src/pages/dashboard/sections.tsx +9 -4
  175. package/src/pages/handbook/HandbookPage.tsx +5 -6
  176. package/src/pages/onboarding/WorkspaceStepPage.tsx +19 -43
  177. package/src/pages/onboarding/onboardingRerun.ts +14 -0
  178. package/src/registry/context.ts +6 -0
  179. package/src/registry/contributions.ts +30 -0
  180. package/src/registry/registry.ts +18 -0
@@ -0,0 +1,80 @@
1
+ import { ApiError } from '../api/client.ts'
2
+ import { useAiRunForAgentRun, useAiSettings } from '../api/resources/ai.ts'
3
+ import { useAgents } from '../api/resources/agentTasks.ts'
4
+ import type { AgentRunner, AgentRunnerAvailability, AgentRunnerProgress } from '../registry/contributions.ts'
5
+
6
+ /** The `managed_by` value the server module writes on its agent row. */
7
+ const AI_MODULE_ID = 'ai'
8
+
9
+ /**
10
+ * Kelpie AI as the Agent menu's runner.
11
+ *
12
+ * Ready only when the workspace can run a task now: the module answers (so it
13
+ * is in the assembly and switched on), AI is enabled, a provider and key are
14
+ * available (the workspace's own, or the deployment's), and the agent row the
15
+ * module manages exists to dispatch to.
16
+ */
17
+ function useAvailability(options: { readonly enabled: boolean }): AgentRunnerAvailability {
18
+ const settings = useAiSettings({ enabled: options.enabled })
19
+ const agents = useAgents({ enabled: options.enabled })
20
+
21
+ if (settings.isLoading || agents.isLoading || !options.enabled) {
22
+ return { status: 'loading' }
23
+ }
24
+
25
+ if (settings.error !== null) {
26
+ // The runtime answers 403 or 404 when the module is switched off.
27
+ return settings.error instanceof ApiError && (settings.error.status === 403 || settings.error.status === 404)
28
+ ? { status: 'unavailable', reason: 'Kelpie AI is switched off for this workspace.' }
29
+ : { status: 'unavailable', reason: 'Kelpie AI settings could not be read.' }
30
+ }
31
+
32
+ const record = settings.record
33
+
34
+ if (record === undefined || !record.enabled) {
35
+ return { status: 'unavailable', reason: 'Kelpie AI is not enabled. An admin can enable it under Admin → AI.' }
36
+ }
37
+
38
+ if (!record.configured) {
39
+ return {
40
+ status: 'unavailable',
41
+ reason: 'Kelpie AI has no provider key. An admin can add one under Admin → AI.',
42
+ }
43
+ }
44
+
45
+ const agent = agents.records.find((candidate) => candidate.managedBy === AI_MODULE_ID)
46
+
47
+ if (agent === undefined) {
48
+ return {
49
+ status: 'unavailable',
50
+ reason: 'The Kelpie AI agent is missing. An admin can save Admin → AI again to restore it.',
51
+ }
52
+ }
53
+
54
+ return { status: 'ready', agentId: agent.id }
55
+ }
56
+
57
+ function useProgress(agentRunId: string | undefined): AgentRunnerProgress | undefined {
58
+ const run = useAiRunForAgentRun(agentRunId)
59
+
60
+ if (agentRunId === undefined) {
61
+ return undefined
62
+ }
63
+
64
+ switch (run?.status) {
65
+ case 'succeeded':
66
+ return { status: 'succeeded' }
67
+ case 'failed':
68
+ return { status: 'failed', reason: run.failureReason ?? 'no reason recorded' }
69
+ case 'queued':
70
+ case 'running':
71
+ case undefined:
72
+ return { status: 'running' }
73
+ }
74
+ }
75
+
76
+ export const aiRunner: AgentRunner = {
77
+ id: AI_MODULE_ID,
78
+ useAvailability,
79
+ useProgress,
80
+ }
@@ -56,6 +56,7 @@ import { SidebarField } from '../components/SidebarField.tsx'
56
56
  import { SummaryBlock } from '../components/SummaryBlock.tsx'
57
57
  import { useRecordTabs } from '../registry/context.ts'
58
58
  import { inSlotOrder } from '../registry/registry.ts'
59
+ import { useRecordTab } from '../lib/fragmentTarget.ts'
59
60
  import { toOptions, toTags } from './fields.ts'
60
61
 
61
62
  /**
@@ -87,7 +88,7 @@ export function CompanyDetail(): React.JSX.Element {
87
88
  const moduleTabs = inSlotOrder(useRecordTabs('company'))
88
89
  const hasCustomFields = useHasCustomFields('company')
89
90
  const eventsEnabled = useModuleEnabled('events')
90
- const [activeTab, setActiveTab] = useState('overview')
91
+ const [activeTab, setActiveTab] = useRecordTab()
91
92
  const formSubmissions = useFormSubmissionsForRecord('company', id)
92
93
 
93
94
  if (isNotFound) {
@@ -42,6 +42,7 @@ import { SidebarField } from '../components/SidebarField.tsx'
42
42
  import { SummaryBlock } from '../components/SummaryBlock.tsx'
43
43
  import { formatDay } from '../lib/dates.ts'
44
44
  import { formatMoney } from '../lib/money.ts'
45
+ import { useRecordTab } from '../lib/fragmentTarget.ts'
45
46
  import { useRecordTabs } from '../registry/context.ts'
46
47
  import { inSlotOrder } from '../registry/registry.ts'
47
48
  import { toTags } from './fields.ts'
@@ -68,7 +69,7 @@ export function DealDetail(): React.JSX.Element {
68
69
  const moduleTabs = inSlotOrder(useRecordTabs('deal'))
69
70
  const hasCustomFields = useHasCustomFields('deal')
70
71
  const eventsEnabled = useModuleEnabled('events')
71
- const [activeTab, setActiveTab] = useState('overview')
72
+ const [activeTab, setActiveTab] = useRecordTab()
72
73
  const [showConvert, setShowConvert] = useState(false)
73
74
  const formSubmissions = useFormSubmissionsForRecord('deal', id)
74
75
 
@@ -46,6 +46,7 @@ import { SidebarField } from '../components/SidebarField.tsx'
46
46
  import { SummaryBlock } from '../components/SummaryBlock.tsx'
47
47
  import { useRecordTabs } from '../registry/context.ts'
48
48
  import { inSlotOrder } from '../registry/registry.ts'
49
+ import { useRecordTab } from '../lib/fragmentTarget.ts'
49
50
  import { toTags } from './fields.ts'
50
51
 
51
52
  /**
@@ -71,7 +72,7 @@ export function EnquiryDetail(): React.JSX.Element {
71
72
  const moduleTabs = inSlotOrder(useRecordTabs('enquiry'))
72
73
  const hasCustomFields = useHasCustomFields('enquiry')
73
74
  const eventsEnabled = useModuleEnabled('events')
74
- const [activeTab, setActiveTab] = useState('overview')
75
+ const [activeTab, setActiveTab] = useRecordTab()
75
76
  const [showConvert, setShowConvert] = useState(false)
76
77
  const formSubmissions = useFormSubmissionsForRecord('enquiry', id)
77
78
 
@@ -64,6 +64,7 @@ import { SidebarField } from '../components/SidebarField.tsx'
64
64
  import { SummaryBlock } from '../components/SummaryBlock.tsx'
65
65
  import { TimezoneSearch } from '../components/TimezoneSearch.tsx'
66
66
  import { formatDateTime } from '../lib/dates.ts'
67
+ import { useRecordTab } from '../lib/fragmentTarget.ts'
67
68
  import { useRecordTabs } from '../registry/context.ts'
68
69
  import { inSlotOrder } from '../registry/registry.ts'
69
70
  import { toTags } from './fields.ts'
@@ -106,7 +107,7 @@ export function EventDetail(): React.JSX.Element {
106
107
  const deleteEvent = useDeleteEvent()
107
108
  const moduleTabs = inSlotOrder(useRecordTabs('event'))
108
109
  const hasCustomFields = useHasCustomFields('event')
109
- const [activeTab, setActiveTab] = useState('overview')
110
+ const [activeTab, setActiveTab] = useRecordTab()
110
111
 
111
112
  if (isNotFound) {
112
113
  return <NotFoundPanel label="Event" backTo="/events" />
@@ -45,6 +45,7 @@ import { SectionHeader } from '../components/SectionHeader.tsx'
45
45
  import { SidebarField } from '../components/SidebarField.tsx'
46
46
  import { SummaryBlock } from '../components/SummaryBlock.tsx'
47
47
  import { formatDay } from '../lib/dates.ts'
48
+ import { useRecordTab } from '../lib/fragmentTarget.ts'
48
49
  import { useRecordTabs } from '../registry/context.ts'
49
50
  import { inSlotOrder } from '../registry/registry.ts'
50
51
  import { toTags } from './fields.ts'
@@ -73,7 +74,7 @@ export function OpportunityDetail(): React.JSX.Element {
73
74
  const moduleTabs = inSlotOrder(useRecordTabs('opportunity'))
74
75
  const hasCustomFields = useHasCustomFields('opportunity')
75
76
  const eventsEnabled = useModuleEnabled('events')
76
- const [activeTab, setActiveTab] = useState('overview')
77
+ const [activeTab, setActiveTab] = useRecordTab()
77
78
  const [showConvert, setShowConvert] = useState(false)
78
79
  const formSubmissions = useFormSubmissionsForRecord('opportunity', id)
79
80
 
@@ -45,6 +45,7 @@ import { SectionHeader } from '../components/SectionHeader.tsx'
45
45
  import { SidebarField } from '../components/SidebarField.tsx'
46
46
  import { SummaryBlock } from '../components/SummaryBlock.tsx'
47
47
  import { formatDay } from '../lib/dates.ts'
48
+ import { useRecordTab } from '../lib/fragmentTarget.ts'
48
49
  import { useRecordTabs } from '../registry/context.ts'
49
50
  import { inSlotOrder } from '../registry/registry.ts'
50
51
  import { toTags } from './fields.ts'
@@ -73,7 +74,7 @@ export function PartnershipDetail(): React.JSX.Element {
73
74
  const moduleTabs = inSlotOrder(useRecordTabs('partnership'))
74
75
  const hasCustomFields = useHasCustomFields('partnership')
75
76
  const eventsEnabled = useModuleEnabled('events')
76
- const [activeTab, setActiveTab] = useState('overview')
77
+ const [activeTab, setActiveTab] = useRecordTab()
77
78
  const [showConvert, setShowConvert] = useState(false)
78
79
  const formSubmissions = useFormSubmissionsForRecord('partnership', id)
79
80
 
@@ -55,6 +55,7 @@ import { PhonesField } from '../components/PhonesField.tsx'
55
55
  import { SummaryBlock } from '../components/SummaryBlock.tsx'
56
56
  import { useRecordTabs } from '../registry/context.ts'
57
57
  import { inSlotOrder } from '../registry/registry.ts'
58
+ import { useRecordTab } from '../lib/fragmentTarget.ts'
58
59
  import {
59
60
  CandidateReferrerField,
60
61
  CandidateStageField,
@@ -91,7 +92,7 @@ export function PersonDetail(): React.JSX.Element {
91
92
  const moduleTabs = inSlotOrder(useRecordTabs('person'))
92
93
  const hasCustomFields = useHasCustomFields('person')
93
94
  const eventsEnabled = useModuleEnabled('events')
94
- const [activeTab, setActiveTab] = useState('overview')
95
+ const [activeTab, setActiveTab] = useRecordTab()
95
96
  const candidacies = useCandidates({ personIds: id === undefined ? [] : [id] }, {
96
97
  enabled: id !== undefined,
97
98
  })
@@ -40,6 +40,7 @@ import { SidebarField } from '../components/SidebarField.tsx'
40
40
  import { SummaryBlock } from '../components/SummaryBlock.tsx'
41
41
  import { formatDay } from '../lib/dates.ts'
42
42
  import { formatMoney } from '../lib/money.ts'
43
+ import { useRecordTab } from '../lib/fragmentTarget.ts'
43
44
  import { useRecordTabs } from '../registry/context.ts'
44
45
  import { inSlotOrder } from '../registry/registry.ts'
45
46
  import { toTags } from './fields.ts'
@@ -72,7 +73,7 @@ export function RaiseDetail(): React.JSX.Element {
72
73
  const moduleTabs = inSlotOrder(useRecordTabs('raise'))
73
74
  const hasCustomFields = useHasCustomFields('raise')
74
75
  const eventsEnabled = useModuleEnabled('events')
75
- const [activeTab, setActiveTab] = useState('overview')
76
+ const [activeTab, setActiveTab] = useRecordTab()
76
77
  const [showConvert, setShowConvert] = useState(false)
77
78
 
78
79
  if (isNotFound) {
@@ -4,6 +4,7 @@ import { Link, useSearchParams } from 'react-router'
4
4
  import { useSearch } from '../api/resources/search.ts'
5
5
  import { ErrorPanel, LoadingPanel } from '../components/QueryState.tsx'
6
6
  import { PageHeader } from '../components/PageHeader.tsx'
7
+ import { attachedHref } from '../lib/recordLinks.ts'
7
8
 
8
9
  /**
9
10
  * `/search?q=`, the destination of the box in the application shell.
@@ -13,21 +14,35 @@ import { PageHeader } from '../components/PageHeader.tsx'
13
14
  * renderer, and the only thing it still owns is where a result links to.
14
15
  */
15
16
 
17
+ /**
18
+ * Where a Decision, Note or Plan item result opens: the page of the record it is
19
+ * on, at the item. With no record to open, the fallback.
20
+ */
21
+ function onItsRecord(fallback: string): (item: SearchResult) => string {
22
+ return (item) => (item.target === null ? fallback : (attachedHref(item.id, item.target) ?? fallback))
23
+ }
24
+
16
25
  /** What each collection is called on screen, and where one of its results lives. */
17
- const COLLECTIONS: Readonly<Record<SearchCollection, { label: string; path: (id: string) => string }>> = {
18
- handbook_page: { label: 'Handbook', path: (id) => `/handbook/${id}` },
19
- person: { label: 'People', path: (id) => `/people/${id}` },
20
- role: { label: 'Roles', path: (id) => `/hiring/${id}` },
21
- company: { label: 'Companies', path: (id) => `/companies/${id}` },
22
- enquiry: { label: 'Enquiries', path: (id) => `/enquiries/${id}` },
23
- deal: { label: 'Deals', path: (id) => `/deals/${id}` },
24
- opportunity: { label: 'Opportunities', path: (id) => `/opportunities/${id}` },
25
- raise: { label: 'Fundraising', path: (id) => `/fundraising/${id}` },
26
- partnership: { label: 'Partnerships', path: (id) => `/partnerships/${id}` },
27
- event: { label: 'Events', path: (id) => `/events/${id}` },
28
- // Decisions have no detail page of their own, in the mockup or here. The global
29
- // list is where one is read.
30
- decision: { label: 'Decisions', path: () => '/decisions' },
26
+ const COLLECTIONS: Readonly<
27
+ Record<SearchCollection, { label: string; path: (item: SearchResult) => string }>
28
+ > = {
29
+ handbook_page: { label: 'Handbook', path: (item) => `/handbook/${item.id}` },
30
+ person: { label: 'People', path: (item) => `/people/${item.id}` },
31
+ role: { label: 'Roles', path: (item) => `/hiring/${item.id}` },
32
+ company: { label: 'Companies', path: (item) => `/companies/${item.id}` },
33
+ enquiry: { label: 'Enquiries', path: (item) => `/enquiries/${item.id}` },
34
+ deal: { label: 'Deals', path: (item) => `/deals/${item.id}` },
35
+ opportunity: { label: 'Opportunities', path: (item) => `/opportunities/${item.id}` },
36
+ raise: { label: 'Fundraising', path: (item) => `/fundraising/${item.id}` },
37
+ partnership: { label: 'Partnerships', path: (item) => `/partnerships/${item.id}` },
38
+ event: { label: 'Events', path: (item) => `/events/${item.id}` },
39
+ // Decisions, Notes and Plan items have no page of their own. Each opens on the
40
+ // record it is on; the global list is where a decision with none is read.
41
+ decision: { label: 'Decisions', path: onItsRecord('/decisions') },
42
+ note: { label: 'Notes', path: onItsRecord('/dashboard') },
43
+ plan_item: { label: 'Plan items', path: onItsRecord('/planning') },
44
+ list: { label: 'Lists', path: (item) => `/lists/${item.id}` },
45
+ form: { label: 'Forms', path: (item) => `/forms/${item.id}` },
31
46
  }
32
47
 
33
48
  export function SearchPage(): React.JSX.Element {
@@ -120,7 +135,7 @@ function ResultRow({
120
135
  }): React.JSX.Element {
121
136
  return (
122
137
  <Link
123
- to={COLLECTIONS[collection].path(item.id)}
138
+ to={COLLECTIONS[collection].path(item)}
124
139
  className="block px-4 py-2.5 transition hover:bg-accent-soft/30"
125
140
  >
126
141
  <div className="flex items-center justify-between gap-3">
@@ -0,0 +1,353 @@
1
+ import { AI_DEFAULT_MODELS, AI_PROVIDER_LABELS, AI_PROVIDERS } from '@kelpie/schemas'
2
+ import type { AiProvider, AiRun, AiSettings, AiSettingsInput } from '@kelpie/schemas'
3
+ import { useState } from 'react'
4
+ import type { FormEvent } from 'react'
5
+
6
+ import { useTimezone } from '../../api/resources/account.ts'
7
+ import { useAiRuns, useAiSettings, useDisableAi, useSaveAiSettings } from '../../api/resources/ai.ts'
8
+ import { Chip } from '../../components/Chip.tsx'
9
+ import type { ChipTone } from '../../components/Chip.tsx'
10
+ import { PageHeader } from '../../components/PageHeader.tsx'
11
+ import { ErrorPanel, LoadingPanel } from '../../components/QueryState.tsx'
12
+ import { formatRelativeTime } from '../../lib/dates.ts'
13
+
14
+ /**
15
+ * The AI admin page at `/admin/ai`, from the optional `ai` module.
16
+ *
17
+ * Two parts: the settings for Kelpie AI in this workspace, and its run log.
18
+ * Both read the same `/v1/ai/*` endpoints an agent would use.
19
+ *
20
+ * What the settings part shows depends on the module's key mode. In
21
+ * `workspace` mode an admin picks a provider, pastes their own API key, and
22
+ * may name a model. The key is write-only: the page shows its last four
23
+ * characters and never the key. In `deployment` mode the operator's
24
+ * environment decides all three, and the page offers only enable and disable.
25
+ */
26
+
27
+ const STATUS_TONES: Readonly<Record<AiRun['status'], ChipTone>> = {
28
+ queued: 'neutral',
29
+ running: 'accent',
30
+ succeeded: 'success',
31
+ failed: 'danger',
32
+ }
33
+
34
+ const OPERATION_TONES: Readonly<Record<string, ChipTone>> = {
35
+ applied: 'success',
36
+ failed: 'danger',
37
+ skipped: 'neutral',
38
+ }
39
+
40
+ const inputClass =
41
+ 'w-full max-w-md rounded-md border border-border bg-surface px-3 py-2 text-[13px] outline-none focus:border-accent focus:ring-2 focus:ring-accent/20'
42
+ const primaryButtonClass =
43
+ 'rounded-md bg-accent px-3.5 py-2 text-[12px] font-semibold text-accent-fg transition hover:bg-accent-hover disabled:opacity-50'
44
+ const secondaryButtonClass =
45
+ 'rounded-md border border-border px-3.5 py-2 text-[12px] font-medium text-ink transition hover:border-border-strong disabled:opacity-50'
46
+
47
+ function keyDescription(settings: AiSettings): string {
48
+ if (settings.keySource === 'workspace') {
49
+ return settings.keyHint === null ? 'Your key is stored.' : `Your key ending in ${settings.keyHint} is stored.`
50
+ }
51
+ if (settings.keySource === 'environment') {
52
+ return 'This install supplies a key. Enter your own to use it instead.'
53
+ }
54
+
55
+ return 'No key is stored.'
56
+ }
57
+
58
+ /**
59
+ * Provider, key and model for `workspace` key mode.
60
+ *
61
+ * Only changed fields are sent. The server keeps what is omitted, and drops the
62
+ * stored key and model when the provider changes, so this form clears the model
63
+ * field on a provider change to match.
64
+ */
65
+ function WorkspaceKeyForm({ settings }: { readonly settings: AiSettings }): React.JSX.Element {
66
+ const save = useSaveAiSettings()
67
+ const [provider, setProvider] = useState<AiProvider>(settings.provider ?? 'openai')
68
+ const [apiKey, setApiKey] = useState('')
69
+ const [model, setModel] = useState(settings.provider === null ? '' : settings.model)
70
+
71
+ const providerChanged = provider !== settings.provider
72
+ const defaultModel = AI_DEFAULT_MODELS[provider]
73
+
74
+ /** `undefined` keeps the stored model, `null` clears it back to the default. */
75
+ function modelChange(): string | null | undefined {
76
+ const trimmed = model.trim()
77
+
78
+ if (trimmed === '') {
79
+ // Nothing to clear when the workspace has not chosen a provider yet.
80
+ if (settings.provider === null) return undefined
81
+ return providerChanged || settings.model !== defaultModel ? null : undefined
82
+ }
83
+
84
+ return !providerChanged && trimmed === settings.model ? undefined : trimmed
85
+ }
86
+
87
+ function changes(): AiSettingsInput {
88
+ const nextModel = modelChange()
89
+
90
+ return {
91
+ ...(providerChanged ? { provider } : {}),
92
+ ...(apiKey.trim() === '' ? {} : { apiKey: apiKey.trim() }),
93
+ ...(nextModel === undefined ? {} : { model: nextModel }),
94
+ }
95
+ }
96
+
97
+ function submit(formEvent: FormEvent): void {
98
+ formEvent.preventDefault()
99
+ save
100
+ .runAsync(changes())
101
+ .then(() => {
102
+ setApiKey('')
103
+ })
104
+ .catch(() => undefined)
105
+ }
106
+
107
+ return (
108
+ <form onSubmit={submit} className="mt-4 space-y-3">
109
+ <label className="block">
110
+ <span className="mb-1.5 block text-[12px] font-medium text-ink">Provider</span>
111
+ <select
112
+ value={provider}
113
+ onChange={(event) => {
114
+ setProvider(event.target.value as AiProvider)
115
+ setModel('')
116
+ }}
117
+ className="w-48 rounded-md border border-border bg-surface-raised px-3 py-2 text-[13px] outline-none focus:border-accent"
118
+ >
119
+ {AI_PROVIDERS.map((option) => (
120
+ <option key={option} value={option}>
121
+ {AI_PROVIDER_LABELS[option]}
122
+ </option>
123
+ ))}
124
+ </select>
125
+ </label>
126
+
127
+ <label className="block">
128
+ <span className="mb-1.5 block text-[12px] font-medium text-ink">API key</span>
129
+ <input
130
+ type="password"
131
+ autoComplete="off"
132
+ value={apiKey}
133
+ onChange={(event) => {
134
+ setApiKey(event.target.value)
135
+ }}
136
+ placeholder={providerChanged ? `Paste your ${AI_PROVIDER_LABELS[provider]} API key` : 'Paste a new key to replace it'}
137
+ className={`${inputClass} font-mono`}
138
+ />
139
+ <span className="mt-1.5 block text-[12px] text-ink-muted">
140
+ {providerChanged && settings.keySource === 'workspace'
141
+ ? 'Changing provider removes the stored key.'
142
+ : keyDescription(settings)}{' '}
143
+ The key is stored encrypted and is never shown again.
144
+ </span>
145
+ </label>
146
+
147
+ <label className="block">
148
+ <span className="mb-1.5 block text-[12px] font-medium text-ink">Model</span>
149
+ <input
150
+ value={model}
151
+ onChange={(event) => {
152
+ setModel(event.target.value)
153
+ }}
154
+ placeholder={defaultModel}
155
+ className={`${inputClass} font-mono`}
156
+ />
157
+ <span className="mt-1.5 block text-[12px] text-ink-muted">Leave it empty to use {defaultModel}.</span>
158
+ </label>
159
+
160
+ {save.error !== null && <ErrorPanel error={save.error} />}
161
+
162
+ <div className="flex flex-wrap gap-2">
163
+ <button type="submit" disabled={save.isPending} className={primaryButtonClass}>
164
+ {save.isPending ? 'Saving…' : settings.enabled ? 'Save' : 'Enable AI'}
165
+ </button>
166
+ {settings.enabled && settings.keySource === 'workspace' && !providerChanged && (
167
+ <button
168
+ type="button"
169
+ disabled={save.isPending}
170
+ onClick={() => {
171
+ save.run({ apiKey: null })
172
+ }}
173
+ className={secondaryButtonClass}
174
+ >
175
+ Remove stored key
176
+ </button>
177
+ )}
178
+ </div>
179
+ </form>
180
+ )
181
+ }
182
+
183
+ function DeploymentKeyControls({ settings }: { readonly settings: AiSettings }): React.JSX.Element {
184
+ const save = useSaveAiSettings()
185
+
186
+ if (!settings.configured) {
187
+ return (
188
+ <p className="mt-3 text-[13px] text-ink-muted">
189
+ The operator has not set up a provider for this install. Set
190
+ <code className="mx-1 rounded bg-surface px-1">AI_PROVIDER</code>
191
+ and
192
+ <code className="mx-1 rounded bg-surface px-1">AI_API_KEY</code>
193
+ in the environment to turn on AI runs.
194
+ </p>
195
+ )
196
+ }
197
+ if (settings.monthlyLimit === 0) {
198
+ return <p className="mt-4 text-[13px] text-ink-muted">AI runs are not included for this workspace. Your own agent still works over MCP.</p>
199
+ }
200
+ if (settings.enabled) {
201
+ return <></>
202
+ }
203
+
204
+ return (
205
+ <div className="mt-4 space-y-2">
206
+ {save.error !== null && <ErrorPanel error={save.error} />}
207
+ <button
208
+ type="button"
209
+ disabled={save.isPending}
210
+ onClick={() => {
211
+ save.run({})
212
+ }}
213
+ className={primaryButtonClass}
214
+ >
215
+ {save.isPending ? 'Saving…' : 'Enable AI'}
216
+ </button>
217
+ </div>
218
+ )
219
+ }
220
+
221
+ function SettingsPanel({ settings }: { readonly settings: AiSettings }): React.JSX.Element {
222
+ const disable = useDisableAi()
223
+
224
+ return (
225
+ <section className="rounded-md border border-border p-5">
226
+ <div className="flex flex-wrap items-center gap-2">
227
+ <h2 className="text-[15px] font-semibold text-ink">Kelpie AI</h2>
228
+ <Chip tone={settings.enabled ? 'success' : 'neutral'}>{settings.enabled ? 'Enabled' : 'Not enabled'}</Chip>
229
+ </div>
230
+ <p className="mt-2 max-w-2xl text-[13px] leading-relaxed text-ink-muted">
231
+ Kelpie AI runs agent tasks for you: enrichment, summaries, follow-ups and notes. It reads the record and its
232
+ neighbours, asks the model for a reply, and applies that reply through the same tools any agent uses.
233
+ </p>
234
+
235
+ <dl className="mt-4 grid max-w-md grid-cols-2 gap-y-2 text-[13px]">
236
+ {settings.provider !== null && (
237
+ <>
238
+ <dt className="text-ink-muted">Provider</dt>
239
+ <dd className="text-ink">{AI_PROVIDER_LABELS[settings.provider]}</dd>
240
+ <dt className="text-ink-muted">Model</dt>
241
+ <dd className="font-mono text-ink">{settings.model}</dd>
242
+ </>
243
+ )}
244
+ <dt className="text-ink-muted">Runs this month</dt>
245
+ <dd className="text-ink">
246
+ {settings.runsThisMonth}
247
+ {settings.monthlyLimit === null ? '' : ` / ${String(settings.monthlyLimit)}`}
248
+ </dd>
249
+ </dl>
250
+
251
+ {settings.keyMode === 'workspace' ? (
252
+ <WorkspaceKeyForm
253
+ // Remount on a saved change, so the form starts from what the server now holds.
254
+ key={`${settings.provider ?? 'none'}:${settings.model}:${settings.keySource ?? 'none'}:${settings.keyHint ?? ''}`}
255
+ settings={settings}
256
+ />
257
+ ) : (
258
+ <DeploymentKeyControls settings={settings} />
259
+ )}
260
+
261
+ {settings.enabled && (
262
+ <div className="mt-4 space-y-2 border-t border-border pt-4">
263
+ {disable.error !== null && <ErrorPanel error={disable.error} />}
264
+ <button
265
+ type="button"
266
+ disabled={disable.isPending}
267
+ onClick={() => {
268
+ disable.run()
269
+ }}
270
+ className="rounded-md border border-danger px-3.5 py-2 text-[12px] font-medium text-danger disabled:opacity-50"
271
+ >
272
+ {disable.isPending ? 'Disabling…' : 'Disable AI'}
273
+ </button>
274
+ <p className="text-[12px] text-ink-muted">
275
+ Disabling removes Kelpie AI from the Run menu
276
+ {settings.keySource === 'workspace' ? ' and deletes the stored key' : ''}. The run log is kept.
277
+ </p>
278
+ </div>
279
+ )}
280
+ </section>
281
+ )
282
+ }
283
+
284
+ function RunLog(): React.JSX.Element {
285
+ const { records: runs, isLoading, error } = useAiRuns()
286
+ const timezone = useTimezone()
287
+
288
+ return (
289
+ <section className="rounded-md border border-border p-5">
290
+ <h2 className="text-[15px] font-semibold text-ink">Run log</h2>
291
+ {isLoading && <LoadingPanel label="Loading runs…" />}
292
+ {error !== null && <ErrorPanel error={error} />}
293
+ {!isLoading && error === null && runs.length === 0 && (
294
+ <p className="mt-2 text-[13px] text-ink-muted">
295
+ No runs yet. Start one from the Agent menu on any record page and pick <em>Kelpie AI</em>.
296
+ </p>
297
+ )}
298
+ {runs.length > 0 && (
299
+ <ul className="mt-3 flex flex-col gap-2">
300
+ {runs.map((run) => (
301
+ <li key={run.id} className="rounded-md border border-border bg-surface p-3">
302
+ <div className="flex flex-wrap items-center gap-2">
303
+ <Chip tone={STATUS_TONES[run.status]}>{run.status}</Chip>
304
+ <span className="text-[13px] font-medium text-ink">{run.taskId}</span>
305
+ <span className="text-[12px] text-ink-muted">
306
+ {run.targetType} · {run.targetId}
307
+ </span>
308
+ <span className="ml-auto text-[12px] text-ink-faint">{formatRelativeTime(run.createdAt, timezone)}</span>
309
+ </div>
310
+ <p className="mt-1 text-[12px] text-ink-muted">
311
+ <span className="font-mono">{run.model}</span>
312
+ {run.inputTokens !== null && run.outputTokens !== null
313
+ ? ` · ${String(run.inputTokens)} in · ${String(run.outputTokens)} out`
314
+ : ''}
315
+ </p>
316
+ {run.failureReason !== null && <p className="mt-2 text-[12px] text-danger">{run.failureReason}</p>}
317
+ {run.output !== null && (
318
+ <pre className="mt-2 max-h-64 overflow-auto whitespace-pre-wrap rounded bg-surface-raised p-2 text-[12px] text-ink">
319
+ {run.output}
320
+ </pre>
321
+ )}
322
+ {run.operations !== null && run.operations.length > 0 && (
323
+ <ul className="mt-2 flex flex-col gap-1">
324
+ {run.operations.map((operation, index) => (
325
+ <li key={`${run.id}-op-${String(index)}`} className="flex flex-wrap items-center gap-2 text-[12px]">
326
+ <Chip tone={OPERATION_TONES[operation.status] ?? 'neutral'}>{operation.status}</Chip>
327
+ <span className="font-medium text-ink">{operation.kind}</span>
328
+ <span className="text-ink-muted">{operation.detail}</span>
329
+ </li>
330
+ ))}
331
+ </ul>
332
+ )}
333
+ </li>
334
+ ))}
335
+ </ul>
336
+ )}
337
+ </section>
338
+ )
339
+ }
340
+
341
+ export function AiPage(): React.JSX.Element {
342
+ const { record: settings, isLoading, error } = useAiSettings()
343
+
344
+ return (
345
+ <div className="animate-slide-in mx-auto max-w-4xl space-y-6">
346
+ <PageHeader title="AI" description="Run agent tasks with your own model provider." />
347
+ {isLoading && <LoadingPanel label="Loading AI settings…" />}
348
+ {error !== null && <ErrorPanel error={error} />}
349
+ {settings !== undefined && <SettingsPanel settings={settings} />}
350
+ <RunLog />
351
+ </div>
352
+ )
353
+ }