Compare commits

..

1 Commits

Author SHA1 Message Date
dependabot[bot] 6bcdf543d6 chore(deps-dev): bump jsdom from 29.1.1 to 30.1.3
Bumps [jsdom](https://github.com/jsdom/jsdom) from 29.1.1 to 30.1.3.
- [Release notes](https://github.com/jsdom/jsdom/releases)
- [Commits](https://github.com/jsdom/jsdom/compare/v29.1.1...v30.1.3)

---
updated-dependencies:
- dependency-name: jsdom
  dependency-version: 30.1.3
  dependency-type: direct:development
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-10-25 11:19:47 +00:00
184 changed files with 830 additions and 3448 deletions
+1 -12
View File
@@ -1161,7 +1161,7 @@ jobs:
docker run -d --name trek-ci -p 127.0.0.1:3000:3000 \
--read-only --tmpfs /tmp:noexec,nosuid,size=128m \
--security-opt no-new-privileges:true \
--cap-drop ALL --cap-add CHOWN --cap-add SETUID --cap-add SETGID --cap-add KILL \
--cap-drop ALL --cap-add CHOWN --cap-add SETUID --cap-add SETGID \
-v "$RUNNER_TEMP/trek/data:/app/data" \
-v "$RUNNER_TEMP/trek/uploads:/app/uploads" \
-e ENCRYPTION_KEY="$(openssl rand -hex 32)" \
@@ -1194,17 +1194,6 @@ jobs:
curl -sf http://127.0.0.1:3000/ | grep -q '<div id="root">' \
|| { echo "::error::/ does not serve the client"; exit 1; }
# Same capabilities as the shipped compose file: dumb-init has to be able
# to pass the stop signal on to node, or docker stop ends in SIGKILL (137).
- name: Stop gracefully
run: |
set -euo pipefail
docker stop -t 30 trek-ci >/dev/null
code="$(docker inspect -f '{{.State.ExitCode}}' trek-ci)"
[ "$code" = "0" ] || { echo "::error::docker stop ended with exit code $code, not a graceful shutdown"; exit 1; }
docker logs trek-ci 2>&1 | grep -q 'SIGTERM received' \
|| { echo "::error::the server never saw SIGTERM"; exit 1; }
- name: Container log
if: always()
run: docker logs trek-ci 2>&1 || true
+2 -5
View File
@@ -234,15 +234,12 @@ the details.
## Get started in 30 seconds
```bash
ENCRYPTION_KEY=$(openssl rand -hex 32) docker run -d --name trek -p 3000:3000 \
ENCRYPTION_KEY=$(openssl rand -hex 32) docker run -d -p 3000:3000 \
-e ENCRYPTION_KEY=$ENCRYPTION_KEY \
-e COOKIE_SECURE=false \
-v ./data:/app/data -v ./uploads:/app/uploads mauriceboe/trek
```
Open `http://localhost:3000`, or `http://<server-ip>:3000` from another machine. On first boot TREK seeds an admin account — if you set `ADMIN_EMAIL`/`ADMIN_PASSWORD` those are used, otherwise the credentials are printed to the container log (`docker logs trek`).
`COOKIE_SECURE=false` is only for trying TREK over plain HTTP: without it the browser drops the session cookie and the login does not stick. Once TREK sits behind HTTPS (see [Reverse Proxy](#reverse-proxy)), remove it.
Open `http://localhost:3000`. On first boot TREK seeds an admin account — if you set `ADMIN_EMAIL`/`ADMIN_PASSWORD` those are used, otherwise the credentials are printed to the container log (`docker logs trek`).
<div align="center">
+2 -2
View File
@@ -1,5 +1,5 @@
apiVersion: v2
name: trek
version: 5.0.0
version: 4.3.4
description: Minimal Helm chart for TREK app
appVersion: "5.0.0"
appVersion: "4.3.4"
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@trek/client",
"version": "5.0.0",
"version": "4.3.4",
"engines": {
"node": "^22.22.2 || ^24.15.0 || >=26.0.0"
},
@@ -131,7 +131,7 @@
"eslint-plugin-react-hooks": "^7.1.1",
"eslint-plugin-react-refresh": "^0.5.7",
"fake-indexeddb": "^6.2.5",
"jsdom": "^29.1.1",
"jsdom": "^30.1.3",
"msw": "^2.15.0",
"postcss": "^8.5.28",
"prettier": "^3.9.8",
+1 -1
View File
@@ -3,7 +3,7 @@
"@typescript-eslint/no-non-null-assertion": 382,
"@typescript-eslint/no-misused-promises": 849,
"no-console": 88,
"complexity": 220,
"complexity": 221,
"@typescript-eslint/no-explicit-any": 146,
"trek/no-swallowed-catch": 130,
"max-params": 32,
+1 -1
View File
@@ -1,5 +1,5 @@
{
"admin.ts": 112,
"admin.ts": 126,
"atlas.ts": 9,
"backup.ts": 10,
"budget.ts": 36,
+1
View File
@@ -150,6 +150,7 @@
"src/pages/resetPassword/useResetPassword.ts",
"src/pages/settings/useSettings.ts",
"src/pages/sharedTrip/useSharedTrip.ts",
"src/pages/tripPlanner/useBookingEdits.ts",
"src/pages/tripPlanner/usePlaceFormOpeners.ts",
"src/pages/tripPlanner/usePlannerDialogs.ts",
"src/pages/tripPlanner/useTripPlanner.ts",
+1 -1
View File
@@ -1,5 +1,5 @@
{
"components/Admin/plugins/pluginMenu.ts": 2,
"components/Admin/AdminPluginsPanel.tsx": 2,
"components/Budget/BudgetPanelMemberChips.tsx": 6,
"components/Budget/CostsPanel.tsx": 3,
"components/Budget/ReceiptPreviewModal.tsx": 2,
+2 -2
View File
@@ -2,13 +2,13 @@
"e2e/help/fixtures.ts": 2291,
"src/api/client.ts": 1873,
"src/components/Admin/AdminPluginsPanel.test.tsx": 2704,
"src/components/Admin/AdminPluginsPanel.tsx": 1277,
"src/components/Admin/AdminPluginsPanel.tsx": 1667,
"src/components/Budget/CostsPanel.test.tsx": 2736,
"src/components/Budget/CostsPanel.tsx": 1798,
"src/components/Map/MapView.tsx": 1385,
"src/components/Map/MapViewGL.test.tsx": 2919,
"src/components/Map/MapViewGL.tsx": 2290,
"src/components/Map/RouteCalculator.ts": 1063,
"src/components/Map/RouteCalculator.ts": 1076,
"src/components/PDF/TripPDF.tsx": 1082,
"src/components/Planner/DayDetailPanel.test.tsx": 2333,
"src/components/Planner/DayPlanSidebar.test.tsx": 5349,
+1 -1
View File
@@ -1,7 +1,7 @@
{
"App.tsx": 11,
"components/Admin/AdminPluginsPanel.tsx": 2,
"components/Admin/DefaultUserSettingsTab.tsx": 1,
"components/Admin/plugins/pluginMenu.ts": 2,
"components/Atlas/AtlasCountryPlaces.tsx": 6,
"components/BackgroundTasks/BackgroundTasksWidget.tsx": 4,
"components/Budget/BudgetPanel.helpers.ts": 2,
-2
View File
@@ -229,8 +229,6 @@ export const aiAdminApi = {
connection: (): Promise<AiAdminConnectionResponse> => apiClient.get('/admin/ai/connection').then((r) => r.data),
saveConnection: (body: AiInstanceConnectionRequest): Promise<AiAdminConnectionResponse> =>
apiClient.put('/admin/ai/connection', body, viaProvider).then((r) => r.data),
setModel: (model: string): Promise<AiAdminConnectionResponse> =>
apiClient.patch('/admin/ai/connection/model', { model }).then((r) => r.data),
removeConnection: (): Promise<SuccessResponse> => apiClient.delete('/admin/ai/connection').then((r) => r.data),
models: (): Promise<AiModelListResponse> => apiClient.get('/admin/ai/models', viaProvider).then((r) => r.data),
};
-1
View File
@@ -692,7 +692,6 @@ describe('client > request payloads', () => {
it('FE-APISURF-030: adminApi.pluginActivate only sends consent when granted', async () => {
expect((await traceOne(() => adminApi.pluginActivate('koffi'))).body).toEqual({})
expect((await traceOne(() => adminApi.pluginActivate('koffi', true))).body).toEqual({ consent: true })
expect((await traceOne(() => adminApi.pluginActivate('koffi', false, true))).body).toEqual({ acceptTrekRange: true })
})
it('FE-APISURF-031: adminApi.pluginInstall spreads its options next to the id', async () => {
+2 -2
View File
@@ -574,9 +574,9 @@ export const adminApi = {
plugins: () => apiClient.get('/admin/plugins').then(r => r.data),
pluginBrowse: (refresh?: boolean) => apiClient.get('/admin/plugins/registry', { params: refresh ? { refresh: 1 } : undefined }).then(r => r.data),
pluginDetail: (id: string) => apiClient.get(`/admin/plugins/registry/${encodeURIComponent(id)}`).then(r => r.data),
pluginInstall: (id: string, opts?: Omit<PluginInstallRequest, 'id'>) =>
pluginInstall: (id: string, opts?: Pick<PluginInstallRequest, 'version' | 'constraint' | 'withDependencies'>) =>
apiClient.post('/admin/plugins/install', { id, ...opts } satisfies PluginInstallRequest).then(r => r.data),
pluginActivate: (id: string, consent?: boolean, accept?: boolean) => apiClient.post(`/admin/plugins/${id}/activate`, { consent: consent || undefined, acceptTrekRange: accept || undefined }).then(r => r.data),
pluginActivate: (id: string, consent?: boolean) => apiClient.post(`/admin/plugins/${id}/activate`, consent ? { consent: true } : {}).then(r => r.data),
pluginDeactivate: (id: string) => apiClient.post(`/admin/plugins/${id}/deactivate`).then(r => r.data),
// `version` pins the exact version to install (the rollback path); omitted, the server
// resolves the newest TREK-compatible version itself.
@@ -489,10 +489,10 @@ describe('AdminPluginsPanel — TREK-version compatibility', () => {
fireEvent.click(await screen.findByText('Discover'))
}
it('marks a plugin no published version runs on, and still lets the admin install it', async () => {
it('blocks Install when no published version runs on this TREK, and says why', async () => {
await openDiscover({ trek: '>=4.0.0', hostVersion: '3.3.0', compatible: false, latestCompatible: null })
expect(await screen.findByText('Not confirmed for TREK 3.3.0 yet')).toBeInTheDocument()
expect(screen.getByRole('button', { name: /^install$/i })).toBeEnabled()
const btn = await screen.findByRole('button', { name: /^incompatible$/i })
expect(btn).toBeDisabled()
})
it('offers the newest version that DOES run here rather than a dead button', async () => {
@@ -549,11 +549,9 @@ function panelRoot(container: HTMLElement): HTMLElement {
}
/** Opens one of the toolbar dropdowns (identified by its current title) and picks an option. */
/** The toolbar's one Filter button; a pick in its menu leaves the menu open. */
const filterButton = (): HTMLElement => screen.getByRole('button', { name: /^Filter/ })
async function pickFilter(option: RegExp) {
if ((await screen.findByRole('button', { name: /^Filter/ })).getAttribute('aria-expanded') !== 'true') fireEvent.click(filterButton())
fireEvent.click(await screen.findByRole('menuitemradio', { name: option }))
async function pickFilter(trigger: RegExp, option: RegExp) {
fireEvent.click(await screen.findByTitle(trigger))
fireEvent.click(await screen.findByRole('button', { name: option }))
}
/** The enable toggle of a named installed row. */
@@ -612,9 +610,9 @@ describe('AdminPluginsPanel — load states and toolbar', () => {
render(<AdminPluginsPanel />)
await screen.findByText('Gotify')
await pickFilter(/^Widget$/)
await pickFilter(/^Type: All types$/, /^Widget$/)
expect(await screen.findByRole('menuitemradio', { name: 'Widget' })).toHaveAttribute('aria-checked', 'true')
expect(await screen.findByTitle('Type: Widget')).toBeInTheDocument()
expect(screen.getByText('Countdown')).toBeInTheDocument()
expect(screen.queryByText('Gotify')).not.toBeInTheDocument()
})
@@ -628,15 +626,15 @@ describe('AdminPluginsPanel — load states and toolbar', () => {
render(<AdminPluginsPanel />)
await screen.findByText('OnOne')
await pickFilter(/^Off$/)
await pickFilter(/^Status: All$/, /^Off$/)
expect(await screen.findByText('OffOne')).toBeInTheDocument()
expect(screen.queryByText('OnOne')).not.toBeInTheDocument()
await pickFilter(/^Error$/)
await pickFilter(/^Status: Off$/, /^Error$/)
expect(await screen.findByText('BadOne')).toBeInTheDocument()
expect(screen.getByText('boom')).toBeInTheDocument()
await pickFilter(/^Update available$/)
await pickFilter(/^Status: Error$/, /^Update available$/)
expect(await screen.findByText('OnOne')).toBeInTheDocument()
expect(screen.queryByText('BadOne')).not.toBeInTheDocument()
})
@@ -646,10 +644,11 @@ describe('AdminPluginsPanel — load states and toolbar', () => {
render(<AdminPluginsPanel />)
await screen.findByText('Gotify')
await pickFilter(/^Updates first$/)
expect(filterButton()).toHaveTextContent('Updates first')
await pickFilter(/^Sort: Name$/, /^Updates first$/)
expect(await screen.findByTitle('Sort: Updates first')).toBeInTheDocument()
await clickDiscover()
await waitFor(() => expect(filterButton()).toHaveTextContent(/Name$/))
await waitFor(() => expect(screen.getByTitle('Sort: Name')).toBeInTheDocument())
})
it('FE-COMP-PLUGINS-PANEL-008: rescan re-pulls the registry past its cache and confirms with a toast', async () => {
@@ -1664,16 +1663,15 @@ describe('AdminPluginsPanel — Discover cards and the detail modal', () => {
})
})
describe('AdminPluginsPanel — security dialog', () => {
it('FE-COMP-PLUGINS-PANEL-048: the shield in the header opens how plugins are contained', async () => {
describe('AdminPluginsPanel — security footer', () => {
it('FE-COMP-PLUGINS-PANEL-048: the containment note expands into its sections', async () => {
panelWith([])
render(<AdminPluginsPanel />)
await screen.findByText('No plugins installed yet.')
expect(screen.queryByText('Every plugin runs boxed in')).not.toBeInTheDocument()
fireEvent.click(screen.getByRole('button', { name: 'How plugins are secured' }))
fireEvent.click(screen.getByText('How plugins are contained — and the limits'))
expect(screen.getByRole('dialog', { name: 'How plugins are secured' })).toBeInTheDocument()
expect(screen.getByText('Every plugin runs boxed in')).toBeInTheDocument()
expect(screen.getByText('What "Reviewed" means')).toBeInTheDocument()
expect(screen.getByText('What "Signed" means')).toBeInTheDocument()
@@ -1702,9 +1700,9 @@ describe('AdminPluginsPanel toolbar and dialogs', () => {
row({ id: 'c-page', name: 'Gamma Page', description: 'a page', type: 'page', enabled: 1, status: 'error', last_error: 'boom' }),
]
const pickFilter = async (user: ReturnType<typeof userEvent.setup>, option: RegExp) => {
if (filterButton().getAttribute('aria-expanded') !== 'true') await user.click(filterButton())
await user.click(screen.getByRole('menuitemradio', { name: option }))
const pickFilter = async (user: ReturnType<typeof userEvent.setup>, filter: RegExp, option: RegExp) => {
await user.click(screen.getByTitle(filter))
await user.click(screen.getByRole('button', { name: option }))
}
it('FE-W5PLG-001: the search box narrows the installed list by name and description', async () => {
@@ -1736,7 +1734,7 @@ describe('AdminPluginsPanel toolbar and dialogs', () => {
render(<AdminPluginsPanel />)
await screen.findByText('Alpha Widget')
await pickFilter(user, /^Widget$/)
await pickFilter(user, /^Type:/, /^Widget$/)
await waitFor(() => expect(screen.queryByText('Beta Bridge')).not.toBeInTheDocument())
expect(screen.getByText('Alpha Widget')).toBeInTheDocument()
@@ -1748,15 +1746,15 @@ describe('AdminPluginsPanel toolbar and dialogs', () => {
render(<AdminPluginsPanel />)
await screen.findByText('Alpha Widget')
await pickFilter(user, /^Active$/)
await pickFilter(user, /^Status:/, /^Active$/)
await waitFor(() => expect(screen.queryByText('Beta Bridge')).not.toBeInTheDocument())
expect(screen.queryByText('Gamma Page')).not.toBeInTheDocument()
await pickFilter(user, /^Off$/)
await pickFilter(user, /^Status:/, /^Off$/)
await waitFor(() => expect(screen.getByText('Beta Bridge')).toBeInTheDocument())
expect(screen.queryByText('Alpha Widget')).not.toBeInTheDocument()
await pickFilter(user, /^Error$/)
await pickFilter(user, /^Status:/, /^Error$/)
await waitFor(() => expect(screen.getByText('Gamma Page')).toBeInTheDocument())
expect(screen.queryByText('Alpha Widget')).not.toBeInTheDocument()
})
@@ -1768,13 +1766,13 @@ describe('AdminPluginsPanel toolbar and dialogs', () => {
await screen.findByText('Alpha Widget')
await waitFor(() => expect(screen.getByText(/updates? available/i)).toBeInTheDocument())
await pickFilter(user, /^Updates first$/)
await pickFilter(user, /^Sort:/, /^Updates first$/)
await waitFor(() => {
const names = screen.getAllByText(/Alpha Widget|Beta Bridge|Gamma Page/).map(e => e.textContent)
expect(names[0]).toBe('Gamma Page')
})
await pickFilter(user, /^Update available$/)
await pickFilter(user, /^Status:/, /^Update available$/)
await waitFor(() => expect(screen.queryByText('Alpha Widget')).not.toBeInTheDocument())
expect(screen.getByText('Gamma Page')).toBeInTheDocument()
})
@@ -1785,10 +1783,11 @@ describe('AdminPluginsPanel toolbar and dialogs', () => {
render(<AdminPluginsPanel />)
await screen.findByText('Alpha Widget')
await pickFilter(user, /^Updates first$/)
expect(filterButton()).toHaveTextContent('Updates first')
await pickFilter(user, /^Sort:/, /^Updates first$/)
expect(screen.getByTitle(/^Sort: Updates first$/)).toBeInTheDocument()
await user.click(screen.getByRole('tab', { name: /Discover/ }))
await waitFor(() => expect(filterButton()).toHaveTextContent(/Name$/))
await waitFor(() => expect(screen.getByTitle(/^Sort: Name$/)).toBeInTheDocument())
})
it('FE-W5PLG-007: the registry sorts by downloads and by review date', async () => {
@@ -1803,19 +1802,19 @@ describe('AdminPluginsPanel toolbar and dialogs', () => {
await user.click(screen.getByRole('tab', { name: /Discover/ }))
await screen.findByText('Old Tool')
await pickFilter(user, /^Most downloads$/)
await pickFilter(user, /^Sort:/, /^Most downloads$/)
await waitFor(() => {
const names = screen.getAllByText(/^(Old|New) Tool$/).map(e => e.textContent)
expect(names[0]).toBe('New Tool')
})
await pickFilter(user, /^Recently updated$/)
await pickFilter(user, /^Sort:/, /^Recently updated$/)
await waitFor(() => {
const names = screen.getAllByText(/^(Old|New) Tool$/).map(e => e.textContent)
expect(names[0]).toBe('New Tool')
})
await pickFilter(user, /^Name$/)
await pickFilter(user, /^Sort:/, /^Name$/)
await waitFor(() => {
const names = screen.getAllByText(/^(Old|New) Tool$/).map(e => e.textContent)
expect(names[0]).toBe('New Tool')
@@ -1834,7 +1833,7 @@ describe('AdminPluginsPanel toolbar and dialogs', () => {
await user.click(screen.getByRole('tab', { name: /Discover/ }))
await screen.findByText('Mapper')
await pickFilter(user, /^Page$/)
await pickFilter(user, /^Type:/, /^Page$/)
await waitFor(() => expect(screen.queryByText('Mapper')).not.toBeInTheDocument())
expect(screen.getByText('Poster')).toBeInTheDocument()
@@ -1963,12 +1962,12 @@ describe('AdminPluginsPanel toolbar and dialogs', () => {
const { container } = render(<AdminPluginsPanel />)
await screen.findByText('Alpha Widget')
await user.click(filterButton())
expect(screen.getByRole('menuitemradio', { name: /^Widget$/ })).toBeInTheDocument()
await user.click(screen.getByTitle(/^Type:/))
expect(screen.getByRole('button', { name: /^Widget$/ })).toBeInTheDocument()
const layer = container.querySelector('.fixed.inset-0.z-20') as HTMLElement
fireEvent.click(layer)
await waitFor(() => expect(screen.queryByRole('menuitemradio', { name: /^Widget$/ })).not.toBeInTheDocument())
await waitFor(() => expect(screen.queryByRole('button', { name: /^Widget$/ })).not.toBeInTheDocument())
})
})
@@ -2005,11 +2004,12 @@ describe('AdminPluginsPanel registry cards and dependency chips', () => {
await screen.findByText('Alpha Widget')
await openDiscover(user)
await user.click(filterButton())
await user.click(screen.getByRole('menuitemradio', { name: /^Most downloads$/ }))
expect(filterButton()).toHaveTextContent('Most downloads')
await user.click(screen.getByTitle(/^Sort:/))
await user.click(screen.getByRole('button', { name: /^Most downloads$/ }))
expect(screen.getByTitle(/^Sort: Most downloads$/)).toBeInTheDocument()
await user.click(screen.getByRole('tab', { name: /Installed/ }))
await waitFor(() => expect(filterButton()).toHaveTextContent(/Name$/))
await waitFor(() => expect(screen.getByTitle(/^Sort: Name$/)).toBeInTheDocument())
})
it('FE-W5PLG-017: an outrun release offers the newest compatible version instead of a dead button', async () => {
@@ -2026,8 +2026,9 @@ describe('AdminPluginsPanel registry cards and dependency chips', () => {
expect(offer).not.toBeDisabled()
expect(offer).toHaveAttribute('title', expect.stringContaining('3.5.0'))
// Nothing fits: no dead button any more, but a card that says so before anything installs.
expect(screen.getByText(/^Not confirmed for TREK .+ yet$/)).toBeInTheDocument()
const dead = screen.getByRole('button', { name: /^Incompatible$/ })
expect(dead).toBeDisabled()
expect(dead.getAttribute('title')).toBeTruthy()
})
it('FE-W5PLG-018: an already installed registry entry cannot be installed again', async () => {
@@ -2555,7 +2556,7 @@ describe('AdminPluginsPanel — TREK-range bypass (TREK_PLUGINS_IGNORE_TREK_RANG
expect(await screen.findByText('Version checks off')).toBeInTheDocument()
})
it('FE-PLG-BYPASS-002: offers Install for an incompatible entry and asks before installing', async () => {
it('FE-PLG-BYPASS-002: offers "Install anyway" for an incompatible entry and asks before installing', async () => {
let posted: unknown = null
bypassPanel([plugin({ id: 'something-else' })], incompatibleEntry())
server.use(http.post('*/api/admin/plugins/install', async ({ request }) => {
@@ -2565,7 +2566,7 @@ describe('AdminPluginsPanel — TREK-range bypass (TREK_PLUGINS_IGNORE_TREK_RANG
withToast()
fireEvent.click(await screen.findByText('Discover'))
const btn = await screen.findByRole('button', { name: /^install$/i })
const btn = await screen.findByRole('button', { name: /^install anyway$/i })
expect(btn).toBeEnabled()
fireEvent.click(btn)
@@ -2584,7 +2585,7 @@ describe('AdminPluginsPanel — TREK-range bypass (TREK_PLUGINS_IGNORE_TREK_RANG
server.use(http.post('*/api/admin/plugins/install', () => { posted = true; return HttpResponse.json({ id: 'trek-gotify', version: '2.0.0', trekRangeBypassed: null }) }))
withToast()
fireEvent.click(await screen.findByText('Discover'))
fireEvent.click(await screen.findByRole('button', { name: /^install$/i }))
fireEvent.click(await screen.findByRole('button', { name: /^install anyway$/i }))
const dialog = await screen.findByRole('dialog', { name: /outside its supported trek versions/i })
fireEvent.click(within(dialog).getByRole('button', { name: /cancel/i }))
+384 -33
View File
@@ -1,9 +1,10 @@
import { useState, type ReactNode } from 'react'
import { useEffect, useRef, useState, type CSSProperties, type ReactNode } from 'react'
import { createPortal } from 'react-dom'
import {
Blocks, AlertTriangle, RefreshCw, Trash2, Download, Bug, ShieldCheck, UploadCloud,
ArrowUpCircle, Github, ExternalLink, Check, Search, Link2, KeyRound, ShieldAlert,
SlidersHorizontal, CircleDot, Database,
Globe, History, Puzzle, Bot, Loader2,
ArrowUpCircle, Github, ExternalLink, ChevronDown, Check, Lock, Search, Link2, KeyRound, ShieldAlert,
SlidersHorizontal, ArrowUpDown, CircleDot, MoreHorizontal, RotateCw, Database,
Globe, Info, History, PauseCircle, Puzzle, Bot, Loader2,
} from 'lucide-react'
import PluginIcon from '../shared/PluginIcon'
import { useInstanceSettings } from './useInstanceSettings'
@@ -22,17 +23,15 @@ import {
SettingsCard, SettingRows, SettingRow, SettingsHint, StatusPill,
SETTINGS_BUTTON_PRIMARY, SETTINGS_ICON_BUTTON,
} from '../Settings/settingsKit'
import { POPOVER } from '../Packing/packingPopoverStyles'
import {
KNOWN_TYPES, PERM_KEYS, blockIsCurrent, dependencyRows, fingerprint, formatCompactCount,
installOffer, signatureBlockView,
type PluginDep, type PluginRow, type RegistryItem, type SigSubject,
type T, type VersionInfo, type VersionMismatch,
KNOWN_TYPES, PERM_KEYS, blockIsCurrent, dependencyRows, deriveDeps, fingerprint, formatCompactCount,
installOffer, isRegistrySourced, parseJson, signatureBlockView, sortLabel, statusLabel,
type PluginDep, type PluginRow, type RegistryItem, type SigSubject, type SortKey,
type StatusFilter, type T, type TypeFilter, type VersionInfo, type VersionMismatch,
} from './plugins/pluginModel'
import { usePluginDetail } from './plugins/usePluginDetail'
import { usePluginsAdmin } from './plugins/usePluginsAdmin'
import PluginFilterMenu from './plugins/PluginFilterMenu'
import PluginInstalledRow from './plugins/PluginInstalledRow'
import PluginSecurityDialog from './plugins/PluginSecurityDialog'
/**
* Admin → Plugins (#plugins). A full plugin-management surface: a segmented
@@ -43,13 +42,31 @@ import PluginSecurityDialog from './plugins/PluginSecurityDialog'
* tile; the security section at the bottom explains the model honestly.
*/
// Runtime health → dot colour on the icon tile.
const HEALTH: Record<string, string> = {
active: 'bg-success',
starting: 'bg-info animate-pulse',
error: 'bg-danger',
inactive: 'bg-content-faint/60',
disabled: 'bg-warning',
incompatible: 'bg-warning',
}
/** The head band of a dialog that warns before something happens: a faint wash of the warning tone. */
const WARN_TINT = 'color-mix(in srgb, var(--warning) 10%, transparent)'
/** The eyebrow over a block, the size the dialogs' sections use. */
const EYEBROW = 'm-0 font-geist font-bold uppercase tracking-[.08em] text-content-faint'
/** A capability or dependency chip on an installed row. */
const CHIP = 'inline-flex max-w-full items-center gap-1.5 rounded-full border px-2 py-[2px] font-medium'
const CHIP_NEUTRAL = 'border-edge-faint bg-surface-secondary text-content-secondary'
const CHIP_NET = 'border-transparent bg-info-soft text-info'
const CHIP_WARN = 'border-transparent bg-warning-soft text-warning'
/** A small action inside a row or a card: the kit's button, a size down. */
const SMALL_BUTTON = 'inline-flex flex-none items-center justify-center gap-1.5 rounded-[10px] bg-surface-card px-2.5 py-1.5 font-semibold text-content shadow-sm ring-1 ring-edge-faint hover:bg-surface-secondary disabled:cursor-default disabled:opacity-50'
const SMALL_PRIMARY = 'inline-flex flex-none items-center justify-center gap-1.5 rounded-[10px] bg-accent px-3 py-1.5 font-semibold text-accent-text hover:opacity-90 disabled:cursor-default disabled:bg-surface-tertiary disabled:text-content-faint'
/** A line of state under a row's name: a refused update, a paused one, an error. */
const ROW_NOTE = 'mt-1.5 flex min-w-0 items-center gap-1.5'
/** A pill that explains itself on hover. */
function HintPill({ hint, children }: { hint: string; children: ReactNode }) {
return (
@@ -59,6 +76,19 @@ function HintPill({ hint, children }: { hint: string; children: ReactNode }) {
)
}
function ReviewedBadge({ t }: { t: T }) {
return <ShieldCheck size={13} className="text-success shrink-0" aria-label={t('admin.plugins.reviewed')} />
}
/** Marks a manually-uploaded (sideloaded) plugin: no registry, unsigned, not reviewed. */
function SideloadedBadge({ t }: { t: T }) {
return (
<HintPill hint={t('admin.plugins.sideloadedHint')}>
<StatusPill tone="warning" icon={<UploadCloud size={11} />}>{t('admin.plugins.sideloaded')}</StatusPill>
</HintPill>
)
}
/**
* Signed / Unsigned, for registry plugins only (see isRegistrySourced).
*
@@ -83,6 +113,15 @@ function TrustBadge({ signed, t }: { signed: boolean; t: T }) {
)
}
/** Marks a dev-linked plugin: loaded from a local build dir + hot-reloaded (dev only). */
function DevLinkBadge({ t }: { t: T }) {
return (
<HintPill hint={t('admin.plugins.devLinkHint')}>
<StatusPill icon={<Link2 size={11} />}>{t('admin.plugins.devLinkBadge')}</StatusPill>
</HintPill>
)
}
function TypeBadge({ type, t }: { type: string; t: T }) {
return (
<span className="inline-flex flex-none items-center rounded-full bg-surface-tertiary px-2 py-[3px] font-geist font-bold uppercase tracking-[.06em] text-content-muted" style={fs(9.5)}>
@@ -106,7 +145,6 @@ export default function AdminPluginsPanel() {
sort, statusFilter, toggle, typeFilter, uninstallConfirmed, updatable, updateAll, updateAvailable, uploadInputRef,
uploadPlugin, versionPicker, view,
} = usePluginsAdmin()
const [securityOpen, setSecurityOpen] = useState(false)
return (
<div className="relative mb-24 sm:mb-0"
@@ -143,9 +181,6 @@ export default function AdminPluginsPanel() {
) : undefined}
action={ready ? (
<>
<BandButton label={t('admin.plugins.security.short')} onClick={() => setSecurityOpen(true)}>
<ShieldCheck size={15} strokeWidth={2} />
</BandButton>
<BandButton label={t('admin.plugins.upload')} onClick={pickUpload} disabled={busy === '__upload'}>
<UploadCloud size={15} strokeWidth={2} />
</BandButton>
@@ -207,9 +242,31 @@ export default function AdminPluginsPanel() {
/>
</label>
<PluginFilterMenu t={t} view={view} typeFilter={typeFilter} setTypeFilter={setTypeFilter}
statusFilter={statusFilter} setStatusFilter={setStatusFilter} sort={sort} setSort={setSort}
menu={menu} setMenu={setMenu} />
<FilterMenu id="type" label={t('admin.plugins.filterType')} value={typeFilter} menu={menu} setMenu={setMenu} icon={<SlidersHorizontal size={14} />}
options={[
['all', t('admin.plugins.allTypes')], ['widget', t('admin.plugins.type.widget')],
['integration', t('admin.plugins.type.integration')], ['page', t('admin.plugins.type.page')],
['trip-page', t('admin.plugins.type.trip-page')],
]}
valueLabel={typeFilter === 'all' ? t('admin.plugins.allTypes') : t(`admin.plugins.type.${typeFilter}` as never)}
onPick={v => setTypeFilter(v as TypeFilter)} />
{view === 'installed' && (
<FilterMenu id="status" label={t('admin.plugins.filterStatus')} value={statusFilter} menu={menu} setMenu={setMenu} icon={<CircleDot size={14} />}
options={[
['all', t('admin.plugins.allStatuses')], ['on', t('admin.plugins.status.active')], ['off', t('admin.plugins.stateOff')],
['update', t('admin.plugins.filterUpdate')], ['err', t('admin.plugins.status.error')],
]}
valueLabel={statusLabel(statusFilter, t)}
onPick={v => setStatusFilter(v as StatusFilter)} />
)}
<FilterMenu id="sort" label={t('admin.plugins.sortBy')} value={sort} menu={menu} setMenu={setMenu} icon={<ArrowUpDown size={14} />}
options={view === 'discover'
? [['name', t('admin.plugins.sortName')], ['recent', t('admin.plugins.sortRecent')], ['downloads', t('admin.plugins.sortDownloads')]]
: [['name', t('admin.plugins.sortName')], ['recent', t('admin.plugins.sortRecent')], ['updates', t('admin.plugins.sortUpdates')]]}
valueLabel={sortLabel(sort, t)}
onPick={v => setSort(v as SortKey)} />
</div>
{view === 'discover' ? (
@@ -242,7 +299,7 @@ export default function AdminPluginsPanel() {
) : (
<SettingRows>
{shownInstalled.map(p => (
<PluginInstalledRow key={p.id} p={p} t={t} busy={busy} menu={menu} setMenu={setMenu}
<InstalledRow key={p.id} p={p} t={t} busy={busy} menu={menu} setMenu={setMenu}
hasUpdate={updateAvailable(p)} latestVer={latest[p.id]}
newerIncompatible={newerIncompatible(p)}
blocked={blockIsCurrent(p, latest[p.id])}
@@ -263,7 +320,7 @@ export default function AdminPluginsPanel() {
)}
</SettingsCard>
{securityOpen && <PluginSecurityDialog t={t} onClose={() => setSecurityOpen(false)} />}
<SecurityInfo t={t} />
{/* Registry detail dialog */}
{detailFor && (
@@ -381,6 +438,268 @@ function SegBtn({ active, onClick, label, count }: { active: boolean; onClick: (
)
}
/** Re-renders while the page moves under an open, portaled menu, so it stays pinned to its trigger. */
function useFollowTrigger(open: boolean) {
const [, reanchor] = useState(0)
useEffect(() => {
if (!open) return
const onMove = () => reanchor(n => n + 1)
window.addEventListener('scroll', onMove, true)
window.addEventListener('resize', onMove)
return () => {
window.removeEventListener('scroll', onMove, true)
window.removeEventListener('resize', onMove)
}
}, [open])
}
function FilterMenu({ id, label, valueLabel, options, onPick, value, menu, setMenu, icon }: {
id: string; label: string; valueLabel: string
options: Array<[string, string]>; onPick: (v: string) => void; value: string
menu: string | null; setMenu: (v: string | null) => void; icon?: ReactNode
}) {
const open = menu === id
const active = value !== options[0]?.[0]
const btnRef = useRef<HTMLButtonElement>(null)
// Portaled like the row menu: the card around the toolbar clips what overflows it.
useFollowTrigger(open)
return (
<div className="relative flex-none">
<button type="button" ref={btnRef} onClick={() => setMenu(open ? null : id)} title={`${label}: ${valueLabel}`} aria-expanded={open}
className={`inline-flex h-9 items-center gap-1.5 whitespace-nowrap rounded-[10px] border bg-surface-card px-3 text-content-secondary transition-colors hover:text-content ${
active ? 'border-[color:var(--text-primary)]' : 'border-edge'}`}
style={fs(12.5, 'body')}>
<span className="flex-none text-content-faint">{icon}</span>
<span>{label}: </span>
<span className="font-semibold text-content">{valueLabel}</span>
<ChevronDown size={13} className={`flex-none text-content-faint transition-transform ${open ? 'rotate-180' : ''}`} />
</button>
{open && createPortal(
<div className="min-w-[200px] max-w-[calc(100vw-2rem)]" style={{ ...POPOVER, ...anchorMenu(btnRef.current) }}>
{options.map(([v, lbl]) => (
<button type="button" key={v} onClick={() => { onPick(v); setMenu(null) }}
className={`${MENU_ITEM} ${value === v ? 'font-semibold text-content' : 'text-content-secondary'}`} style={fs(12.5, 'body')}>
<span className="min-w-0 flex-1 truncate text-start">{lbl}</span>
<Check size={14} className={`flex-none text-content-muted ${value === v ? 'opacity-100' : 'opacity-0'}`} />
</button>
))}
</div>,
document.body,
)}
</div>
)
}
function InstalledRow({ p, t, busy, menu, setMenu, hasUpdate, latestVer, newerIncompatible, blocked, onToggle, onUpdate, onRestart, onChangeVersion, onResume, onReviewBlock, onErrors, onEgress, onSettings, onUninstall }: {
p: PluginRow; t: T; busy: string | null; menu: string | null; setMenu: (v: string | null) => void
hasUpdate: boolean; latestVer?: string; newerIncompatible: { version: string; range: string } | null; blocked: boolean
onToggle: () => void; onUpdate: () => void; onRestart: () => void; onChangeVersion: () => void; onResume: () => void; onReviewBlock: () => void
onErrors: () => void; onEgress: () => void; onSettings: () => void; onUninstall: () => void
}) {
const caps = deriveCaps(parseJson<string[]>(p.permissions, []), parseJson<{ widget?: { slot?: string } }>(p.capabilities, {}), t)
const deps = deriveDeps(p, t)
const menuOpen = menu === `row:${p.id}`
const menuBtnRef = useRef<HTMLButtonElement>(null)
const working = busy === p.id
const on = p.enabled === 1 && p.status !== 'error'
// The menu is portaled to <body> and positioned `fixed` against the ⋯ button,
// because the row's ancestor (PageSidebar) is `overflow-hidden` and would clip
// an in-flow `absolute` menu — losing Delete on the lower rows of a long list.
// Re-anchor while the page moves under it.
useFollowTrigger(menuOpen)
const hostCount = p.egressHostCount ?? 0
return (
<div className={`group relative flex items-start gap-3 px-3.5 py-3 transition-colors hover:bg-surface-secondary ${working ? 'opacity-60' : ''}`}>
<div className="relative mt-0.5 flex-none">
<span className="grid h-10 w-10 place-items-center rounded-[12px] border border-edge-faint bg-surface-secondary">
<PluginIcon name={p.icon} size={19} className="text-content-secondary" />
</span>
<Tooltip label={t(`admin.plugins.status.${p.status}` as never)}>
<span className={`absolute -bottom-0.5 -end-0.5 h-3 w-3 rounded-full ring-2 ring-surface-card ${HEALTH[p.status] || HEALTH.inactive}`} />
</Tooltip>
</div>
<div className="min-w-0 flex-1">
<div className="flex flex-wrap items-center gap-x-2 gap-y-1">
<span className="min-w-0 truncate font-semibold tracking-[-.006em] text-content" style={fs(13.5, 'body')}>{p.name}</span>
{p.version && <span className="font-geist font-medium tabular-nums text-content-faint" style={fs(11)}>v{p.version}</span>}
{p.reviewed_at && <ReviewedBadge t={t} />}
{p.source_repo === 'local:upload' && <SideloadedBadge t={t} />}
{p.source_repo === 'local:link' && <DevLinkBadge t={t} />}
{/* Registry plugins only — a sideloaded/dev-linked plugin already says something
strictly stronger, and stacking "Unsigned" on top of it just dilutes the amber. */}
{isRegistrySourced(p.source_repo) && <TrustBadge signed={!!p.signed} t={t} />}
</div>
{p.description && <p className="m-0 mt-0.5 truncate text-content-muted" style={fs(12, 'body')}>{p.description}</p>}
{/* A refused update leaves a WORKING plugin pinned at its old version — so this is
its own row state, not an error state, and it persists until it is resolved
rather than dying with the toast that first reported it. */}
{blocked && p.updateBlock && (
<div className={`${ROW_NOTE} text-warning`} style={fs(11.5)}>
<ShieldAlert size={13} className="flex-none" />
<span className="truncate">{t('admin.plugins.updateBlocked', { reason: p.updateBlock.detail ?? p.updateBlock.code })}</span>
<button type="button" onClick={onReviewBlock}
className="flex-none font-semibold underline underline-offset-2 hover:opacity-80">
{t('admin.plugins.reviewBlock')}
</button>
</div>
)}
{/* A newer version this TREK can't run — informational, never a button: the fix
is a TREK upgrade, so the row must not nag or offer a doomed install. */}
{newerIncompatible && (
<div className={`${ROW_NOTE} text-content-faint`} style={fs(11.5)}>
<Info size={13} className="flex-none" />
<span className="truncate">{t('admin.plugins.newerNeedsTrek', { version: newerIncompatible.version, range: newerIncompatible.range })}</span>
</div>
)}
{/* Held: the admin deliberately installed a non-latest version, so updates are
paused rather than nagged — resuming is one click, right where the pause shows. */}
{p.updateHold && (
<div className={`${ROW_NOTE} text-content-faint`} style={fs(11.5)}>
<PauseCircle size={13} className="flex-none" />
<span className="truncate">{t('admin.plugins.updatesHeld', { version: p.version ?? '' })}</span>
<button type="button" onClick={onResume} disabled={working}
className="flex-none font-semibold text-content-secondary underline underline-offset-2 hover:opacity-80 disabled:opacity-50">
{t('admin.plugins.resumeUpdates')}
</button>
</div>
)}
{p.status === 'error' && p.last_error ? (
<div className={`${ROW_NOTE} text-danger`} style={fs(11.5)}>
<AlertTriangle size={13} className="flex-none" /><span className="truncate">{p.last_error}</span>
</div>
) : (caps.length > 0 || p.operatorEgress) && (
<div className="mt-2 flex flex-wrap items-center gap-1.5">
{caps.map((c, i) => (
<span key={i} className={`${CHIP} ${c.net ? CHIP_NET : CHIP_NEUTRAL}`} style={fs(11)}>
<c.icon size={12} className={c.net ? 'text-info' : 'text-content-muted'} /><span className="truncate">{c.label}</span>
</span>
))}
{/* This plugin talks to a service only the OPERATOR can name (a self-hosted
Gotify/ntfy), so its manifest can't list the host — the admin adds it.
Actionable, and warning-toned until at least one host exists, because
until then the plugin cannot reach anything and looks silently broken. */}
{p.operatorEgress && (
<Tooltip label={t('admin.plugins.allowedHosts.hint')}>
<button type="button" onClick={onEgress}
className={`${CHIP} ${hostCount > 0 ? CHIP_NET : CHIP_WARN} hover:opacity-80`} style={fs(11)}>
<Globe size={12} />
{hostCount > 0
? t('admin.plugins.allowedHosts.count', { n: hostCount })
: t('admin.plugins.allowedHosts.add')}
</button>
</Tooltip>
)}
</div>
)}
{deps.length > 0 && (
<div className="mt-1.5 flex flex-wrap items-center gap-1.5">
{deps.map((d, i) => (
<span key={i} className={`${CHIP} ${d.blocked || d.warn ? CHIP_WARN : CHIP_NEUTRAL}`} style={fs(11)}>
<d.icon size={12} className={d.blocked || d.warn ? 'text-warning' : 'text-content-muted'} /><span className="truncate">{d.label}</span>
</span>
))}
</div>
)}
</div>
<div className="flex flex-none items-center gap-2 self-center">
{hasUpdate && (
<button type="button" onClick={onUpdate} disabled={working}
className="inline-flex items-center gap-1.5 rounded-full bg-warning-soft px-2.5 py-1 font-semibold text-warning hover:opacity-90 disabled:opacity-50"
style={fs(11.5)}>
<ArrowUpCircle size={13} /> <span>{t('admin.plugins.updateTo', { version: latestVer })}</span>
</button>
)}
<span className={`min-w-[42px] text-end font-medium ${on ? 'text-content-secondary' : 'text-content-faint'}`} style={fs(12)}>
{p.enabled === 1 ? t('admin.plugins.status.active') : t('admin.plugins.stateOff')}
</span>
<ToggleSwitch on={p.enabled === 1} label={t('admin.plugins.enabledToggle')} onToggle={onToggle} />
<div className="relative">
<Tooltip label={t('admin.table.actions')} disabled={menuOpen}>
<button type="button" ref={menuBtnRef} data-testid={`plugin-row-menu-btn-${p.id}`} onClick={() => setMenu(menuOpen ? null : `row:${p.id}`)}
aria-expanded={menuOpen} aria-label={t('admin.table.actions')}
className={`grid h-8 w-8 place-items-center rounded-[10px] transition-colors ${menuOpen ? 'bg-surface-card text-content shadow-sm ring-1 ring-edge-faint' : 'text-content-faint hover:bg-surface-card hover:text-content'}`}>
<MoreHorizontal size={17} />
</button>
</Tooltip>
{menuOpen && createPortal(
<div data-testid={`plugin-row-menu-${p.id}`} style={{ ...POPOVER, ...anchorMenu(menuBtnRef.current) }}
className="min-w-[200px]">
{p.enabled === 1 && (
<MenuItem icon={<RotateCw size={14} />} label={t('admin.plugins.restart')} onClick={onRestart} />
)}
{/* A plugin gets the item if it declares scope:'instance' fields OR actions —
an action-only plugin still needs the dialog to run its buttons. */}
{((p.instanceSettingsCount ?? 0) > 0 || (p.instanceActionsCount ?? 0) > 0) && (
<MenuItem icon={<SlidersHorizontal size={14} />} label={t('admin.plugins.instanceSettings')} onClick={onSettings} />
)}
<MenuItem icon={<Bug size={14} />} label={t('admin.plugins.viewErrors')} onClick={onErrors} />
{/* Only a plugin that DECLARED operatorEgress gets the item — an admin must
never be invited to widen egress for a plugin that didn't ask for it
(same rule the row's egress chip follows). */}
{p.operatorEgress && (
<MenuItem icon={<Globe size={14} />} label={t('admin.plugins.allowedHosts')} onClick={onEgress} />
)}
{/* Registry plugins only — a sideload/dev-link has no registry versions to pick from. */}
{isRegistrySourced(p.source_repo) && (
<MenuItem icon={<History size={14} />} label={t('admin.plugins.changeVersion')} onClick={onChangeVersion} />
)}
{p.source_repo && p.source_repo !== 'local:upload' && p.source_repo !== 'local:link' && (
<>
<a href={`https://github.com/${p.source_repo}`} target="_blank" rel="noreferrer" onClick={() => setMenu(null)}
className={`${MENU_ITEM} text-content-secondary`} style={fs(12.5, 'body')}>
<span className="flex w-4 flex-none justify-center text-content-muted"><Github size={14} /></span> {t('admin.plugins.sourceRepo')}
</a>
<a href={`https://github.com/${p.source_repo}/issues`} target="_blank" rel="noreferrer" onClick={() => setMenu(null)}
className={`${MENU_ITEM} text-content-secondary`} style={fs(12.5, 'body')}>
<span className="flex w-4 flex-none justify-center text-content-muted"><CircleDot size={14} /></span> {t('admin.plugins.reportIssue')}
</a>
</>
)}
<div className="mx-1.5 my-1 h-px bg-edge-faint" />
<MenuItem icon={<Trash2 size={14} />} label={t('common.delete')} danger onClick={onUninstall} />
</div>,
document.body,
)}
</div>
</div>
</div>
)
}
/** Tallest the ⋯ menu gets (6 items + divider + padding). Drives the flip. */
const ROW_MENU_MAX_H = 260
/** Pin a portaled menu to the right edge of its trigger, flipping up when the bottom is tight. */
function anchorMenu(trigger: HTMLElement | null): CSSProperties {
const r = trigger?.getBoundingClientRect()
if (!r) return { position: 'fixed', top: 0, right: 0, zIndex: 100 }
const spaceBelow = window.innerHeight - r.bottom
const openUp = spaceBelow < ROW_MENU_MAX_H && r.top > spaceBelow
return {
position: 'fixed',
right: Math.max(8, window.innerWidth - r.right),
...(openUp ? { bottom: window.innerHeight - r.top + 4 } : { top: r.bottom + 4 }),
zIndex: 100,
}
}
/** One entry of a popover menu, in the packing popovers' shape. */
const MENU_ITEM = 'flex w-full items-center gap-2.5 rounded-[9px] px-2.5 py-2 font-medium transition-colors hover:bg-surface-tertiary'
function MenuItem({ icon, label, onClick, danger }: { icon: ReactNode; label: string; onClick: () => void; danger?: boolean }) {
return (
<button type="button" onClick={onClick}
className={`${MENU_ITEM} ${danger ? 'text-danger hover:bg-danger-soft' : 'text-content-secondary'}`} style={fs(12.5, 'body')}>
<span className={`flex w-4 flex-none justify-center ${danger ? 'text-danger' : 'text-content-muted'}`}>{icon}</span> {label}
</button>
)
}
function Screenshot({ url, className, iconSize = 28 }: { url: string | null; className: string; iconSize?: number }) {
const [failed, setFailed] = useState(false)
return (
@@ -432,16 +751,6 @@ function RegistryGrid({ items, onInstall, onOpenDetail, busy, t, installedIds, f
<StatusPill icon={<ShieldCheck size={11} className="text-success" />}>{t('admin.plugins.reviewed')}</StatusPill>
</span>
)}
{/* Says up front that this one has not been confirmed for the TREK it would run on,
so "Install" never reads as a plain install; the dialog explains the risk. */}
{!installed && offer.warn && (
// Solid, not the soft pill "Reviewed" uses: it has to stand out on any screenshot.
<span className="absolute start-2.5 top-2.5 inline-flex max-w-[62%] items-center gap-1 rounded-full bg-warning px-2 py-[3px] font-geist font-semibold text-[color:var(--surface-card)] shadow-md"
style={fs(11)}>
<AlertTriangle size={11} className="flex-none" />
<span className="truncate">{t('admin.plugins.untestedChip', { host: offer.warn.hostVersion })}</span>
</span>
)}
<span className="absolute -bottom-4 start-3.5 z-[1] grid h-10 w-10 place-items-center rounded-[12px] border border-edge-faint bg-surface-card shadow-sm">
<PluginIcon name={item.icon} size={20} className="text-content-secondary" />
</span>
@@ -520,8 +829,8 @@ function Tile({ children, warn }: { children: ReactNode; warn?: boolean }) {
* The TREK_PLUGINS_IGNORE_TREK_RANGE warning (copy and modes from useRangeBypass). Its own
* component rather than ConfirmDialog because the notice mode has no cancel button.
*/
function RangeBypassDialog({ copy: { title, body, confirm, confirmLabel }, onConfirm, onClose, t }: {
copy: { title: string; body: string; confirm: boolean; confirmLabel: string }; onConfirm: () => void; onClose: () => void; t: T
function RangeBypassDialog({ copy: { title, body, confirm }, onConfirm, onClose, t }: {
copy: { title: string; body: string; confirm: boolean }; onConfirm: () => void; onClose: () => void; t: T
}) {
return (
<DialogShell
@@ -535,7 +844,7 @@ function RangeBypassDialog({ copy: { title, body, confirm, confirmLabel }, onCon
{confirm ? (
<>
<DialogButton onClick={onClose}>{t('common.cancel')}</DialogButton>
<DialogButton variant="primary" onClick={onConfirm}>{confirmLabel}</DialogButton>
<DialogButton variant="primary" onClick={onConfirm}>{t('admin.plugins.installAnyway')}</DialogButton>
</>
) : (
<DialogButton variant="primary" onClick={onClose}>{t('common.ok')}</DialogButton>
@@ -1186,3 +1495,45 @@ function DependencyResolveDialog({ data, t, busy, installedIds, onDownload, onCl
</DialogShell>
)
}
// Footer: a plain-language note on what "Reviewed" means, plus a collapsible
// panel that lays out how plugins are contained, the limits, and the worst case.
function SecurityInfo({ t }: { t: T }) {
const [open, setOpen] = useState(false)
const sections: Array<[string, string]> = [
['admin.plugins.security.isolationTitle', 'admin.plugins.security.isolationBody'],
['admin.plugins.security.permsTitle', 'admin.plugins.security.permsBody'],
['admin.plugins.security.limitsTitle', 'admin.plugins.security.limitsBody'],
['admin.plugins.security.worstTitle', 'admin.plugins.security.worstBody'],
['admin.plugins.security.reviewedTitle', 'admin.plugins.security.reviewedBody'],
['admin.plugins.security.signedTitle', 'admin.plugins.security.signedBody'],
['admin.plugins.security.trustTitle', 'admin.plugins.security.trustBody'],
]
return (
<SettingsCard
icon={Lock}
title={(
<button type="button" onClick={() => setOpen(o => !o)} aria-expanded={open}
className="inline-flex max-w-full items-center gap-1.5 text-start font-bold text-content hover:opacity-80">
<span className="truncate">{t('admin.plugins.security.title')}</span>
<ChevronDown size={15} className={`flex-none text-content-faint transition-transform ${open ? 'rotate-180' : ''}`} />
</button>
)}
>
<div className="flex items-start gap-2.5">
<ShieldCheck size={14} className="mt-0.5 flex-none text-content-faint" />
<SettingsHint>{t('admin.plugins.reviewedMeaning')}</SettingsHint>
</div>
{open && (
<div className="grid gap-2.5 sm:grid-cols-2">
{sections.map(([h, b]) => (
<div key={h} className="rounded-[12px] border border-edge-faint bg-surface-card px-3.5 py-3">
<h4 className="m-0 font-semibold text-content" style={fs(12.5, 'body')}>{t(h as never)}</h4>
<p className="m-0 mt-1 leading-relaxed text-content-muted" style={fs(12, 'body')}>{t(b as never)}</p>
</div>
))}
</div>
)}
</SettingsCard>
)
}
@@ -1,6 +1,5 @@
import { useState } from 'react';
import { useSearchParams } from 'react-router';
import { openrouterReturnCode } from '../../Settings/ai/aiConnectModel';
import type { Addon } from './addonModel';
import { usesConnection } from './aiAddons';
@@ -12,7 +11,7 @@ import { usesConnection } from './aiAddons';
*/
export function useAiAddonTile(aiAddons: Addon[]) {
const [params] = useSearchParams();
const [open, setOpen] = useState(() => openrouterReturnCode(params) !== undefined);
const [open, setOpen] = useState(() => params.get('ai') === 'openrouter');
const canSetUp = usesConnection(aiAddons);
return {
enabledCount: aiAddons.filter((a) => a.enabled).length,
@@ -1,4 +1,4 @@
// FE-HOOK-AI-ADMIN-001 to FE-HOOK-AI-ADMIN-008: the AI assistant's settings and connection for everyone.
// FE-HOOK-AI-ADMIN-001 to FE-HOOK-AI-ADMIN-007: the AI assistant's settings and connection for everyone.
import { act, renderHook, waitFor } from '@testing-library/react';
import type { AiAdminConnectionResponse, AiAdminSettings } from '@trek/shared';
import { MASKED_SETTING_VALUE } from '@trek/shared';
@@ -16,7 +16,6 @@ const repo = vi.hoisted(() => ({
saveAdminSettings: vi.fn(),
adminConnection: vi.fn(),
saveAdminConnection: vi.fn(),
setAdminModel: vi.fn(),
removeAdminConnection: vi.fn(),
adminModels: vi.fn(),
}));
@@ -158,29 +157,6 @@ describe('useAiAdminConfig', () => {
});
});
it("FE-HOOK-AI-ADMIN-008: a shared ChatGPT plan's model is switched on its own, and the answer shows (#2783)", async () => {
const plan = (model: string): AiAdminConnectionResponse => ({
connection: {
scope: 'instance',
kind: 'chatgpt',
model,
hint: null,
status: 'ok',
host: 'api.openai.com',
baseUrl: null,
},
prefill: null,
});
repo.adminConnection.mockResolvedValue(plan('gpt-6.1-sol'));
repo.setAdminModel.mockResolvedValue(plan('gpt-6.1-sol-mini'));
const { result } = await renderLoaded();
await act(async () => result.current.instance.setModel('gpt-6.1-sol-mini'));
await waitFor(() => expect(repo.setAdminModel).toHaveBeenCalledWith('gpt-6.1-sol-mini'));
expect(repo.saveAdminConnection).not.toHaveBeenCalled();
await waitFor(() => expect(result.current.instance.live?.model).toBe('gpt-6.1-sol-mini'));
expect(toast.success).toHaveBeenCalled();
});
it('FE-HOOK-AI-ADMIN-007: removing asks first, then shows the setup again; replacing opens it beside the old one', async () => {
repo.adminConnection.mockResolvedValueOnce(LIVE).mockResolvedValue(NONE);
const { result } = await renderLoaded();
@@ -124,16 +124,9 @@ function useInstanceConnection(onChanged: () => void) {
}
};
/**
* Another model on the same connection: the stored key is kept by sending the mask in its place.
* A shared ChatGPT plan has a sign-in, not a key, so its model is switched on its own (#2783).
*/
/** Another model on the same connection: the stored key is kept by sending the mask in its place. */
const setModel = (model: string) => {
if (!live) return;
if (live.kind === 'chatgpt') {
void act(() => aiConnectionsRepo.setAdminModel(model), 'common.saved');
return;
}
if (!live || live.kind === 'chatgpt') return;
const request: AiInstanceConnectionRequest =
live.kind === 'custom'
? { kind: 'custom', baseUrl: live.baseUrl ?? '', model, ...(live.hint ? { apiKey: MASKED_SETTING_VALUE } : {}) }
@@ -1,167 +0,0 @@
import { Check, ChevronDown, SlidersHorizontal } from 'lucide-react';
import { useRef } from 'react';
import { createPortal } from 'react-dom';
import { POPOVER } from '../../Packing/packingPopoverStyles';
import { fs } from '../../shared/DialogShell';
import { anchorMenu, MENU_ITEM, useFollowTrigger } from './pluginMenu';
import { sortLabel, type SortKey, type StatusFilter, type T, type TypeFilter } from './pluginModel';
const MENU_ID = 'filters';
interface Section {
title: string;
value: string;
options: Array<[string, string]>;
onPick: (v: string) => void;
}
/**
* Type, status and order of the plugin list behind one button instead of three, so the
* toolbar stays search plus one control. The button counts the filters that narrow the
* list (the order does not narrow it) and names the order it is in.
*/
export default function PluginFilterMenu({
t,
view,
typeFilter,
setTypeFilter,
statusFilter,
setStatusFilter,
sort,
setSort,
menu,
setMenu,
}: {
t: T;
view: 'installed' | 'discover';
typeFilter: TypeFilter;
setTypeFilter: (v: TypeFilter) => void;
statusFilter: StatusFilter;
setStatusFilter: (v: StatusFilter) => void;
sort: SortKey;
setSort: (v: SortKey) => void;
menu: string | null;
setMenu: (v: string | null) => void;
}) {
const open = menu === MENU_ID;
const btnRef = useRef<HTMLButtonElement>(null);
useFollowTrigger(open);
const sections: Section[] = [
{
title: t('admin.plugins.filterType'),
value: typeFilter,
options: [
['all', t('admin.plugins.allTypes')],
['widget', t('admin.plugins.type.widget')],
['integration', t('admin.plugins.type.integration')],
['page', t('admin.plugins.type.page')],
['trip-page', t('admin.plugins.type.trip-page')],
],
onPick: (v) => setTypeFilter(v as TypeFilter),
},
...(view === 'installed'
? [
{
title: t('admin.plugins.filterStatus'),
value: statusFilter,
options: [
['all', t('admin.plugins.allStatuses')],
['on', t('admin.plugins.status.active')],
['off', t('admin.plugins.stateOff')],
['update', t('admin.plugins.filterUpdate')],
['err', t('admin.plugins.status.error')],
] as Array<[string, string]>,
onPick: (v: string) => setStatusFilter(v as StatusFilter),
},
]
: []),
{
title: t('admin.plugins.sortBy'),
value: sort,
options:
view === 'discover'
? [
['name', t('admin.plugins.sortName')],
['recent', t('admin.plugins.sortRecent')],
['downloads', t('admin.plugins.sortDownloads')],
]
: [
['name', t('admin.plugins.sortName')],
['recent', t('admin.plugins.sortRecent')],
['updates', t('admin.plugins.sortUpdates')],
],
onPick: (v) => setSort(v as SortKey),
},
];
const narrowing = (typeFilter !== 'all' ? 1 : 0) + (view === 'installed' && statusFilter !== 'all' ? 1 : 0);
return (
<div className="relative flex-none">
<button
type="button"
ref={btnRef}
onClick={() => setMenu(open ? null : MENU_ID)}
aria-expanded={open}
aria-haspopup="menu"
className={`inline-flex h-9 items-center gap-2 whitespace-nowrap rounded-[10px] border bg-surface-card px-3 text-content-secondary transition-colors hover:text-content ${
narrowing ? 'border-[color:var(--text-primary)]' : 'border-edge'
}`}
style={fs(12.5, 'body')}
>
<SlidersHorizontal size={14} className="flex-none text-content-faint" />
<span className="font-semibold text-content">{t('admin.plugins.filters')}</span>
{narrowing > 0 && (
<span
className="inline-flex h-[18px] min-w-[18px] items-center justify-center rounded-full bg-accent px-1.5 font-geist font-bold tabular-nums text-accent-text"
style={fs(10.5)}
>
{narrowing}
</span>
)}
<span className="text-content-faint">{sortLabel(sort, t)}</span>
<ChevronDown
size={13}
className={`flex-none text-content-faint transition-transform ${open ? 'rotate-180' : ''}`}
/>
</button>
{open &&
createPortal(
<div
role="menu"
className="w-[240px] max-w-[calc(100vw-2rem)]"
style={{ ...POPOVER, ...anchorMenu(btnRef.current) }}
>
{sections.map((s, i) => (
<div key={s.title} className={i > 0 ? 'mt-1.5 border-t border-edge-faint pt-1.5' : undefined}>
<p
className="m-0 px-2.5 pb-1 pt-1 font-geist font-bold uppercase tracking-[.08em] text-content-faint"
style={fs(10)}
>
{s.title}
</p>
{s.options.map(([v, label]) => (
<button
type="button"
role="menuitemradio"
aria-checked={s.value === v}
key={v}
onClick={() => s.onPick(v)}
className={`${MENU_ITEM} ${s.value === v ? 'font-semibold text-content' : 'text-content-secondary'}`}
style={fs(12.5, 'body')}
>
<span className="min-w-0 flex-1 truncate text-start">{label}</span>
<Check
size={14}
className={`flex-none text-content-muted ${s.value === v ? 'opacity-100' : 'opacity-0'}`}
/>
</button>
))}
</div>
))}
</div>,
document.body
)}
</div>
);
}
@@ -1,426 +0,0 @@
import {
AlertTriangle,
ArrowUpCircle,
Bug,
CircleDot,
Github,
Globe,
History,
Info,
KeyRound,
Link2,
MoreHorizontal,
PauseCircle,
RotateCw,
ShieldAlert,
ShieldCheck,
SlidersHorizontal,
Trash2,
UploadCloud,
} from 'lucide-react';
import { useRef, type ComponentType, type ReactNode } from 'react';
import { createPortal } from 'react-dom';
import { POPOVER } from '../../Packing/packingPopoverStyles';
import ToggleSwitch from '../../Settings/ToggleSwitch';
import { fs } from '../../shared/DialogShell';
import PluginIcon from '../../shared/PluginIcon';
import { Tooltip } from '../../shared/Tooltip';
import { deriveCaps } from '../pluginCaps';
import { anchorMenu, MENU_ITEM, useFollowTrigger } from './pluginMenu';
import { deriveDeps, isRegistrySourced, parseJson, type PluginRow, type T } from './pluginModel';
// Runtime health → dot colour on the icon tile.
const HEALTH: Record<string, string> = {
active: 'bg-success',
starting: 'bg-info animate-pulse',
error: 'bg-danger',
inactive: 'bg-content-faint/60',
disabled: 'bg-warning',
incompatible: 'bg-warning',
};
/** Every fact about a plugin wears the same chip; only its icon carries a colour. */
const FACT =
'inline-flex max-w-full items-center gap-1.5 rounded-full border border-edge-faint bg-surface-secondary px-2 py-[2px] font-medium text-content-secondary';
type Tone = 'warning' | 'danger' | 'neutral';
const NOTICE_LOOK: Record<Tone, string> = {
warning: 'bg-warning-soft text-warning',
danger: 'bg-danger-soft text-danger',
neutral: 'bg-surface-secondary text-content-muted',
};
/** A state of the plugin worth reading on its own line: what it means, and the one action that fixes it. */
interface Notice {
key: string;
tone: Tone;
icon: ComponentType<{ size?: number; className?: string }>;
text: string;
action?: { label: string; onClick: () => void; disabled?: boolean };
}
function Fact({
icon,
iconClass = 'text-content-muted',
hint,
children,
}: {
icon: ReactNode;
iconClass?: string;
hint?: string;
children: ReactNode;
}) {
const chip = (
<span className={FACT} style={fs(11)}>
<span className={`flex flex-none ${iconClass}`}>{icon}</span>
<span className="truncate">{children}</span>
</span>
);
return hint ? (
<Tooltip label={hint}>
<span className="inline-flex max-w-full">{chip}</span>
</Tooltip>
) : (
chip
);
}
function NoticeLine({ n }: { n: Notice }) {
return (
<div
className={`flex min-w-0 items-center gap-2 rounded-[10px] px-2.5 py-1.5 ${NOTICE_LOOK[n.tone]}`}
style={fs(11.5)}
>
<n.icon size={13} className="flex-none" />
<span className="min-w-0 flex-1 truncate">{n.text}</span>
{n.action && (
<button
type="button"
onClick={n.action.onClick}
disabled={n.action.disabled}
className="flex-none font-semibold underline underline-offset-2 hover:opacity-80 disabled:opacity-50"
>
{n.action.label}
</button>
)}
</div>
);
}
function MenuItem({
icon,
label,
onClick,
danger,
}: {
icon: ReactNode;
label: string;
onClick: () => void;
danger?: boolean;
}) {
return (
<button
type="button"
onClick={onClick}
className={`${MENU_ITEM} ${danger ? 'text-danger hover:bg-danger-soft' : 'text-content-secondary'}`}
style={fs(12.5, 'body')}
>
<span className={`flex w-4 flex-none justify-center ${danger ? 'text-danger' : 'text-content-muted'}`}>
{icon}
</span>{' '}
{label}
</button>
);
}
interface InstalledRowProps {
p: PluginRow;
t: T;
busy: string | null;
menu: string | null;
setMenu: (v: string | null) => void;
hasUpdate: boolean;
latestVer?: string;
newerIncompatible: { version: string; range: string } | null;
blocked: boolean;
onToggle: () => void;
onUpdate: () => void;
onRestart: () => void;
onChangeVersion: () => void;
onResume: () => void;
onReviewBlock: () => void;
onErrors: () => void;
onEgress: () => void;
onSettings: () => void;
onUninstall: () => void;
}
/**
* One installed plugin, read top to bottom: its name and version, what it does, the
* facts about it as one row of alike chips (what it adds, whether it was reviewed and
* signed, where it may connect), then each state that needs attention on a line of its
* own with the action that resolves it. The controls stay on the right.
*/
export default function PluginInstalledRow(props: InstalledRowProps) {
const { p, t, busy, menu, setMenu, hasUpdate, latestVer, newerIncompatible, blocked } = props;
const caps = deriveCaps(
parseJson<string[]>(p.permissions, []),
parseJson<{ widget?: { slot?: string } }>(p.capabilities, {}),
t
);
const deps = deriveDeps(p, t);
const menuOpen = menu === `row:${p.id}`;
const menuBtnRef = useRef<HTMLButtonElement>(null);
const working = busy === p.id;
const hostCount = p.egressHostCount ?? 0;
// The menu is portaled to <body> and positioned `fixed` against the ⋯ button,
// because the row's ancestor (PageSidebar) is `overflow-hidden` and would clip
// an in-flow `absolute` menu — losing Delete on the lower rows of a long list.
useFollowTrigger(menuOpen);
const notices: Notice[] = [];
if (p.status === 'error' && p.last_error) {
notices.push({ key: 'error', tone: 'danger', icon: AlertTriangle, text: p.last_error });
}
// A refused update leaves a WORKING plugin pinned at its old version: its own state,
// kept until resolved rather than dying with the toast that first reported it.
if (blocked && p.updateBlock) {
notices.push({
key: 'block',
tone: 'warning',
icon: ShieldAlert,
text: t('admin.plugins.updateBlocked', { reason: p.updateBlock.detail ?? p.updateBlock.code }),
action: { label: t('admin.plugins.reviewBlock'), onClick: props.onReviewBlock },
});
}
for (const [i, d] of deps.entries()) {
if (d.blocked || d.warn) notices.push({ key: `dep${i}`, tone: 'warning', icon: d.icon, text: d.label });
}
// Held: the admin deliberately installed a non-latest version, so updates are paused
// rather than nagged — resuming is one click, right where the pause shows.
if (p.updateHold) {
notices.push({
key: 'hold',
tone: 'neutral',
icon: PauseCircle,
text: t('admin.plugins.updatesHeld', { version: p.version ?? '' }),
action: { label: t('admin.plugins.resumeUpdates'), onClick: props.onResume, disabled: working },
});
}
// A newer version this TREK can't run: informational, never a button, the fix is a TREK upgrade.
if (newerIncompatible) {
notices.push({
key: 'newer',
tone: 'neutral',
icon: Info,
text: t('admin.plugins.newerNeedsTrek', { version: newerIncompatible.version, range: newerIncompatible.range }),
});
}
return (
<div
className={`group relative flex items-start gap-3 px-3.5 py-3.5 transition-colors hover:bg-surface-secondary ${working ? 'opacity-60' : ''}`}
>
<div className="relative mt-0.5 flex-none">
<span className="grid h-10 w-10 place-items-center rounded-[12px] border border-edge-faint bg-surface-secondary">
<PluginIcon name={p.icon} size={19} className="text-content-secondary" />
</span>
<Tooltip label={t(`admin.plugins.status.${p.status}` as never)}>
<span
className={`absolute -bottom-0.5 -end-0.5 h-3 w-3 rounded-full ring-2 ring-surface-card ${HEALTH[p.status] || HEALTH.inactive}`}
/>
</Tooltip>
</div>
<div className="min-w-0 flex-1">
<div className="flex min-w-0 items-baseline gap-2">
<span className="min-w-0 truncate font-semibold tracking-[-.006em] text-content" style={fs(13.5, 'body')}>
{p.name}
</span>
{p.version && (
<span className="flex-none font-geist font-medium tabular-nums text-content-faint" style={fs(11)}>
v{p.version}
</span>
)}
</div>
{p.description && (
<p className="m-0 mt-0.5 truncate text-content-muted" style={fs(12, 'body')}>
{p.description}
</p>
)}
<div className="mt-2 flex flex-wrap items-center gap-1.5">
{caps.map((c, i) => (
<Fact key={i} icon={<c.icon size={12} />} iconClass={c.net ? 'text-info' : 'text-content-muted'}>
{c.label}
</Fact>
))}
{deps
.filter((d) => !d.blocked && !d.warn)
.map((d, i) => (
<Fact key={`d${i}`} icon={<d.icon size={12} />}>
{d.label}
</Fact>
))}
{p.reviewed_at && (
<Fact icon={<ShieldCheck size={12} />} iconClass="text-success">
{t('admin.plugins.reviewed')}
</Fact>
)}
{p.source_repo === 'local:upload' && (
<Fact icon={<UploadCloud size={12} />} iconClass="text-warning" hint={t('admin.plugins.sideloadedHint')}>
{t('admin.plugins.sideloaded')}
</Fact>
)}
{p.source_repo === 'local:link' && (
<Fact icon={<Link2 size={12} />} hint={t('admin.plugins.devLinkHint')}>
{t('admin.plugins.devLinkBadge')}
</Fact>
)}
{/* Registry plugins only: a sideloaded or dev-linked plugin already says something stronger. */}
{isRegistrySourced(p.source_repo) &&
(p.signed ? (
<Fact icon={<KeyRound size={12} />} hint={t('admin.plugins.signedHint')}>
{t('admin.plugins.signed')}
</Fact>
) : (
<Fact icon={<ShieldAlert size={12} />} iconClass="text-warning" hint={t('admin.plugins.unsignedHint')}>
{t('admin.plugins.unsigned')}
</Fact>
))}
{/* A service only the operator can name (a self-hosted Gotify/ntfy): the admin adds
its host, and until one exists the plugin reaches nothing, so it asks for it. */}
{p.operatorEgress && (
<Tooltip label={t('admin.plugins.allowedHosts.hint')}>
<button type="button" onClick={props.onEgress} className={`${FACT} hover:opacity-80`} style={fs(11)}>
<Globe size={12} className={hostCount > 0 ? 'text-info' : 'text-warning'} />
{hostCount > 0
? t('admin.plugins.allowedHosts.count', { n: hostCount })
: t('admin.plugins.allowedHosts.add')}
</button>
</Tooltip>
)}
</div>
{notices.length > 0 && (
<div className="mt-2.5 flex flex-col gap-1.5">
{notices.map((n) => (
<NoticeLine key={n.key} n={n} />
))}
</div>
)}
</div>
<div className="flex flex-none items-center gap-2 self-center">
{hasUpdate && (
<button
type="button"
onClick={props.onUpdate}
disabled={working}
className="inline-flex items-center gap-1.5 rounded-full bg-warning-soft px-2.5 py-1 font-semibold text-warning hover:opacity-90 disabled:opacity-50"
style={fs(11.5)}
>
<ArrowUpCircle size={13} /> <span>{t('admin.plugins.updateTo', { version: latestVer })}</span>
</button>
)}
<span
className={`min-w-[42px] text-end font-medium ${p.enabled === 1 ? 'text-content-secondary' : 'text-content-faint'}`}
style={fs(12)}
>
{p.enabled === 1 ? t('admin.plugins.status.active') : t('admin.plugins.stateOff')}
</span>
<ToggleSwitch on={p.enabled === 1} label={t('admin.plugins.enabledToggle')} onToggle={props.onToggle} />
<div className="relative">
<Tooltip label={t('admin.table.actions')} disabled={menuOpen}>
<button
type="button"
ref={menuBtnRef}
data-testid={`plugin-row-menu-btn-${p.id}`}
onClick={() => setMenu(menuOpen ? null : `row:${p.id}`)}
aria-expanded={menuOpen}
aria-label={t('admin.table.actions')}
className={`grid h-8 w-8 place-items-center rounded-[10px] transition-colors ${menuOpen ? 'bg-surface-card text-content shadow-sm ring-1 ring-edge-faint' : 'text-content-faint hover:bg-surface-card hover:text-content'}`}
>
<MoreHorizontal size={17} />
</button>
</Tooltip>
{menuOpen &&
createPortal(
<div
data-testid={`plugin-row-menu-${p.id}`}
style={{ ...POPOVER, ...anchorMenu(menuBtnRef.current) }}
className="min-w-[200px]"
>
{p.enabled === 1 && (
<MenuItem
icon={<RotateCw size={14} />}
label={t('admin.plugins.restart')}
onClick={props.onRestart}
/>
)}
{/* Instance fields OR actions: an action-only plugin still needs the dialog to run its buttons. */}
{((p.instanceSettingsCount ?? 0) > 0 || (p.instanceActionsCount ?? 0) > 0) && (
<MenuItem
icon={<SlidersHorizontal size={14} />}
label={t('admin.plugins.instanceSettings')}
onClick={props.onSettings}
/>
)}
<MenuItem icon={<Bug size={14} />} label={t('admin.plugins.viewErrors')} onClick={props.onErrors} />
{/* Only a plugin that DECLARED operatorEgress: an admin is never invited to widen egress for one that did not ask. */}
{p.operatorEgress && (
<MenuItem
icon={<Globe size={14} />}
label={t('admin.plugins.allowedHosts')}
onClick={props.onEgress}
/>
)}
{/* Registry plugins only — a sideload/dev-link has no registry versions to pick from. */}
{isRegistrySourced(p.source_repo) && (
<MenuItem
icon={<History size={14} />}
label={t('admin.plugins.changeVersion')}
onClick={props.onChangeVersion}
/>
)}
{p.source_repo && p.source_repo !== 'local:upload' && p.source_repo !== 'local:link' && (
<>
<a
href={`https://github.com/${p.source_repo}`}
target="_blank"
rel="noreferrer"
onClick={() => setMenu(null)}
className={`${MENU_ITEM} text-content-secondary`}
style={fs(12.5, 'body')}
>
<span className="flex w-4 flex-none justify-center text-content-muted">
<Github size={14} />
</span>{' '}
{t('admin.plugins.sourceRepo')}
</a>
<a
href={`https://github.com/${p.source_repo}/issues`}
target="_blank"
rel="noreferrer"
onClick={() => setMenu(null)}
className={`${MENU_ITEM} text-content-secondary`}
style={fs(12.5, 'body')}
>
<span className="flex w-4 flex-none justify-center text-content-muted">
<CircleDot size={14} />
</span>{' '}
{t('admin.plugins.reportIssue')}
</a>
</>
)}
<div className="mx-1.5 my-1 h-px bg-edge-faint" />
<MenuItem icon={<Trash2 size={14} />} label={t('common.delete')} danger onClick={props.onUninstall} />
</div>,
document.body
)}
</div>
</div>
</div>
);
}
@@ -1,72 +0,0 @@
import { ShieldCheck } from 'lucide-react';
import {
DialogButton,
DialogFooter,
DialogHeader,
DialogShell,
DialogTile,
FooterSpacer,
NEUTRAL_TINT,
fs,
} from '../../shared/DialogShell';
import type { T } from './pluginModel';
/**
* How plugins are contained and where that ends, opened from the shield in the panel's
* header. It used to sit under the list as a card of its own, which pushed a wall of
* text into the page every admin scrolls past.
*/
export default function PluginSecurityDialog({ t, onClose }: { t: T; onClose: () => void }) {
const sections: Array<[string, string]> = [
[t('admin.plugins.security.isolationTitle'), t('admin.plugins.security.isolationBody')],
[t('admin.plugins.security.permsTitle'), t('admin.plugins.security.permsBody')],
[t('admin.plugins.security.limitsTitle'), t('admin.plugins.security.limitsBody')],
[t('admin.plugins.security.worstTitle'), t('admin.plugins.security.worstBody')],
[t('admin.plugins.security.reviewedTitle'), t('admin.plugins.security.reviewedBody')],
[t('admin.plugins.security.signedTitle'), t('admin.plugins.security.signedBody')],
[t('admin.plugins.security.trustTitle'), t('admin.plugins.security.trustBody')],
];
return (
<DialogShell
onClose={onClose}
labelledBy="plugin-security-title"
width="detail"
header={
<DialogHeader
tile={
<DialogTile>
<ShieldCheck size={20} className="text-content-secondary" />
</DialogTile>
}
tint={NEUTRAL_TINT}
labelId="plugin-security-title"
title={t('admin.plugins.security.short')}
sub={t('admin.plugins.reviewedMeaning')}
subWraps
onClose={onClose}
/>
}
footer={
<DialogFooter>
<FooterSpacer />
<DialogButton variant="primary" onClick={onClose}>
{t('common.ok')}
</DialogButton>
</DialogFooter>
}
>
<div className="grid gap-2.5 sm:grid-cols-2">
{sections.map(([h, b]) => (
<div key={h} className="rounded-[12px] border border-edge-faint bg-surface-card px-3.5 py-3">
<h4 className="m-0 font-semibold text-content" style={fs(12.5, 'body')}>
{h}
</h4>
<p className="m-0 mt-1 leading-relaxed text-content-muted" style={fs(12, 'body')}>
{b}
</p>
</div>
))}
</div>
</DialogShell>
);
}
@@ -1,41 +0,0 @@
import { useEffect, useState, type CSSProperties } from 'react';
/** The tallest a row's ⋯ menu gets; below that it opens upwards instead. */
const ROW_MENU_MAX_H = 260;
/**
* Where a portaled menu sits: right-aligned under its trigger, or above it when the
* window has no room below. Fixed, because the cards around the toolbar and the rows
* clip whatever overflows them.
*/
export function anchorMenu(trigger: HTMLElement | null): CSSProperties {
const r = trigger?.getBoundingClientRect();
if (!r) return { position: 'fixed', top: 0, right: 0, zIndex: 100 };
const spaceBelow = window.innerHeight - r.bottom;
const openUp = spaceBelow < ROW_MENU_MAX_H && r.top > spaceBelow;
return {
position: 'fixed',
right: Math.max(8, window.innerWidth - r.right),
...(openUp ? { bottom: window.innerHeight - r.top + 4 } : { top: r.bottom + 4 }),
zIndex: 100,
};
}
/** One entry of a popover menu, in the packing popovers' shape. */
export const MENU_ITEM =
'flex w-full items-center gap-2.5 rounded-[9px] px-2.5 py-2 font-medium transition-colors hover:bg-surface-tertiary';
/** Re-renders while the page moves under an open, portaled menu, so it stays pinned to its trigger. */
export function useFollowTrigger(open: boolean) {
const [, reanchor] = useState(0);
useEffect(() => {
if (!open) return;
const onMove = () => reanchor((n) => n + 1);
window.addEventListener('scroll', onMove, true);
window.addEventListener('resize', onMove);
return () => {
window.removeEventListener('scroll', onMove, true);
window.removeEventListener('resize', onMove);
};
}, [open]);
}
@@ -111,14 +111,8 @@ describe('pluginModel', () => {
blocked: false,
version: '0.9.0',
});
// Nothing fits this TREK: still an Install, behind the admin's own warning for this plugin.
expect(installOffer(incompatible, t)).toMatchObject({
blocked: false,
label: 'admin.plugins.install',
warn: { acceptedByAdmin: true, trekRange: '>=9', hostVersion: '4.0.0' },
});
// TREK_PLUGINS_IGNORE_TREK_RANGE lets every plugin through, so the warning is not the admin's own choice.
expect(installOffer(incompatible, t, true)).toMatchObject({ blocked: false, warn: { acceptedByAdmin: false } });
expect(installOffer(incompatible, t)).toMatchObject({ blocked: true, label: 'admin.plugins.incompatible' });
expect(installOffer(incompatible, t, true)).toMatchObject({ blocked: false, label: 'admin.plugins.installAnyway' });
});
it('FE-ADMIN-PLUGIN-MODEL-008: deriveDeps marks the blockers among the declared dependencies', () => {
@@ -298,8 +298,7 @@ export function installOffer(
title,
};
}
// No version fits this TREK: the admin may still install this one plugin at their own risk.
return bypassOffer(item, t, title, true);
return { blocked: true, label: t('admin.plugins.incompatible'), title };
}
/**
@@ -1,4 +1,4 @@
// FE-ADMIN-PLUGINS-HOOK-001 to -014: the plugin admin logic behind both admin shells.
// FE-ADMIN-PLUGINS-HOOK-001 to -012: the plugin admin logic behind both admin shells.
import { act, renderHook, waitFor } from '@testing-library/react';
import type { DragEvent } from 'react';
@@ -266,36 +266,4 @@ describe('usePluginsAdmin', () => {
expect(toast.success).toHaveBeenCalledWith('admin.plugins.uninstalled');
expect(result.current.confirmUninstall).toBeNull();
});
it('FE-ADMIN-PLUGINS-HOOK-013: switching on a plugin outside its TREK range asks first, then runs it anyway', async () => {
serve([
row({ enabled: 0, dependencyStatus: 'hostIncompatible', trekRange: '>=3.2.0 <4.0.0', hostVersion: '5.0.0' }),
]);
vi.spyOn(adminApi, 'pluginActivate').mockResolvedValue({});
const { result } = await mounted();
act(() => result.current.toggle(result.current.plugins[0] as PluginRow));
expect(adminApi.pluginActivate).not.toHaveBeenCalled();
expect(result.current.bypass.warning).toMatchObject({
acceptedByAdmin: true,
action: 'activate',
trekRange: '>=3.2.0 <4.0.0',
});
await act(async () => {
result.current.bypass.confirm();
});
await waitFor(() => expect(adminApi.pluginActivate).toHaveBeenCalledWith('alpha', false, true));
});
it('FE-ADMIN-PLUGINS-HOOK-014: installing behind the admin warning sends their consent for this plugin', async () => {
serve([], [entry({ id: 'beta', name: 'Beta' })]);
vi.spyOn(adminApi, 'pluginInstall').mockResolvedValue({ id: 'beta', version: '1.0.0', trekRangeBypassed: null });
const { result } = await mounted();
const warn = { name: 'Beta', trekRange: '<5.0.0', hostVersion: '5.0.0', acceptedByAdmin: true, onConfirm: null };
act(() => result.current.install('beta', undefined, warn));
expect(adminApi.pluginInstall).not.toHaveBeenCalled();
await act(async () => {
result.current.bypass.confirm();
});
await waitFor(() => expect(adminApi.pluginInstall).toHaveBeenCalledWith('beta', { acceptTrekRange: true }));
});
});
@@ -317,14 +317,9 @@ export function usePluginsAdmin() {
act(
id,
() =>
adminApi
.pluginInstall(id, {
...(version ? { version } : {}),
...(warn?.acceptedByAdmin ? { acceptTrekRange: true } : {}),
})
.then((r) => {
if (!warn) bypass.notice(id, r?.trekRangeBypassed);
}),
adminApi.pluginInstall(id, version ? { version } : undefined).then((r) => {
if (!warn) bypass.notice(id, r?.trekRangeBypassed);
}),
t('admin.plugins.installed')
)
);
@@ -397,10 +392,10 @@ export function usePluginsAdmin() {
}
};
const attemptActivate = (p: PluginRow, acceptTrekRange = false) => {
const attemptActivate = (p: PluginRow) => {
const cascaded = autoEnabledDeps(p);
return adminApi
.pluginActivate(p.id, false, acceptTrekRange)
.pluginActivate(p.id)
.then(() => {
toast.success(t('admin.plugins.activated'));
if (cascaded.length)
@@ -420,29 +415,12 @@ export function usePluginsAdmin() {
void act(p.id, () => adminApi.pluginDeactivate(p.id), t('admin.plugins.deactivated'));
return;
}
const run = (acceptTrekRange: boolean) => {
setBusy(p.id);
setMenu(null);
attemptActivate(p, acceptTrekRange).finally(() => {
setBusy(null);
refresh();
});
};
// Outside the TREK versions its author declared: the admin may run it anyway, after
// reading what that risks. The choice holds for this version of the plugin only.
if (p.dependencyStatus === 'hostIncompatible') {
const warn: RangeWarning = {
name: p.name,
trekRange: p.trekRange ?? null,
hostVersion: p.hostVersion ?? '?',
acceptedByAdmin: true,
onConfirm: null,
action: 'activate',
};
bypass.guard(warn, () => run(true));
return;
}
run(false);
setBusy(p.id);
setMenu(null);
attemptActivate(p).finally(() => {
setBusy(null);
refresh();
});
};
// Download a missing/outdated plugin dependency (latest compatible for its range,
@@ -16,23 +16,15 @@ describe('rangeBypass helpers', () => {
blocked: false, warn: true, label: 'admin.plugins.dep.trekBypassed:{"range":">=3.2.0 <4.0.0","host":"4.0.0"}',
})
expect(bypassChip({ trekRange: null, hostVersion: '4.0.0' }, t)).toMatchObject({ label: 'admin.plugins.dep.trekBypassedUnknown' })
// An admin's own "run it anyway" for this one plugin says so, not "version checks off".
expect(bypassChip({ trekRange: '>=3.2.0 <4.0.0', hostVersion: '5.0.0', acceptedByAdmin: true }, t)).toMatchObject({
warn: true, label: 'admin.plugins.dep.trekAccepted:{"range":">=3.2.0 <4.0.0","host":"5.0.0"}',
})
expect(bypassChip({ trekRange: null, hostVersion: '5.0.0', acceptedByAdmin: true }, t)).toMatchObject({
label: 'admin.plugins.dep.trekAcceptedUnknown',
})
})
it('bypassOffer: an enabled Install that carries what the dialog must say first', () => {
it('bypassOffer: an enabled "Install anyway" carrying what the dialog must say', () => {
const offer = bypassOffer({ name: 'Gotify', trek: '>=4.0.0', hostVersion: '3.3.0' }, t, 'why')
expect(offer).toEqual({
blocked: false, label: 'admin.plugins.install', title: 'why',
warn: { name: 'Gotify', trekRange: '>=4.0.0', hostVersion: '3.3.0', acceptedByAdmin: false, onConfirm: null },
blocked: false, label: 'admin.plugins.installAnyway', title: 'why',
warn: { name: 'Gotify', trekRange: '>=4.0.0', hostVersion: '3.3.0', onConfirm: null },
})
expect(bypassOffer({ name: 'X' }, t, 'why').warn).toMatchObject({ trekRange: null, hostVersion: '?' })
expect(bypassOffer({ name: 'X' }, t, 'why', true).warn).toMatchObject({ acceptedByAdmin: true })
})
it('rangeWarningCopy: confirm vs notice title, ranged vs rangeless body', () => {
@@ -40,25 +32,10 @@ describe('rangeBypass helpers', () => {
expect(rangeWarningCopy({ ...ranged, onConfirm: () => {} }, t)).toEqual({
confirm: true, title: 'admin.plugins.rangeBypass.title',
body: 'admin.plugins.rangeBypass.body:{"name":"G","range":">=4.0.0","host":"3.3.0"}',
confirmLabel: 'admin.plugins.installAnyway',
})
expect(rangeWarningCopy({ name: 'G', trekRange: null, hostVersion: '3.3.0', onConfirm: null }, t)).toEqual({
confirm: false, title: 'admin.plugins.rangeBypass.noticeTitle',
body: 'admin.plugins.rangeBypass.bodyUnknown:{"name":"G","range":null,"host":"3.3.0"}',
confirmLabel: 'admin.plugins.installAnyway',
})
})
it('rangeWarningCopy: an admin choosing for one plugin gets the short title, their own body and the right button', () => {
const mine = { name: 'G', trekRange: '>=4.0.0', hostVersion: '5.0.0', acceptedByAdmin: true, onConfirm: () => {} }
expect(rangeWarningCopy(mine, t)).toEqual({
confirm: true, title: 'admin.plugins.rangeBypass.titleAdmin',
body: 'admin.plugins.rangeBypass.bodyAdmin:{"name":"G","range":">=4.0.0","host":"5.0.0"}',
confirmLabel: 'admin.plugins.installAnyway',
})
expect(rangeWarningCopy({ ...mine, trekRange: null, action: 'activate' }, t)).toMatchObject({
body: 'admin.plugins.rangeBypass.bodyAdminUnknown:{"name":"G","range":null,"host":"5.0.0"}',
confirmLabel: 'admin.plugins.activateAnyway',
body: 'admin.plugins.rangeBypass.bodyUnknown:{"name":"G","host":"3.3.0"}',
})
})
})
+22 -61
View File
@@ -4,21 +4,10 @@ import { useTranslation } from '../../i18n'
type T = (k: string, p?: Record<string, unknown>) => string
/**
* The server's "this only went through because the version check was set aside" marker:
* by an admin for this one plugin (`acceptedByAdmin`), or for every plugin through
* TREK_PLUGINS_IGNORE_TREK_RANGE.
*/
export interface TrekRangeBypass { trekRange: string | null; hostVersion: string; acceptedByAdmin?: boolean }
/**
* What the range-bypass warning needs to say, and what to do if the admin accepts (null = a
* notice). `action` names what the confirm button does: install (the default) or activate.
*/
export interface RangeWarning extends TrekRangeBypass {
name: string
onConfirm: (() => void) | null
action?: 'install' | 'activate'
}
/** The server's "this only went through because TREK_PLUGINS_IGNORE_TREK_RANGE is set" marker. */
export interface TrekRangeBypass { trekRange: string | null; hostVersion: string }
/** What the range-bypass warning needs to say, and what to do if the admin accepts (null = a notice). */
export interface RangeWarning extends TrekRangeBypass { name: string; onConfirm: (() => void) | null }
/**
* The chip a row carries while it runs outside its declared range on the operator's
@@ -27,42 +16,29 @@ export interface RangeWarning extends TrekRangeBypass {
*/
export function bypassChip(b: TrekRangeBypass | null | undefined, t: T) {
if (!b) return null
const label = b.acceptedByAdmin
? b.trekRange
? t('admin.plugins.dep.trekAccepted', { range: b.trekRange, host: b.hostVersion })
: t('admin.plugins.dep.trekAcceptedUnknown')
: b.trekRange
? t('admin.plugins.dep.trekBypassed', { range: b.trekRange, host: b.hostVersion })
: t('admin.plugins.dep.trekBypassedUnknown')
return {
icon: AlertTriangle,
label,
label: b.trekRange
? t('admin.plugins.dep.trekBypassed', { range: b.trekRange, host: b.hostVersion })
: t('admin.plugins.dep.trekBypassedUnknown'),
blocked: false,
warn: true,
}
}
/**
* The Install button for a registry entry the server flagged incompatible: the server will
* take the newest version regardless, so the button says exactly that — and carries what
* the warning has to say first. `byAdmin` is the admin's own "install anyway" for this one
* plugin; without it the operator set TREK_PLUGINS_IGNORE_TREK_RANGE for every plugin.
* `title` is the shell's existing "why" line (needs TREK X — this server runs Y).
* The Install button for a registry entry the server flagged incompatible, once the
* operator set TREK_PLUGINS_IGNORE_TREK_RANGE: the server will take the newest version
* regardless, so the button says exactly that — and carries what the warning has to say
* first. `title` is the shell's existing "why" line (needs TREK X — this server runs Y).
*/
export function bypassOffer(
item: { name: string; trek?: string | null; hostVersion?: string },
t: T,
title: string,
byAdmin = false
) {
const warn: RangeWarning = {
name: item.name,
trekRange: item.trek ?? null,
hostVersion: item.hostVersion ?? '?',
acceptedByAdmin: byAdmin,
onConfirm: null,
export function bypassOffer(item: { name: string; trek?: string | null; hostVersion?: string }, t: T, title: string) {
return {
blocked: false,
label: t('admin.plugins.installAnyway'),
title,
warn: { name: item.name, trekRange: item.trek ?? null, hostVersion: item.hostVersion ?? '?', onConfirm: null } as RangeWarning,
}
return { blocked: false, label: t('admin.plugins.install'), title, warn }
}
/**
@@ -72,29 +48,14 @@ export function bypassOffer(
* whole point: the admin is accepting that the author never vouched for this TREK and
* that, in rare cases, that can cost them data.
*/
export function rangeWarningCopy(
w: RangeWarning,
t: T
): { title: string; body: string; confirm: boolean; confirmLabel: string } {
export function rangeWarningCopy(w: RangeWarning, t: T): { title: string; body: string; confirm: boolean } {
const confirm = w.onConfirm !== null
const vars = { name: w.name, range: w.trekRange, host: w.hostVersion }
const body = w.acceptedByAdmin
? w.trekRange
? t('admin.plugins.rangeBypass.bodyAdmin', vars)
: t('admin.plugins.rangeBypass.bodyAdminUnknown', vars)
: w.trekRange
? t('admin.plugins.rangeBypass.body', vars)
: t('admin.plugins.rangeBypass.bodyUnknown', vars)
const title = w.acceptedByAdmin
? t('admin.plugins.rangeBypass.titleAdmin')
: confirm
? t('admin.plugins.rangeBypass.title')
: t('admin.plugins.rangeBypass.noticeTitle')
return {
confirm,
title,
body,
confirmLabel: w.action === 'activate' ? t('admin.plugins.activateAnyway') : t('admin.plugins.installAnyway'),
title: confirm ? t('admin.plugins.rangeBypass.title') : t('admin.plugins.rangeBypass.noticeTitle'),
body: w.trekRange
? t('admin.plugins.rangeBypass.body', { name: w.name, range: w.trekRange, host: w.hostVersion })
: t('admin.plugins.rangeBypass.bodyUnknown', { name: w.name, host: w.hostVersion }),
}
}
@@ -426,23 +426,6 @@ describe('calculateRouteWithLegs', () => {
expect(second).toBe(first)
})
it('FE-COMP-ROUTECALCULATOR-035b: a route answered once is still there after a reload, without asking the router (#2794)', async () => {
let hits = 0
server.use(http.get(`${FOSSGIS.driving}/:coords`, () => { hits++; return HttpResponse.json(buildLegsResponse()) }))
const wps = freshWaypoints()
const first = await calculateRouteWithLegs(wps)
const { offlineDb } = await import('../../db/offlineDb')
await vi.waitFor(async () => expect(await offlineDb.routeCache.count()).toBeGreaterThan(0))
// A reload: the module, and with it the cache in memory, starts over.
vi.resetModules()
const reloaded = await import('./RouteCalculator')
const again = await reloaded.calculateRouteWithLegs(wps)
expect(hits).toBe(1)
expect(again).toEqual(first)
})
it('FE-COMP-ROUTECALCULATOR-036: switching the distance unit re-fetches instead of reusing stale text (#1300)', async () => {
server.use(http.get(`${FOSSGIS.driving}/:coords`, () => HttpResponse.json(buildLegsResponse())))
const wps = freshWaypoints()
+20 -7
View File
@@ -4,7 +4,6 @@ import type { DistanceUnit, RouteResult, RouteSegment, RouteWithLegs, SnappedWay
import { haversineKm } from '../../utils/geo'
import { formatDistance } from '../../utils/units'
import { countRoute } from './routeUsageCounter'
import { cacheRoute, rememberRoute, routeInMemory, storedRoute } from './routeStore'
import { valhallaRouteAvoiding, valhallaRun, valhallaAvailable, valhallaAlternates, valhallaSpacing, legAvoids, type AvoidClass, type ValhallaLeg } from './valhallaRoute'
import { furthestFrom, sameRoad, type RouteUsageSurface } from '@trek/shared'
@@ -197,6 +196,10 @@ function retryAfterMs(response: Response): number | null {
return Number.isNaN(at) ? null : Math.max(0, at - Date.now())
}
// Cache route responses keyed by the exact waypoint list. Routes are stable, so
// this avoids re-hitting the public OSRM demo server on every day switch / reorder.
const routeCache = new Map<string, RouteWithLegs>()
const ROUTE_CACHE_MAX = 200
/**
* A route profile is either one of the built-in OSRM profiles or a plugin profile
@@ -537,10 +540,7 @@ export async function calculateRouteWithLegs(
const avoidScope = avoiding.length ? `:avoid=${avoiding.join(',')}` : ''
const plainKey = `${profile}:${getDistanceUnit()}:${coords}${pluginScope}`
const cacheKey = `${plainKey}${avoidScope}`
// A plugin route stays in memory: its answer depends on the trip and the day,
// and may carry live data such as charging stops. The rest is kept on the device
// too, so a trip that shows its whole route opens drawn (#2794).
const cached = pluginScope ? routeInMemory(cacheKey) : await storedRoute(cacheKey)
const cached = routeCache.get(cacheKey)
if (cached) return cached
if (avoiding.length) {
@@ -552,7 +552,7 @@ export async function calculateRouteWithLegs(
// Null is a Valhalla that could not answer at all. OSRM keeps the day drawn rather
// than blank, and the answer says that nothing was avoided, with the reason, so the
// rail flags the day instead of implying the setting held on a road nobody weighed.
const plain = (await storedRoute(plainKey)) ?? await osrmWithLegs(waypoints, coords, profile, signal)
const plain = routeCache.get(plainKey) ?? await osrmWithLegs(waypoints, coords, profile, signal)
cacheRoute(plainKey, plain)
return { ...plain, avoidance: { asked: avoiding, achieved: [], fellBack: true } }
}
@@ -591,7 +591,11 @@ export async function calculateRouteWithLegs(
legs,
...(route.viaPoints.length ? { vias: route.viaPoints } : {}),
}
rememberRoute(cacheKey, result)
routeCache.set(cacheKey, result)
if (routeCache.size > ROUTE_CACHE_MAX) {
const oldest = routeCache.keys().next().value
if (oldest !== undefined) routeCache.delete(oldest)
}
return result
}
@@ -634,6 +638,15 @@ async function osrmWithLegs(
return { coordinates, distance: route.distance, duration: route.duration, legs, ...(snapped ? { snapped } : {}) }
}
/** Store a route and drop the oldest once the cache is over its cap. */
function cacheRoute(key: string, route: RouteWithLegs): void {
routeCache.set(key, route)
if (routeCache.size > ROUTE_CACHE_MAX) {
const oldest = routeCache.keys().next().value
if (oldest !== undefined) routeCache.delete(oldest)
}
}
/**
* A whole chain from the second engine, weighted away from some road classes.
*
-41
View File
@@ -1,41 +0,0 @@
import { routeCacheRepo } from '../../repo/routeCacheRepo';
import type { RouteWithLegs } from '../../types';
/**
* Route answers by RouteCalculator's cache key (profile, unit, waypoints,
* avoided roads). Routes are stable, so this keeps the router from being asked
* again on every day switch or reorder: in memory for this visit, and on the
* device for the next one, so a trip that shows its whole route opens drawn
* instead of routing every leg again, one a second (#2794).
*/
const inMemory = new Map<string, RouteWithLegs>();
const MEMORY_MAX = 200;
/** Keeps a route for this visit only, dropping the oldest past the limit. */
export function rememberRoute(key: string, route: RouteWithLegs): void {
inMemory.set(key, route);
if (inMemory.size > MEMORY_MAX) {
const oldest = inMemory.keys().next().value;
if (oldest !== undefined) inMemory.delete(oldest);
}
}
/** The route this visit already holds, without asking the device. */
export function routeInMemory(key: string): RouteWithLegs | undefined {
return inMemory.get(key);
}
/** Keeps a route the router just answered, in memory and on the device. */
export function cacheRoute(key: string, route: RouteWithLegs): void {
rememberRoute(key, route);
void routeCacheRepo.put(key, route);
}
/** The route kept in memory, else the one kept on the device, which then stays in memory too. */
export async function storedRoute(key: string): Promise<RouteWithLegs | null> {
const held = inMemory.get(key);
if (held) return held;
const kept = await routeCacheRepo.get<RouteWithLegs>(key);
if (kept) rememberRoute(key, kept);
return kept;
}
@@ -5,22 +5,19 @@ import { useLocationBias } from '../../hooks/useLocationBias'
import { usePlaceLanguage } from '../../hooks/usePlaceLanguage'
import { useSuggestionDropdown } from './useSuggestionDropdown'
import { PlaceSuggestion, SuggestionList, SuggestionRow } from './SuggestionDropdown'
import type { MapMatch } from '../../repo/mapMatchRepo'
interface Props {
value: string
onChange: (value: string) => void
placeholder?: string
className?: string
/** A picked suggestion's spot on the map, for a form that saves where the address is (an imported stay). */
onPick?: (match: MapMatch) => void
}
// Free-text address input with location autocomplete, backed by the same maps
// search as LocationSelect. Unlike LocationSelect the typed text is
// authoritative: every keystroke reaches the parent so a hand-written address
// is never lost, and picking a suggestion just replaces the text (#1496).
export default function AddressInput({ value, onChange, placeholder, className, onPick }: Props) {
export default function AddressInput({ value, onChange, placeholder, className }: Props) {
const { locale } = useTranslation()
const placeLang = usePlaceLanguage()
// Ohne Reisekontext ist der Hinweis leer, und die Suche laeuft wie bisher.
@@ -63,9 +60,6 @@ export default function AddressInput({ value, onChange, placeholder, className,
// A response still on its way must not repopulate the list behind the pick.
reqIdRef.current++
onChange(r.address || r.name || '')
if (onPick && Number.isFinite(r.lat) && Number.isFinite(r.lng)) {
onPick({ lat: r.lat, lng: r.lng, label: [r.name, r.address].filter(Boolean).join(', ') })
}
setOpen(false)
setResults([])
setLoading(false)
@@ -29,7 +29,6 @@ import { useReservationForm } from './useReservationForm'
import { expenseRequestAfterSave, pendingImportExpense, travelerIdsOf, travelersChanged, filesNeedConnection, uploadBookingFiles } from './bookingFormModel'
import { useBookingExpenseIntent } from './useBookingExpenseIntent'
import { useBookingFileAttach } from './useBookingFileAttach'
import StayPinStatus from './StayPinStatus'
const EMPTY_FORM = {
title: '', type: 'other', status: 'pending',
@@ -82,7 +81,7 @@ export function ReservationModal({ isOpen, onClose, onSave, reservation, days, p
const {
form, setForm, set, isSaving, setIsSaving, pendingFiles, setPendingFiles, travelerIds, setTravelerIds, toggleTraveler,
isEndBeforeStart, endTimeBeforeStartTime, dateBounds: tripDateRange, startDate, startTime, setStartDate, setStartTime, takeStopDay,
pickPlace, pickHotelPlace, pickHotelStart, pickHotelEnd, stayPin, saveData: buildSaveData,
pickPlace, pickHotelPlace, pickHotelStart, pickHotelEnd, saveData: buildSaveData,
} = useReservationForm(EMPTY_FORM, days, places)
const attach = useBookingFileAttach({ reservation, files, onFileUpload, setPendingFiles, toast, t })
@@ -103,22 +102,17 @@ export function ReservationModal({ isOpen, onClose, onSave, reservation, days, p
}
setTravelerIds(travelerIdsOf(reservation))
stayPin.reset()
if (reservation) {
setForm({ ...reservationFieldsFrom(reservation, accommodations, places, true), assignment_id: reservation.assignment_id || '' })
} else if (prefill) {
// Review-before-save: populate from a parsed import item, stay in create mode.
const hotelPlaceId = matchPlaceId(prefill._venue?.name || prefill.title)
setForm({
...reservationFieldsFromPrefill(prefill, days, true),
assignment_id: defaultAssignmentId ?? '',
accommodation_id: '',
place_id: '',
hotel_place_id: hotelPlaceId,
hotel_place_id: matchPlaceId(prefill._venue?.name || prefill.title),
})
// A stay the trip does not hold yet: find it on the map now, so the review
// says whether it will show there before it is saved.
if (prefill.type === 'hotel' && !hotelPlaceId) stayPin.lookUp(prefill._venue?.name || prefill.title, prefill._venue?.address)
// Seed the booking's Files with the document this item was parsed from.
setPendingFiles(prefill._sourceFiles ?? [])
} else {
@@ -368,14 +362,8 @@ export function ReservationModal({ isOpen, onClose, onSave, reservation, days, p
</div>
<EditorField label={t('reservations.locationAddress')}>
<AddressInput value={form.hotel_address} onChange={v => set('hotel_address', v)}
onPick={stayPin.pick}
placeholder={t('reservations.locationPlaceholder')} className={INPUT} />
</EditorField>
<StayPinStatus
pin={stayPin.pin}
hidden={!!form.hotel_place_id}
onRetry={() => stayPin.lookUp(form.title, form.hotel_address)}
/>
</>
)}
@@ -1,54 +0,0 @@
import { fireEvent, render, screen } from '@testing-library/react';
import { createElement } from 'react';
import { describe, expect, it, vi } from 'vitest';
import { TranslationProvider } from '../../i18n/TranslationContext';
import StayPinStatus from './StayPinStatus';
import type { StayPin } from './useStayPin';
function show(pin: StayPin, onRetry = vi.fn()) {
render(createElement(TranslationProvider, null, createElement(StayPinStatus, { pin, onRetry })));
return onRetry;
}
describe('StayPinStatus', () => {
it('FE-STAY-PIN-STATUS-001: shows nothing before a lookup', () => {
const { container } = render(
createElement(
TranslationProvider,
null,
createElement(StayPinStatus, { pin: { status: 'idle' }, onRetry: vi.fn() })
)
);
expect(container.textContent).toBe('');
});
it('FE-STAY-PIN-STATUS-001b: a stay already linked to a place of the trip shows nothing', () => {
const { container } = render(
createElement(
TranslationProvider,
null,
createElement(StayPinStatus, { pin: { status: 'missing' }, hidden: true, onRetry: vi.fn() })
)
);
expect(container.textContent).toBe('');
});
it('FE-STAY-PIN-STATUS-002: says it is looking, then where it found the stay', () => {
show({ status: 'searching' });
expect(screen.getByRole('status')).toHaveTextContent('Looking for it on the map');
});
it('FE-STAY-PIN-STATUS-003: a found stay names the match, so a wrong one is plain', () => {
show({ status: 'found', match: { lat: 1, lng: 2, label: 'Hotel Gracery Shinjuku, Tokyo' } });
expect(screen.getByRole('status')).toHaveTextContent('On the map');
expect(screen.getByText('Hotel Gracery Shinjuku, Tokyo')).toBeInTheDocument();
});
it('FE-STAY-PIN-STATUS-004: a missing stay says so and offers to search again', () => {
const onRetry = show({ status: 'missing' });
expect(screen.getByText('Not on the map yet')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: /search again/i }));
expect(onRetry).toHaveBeenCalledTimes(1);
});
});
@@ -1,62 +0,0 @@
import { MapPin, MapPinOff, RotateCw } from 'lucide-react';
import { useTranslation } from '../../i18n';
import type { StayPin } from './useStayPin';
interface StayPinStatusProps {
pin: StayPin;
/** A stay already linked to a place of the trip shows on the map through that place. */
hidden?: boolean;
/** Asks the map again with what the form now holds. */
onRetry: () => void;
}
/**
* Whether an imported stay will show on the map, under its address in the
* review: being looked up, found (and where, so a wrong match is plain), or not
* found, with a way to search again before it is saved without a pin. Shared by
* the desktop booking dialog and the phone's booking sheet.
*/
export default function StayPinStatus({ pin, hidden = false, onRetry }: StayPinStatusProps) {
const { t } = useTranslation();
if (hidden || pin.status === 'idle') return null;
if (pin.status === 'searching') {
return (
<div role="status" className="flex items-center gap-2 px-1 text-caption text-content-muted">
<span className="h-3.5 w-3.5 flex-none animate-spin rounded-full border-2 border-edge border-t-content-muted" />
{t('reservations.import.pinSearching')}
</div>
);
}
if (pin.status === 'found') {
return (
<div role="status" className="flex min-w-0 items-center gap-2 rounded-lg bg-success-soft px-3 py-2 text-caption">
<MapPin size={14} strokeWidth={2.2} className="flex-none text-success" />
<span className="flex-none font-semibold text-success">{t('reservations.import.pinFound')}</span>
<span className="min-w-0 truncate text-content-secondary" title={pin.match.label}>
{pin.match.label}
</span>
</div>
);
}
return (
<div role="status" className="flex items-start gap-3 rounded-xl bg-warning-soft px-3.5 py-3">
<MapPinOff size={16} strokeWidth={2.2} className="mt-0.5 flex-none text-warning" />
<div className="min-w-0 flex-1">
<p className="m-0 text-body font-semibold text-content">{t('reservations.import.pinMissingTitle')}</p>
<p className="m-0 mt-0.5 text-caption text-content-muted">{t('reservations.import.pinMissingBody')}</p>
<button
type="button"
onClick={onRetry}
className="mt-2 inline-flex items-center gap-1.5 rounded-lg border border-edge bg-surface-card px-2.5 py-1 text-caption font-medium text-content hover:bg-surface-hover"
>
<RotateCw size={12} strokeWidth={2.2} />
{t('reservations.import.pinRetry')}
</button>
</div>
</div>
);
}
@@ -287,8 +287,6 @@ export interface ReservationSaveOptions {
isEdit: boolean;
/** The desktop also saves the end of the check-in window. */
withCheckInEnd: boolean;
/** Where the review found an imported stay on the map, so the save creates its place right there. */
venuePin?: { lat: number; lng: number } | null;
}
export type ReservationSaveData = Record<string, unknown> & { title: string };
@@ -346,11 +344,7 @@ export function reservationSaveData(
// import): the save handler geocodes it and creates the place.
venue:
!form.hotel_place_id && (form.hotel_address || form.title)
? {
name: form.title,
address: form.hotel_address || null,
...(opts.venuePin ? { lat: opts.venuePin.lat, lng: opts.venuePin.lng } : {}),
}
? { name: form.title, address: form.hotel_address || null }
: null,
// The typed address, so the save handler can write it through to a linked
// place; an edited address used to be silently dropped (#1496).
@@ -19,7 +19,6 @@ import {
withStartDate,
withStartTime,
} from './reservationFormModel';
import { useStayPin } from './useStayPin';
/**
* The booking form behind the desktop ReservationModal and the phone's booking
@@ -40,8 +39,6 @@ export function useReservationForm<F extends ReservationFields & CheckInEndField
const set = (field: keyof F, value: string | number) => setForm((prev) => ({ ...prev, [field]: value }));
const toggleTraveler = (id: number) => setTravelerIds((prev) => toggledTraveler(prev, id));
// Where an imported stay will land on the map, looked up while it is reviewed.
const stayPin = useStayPin();
// Restrict non-hotel booking dates to the trip's span (#1662). Hotels already
// constrain to trip days via their day dropdowns.
@@ -74,7 +71,6 @@ export function useReservationForm<F extends ReservationFields & CheckInEndField
pickHotelPlace: (value: string | number) => setForm((prev) => withHotelPlace(prev, value, places)),
pickHotelStart: (value: string | number) => setForm((prev) => withHotelStart(prev, value, days)),
pickHotelEnd: (value: string | number) => setForm((prev) => withHotelEnd(prev, value, days)),
stayPin,
saveData: (opts: ReservationSaveOptions) => reservationSaveData(form, { ...opts, venuePin: stayPin.match }),
saveData: (opts: ReservationSaveOptions) => reservationSaveData(form, opts),
};
}
@@ -1,74 +0,0 @@
import { act, renderHook, waitFor } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { findOnMap } from '../../repo/mapMatchRepo';
import { isEffectivelyOffline } from '../../sync/networkMode';
import { useStayPin } from './useStayPin';
vi.mock('../../hooks/usePlaceLanguage', () => ({ usePlaceLanguage: () => 'en' }));
vi.mock('../../sync/networkMode', () => ({ isEffectivelyOffline: vi.fn(() => false) }));
vi.mock('../../repo/mapMatchRepo', async (importOriginal) => ({
...(await importOriginal<typeof import('../../repo/mapMatchRepo')>()),
findOnMap: vi.fn(),
}));
const SPOT = { lat: 35.69, lng: 139.7, label: 'Hotel Gracery Shinjuku' };
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(isEffectivelyOffline).mockReturnValue(false);
});
describe('useStayPin', () => {
it('FE-STAY-PIN-001: looks the stay up by name and address and says where it found it', async () => {
vi.mocked(findOnMap).mockResolvedValueOnce(SPOT);
const { result } = renderHook(() => useStayPin());
expect(result.current.pin).toEqual({ status: 'idle' });
act(() => result.current.lookUp('Hotel Gracery', '1-19-1 Kabukicho'));
expect(result.current.pin).toEqual({ status: 'searching' });
await waitFor(() => expect(result.current.pin).toEqual({ status: 'found', match: SPOT }));
expect(result.current.match).toEqual(SPOT);
expect(findOnMap).toHaveBeenCalledWith(
['Hotel Gracery 1-19-1 Kabukicho', 'Hotel Gracery', '1-19-1 Kabukicho'],
'en'
);
});
it('FE-STAY-PIN-002: nothing found, a failed search and an empty name all read as not on the map', async () => {
const { result } = renderHook(() => useStayPin());
vi.mocked(findOnMap).mockResolvedValueOnce(null);
act(() => result.current.lookUp('Ryokan', null));
await waitFor(() => expect(result.current.pin).toEqual({ status: 'missing' }));
expect(result.current.match).toBeNull();
vi.mocked(findOnMap).mockRejectedValueOnce(new Error('down'));
act(() => result.current.lookUp('Ryokan', null));
await waitFor(() => expect(result.current.pin).toEqual({ status: 'missing' }));
act(() => result.current.lookUp('', ''));
expect(result.current.pin).toEqual({ status: 'missing' });
});
it('FE-STAY-PIN-003: a later lookup or a hand-picked spot wins over an answer still on its way', async () => {
let answer: (m: typeof SPOT | null) => void = () => undefined;
vi.mocked(findOnMap).mockImplementationOnce(() => new Promise((resolve) => (answer = resolve)));
const { result } = renderHook(() => useStayPin());
act(() => result.current.lookUp('Hotel', 'Somewhere'));
const picked = { lat: 1, lng: 2, label: 'Picked' };
act(() => result.current.pick(picked));
await act(async () => answer(SPOT));
expect(result.current.pin).toEqual({ status: 'found', match: picked });
act(() => result.current.reset());
expect(result.current.pin).toEqual({ status: 'idle' });
});
it('FE-STAY-PIN-004: offline there is nothing to ask, so the review shows nothing', () => {
vi.mocked(isEffectivelyOffline).mockReturnValue(true);
const { result } = renderHook(() => useStayPin());
act(() => result.current.lookUp('Hotel', 'Somewhere'));
expect(result.current.pin).toEqual({ status: 'idle' });
expect(findOnMap).not.toHaveBeenCalled();
});
});
@@ -1,69 +0,0 @@
import { useEffect, useRef, useState } from 'react';
import { usePlaceLanguage } from '../../hooks/usePlaceLanguage';
import { findOnMap, type MapMatch, stayQueries } from '../../repo/mapMatchRepo';
import { isEffectivelyOffline } from '../../sync/networkMode';
/**
* Where an imported stay will sit on the map, as the review shows it: not asked
* yet (or offline, where there is nothing to ask), being looked up, found, or
* not found at all.
*/
export type StayPin =
{ status: 'idle' } | { status: 'searching' } | { status: 'found'; match: MapMatch } | { status: 'missing' };
/**
* The map spot of a stay reviewed from an import, looked up before it is saved
* so the review can say whether it will show on the map. A stay the search did
* not find used to be saved without coordinates and simply never appeared.
* A later lookup always wins over an earlier one still on its way.
*/
export function useStayPin() {
const lang = usePlaceLanguage();
const [pin, setPin] = useState<StayPin>({ status: 'idle' });
const ticket = useRef(0);
useEffect(
() => () => {
ticket.current++;
},
[]
);
const lookUp = (name: string | null | undefined, address: string | null | undefined) => {
const mine = ++ticket.current;
const queries = stayQueries(name ?? '', address);
if (isEffectivelyOffline()) {
setPin({ status: 'idle' });
return;
}
if (queries.length === 0) {
setPin({ status: 'missing' });
return;
}
setPin({ status: 'searching' });
findOnMap(queries, lang).then(
(match) => {
if (mine === ticket.current) setPin(match ? { status: 'found', match } : { status: 'missing' });
},
() => {
if (mine === ticket.current) setPin({ status: 'missing' });
}
);
};
return {
pin,
/** The spot to save the stay at, once one is known. */
match: pin.status === 'found' ? pin.match : null,
lookUp,
/** A spot the reader picked by hand, which beats any lookup. */
pick: (match: MapMatch) => {
ticket.current++;
setPin({ status: 'found', match });
},
reset: () => {
ticket.current++;
setPin({ status: 'idle' });
},
};
}
@@ -1,4 +1,4 @@
// FE-AI-CONNECT-MODEL-001 to FE-AI-CONNECT-MODEL-008: the pure rules behind connecting an AI provider.
// FE-AI-CONNECT-MODEL-001 to FE-AI-CONNECT-MODEL-007: the pure rules behind connecting an AI provider.
import type { AiConnectionView } from '@trek/shared';
import { describe, expect, it } from 'vitest';
import { OnlineOnlyError } from '../../../repo/onlineOnly';
@@ -6,7 +6,6 @@ import {
connectErrorKey,
httpHostOf,
isPublicHttpsUrl,
openrouterReturnCode,
refusalCode,
rememberOpenrouterFlow,
repairModeOf,
@@ -94,14 +93,4 @@ describe('aiConnectModel', () => {
expect(src).not.toContain('<');
expect(decodeURIComponent(src.split(',')[1])).toBe('<svg><path d="M0 0"/></svg>');
});
it('FE-AI-CONNECT-MODEL-008: reads the OpenRouter return with the code after an & or after a second ?', () => {
const read = (query: string) => openrouterReturnCode(new URLSearchParams(query));
expect(read('tab=integrations&ai=openrouter&code=abc')).toBe('abc');
expect(read('tab=integrations&ai=openrouter?code=abc')).toBe('abc');
expect(read('tab=addons&ai=openrouter?code=abc&state=x')).toBe('abc');
expect(read('ai=openrouter')).toBeNull();
expect(read('tab=integrations')).toBeUndefined();
expect(read('ai=chatgpt&code=abc')).toBeUndefined();
});
});
@@ -56,26 +56,6 @@ export function repairModeOf(view: AiConnectionView): AiConnectMode | null {
return view.kind === 'custom' ? 'custom' : 'key';
}
/**
* Whether a pasted ChatGPT callback ended this sign-in rather than an earlier
* one: its `state` is the one the sign-in address carried. The server takes a
* sign-in only once, so an address from an earlier attempt still on the
* clipboard would use up the one in progress. Without a state on either side
* the server decides.
*/
export function callbackMatchesFlow(callback: string, authorizeUrl: string): boolean {
const stateOf = (address: string) => {
try {
return new URL(address.trim()).searchParams.get('state');
} catch {
return null;
}
};
const expected = stateOf(authorizeUrl);
const pasted = stateOf(callback);
return !expected || !pasted || pasted === expected;
}
// The OpenRouter sign-in leaves the page and comes back with a code only; the
// flow it belongs to waits here for that one return. Tab-scoped on purpose.
const OPENROUTER_FLOW_KEY = 'trek.ai.openrouterFlow';
@@ -99,21 +79,6 @@ export function takeOpenrouterFlow(): string | null {
}
}
/**
* The code an OpenRouter sign-in came back with, or `undefined` when the page
* was not opened by one. The return address already carries a query
* (`?tab=…&ai=openrouter`), and OpenRouter may add its code with a second `?`
* rather than an `&`, which leaves it inside the `ai` value
* (`ai=openrouter?code=…`); both shapes count.
*/
export function openrouterReturnCode(params: URLSearchParams): string | null | undefined {
const ai = params.get('ai');
if (ai === null) return undefined;
const [marker, rest] = ai.split('?', 2);
if (marker !== 'openrouter') return undefined;
return params.get('code') ?? new URLSearchParams(rest ?? '').get('code');
}
const PRIVATE_V4 = [/^10\./, /^127\./, /^169\.254\./, /^192\.168\./, /^172\.(1[6-9]|2\d|3[01])\./, /^0\./];
/**
@@ -1,4 +1,4 @@
// FE-HOOK-AI-CONNECT-001 to FE-HOOK-AI-CONNECT-015: pasting a key, an own server, the ChatGPT sign-in and the OpenRouter return.
// FE-HOOK-AI-CONNECT-001 to FE-HOOK-AI-CONNECT-013: pasting a key, an own server, the ChatGPT sign-in and the OpenRouter return.
import { act, fireEvent, renderHook, waitFor } from '@testing-library/react';
import { createElement, type ReactNode } from 'react';
import { MemoryRouter, useLocation } from 'react-router';
@@ -249,52 +249,6 @@ describe('useChatgptConnect', () => {
expect(readText).toHaveBeenCalledTimes(1);
input.remove();
});
it('FE-HOOK-AI-CONNECT-014: the same address handed in twice at once is sent once, so the sign-in is not used up', async () => {
let answer: (value: unknown) => void = () => undefined;
repo.chatgptFinish.mockImplementationOnce(() => new Promise((resolve) => (answer = resolve)));
const onConnected = vi.fn();
const { result } = renderHook(() => useChatgptConnect({ active: true, onConnected }), { wrapper: wrapperAt() });
await waitFor(() => expect(result.current.flow).not.toBeNull());
act(() => {
result.current.paste(CALLBACK);
result.current.paste(CALLBACK);
});
await act(async () => answer({}));
await waitFor(() => expect(onConnected).toHaveBeenCalledTimes(1));
expect(repo.chatgptFinish).toHaveBeenCalledTimes(1);
expect(result.current.error).toBeNull();
});
it('FE-HOOK-AI-CONNECT-015: an address from an earlier sign-in is not sent, and the one in progress stays usable', async () => {
repo.chatgptStart.mockResolvedValue({ ...FLOW, authorizeUrl: 'https://auth.openai.com/oauth/authorize?state=s2' });
const readText = vi.fn(async () => CALLBACK);
Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { readText } });
Object.defineProperty(window, 'isSecureContext', { configurable: true, value: true });
const onConnected = vi.fn();
const { result } = renderHook(() => useChatgptConnect({ active: true, onConnected }), { wrapper: wrapperAt() });
await waitFor(() => expect(result.current.flow).not.toBeNull());
// Back from the sign-in window with the old address still on the clipboard: nothing is sent.
act(() => result.current.markOpened());
fireEvent.focus(window);
await waitFor(() => expect(readText).toHaveBeenCalled());
expect(repo.chatgptFinish).not.toHaveBeenCalled();
expect(result.current.error).toBeNull();
// Pasted by hand it is refused here, and the address this sign-in ended on still goes through.
act(() => {
result.current.paste(CALLBACK);
});
expect(result.current.error).toEqual({ messageKey: 'assistant.connect.chatgptWrong', code: 'wrong_url' });
const current = CALLBACK.replace('state=s1', 'state=s2');
act(() => {
result.current.paste(current);
});
await waitFor(() => expect(onConnected).toHaveBeenCalledTimes(1));
expect(repo.chatgptFinish).toHaveBeenCalledWith({ flowId: FLOW.flowId, pastedUrl: current });
expect(repo.chatgptStart).toHaveBeenCalledTimes(1);
});
});
describe('OpenRouter', () => {
@@ -326,19 +280,4 @@ describe('OpenRouter', () => {
await waitFor(() => expect(toast.error).toHaveBeenCalledTimes(1));
expect(repo.openrouterFinish).not.toHaveBeenCalled();
});
it('FE-HOOK-AI-CONNECT-012b: a code OpenRouter added with a second question mark still finishes the sign-in', async () => {
rememberOpenrouterFlow(FLOW.flowId);
const onConnected = vi.fn();
const { result } = renderHook(
() => {
useOpenrouterReturn(onConnected);
return useLocation();
},
{ wrapper: wrapperAt('/settings?tab=integrations&ai=openrouter?code=or-code') }
);
await waitFor(() => expect(onConnected).toHaveBeenCalledTimes(1));
expect(repo.openrouterFinish).toHaveBeenCalledWith({ flowId: FLOW.flowId, code: 'or-code' });
expect(result.current.search).toBe('?tab=integrations');
});
});
@@ -5,15 +5,7 @@ import { useTranslation } from '../../../i18n';
import { aiConnectionsRepo } from '../../../repo/aiConnectionsRepo';
import { detectKeyKind, isChatgptCallback, providerLabel } from '../../Assistant/providerCatalog';
import { useToast } from '../../shared/Toast';
import {
callbackMatchesFlow,
connectErrorKey,
httpHostOf,
openrouterReturnCode,
refusalCode,
rememberOpenrouterFlow,
takeOpenrouterFlow,
} from './aiConnectModel';
import { connectErrorKey, httpHostOf, refusalCode, rememberOpenrouterFlow, takeOpenrouterFlow } from './aiConnectModel';
/**
* The ways to connect a provider, one hook each, behind `AiConnectPanel`: a
@@ -213,10 +205,6 @@ export function useChatgptConnect({
const [busy, setBusy] = useState(false);
const [error, setError] = useState<ConnectError | null>(null);
const inputRef = useRef<HTMLInputElement>(null);
// Set at once, unlike `busy`: the clipboard read on return and the user's own
// paste can hand in the same address within one render, and the server takes
// a sign-in only once, so the second would come back as expired.
const finishing = useRef(false);
useEffect(() => {
if (!active) return;
@@ -244,8 +232,8 @@ export function useChatgptConnect({
const finish = async (raw: string) => {
const url = raw.trim();
if (!flow || finishing.current) return;
if (!isChatgptCallback(url) || !callbackMatchesFlow(url, flow.authorizeUrl)) {
if (!flow || busy) return;
if (!isChatgptCallback(url)) {
setError({ messageKey: 'assistant.connect.chatgptWrong', code: 'wrong_url' });
return;
}
@@ -254,7 +242,6 @@ export function useChatgptConnect({
restart();
return;
}
finishing.current = true;
setBusy(true);
setError(null);
try {
@@ -266,7 +253,6 @@ export function useChatgptConnect({
setError({ messageKey: connectErrorKey(err), code });
if (code === 'expired') restart();
} finally {
finishing.current = false;
setBusy(false);
}
};
@@ -294,12 +280,10 @@ export function useChatgptConnect({
// Back from the sign-in window: the address the user just copied is taken
// off the clipboard where the browser allows it, else the field has the cursor.
// An address left over from an earlier sign-in is not sent: it would use up this one.
useOnReturnToTab(opened, () => {
if (pasted.trim() || busy) return;
readClipboard((text) => {
if (flow && !callbackMatchesFlow(text, flow.authorizeUrl)) focusField();
else if (!paste(text)) focusField();
if (!paste(text)) focusField();
}, focusField);
});
@@ -367,9 +351,9 @@ export function useOpenrouterReturn(onConnected: () => void) {
});
useEffect(() => {
const code = openrouterReturnCode(params);
if (handled.current || code === undefined) return;
if (handled.current || params.get('ai') !== 'openrouter') return;
handled.current = true;
const code = params.get('code');
setParams(
(prev) => {
const next = new URLSearchParams(prev);
-19
View File
@@ -70,19 +70,6 @@ interface CachedTourDraft {
draft: TourDraft;
}
/**
* A road route as the router answered it, kept on the device so a trip opens
* with its roads drawn instead of asking the router for every leg again (#2794).
* `key` is RouteCalculator's cache key (profile, unit, waypoints, avoided
* roads), `route` its answer as it came, `savedAt` when it came: an old answer
* is asked again, and the oldest give way first.
*/
interface CachedRoute {
key: string;
route: unknown;
savedAt: number;
}
// ── Queue + sync types ────────────────────────────────────────────────────────
// 'conflict' is terminal-until-resolved: the server rejected the replay because
@@ -292,7 +279,6 @@ export class TrekOfflineDb extends Dexie {
ferrataTiles!: Table<CachedFerrataTile, [number, string]>;
tourStationVisits!: Table<CachedTourStationVisit, [number, string]>;
tourDrafts!: Table<CachedTourDraft, number>;
routeCache!: Table<CachedRoute, string>;
constructor(name: string = ANON_DB_NAME) {
super(name);
@@ -380,11 +366,6 @@ export class TrekOfflineDb extends Dexie {
// v13: the Tours planner's unsaved draft as the account last said it, one
// per trip (the database is the signed-in user's own), so it opens offline.
this.version(13).stores({ tourDrafts: 'tripId' });
// v14: road routes the router answered, by their cache key, so a trip with its
// whole route shown opens drawn instead of re-routing every leg (#2794). Not per
// trip: the same waypoints are the same road in any trip; `savedAt` to prune.
this.version(14).stores({ routeCache: 'key, savedAt' });
}
}
@@ -294,7 +294,7 @@ export default function MAdminPluginsPanel() {
{bypass.copy && (
<MConfirmSheet open onClose={bypass.dismiss} onConfirm={bypass.copy.confirm ? bypass.confirm : undefined}
title={bypass.copy.title} message={bypass.copy.body}
confirmLabel={bypass.copy.confirmLabel} cancelLabel={bypass.copy.confirm ? t('common.cancel') : t('common.ok')} danger />
confirmLabel={t('admin.plugins.installAnyway')} cancelLabel={bypass.copy.confirm ? t('common.cancel') : t('common.ok')} danger />
)}
{/* Row ⋯ action sheet */}
@@ -50,17 +50,13 @@ export default function MAssistantHomeScreen() {
useAssistantStatus();
if (inTrip || !available || !open || minimized) return null;
// Mounted beside MobileShell, not inside it, so the --m-* tokens the screen paints
// with only resolve under an m-root of its own; without it the chat is see-through.
return (
<div className="m-root">
<AssistantScreen
tripId={chat.id}
tripTitle={chat.title}
hidden={false}
hops={hops}
onOpenTripChat={journal ? undefined : home.openTripChat}
/>
</div>
<AssistantScreen
tripId={chat.id}
tripTitle={chat.title}
hidden={false}
hops={hops}
onOpenTripChat={journal ? undefined : home.openTripChat}
/>
);
}
@@ -15,7 +15,6 @@ import {
RESERVATION_TYPE_OPTIONS as TYPE_OPTIONS, reservationFieldsFrom, reservationFieldsFromPrefill, selectedDayDate,
} from '../../../../components/Planner/reservationFormModel'
import { useReservationForm } from '../../../../components/Planner/useReservationForm'
import StayPinStatus from '../../../../components/Planner/StayPinStatus'
import { buildAssignmentOptions } from '../../../../components/Planner/assignmentOptions'
import { useTripStore } from '../../../../store/tripStore'
import type { BookingExpenseRequest } from '../../../../components/Planner/BookingCostsSection.types'
@@ -61,7 +60,7 @@ export default function MReservationSheet({ planner, onOpenExpense }: MReservati
const {
form, setForm, set, isSaving, setIsSaving, pendingFiles, setPendingFiles, travelerIds, setTravelerIds, toggleTraveler,
isEndBeforeStart, endTimeBeforeStartTime, dateBounds, startDate, startTime, setStartDate, setStartTime, takeStopDay,
pickPlace, pickHotelPlace, pickHotelStart, pickHotelEnd, stayPin, saveData: buildSaveData,
pickPlace, pickHotelPlace, pickHotelStart, pickHotelEnd, saveData: buildSaveData,
} = useReservationForm(EMPTY, days, places)
const assignmentOptions = useMemo(
() => buildAssignmentOptions(days, assignments, t, locale),
@@ -86,7 +85,6 @@ export default function MReservationSheet({ planner, onOpenExpense }: MReservati
expense.reset()
setPendingFiles([])
setTravelerIds(travelerIdsOf(editingReservation))
stayPin.reset()
const res = editingReservation
if (res) {
@@ -95,8 +93,6 @@ export default function MReservationSheet({ planner, onOpenExpense }: MReservati
const pf = reservationPrefill
setForm({ ...EMPTY, ...reservationFieldsFromPrefill(pf, days, false) })
setPendingFiles(pf._sourceFiles ?? [])
// Find an imported stay on the map now, so the review says whether it will show there.
if (pf.type === 'hotel') stayPin.lookUp(pf._venue?.name || pf.title, pf._venue?.address)
} else {
// Opened from a day's toolbar: start on that day rather than on a blank
// date the user has to look up again (#1998). A hotel spans to the next
@@ -339,13 +335,6 @@ export default function MReservationSheet({ planner, onOpenExpense }: MReservati
placeholder={t('reservations.locationPlaceholder')}
className={FIELD_CLS}
/>
<div className="mt-2 empty:hidden">
<StayPinStatus
pin={stayPin.pin}
hidden={!!form.hotel_place_id}
onRetry={() => stayPin.lookUp(form.title, form.hotel_address)}
/>
</div>
</>
)}
@@ -18,7 +18,7 @@ import type { Translate } from './plannerTypes'
import { useBookingEdits } from './useBookingEdits'
type Options = Parameters<typeof useBookingEdits>[0]
type ImportedStay = { place_id?: number; venue?: { name?: string; address?: string | null; lat?: number; lng?: number }; address?: string }
type ImportedStay = { place_id?: number; venue?: { name?: string; address?: string | null }; address?: string }
const toast = { success: vi.fn(), error: vi.fn(), warning: vi.fn(), info: vi.fn() }
const t = ((key: string) => key) as Translate
@@ -231,32 +231,6 @@ describe('useBookingEdits', () => {
expect(actions.addReservation).toHaveBeenCalledTimes(4)
})
it('FE-TP-BOOKING-007b: a stay lands where the review found it, falls back to its name, and says when it has no spot', async () => {
const { result } = renderEdits()
// The review already found it: no second search, the place sits right there.
vi.mocked(mapsApi.search).mockClear()
await saveHotel(result, { venue: { name: 'Gracery', address: '1-19-1 Kabukicho', lat: 35.69, lng: 139.7 } })
expect(mapsApi.search).not.toHaveBeenCalled()
expect(actions.addPlace).toHaveBeenLastCalledWith(42, { name: 'Gracery', lat: 35.69, lng: 139.7, address: '1-19-1 Kabukicho' })
expect(toast.warning).not.toHaveBeenCalled()
// A romanized address that matches nothing no longer sinks the hotel's name.
vi.mocked(mapsApi.search).mockImplementation(async (query: string) =>
(query === 'Gracery' ? { places: [{ lat: 35.69, lng: 139.7 }] } : { places: [] }) as never)
await saveHotel(result, { venue: { name: 'Gracery', address: '1-19-1 Kabukicho' } })
expect(vi.mocked(mapsApi.search).mock.calls.map(([q]) => q)).toEqual(['Gracery 1-19-1 Kabukicho', 'Gracery'])
expect(actions.addPlace).toHaveBeenLastCalledWith(42, { name: 'Gracery', lat: 35.69, lng: 139.7, address: '1-19-1 Kabukicho' })
expect(toast.warning).not.toHaveBeenCalled()
// Found nowhere: the booking is still saved, and the reader is told it has no pin.
vi.mocked(mapsApi.search).mockResolvedValue({ places: [] } as never)
await saveHotel(result, { venue: { name: 'Nowhere Inn', address: 'Nowhere 1' } })
expect(actions.addPlace).toHaveBeenLastCalledWith(42, { name: 'Nowhere Inn', lat: null, lng: null, address: 'Nowhere 1' })
expect(toast.warning).toHaveBeenCalledWith('reservations.import.savedWithoutPin')
expect(actions.addReservation).toHaveBeenCalledTimes(3)
})
it('FE-TP-BOOKING-008: a booking that cannot be saved says so, whatever was thrown', async () => {
const { result } = renderEdits()
+18 -25
View File
@@ -1,11 +1,11 @@
import { useEffect, useRef, useState, type Dispatch, type SetStateAction } from 'react'
import type { BookingImportPreviewItem } from '@trek/shared'
import { mapsApi } from '../../api/client'
import { receiptToPrefill } from '../../components/Budget/CostsPanel.helpers'
import type { ExpensePrefill } from '../../components/Budget/CostsPanel'
import { parsedItemToDraft, isTransportItem, isUnplaceableItem, type BookingReviewDraft } from '../../components/Planner/parsedItemToDraft'
import { getImportFiles, deleteImportFiles } from '../../db/offlineDb'
import { accommodationRepo } from '../../repo/accommodationRepo'
import { findOnMap, stayQueries } from '../../repo/mapMatchRepo'
import { useBackgroundTasksStore } from '../../store/backgroundTasksStore'
import type { TripStoreState } from '../../store/tripStore'
import { isEffectivelyOffline } from '../../sync/networkMode'
@@ -63,10 +63,7 @@ export function useBookingEdits(options: BookingEditsOptions) {
// an existing place by name, else geocode the address and create one, then link it.
const acc = (data as Record<string, any>).create_accommodation
if (data.type === 'hotel' && acc && acc.venue && !acc.place_id) {
const resolved = await resolveImportedPlace(acc.venue)
acc.place_id = resolved?.id ?? undefined
// Saved, but nowhere on the map: say so rather than leave the pin to go missing.
if (resolved && !resolved.placed) toast.warning(t('reservations.import.savedWithoutPin'))
acc.place_id = (await resolveImportedPlace(acc.venue)) ?? undefined
delete acc.venue
}
// A hotel's address lives on the linked place. Write an edited address
@@ -144,13 +141,9 @@ export function useBookingEdits(options: BookingEditsOptions) {
}
// ── Review-before-save booking import ───────────────────────────────────────
// Match an existing trip place by name, else create one at the spot the review
// found, or the first spot the map search knows for its name and address.
// Returns the place and whether it has a spot on the map (null if even creation
// failed).
const resolveImportedPlace = async (
venue: { name?: string; address?: string | null; lat?: number; lng?: number },
): Promise<{ id: number; placed: boolean } | null> => {
// Match an existing trip place by name, else geocode the reviewed address and
// create one. Returns the place id (or null if even creation failed).
const resolveImportedPlace = async (venue: { name?: string; address?: string | null }): Promise<number | null> => {
const name = (venue.name || '').trim()
const n = name.toLowerCase()
if (n) {
@@ -160,23 +153,23 @@ export function useBookingEdits(options: BookingEditsOptions) {
// the booking waits in the queue behind that place and is sent with its real
// id. Online the booking goes out at once, and day_accommodations.place_id
// carries a foreign key, so a temp id there is a 500 instead of a saved booking.
if (existing && (existing.id > 0 || isEffectivelyOffline())) return { id: existing.id, placed: existing.lat != null && existing.lng != null }
if (existing && (existing.id > 0 || isEffectivelyOffline())) return existing.id
}
let lat: number | null = venue.lat ?? null
let lng: number | null = venue.lng ?? null
let lat: number | null = null
let lng: number | null = null
let address: string | null = venue.address ?? null
if (lat == null || lng == null) {
try {
// Name and address, then each alone: a booking site's romanized address
// often matches nothing and sinks the hotel's name with it. Offline
// findOnMap answers null and the place is created without coords.
const hit = await findOnMap(stayQueries(name, venue.address))
if (hit) {
try {
const query = venue.address ? `${name} ${venue.address}`.trim() : name
// Offline there is no geocoder to ask; the place is created without coords.
if (query && !isEffectivelyOffline()) {
const res = await mapsApi.search(query)
const hit = res?.places?.[0] as { lat?: number; lng?: number; address?: string } | undefined
if (hit && hit.lat != null && hit.lng != null) {
lat = hit.lat; lng = hit.lng
if (!address && hit.address) address = hit.address
}
} catch { /* geocode failure is non-fatal: create the place without coords, and say so */ }
}
}
} catch { /* geocode failure is non-fatal: create the place without coords */ }
try {
// Through the store, not placesApi directly: the API answers { place },
// and reading .id off that wrapper linked nothing. Every save of the
@@ -185,7 +178,7 @@ export function useBookingEdits(options: BookingEditsOptions) {
// find it. addPlace unwraps the response and puts the place into
// `places`, so the next save reuses it.
const place = await tripActions.addPlace(tripId, { name: name || address || 'Accommodation', lat, lng, address })
return place && (place.id > 0 || isEffectivelyOffline()) ? { id: place.id, placed: lat != null && lng != null } : null
return place && (place.id > 0 || isEffectivelyOffline()) ? place.id : null
} catch { return null }
}
-5
View File
@@ -104,11 +104,6 @@ export const aiConnectionsRepo = {
return aiAdminConnectionResponseSchema.parse(await aiAdminApi.saveConnection(body));
},
async setAdminModel(model: string) {
requireOnline();
return aiAdminConnectionResponseSchema.parse(await aiAdminApi.setModel(model));
},
async removeAdminConnection(): Promise<void> {
requireOnline();
await aiAdminApi.removeConnection();
-69
View File
@@ -1,69 +0,0 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { mapsApi } from '../api/client';
import { isEffectivelyOffline } from '../sync/networkMode';
import { findOnMap, stayQueries } from './mapMatchRepo';
vi.mock('../sync/networkMode', () => ({ isEffectivelyOffline: vi.fn(() => false) }));
vi.mock('../api/client', () => ({ mapsApi: { search: vi.fn() } }));
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(isEffectivelyOffline).mockReturnValue(false);
vi.mocked(mapsApi.search).mockResolvedValue({ places: [] } as never);
});
describe('finding a stay on the map', () => {
it('FE-MAP-MATCH-001: asks name and address together, then the name, then the address, each once', () => {
expect(stayQueries('Hotel Gracery', '1-19-1 Kabukicho, Shinjuku')).toEqual([
'Hotel Gracery 1-19-1 Kabukicho, Shinjuku',
'Hotel Gracery',
'1-19-1 Kabukicho, Shinjuku',
]);
expect(stayQueries(' Hut ', null)).toEqual(['Hut']);
expect(stayQueries('', 'Main 1')).toEqual(['Main 1']);
expect(stayQueries('Inn', 'Inn')).toEqual(['Inn Inn', 'Inn']);
expect(stayQueries('', ' ')).toEqual([]);
});
it('FE-MAP-MATCH-002: a romanized address that finds nothing falls back to the hotel name', async () => {
vi.mocked(mapsApi.search).mockImplementation(async (query: string) =>
query === 'Hotel Gracery'
? ({
places: [{ name: 'Hotel Gracery Shinjuku', address: 'Kabukicho, Tokyo', lat: 35.69, lng: 139.7 }],
} as never)
: ({ places: [] } as never)
);
await expect(findOnMap(stayQueries('Hotel Gracery', '1-19-1 Kabukicho'), 'en')).resolves.toEqual({
lat: 35.69,
lng: 139.7,
label: 'Hotel Gracery Shinjuku, Kabukicho, Tokyo',
address: 'Kabukicho, Tokyo',
});
expect(vi.mocked(mapsApi.search).mock.calls.map(([q]) => q)).toEqual([
'Hotel Gracery 1-19-1 Kabukicho',
'Hotel Gracery',
]);
expect(mapsApi.search).toHaveBeenLastCalledWith('Hotel Gracery', 'en');
});
it('FE-MAP-MATCH-003: a row without coordinates is no match, and without a language the search is asked as before', async () => {
vi.mocked(mapsApi.search).mockResolvedValueOnce({
places: [
{ name: 'Nowhere', lat: null, lng: 2 },
{ name: 'Inn', lat: 1, lng: 2 },
],
} as never);
await expect(findOnMap(['Inn'])).resolves.toEqual({ lat: 1, lng: 2, label: 'Inn' });
expect(mapsApi.search).toHaveBeenCalledWith('Inn');
vi.mocked(mapsApi.search).mockResolvedValueOnce(undefined as never);
await expect(findOnMap(['Gone'])).resolves.toBeNull();
});
it('FE-MAP-MATCH-004: offline there is nothing to ask', async () => {
vi.mocked(isEffectivelyOffline).mockReturnValue(true);
await expect(findOnMap(['Hotel'])).resolves.toBeNull();
expect(mapsApi.search).not.toHaveBeenCalled();
});
});
-47
View File
@@ -1,47 +0,0 @@
import { mapsApi } from '../api/client';
import { isEffectivelyOffline } from '../sync/networkMode';
/** A spot the map search found for a place that so far is only a name and an address. */
export interface MapMatch {
lat: number;
lng: number;
/** What the search found, as the reader sees it: its name, and its address when it has one. */
label: string;
/** The found place's own address, for a stay whose booking named none. */
address?: string;
}
/**
* The ways to ask for a stay, best first: name and address together, then the
* name alone, then the address alone. A booking site's romanized address (an
* Agoda stay in Japan, say) often matches nothing, and asked together with the
* hotel's name it sinks the name too; the name alone usually finds the hotel.
*/
export function stayQueries(name: string, address: string | null | undefined): string[] {
const n = name.trim();
const a = (address ?? '').trim();
const queries = [n && a ? `${n} ${a}` : '', n, a].filter((q) => q.length >= 3);
return [...new Set(queries)];
}
/**
* The first spot the map search knows for one of `queries`, asked in order.
* Online only, on purpose: offline there is no search to ask, and the answer
* is null rather than a guess.
*/
export async function findOnMap(queries: string[], lang?: string): Promise<MapMatch | null> {
if (isEffectivelyOffline()) return null;
for (const query of queries) {
const res = lang ? await mapsApi.search(query, lang) : await mapsApi.search(query);
for (const row of res?.places ?? []) {
const place = row as { lat?: unknown; lng?: unknown; name?: unknown; address?: unknown };
const lat = typeof place.lat === 'number' ? place.lat : NaN;
const lng = typeof place.lng === 'number' ? place.lng : NaN;
if (!Number.isFinite(lat) || !Number.isFinite(lng)) continue;
const parts = [place.name, place.address].filter((v): v is string => typeof v === 'string' && v.trim() !== '');
const address = typeof place.address === 'string' && place.address.trim() ? place.address : undefined;
return { lat, lng, label: parts.join(', ') || query, ...(address ? { address } : {}) };
}
}
return null;
}
-35
View File
@@ -1,35 +0,0 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { offlineDb } from '../db/offlineDb';
import { routeCacheRepo } from './routeCacheRepo';
afterEach(async () => {
vi.restoreAllMocks();
vi.useRealTimers();
await offlineDb.routeCache.clear();
});
const ROUTE = { coordinates: [[48.1, 11.5]], distance: 4200, duration: 600, legs: [] };
describe('road routes kept on the device', () => {
it('FE-ROUTE-CACHE-001: a kept route comes back as it went in, a missing one as null', async () => {
await routeCacheRepo.put('driving:km:11.5,48.1;11.6,48.2', ROUTE);
await expect(routeCacheRepo.get('driving:km:11.5,48.1;11.6,48.2')).resolves.toEqual(ROUTE);
await expect(routeCacheRepo.get('walking:km:11.5,48.1;11.6,48.2')).resolves.toBeNull();
});
it('FE-ROUTE-CACHE-002: a route older than a month is asked again', async () => {
vi.useFakeTimers({ toFake: ['Date'] });
vi.setSystemTime(new Date('2026-09-01T00:00:00Z'));
await routeCacheRepo.put('driving:km:old', ROUTE);
vi.setSystemTime(new Date('2026-10-25T00:00:00Z'));
await expect(routeCacheRepo.get('driving:km:old')).resolves.toBeNull();
});
it('FE-ROUTE-CACHE-003: a database that fails is a miss on read and nothing on write', async () => {
vi.spyOn(offlineDb.routeCache, 'get').mockRejectedValueOnce(new Error('closed'));
await expect(routeCacheRepo.get('driving:km:any')).resolves.toBeNull();
vi.spyOn(offlineDb.routeCache, 'put').mockRejectedValueOnce(new Error('quota'));
await expect(routeCacheRepo.put('driving:km:any', ROUTE)).resolves.toBeUndefined();
});
});
-48
View File
@@ -1,48 +0,0 @@
import { offlineDb } from '../db/offlineDb';
/** Roads change; an answer older than this is asked again. */
const MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;
/** How many routes the device keeps before the oldest give way. */
const MAX_ROWS = 3000;
/** Pruning counts the table, so it runs every so many writes rather than on each one. */
const PRUNE_EVERY = 100;
let writes = 0;
async function prune(): Promise<void> {
const extra = (await offlineDb.routeCache.count()) - MAX_ROWS;
if (extra <= 0) return;
const oldest = await offlineDb.routeCache.orderBy('savedAt').limit(extra).primaryKeys();
await offlineDb.routeCache.bulkDelete(oldest);
}
/**
* Road routes kept on the device, by RouteCalculator's cache key, so a trip that
* shows its whole route opens with its roads instead of asking the router for
* every leg again, one a second, on every visit (#2794). A convenience only:
* anything this store cannot read or write is simply routed again.
*/
export const routeCacheRepo = {
/** The route kept under `key`, unless it is missing or too old. */
async get<T>(key: string): Promise<T | null> {
try {
const row = await offlineDb.routeCache.get(key);
if (!row || Date.now() - row.savedAt > MAX_AGE_MS) return null;
return row.route as T;
} catch {
// A closed or blocked database: the leg is routed again.
return null;
}
},
/** Keeps a route the router just answered. */
async put(key: string, route: unknown): Promise<void> {
try {
await offlineDb.routeCache.put({ key, route, savedAt: Date.now() });
writes += 1;
if (writes % PRUNE_EVERY === 0) await prune();
} catch {
// A full or blocked database: the route still serves this visit from memory.
}
},
};
@@ -56,7 +56,6 @@ const HISTORY: Record<number, StoreSpec> = {
11: { ferrataTiles: '[tripId+tile], tripId, fetchedAt' },
12: { tourStationVisits: '[assignment_id+station_key], trip_id, assignment_id' },
13: { tourDrafts: 'tripId' },
14: { routeCache: 'key, savedAt' },
};
const HISTORY_VERSIONS = Object.keys(HISTORY)
@@ -137,7 +136,6 @@ function rowsAt(version: number): Record<string, Record<string, unknown>> {
ferrataTiles: { tripId: 1, tile: '930:236', fetchedAt: 11, ferratas: [] },
tourStationVisits: { assignment_id: 71, station_key: 'stop-01', status: 'visited', trip_id: 1 },
tourDrafts: { tripId: 1, draft: { payload: '{"version":11}', updated_at: '2026-10-22 09:00:00' } },
routeCache: { key: 'driving:km:11.5,48.1;11.6,48.2', route: { coordinates: [], legs: [] }, savedAt: 13 },
};
const tables = schemaAt(version);
return Object.fromEntries(Object.entries(all).filter(([table]) => table in tables));
@@ -346,24 +344,6 @@ const UPGRADE_CASES: Record<number, UpgradeCase> = {
expect((await db.tourDrafts.get(3))?.draft.payload).toBe('{"name":"C"}');
},
},
14: {
intent: 'adds the road routes kept on the device and keeps the account drafts of the Tours planner',
check: async (db) => {
expect((await db.tourDrafts.get(1))?.draft.payload).toBe('{"version":11}');
await db.table('routeCache').bulkPut([
{ key: 'driving:km:1,2;3,4', route: { legs: [] }, savedAt: 20 },
{ key: 'walking:km:1,2;3,4', route: { legs: [] }, savedAt: 10 },
]);
// One row per key: the same route answered again replaces the old one.
await db.table('routeCache').put({ key: 'driving:km:1,2;3,4', route: { legs: [1] }, savedAt: 30 });
expect(await db.routeCache.count()).toBe(2);
// The oldest come first, which is how the store prunes.
expect(await db.routeCache.orderBy('savedAt').primaryKeys()).toEqual([
'walking:km:1,2;3,4',
'driving:km:1,2;3,4',
]);
},
},
};
describe('offlineDb upgrades', () => {
@@ -7,7 +7,7 @@ import MAssistantHomeScreen from '../../../src/mobile/screens/assistant/MAssista
import { chatOf, useAssistantStore } from '../../../src/store/assistantStore';
import { act, cleanup, fireEvent, render, screen } from '../../helpers/render';
// FE-MOB-ASSIST-HOME-001 to FE-MOB-ASSIST-HOME-006
// FE-MOB-ASSIST-HOME-001 to FE-MOB-ASSIST-HOME-005
//
// The phone's home chat, full screen outside a trip, around the shared chat
// surface, which is replaced here: what is tested is when it shows, its
@@ -141,9 +141,4 @@ describe('MAssistantHomeScreen', () => {
renderAt('/settings');
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
});
it('FE-MOB-ASSIST-HOME-006: brings its own m-root, so the phone tokens resolve outside the mobile shell', () => {
renderAt('/dashboard');
expect(screen.getByRole('dialog', { name: 'Assistant' }).closest('.m-root')).not.toBeNull();
});
});
@@ -359,22 +359,12 @@ describe('MAdminPluginsPanel — Discover', () => {
await waitFor(() => expect(toastMessages()).toContain('Installed'));
});
it('FE-MOB-PLUGP-018: an entry no published version fits installs only after the admin accepts the risk', async () => {
let body: unknown = null;
it('FE-MOB-PLUGP-018: an entry no published version fits gets a dead, explained button', async () => {
await openDiscover([registryEntry({ trek: '>=4.0.0', hostVersion: '3.3.0', compatible: false, latestCompatible: null })]);
server.use(http.post('*/api/admin/plugins/install', async ({ request }) => {
body = await request.json();
return HttpResponse.json({ id: 'trek-gotify', version: '2.0.0', trekRangeBypassed: null });
}));
const btn = await screen.findByRole('button', { name: /^Install$/ });
const btn = await screen.findByRole('button', { name: 'Incompatible' });
expect(btn).toBeDisabled();
expect(btn).toHaveAttribute('title', 'Needs TREK >=4.0.0 — this server runs 3.3.0');
fireEvent.click(btn);
const sheet = await screen.findByRole('dialog', { name: 'Untested on this TREK' });
expect(body).toBeNull();
fireEvent.click(within(sheet).getByRole('button', { name: 'Install anyway' }));
await waitFor(() => expect(body).toEqual({ id: 'trek-gotify', acceptTrekRange: true }));
});
it('FE-MOB-PLUGP-019: when only an older release fits, that version is offered and installed', async () => {
@@ -1816,7 +1806,7 @@ describe('MAdminPluginsPanel — TREK-range bypass (TREK_PLUGINS_IGNORE_TREK_RAN
expect(await screen.findByText('Version checks off')).toBeInTheDocument();
});
it('FE-MOB-PLUGP-BYPASS-002: offers Install and asks before installing', async () => {
it('FE-MOB-PLUGP-BYPASS-002: offers "Install anyway" and asks before installing', async () => {
let body: unknown = null;
mockPanel([], [incompatibleEntry()], { ignoreTrekRange: true });
server.use(http.post('*/api/admin/plugins/install', async ({ request }) => {
@@ -1826,7 +1816,7 @@ describe('MAdminPluginsPanel — TREK-range bypass (TREK_PLUGINS_IGNORE_TREK_RAN
render(<MAdminPluginsPanel />);
fireEvent.click(await screen.findByRole('tab', { name: /Discover/ }));
const btn = await screen.findByRole('button', { name: /^Install$/ });
const btn = await screen.findByRole('button', { name: 'Install anyway' });
expect(btn).toBeEnabled();
fireEvent.click(btn);
@@ -1844,7 +1834,7 @@ describe('MAdminPluginsPanel — TREK-range bypass (TREK_PLUGINS_IGNORE_TREK_RAN
server.use(http.post('*/api/admin/plugins/install', () => { posted = true; return HttpResponse.json({ id: 'trek-gotify', version: '2.0.0', trekRangeBypassed: null }); }));
render(<MAdminPluginsPanel />);
fireEvent.click(await screen.findByRole('tab', { name: /Discover/ }));
fireEvent.click(await screen.findByRole('button', { name: /^Install$/ }));
fireEvent.click(await screen.findByRole('button', { name: 'Install anyway' }));
const sheet = await screen.findByRole('dialog', { name: 'Outside its supported TREK versions' });
fireEvent.click(within(sheet).getByRole('button', { name: 'Cancel' }));
-4
View File
@@ -11,10 +11,6 @@ services:
- CHOWN
- SETUID
- SETGID
# dumb-init runs as root and forwards SIGTERM to node, which runs as the
# node user; signalling another user's process needs KILL. Without it
# docker stop ends in SIGKILL and the graceful shutdown never runs.
- KILL
tmpfs:
- /tmp:noexec,nosuid,size=128m
ports:
+140 -268
View File
@@ -1,12 +1,12 @@
{
"name": "@trek/root",
"version": "5.0.0",
"version": "4.3.4",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@trek/root",
"version": "5.0.0",
"version": "4.3.4",
"workspaces": [
"client",
"server",
@@ -29,7 +29,7 @@
},
"client": {
"name": "@trek/client",
"version": "5.0.0",
"version": "4.3.4",
"dependencies": {
"@assistant-ui/react": "0.15.25",
"@fontsource/abril-fatface": "^5.3.0",
@@ -118,7 +118,7 @@
"eslint-plugin-react-hooks": "^7.1.1",
"eslint-plugin-react-refresh": "^0.5.7",
"fake-indexeddb": "^6.2.5",
"jsdom": "^29.1.1",
"jsdom": "^30.1.3",
"msw": "^2.15.0",
"postcss": "^8.5.28",
"prettier": "^3.9.8",
@@ -205,56 +205,54 @@
}
},
"node_modules/@asamuzakjp/css-color": {
"version": "5.1.11",
"resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-5.1.11.tgz",
"integrity": "sha512-KVw6qIiCTUQhByfTd78h2yD1/00waTmm9uy/R7Ck/ctUyAPj+AEDLkQIdJW0T8+qGgj3j5bpNKK7Q3G+LedJWg==",
"dev": true,
"version": "7.1.7",
"resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-7.1.7.tgz",
"integrity": "sha512-Q7ioeear07HwixdIitIn9KS1LZi97CEDFCSjPNm9v+y8KNbsu9q4Lrd4zUQW4faED+E7qxvfeVnbNRW46wFKuw==",
"license": "MIT",
"dependencies": {
"@asamuzakjp/generational-cache": "^1.0.1",
"@csstools/css-calc": "^3.2.0",
"@csstools/css-color-parser": "^4.1.0",
"@csstools/css-parser-algorithms": "^4.0.0",
"@csstools/css-tokenizer": "^4.0.0"
"@csstools/css-calc": "^3.4.3",
"@csstools/css-color-parser": "^4.2.6",
"@csstools/css-parser-algorithms": "^4.0.2",
"@csstools/css-tokenizer": "^4.0.2",
"lru-cache": "^11.5.3"
},
"engines": {
"node": "^20.19.0 || ^22.12.0 || >=24.0.0"
"node": "^22.22.2 || ^24.15.0 || >=26.0.0"
}
},
"node_modules/@asamuzakjp/css-color/node_modules/lru-cache": {
"version": "11.5.3",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz",
"integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==",
"license": "BlueOak-1.0.0",
"engines": {
"node": "20 || >=22"
}
},
"node_modules/@asamuzakjp/dom-selector": {
"version": "7.1.1",
"resolved": "https://registry.npmjs.org/@asamuzakjp/dom-selector/-/dom-selector-7.1.1.tgz",
"integrity": "sha512-67RZDnYRc8H/8MLDgQCDE//zoqVFwajkepHZgmXrbwybzXOEwOWGPYGmALYl9J2DOLfFPPs6kKCqmbzV895hTQ==",
"dev": true,
"version": "10.0.4",
"resolved": "https://registry.npmjs.org/@asamuzakjp/dom-selector/-/dom-selector-10.0.4.tgz",
"integrity": "sha512-A6f1nKy99I6tyoK82U6kBHvQQZmdHmTmPzJYPY/0eaOW0r8/qPmEOwjGHs+hL/vCgOwQTupu4LT1XtXNUuDruA==",
"license": "MIT",
"dependencies": {
"@asamuzakjp/generational-cache": "^1.0.1",
"@asamuzakjp/nwsapi": "^2.3.9",
"bidi-js": "^1.0.3",
"bidi-js": "^1.1.0",
"css-tree": "^3.2.1",
"is-potential-custom-element-name": "^1.0.1"
"is-potential-custom-element-name": "^1.0.1",
"lru-cache": "^11.5.3"
},
"engines": {
"node": "^20.19.0 || ^22.12.0 || >=24.0.0"
"node": "^22.22.2 || ^24.15.0 || >=26.0.0"
}
},
"node_modules/@asamuzakjp/generational-cache": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/@asamuzakjp/generational-cache/-/generational-cache-1.0.1.tgz",
"integrity": "sha512-wajfB8KqzMCN2KGNFdLkReeHncd0AslUSrvHVvvYWuU8ghncRJoA50kT3zP9MVL0+9g4/67H+cdvBskj9THPzg==",
"dev": true,
"license": "MIT",
"node_modules/@asamuzakjp/dom-selector/node_modules/lru-cache": {
"version": "11.5.3",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz",
"integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==",
"license": "BlueOak-1.0.0",
"engines": {
"node": "^20.19.0 || ^22.12.0 || >=24.0.0"
"node": "20 || >=22"
}
},
"node_modules/@asamuzakjp/nwsapi": {
"version": "2.3.9",
"resolved": "https://registry.npmjs.org/@asamuzakjp/nwsapi/-/nwsapi-2.3.9.tgz",
"integrity": "sha512-n8GuYSrI9bF7FFZ/SjhwevlHc8xaVlb/7HmHelnc/PZXBD2ZR49NnN9sMMuDdEGPeeRQ5d0hqlSlEpgCX3Wl0Q==",
"dev": true,
"license": "MIT"
},
"node_modules/@assistant-ui/core": {
"version": "0.3.30",
"resolved": "https://registry.npmjs.org/@assistant-ui/core/-/core-0.3.30.tgz",
@@ -2450,9 +2448,9 @@
}
},
"node_modules/@csstools/color-helpers": {
"version": "6.1.1",
"resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-6.1.1.tgz",
"integrity": "sha512-gLNsunvwf3mCi5u5o46/Z/JcJMnhbHSaZ69rkgPzNM3J4s8hWwpPUQB6/tt0EDFyCiWzxANlx+2LJwpYj4zS1w==",
"version": "6.1.2",
"resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-6.1.2.tgz",
"integrity": "sha512-grhRy3OKmniaAEKXMjua5z/EODX0MSqBGjunw8+j/3HQjOnahs2AGhvEOIYVUWcU6ScApbhLhVrQTX8XqrMrow==",
"funding": [
{
"type": "github",
@@ -2469,9 +2467,9 @@
}
},
"node_modules/@csstools/css-calc": {
"version": "3.4.0",
"resolved": "https://registry.npmjs.org/@csstools/css-calc/-/css-calc-3.4.0.tgz",
"integrity": "sha512-XQKj5B7QiZcHiegCOCAzcAOJdhGgWOHbbu62h5e5mkHnn8lWcfiJhllkqWmxu5zWR9jucPHuo1iTB56P033hcg==",
"version": "3.4.3",
"resolved": "https://registry.npmjs.org/@csstools/css-calc/-/css-calc-3.4.3.tgz",
"integrity": "sha512-iex20d8CHVkyvg6B7UKV7uHnI2Bqo9g+EFfT9E0y+GvTvhZ/DwONJ+9aKb1dlqm0ZiGsL5RXjp0fCoJYnkeDjA==",
"funding": [
{
"type": "github",
@@ -2487,14 +2485,14 @@
"node": ">=20.19.0"
},
"peerDependencies": {
"@csstools/css-parser-algorithms": "^4.0.0",
"@csstools/css-tokenizer": "^4.0.0"
"@csstools/css-parser-algorithms": "^4.0.2",
"@csstools/css-tokenizer": "^4.0.2"
}
},
"node_modules/@csstools/css-color-parser": {
"version": "4.2.3",
"resolved": "https://registry.npmjs.org/@csstools/css-color-parser/-/css-color-parser-4.2.3.tgz",
"integrity": "sha512-y4LpL+lmpuyKDiEFq2PnZUVFdAjsoB/qQJod79yLNokXyW7jewi+/WJ69EfItj8A2unWtxXnGjw6LYXgXu5ZjA==",
"version": "4.2.6",
"resolved": "https://registry.npmjs.org/@csstools/css-color-parser/-/css-color-parser-4.2.6.tgz",
"integrity": "sha512-iiPQ3iRWwnJkeEn6RIu6SJPr7hYrLz6XZ9s/QZl+2/LI5KQVjpl2fdmDSZKuD4xP6GMmMPgHFFXg6k1Wkz0Trg==",
"funding": [
{
"type": "github",
@@ -2507,21 +2505,21 @@
],
"license": "MIT",
"dependencies": {
"@csstools/color-helpers": "^6.1.1",
"@csstools/css-calc": "^3.4.0"
"@csstools/color-helpers": "^6.1.2",
"@csstools/css-calc": "^3.4.3"
},
"engines": {
"node": ">=20.19.0"
},
"peerDependencies": {
"@csstools/css-parser-algorithms": "^4.0.0",
"@csstools/css-tokenizer": "^4.0.0"
"@csstools/css-parser-algorithms": "^4.0.2",
"@csstools/css-tokenizer": "^4.0.2"
}
},
"node_modules/@csstools/css-parser-algorithms": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/@csstools/css-parser-algorithms/-/css-parser-algorithms-4.0.0.tgz",
"integrity": "sha512-+B87qS7fIG3L5h3qwJ/IFbjoVoOe/bpOdh9hAjXbvx0o8ImEmUsGXN0inFOnk2ChCFgqkkGFQ+TpM5rbhkKe4w==",
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/@csstools/css-parser-algorithms/-/css-parser-algorithms-4.0.2.tgz",
"integrity": "sha512-40cSKyMvK+tq4qz6Awrlye2WGuOKt3FwPgtGg6KTfbHOWNw+Rk1rzbAtZnZ6IBhsY491HLRnDXwoyBAijmmILA==",
"funding": [
{
"type": "github",
@@ -2537,13 +2535,13 @@
"node": ">=20.19.0"
},
"peerDependencies": {
"@csstools/css-tokenizer": "^4.0.0"
"@csstools/css-tokenizer": "^4.0.2"
}
},
"node_modules/@csstools/css-syntax-patches-for-csstree": {
"version": "1.1.14",
"resolved": "https://registry.npmjs.org/@csstools/css-syntax-patches-for-csstree/-/css-syntax-patches-for-csstree-1.1.14.tgz",
"integrity": "sha512-HpbVXyrofRXpHpgkNIjU/3EWR4WJvOkO3emNK/L6X/mTJU7bGUI3AkkpoTNXznQLp0KRjLHELTGeKI5dIkI9JQ==",
"version": "1.1.15",
"resolved": "https://registry.npmjs.org/@csstools/css-syntax-patches-for-csstree/-/css-syntax-patches-for-csstree-1.1.15.tgz",
"integrity": "sha512-J0u7HkVl2nzSlhsiTOp4AmwcUQ3D+mGEEKfBy/7To5/y7F2OHwyLrXfrhR0SMgr4p5Lo+eaMVSeai24zUcBIxA==",
"funding": [
{
"type": "github",
@@ -2565,9 +2563,9 @@
}
},
"node_modules/@csstools/css-tokenizer": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/@csstools/css-tokenizer/-/css-tokenizer-4.0.0.tgz",
"integrity": "sha512-QxULHAm7cNu72w97JUNCBFODFaXpbDg+dP8b/oWFAZ2MTRppA3U00Y2L1HqaS4J6yBqxwa/Y3nMBaxVKbB/NsA==",
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/@csstools/css-tokenizer/-/css-tokenizer-4.0.2.tgz",
"integrity": "sha512-OoKoR0f76dCY666JlcbhmVTs2drYj1GUXZTYTcbUgJjh9Nv41aFfZ21bPQTERm5+L5cBDo466NltB2lplS5GBw==",
"funding": [
{
"type": "github",
@@ -3338,9 +3336,9 @@
}
},
"node_modules/@exodus/bytes": {
"version": "1.15.1",
"resolved": "https://registry.npmjs.org/@exodus/bytes/-/bytes-1.15.1.tgz",
"integrity": "sha512-S6mL0yNB/Abt9Ei4tq8gDhcczc4S3+vQ4ra7vxnAf+YHC02srtqxKKZghx2Dq6p0e66THKwR6r8N6P95wEty7Q==",
"version": "1.16.0",
"resolved": "https://registry.npmjs.org/@exodus/bytes/-/bytes-1.16.0.tgz",
"integrity": "sha512-IcpW84uEn3N7ETtNZMlxKhfl6Pec8rUNGOTBtWbK1FKhJxIFAptZyVrvVRVBimAJxJCgc3PxepxkdWWG4DVzfA==",
"license": "MIT",
"engines": {
"node": "^20.19.0 || ^22.12.0 || >=24.0.0"
@@ -9370,8 +9368,7 @@
"optional": true,
"os": [
"android"
],
"peer": true
]
},
"node_modules/@rollup/rollup-android-arm64": {
"version": "4.62.0",
@@ -9385,8 +9382,7 @@
"optional": true,
"os": [
"android"
],
"peer": true
]
},
"node_modules/@rollup/rollup-darwin-arm64": {
"version": "4.62.0",
@@ -9400,8 +9396,7 @@
"optional": true,
"os": [
"darwin"
],
"peer": true
]
},
"node_modules/@rollup/rollup-darwin-x64": {
"version": "4.62.0",
@@ -9415,8 +9410,7 @@
"optional": true,
"os": [
"darwin"
],
"peer": true
]
},
"node_modules/@rollup/rollup-freebsd-arm64": {
"version": "4.62.0",
@@ -9430,8 +9424,7 @@
"optional": true,
"os": [
"freebsd"
],
"peer": true
]
},
"node_modules/@rollup/rollup-freebsd-x64": {
"version": "4.62.0",
@@ -9445,8 +9438,7 @@
"optional": true,
"os": [
"freebsd"
],
"peer": true
]
},
"node_modules/@rollup/rollup-linux-arm-gnueabihf": {
"version": "4.62.0",
@@ -9460,8 +9452,7 @@
"optional": true,
"os": [
"linux"
],
"peer": true
]
},
"node_modules/@rollup/rollup-linux-arm-musleabihf": {
"version": "4.62.0",
@@ -9475,8 +9466,7 @@
"optional": true,
"os": [
"linux"
],
"peer": true
]
},
"node_modules/@rollup/rollup-linux-arm64-gnu": {
"version": "4.62.0",
@@ -9490,8 +9480,7 @@
"optional": true,
"os": [
"linux"
],
"peer": true
]
},
"node_modules/@rollup/rollup-linux-arm64-musl": {
"version": "4.62.0",
@@ -9518,8 +9507,7 @@
"optional": true,
"os": [
"linux"
],
"peer": true
]
},
"node_modules/@rollup/rollup-linux-loong64-musl": {
"version": "4.62.0",
@@ -9533,8 +9521,7 @@
"optional": true,
"os": [
"linux"
],
"peer": true
]
},
"node_modules/@rollup/rollup-linux-ppc64-gnu": {
"version": "4.62.0",
@@ -9548,8 +9535,7 @@
"optional": true,
"os": [
"linux"
],
"peer": true
]
},
"node_modules/@rollup/rollup-linux-ppc64-musl": {
"version": "4.62.0",
@@ -9563,8 +9549,7 @@
"optional": true,
"os": [
"linux"
],
"peer": true
]
},
"node_modules/@rollup/rollup-linux-riscv64-gnu": {
"version": "4.62.0",
@@ -9578,8 +9563,7 @@
"optional": true,
"os": [
"linux"
],
"peer": true
]
},
"node_modules/@rollup/rollup-linux-riscv64-musl": {
"version": "4.62.0",
@@ -9593,8 +9577,7 @@
"optional": true,
"os": [
"linux"
],
"peer": true
]
},
"node_modules/@rollup/rollup-linux-s390x-gnu": {
"version": "4.62.0",
@@ -9608,8 +9591,7 @@
"optional": true,
"os": [
"linux"
],
"peer": true
]
},
"node_modules/@rollup/rollup-linux-x64-gnu": {
"version": "4.62.0",
@@ -9623,8 +9605,7 @@
"optional": true,
"os": [
"linux"
],
"peer": true
]
},
"node_modules/@rollup/rollup-linux-x64-musl": {
"version": "4.62.0",
@@ -9651,8 +9632,7 @@
"optional": true,
"os": [
"openbsd"
],
"peer": true
]
},
"node_modules/@rollup/rollup-openharmony-arm64": {
"version": "4.62.0",
@@ -9666,8 +9646,7 @@
"optional": true,
"os": [
"openharmony"
],
"peer": true
]
},
"node_modules/@rollup/rollup-win32-arm64-msvc": {
"version": "4.62.0",
@@ -9681,8 +9660,7 @@
"optional": true,
"os": [
"win32"
],
"peer": true
]
},
"node_modules/@rollup/rollup-win32-ia32-msvc": {
"version": "4.62.0",
@@ -9696,8 +9674,7 @@
"optional": true,
"os": [
"win32"
],
"peer": true
]
},
"node_modules/@rollup/rollup-win32-x64-gnu": {
"version": "4.62.0",
@@ -9711,8 +9688,7 @@
"optional": true,
"os": [
"win32"
],
"peer": true
]
},
"node_modules/@rollup/rollup-win32-x64-msvc": {
"version": "4.62.0",
@@ -9726,8 +9702,7 @@
"optional": true,
"os": [
"win32"
],
"peer": true
]
},
"node_modules/@scarf/scarf": {
"version": "1.4.0",
@@ -13151,16 +13126,16 @@
"license": "MIT"
},
"node_modules/data-urls": {
"version": "7.0.0",
"resolved": "https://registry.npmjs.org/data-urls/-/data-urls-7.0.0.tgz",
"integrity": "sha512-23XHcCF+coGYevirZceTVD7NdJOqVn+49IHyxgszm+JIiHLoB2TkmPtsYkNWT1pvRSGkc35L6NHs0yHkN2SumA==",
"version": "8.0.0",
"resolved": "https://registry.npmjs.org/data-urls/-/data-urls-8.0.0.tgz",
"integrity": "sha512-JQUCCK+/CAGbGGx618PlFZMXH81Jtj7t73CHv9dd/zVWvxgGT2zLFRjnKb+Ng46GIwcy+f7f88qd4duqllK+WQ==",
"license": "MIT",
"dependencies": {
"whatwg-mimetype": "^5.0.0",
"whatwg-url": "^16.0.0"
"whatwg-url": "^17.1.2"
},
"engines": {
"node": "^20.19.0 || ^22.12.0 || >=24.0.0"
"node": "^22.14.0 || >=24.0.0"
}
},
"node_modules/data-view-buffer": {
@@ -15427,15 +15402,15 @@
"license": "MIT"
},
"node_modules/html-encoding-sniffer": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-6.0.0.tgz",
"integrity": "sha512-CV9TW3Y3f8/wT0BRFc1/KAVQ3TUHiXmaAb6VW9vtiMFf7SLoMd1PdAc4W3KFOFETBJUb90KatHqlsZMWV+R9Gg==",
"version": "7.0.0",
"resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-7.0.0.tgz",
"integrity": "sha512-UikN5yr7xsCDAq87Or5or0PAlD3HJJOKVzM05az588WnpDJ4Ux7a2A53Qi6gofGg2/EtvF/H4hCi/TXfCW4Y6w==",
"license": "MIT",
"dependencies": {
"@exodus/bytes": "^1.6.0"
"@exodus/bytes": "^1.15.1"
},
"engines": {
"node": "^20.19.0 || ^22.12.0 || >=24.0.0"
"node": "^22.13.0 || >=24.0.0"
}
},
"node_modules/html-escaper": {
@@ -16311,108 +16286,6 @@
"node": "^22.22.2 || ^24.15.0 || >=26.0.0"
}
},
"node_modules/isomorphic-dompurify/node_modules/@asamuzakjp/css-color": {
"version": "7.0.0",
"resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-7.0.0.tgz",
"integrity": "sha512-IxddtGnnoidVSO6O/aiTueptbTThHvi2qGHu9/AWuD1J7i86Ox+jl+Y5SXcDH1RixzQlP2cjH/PjnlImZiAurQ==",
"license": "MIT",
"dependencies": {
"@csstools/css-calc": "^3.3.0",
"@csstools/css-color-parser": "^4.2.0",
"@csstools/css-parser-algorithms": "^4.0.0",
"@csstools/css-tokenizer": "^4.0.0",
"lru-cache": "^11.5.2"
},
"engines": {
"node": "^22.22.2 || ^24.15.0 || >=26.0.0"
}
},
"node_modules/isomorphic-dompurify/node_modules/@asamuzakjp/dom-selector": {
"version": "9.2.1",
"resolved": "https://registry.npmjs.org/@asamuzakjp/dom-selector/-/dom-selector-9.2.1.tgz",
"integrity": "sha512-NT4s3yZLjovPpliRpTvdsdzyPjqRqiCZj9MxnarBihbaY5MbAG7DWAJcrLlhmC7xKTNCXsTELcqB8YsqpLnUFQ==",
"license": "MIT",
"dependencies": {
"bidi-js": "^1.1.0",
"css-tree": "^3.2.1",
"is-potential-custom-element-name": "^1.0.1",
"lru-cache": "^11.5.3"
},
"engines": {
"node": "^22.22.2 || ^24.15.0 || >=26.0.0"
}
},
"node_modules/isomorphic-dompurify/node_modules/jsdom": {
"version": "30.1.0",
"resolved": "https://registry.npmjs.org/jsdom/-/jsdom-30.1.0.tgz",
"integrity": "sha512-h/Q+H+KmlGf49ITw3TrykSVbg04S75S2O7ZtJc9gMGOWBrQRZmx5AJIKLtJ01e6Kszl+/tpFthCVqxNifxhoqg==",
"license": "MIT",
"dependencies": {
"@asamuzakjp/css-color": "^7.0.0",
"@asamuzakjp/dom-selector": "^9.1.2",
"@bramus/specificity": "^2.4.2",
"@csstools/css-syntax-patches-for-csstree": "^1.1.13",
"@exodus/bytes": "^1.15.1",
"css-tree": "^3.2.1",
"data-urls": "^7.0.0",
"decimal.js": "^10.6.0",
"html-encoding-sniffer": "^6.0.0",
"is-potential-custom-element-name": "^1.0.1",
"lru-cache": "^11.5.2",
"parse5": "^8.0.1",
"saxes": "^6.0.0",
"tough-cookie": "^6.0.2",
"undici": "^8.10.2",
"w3c-xmlserializer": "^5.0.0",
"webidl-conversions": "^8.0.1",
"whatwg-mimetype": "^5.0.0",
"whatwg-url": "^17.1.1",
"xml-name-validator": "^5.0.0"
},
"engines": {
"node": "^22.22.2 || ^24.15.0 || >=26.0.0"
},
"peerDependencies": {
"canvas": "^3.2.3"
},
"peerDependenciesMeta": {
"canvas": {
"optional": true
}
}
},
"node_modules/isomorphic-dompurify/node_modules/lru-cache": {
"version": "11.5.3",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz",
"integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==",
"license": "BlueOak-1.0.0",
"engines": {
"node": "20 || >=22"
}
},
"node_modules/isomorphic-dompurify/node_modules/undici": {
"version": "8.12.3",
"resolved": "https://registry.npmjs.org/undici/-/undici-8.12.3.tgz",
"integrity": "sha512-+fdndUTwBP86cVjihTp21hZHo7d6oj1c/47XPA3lL8mM0XHs+C4EkcjmgRsFnFk2f/UONGDy9ItBItmXsLOQHw==",
"license": "MIT",
"engines": {
"node": ">=22.19.0"
}
},
"node_modules/isomorphic-dompurify/node_modules/whatwg-url": {
"version": "17.1.1",
"resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-17.1.1.tgz",
"integrity": "sha512-ohjk1mdUebJVadRt3bAhQhx8lSnISq+GDttK79LFl8EHQkAPvzwctoasC4hs8tBt6kLAncBWWyq1N52qEfKvDw==",
"license": "MIT",
"dependencies": {
"@exodus/bytes": "^1.15.1",
"tr46": "^6.0.0",
"webidl-conversions": "^8.0.1"
},
"engines": {
"node": "^22.14.0 || >=24.0.0"
}
},
"node_modules/istanbul-lib-coverage": {
"version": "3.2.2",
"resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-3.2.2.tgz",
@@ -16608,39 +16481,37 @@
}
},
"node_modules/jsdom": {
"version": "29.1.1",
"resolved": "https://registry.npmjs.org/jsdom/-/jsdom-29.1.1.tgz",
"integrity": "sha512-ECi4Fi2f7BdJtUKTflYRTiaMxIB0O6zfR1fX0GXpUrf6flp8QIYn1UT20YQqdSOfk2dfkCwS8LAFoJDEppNK5Q==",
"dev": true,
"version": "30.1.3",
"resolved": "https://registry.npmjs.org/jsdom/-/jsdom-30.1.3.tgz",
"integrity": "sha512-hQMUPvRgN7KxsfIytDQji7bimuJeRQa6Qo5+iuiZQk5CafeRxLIA10/cG5YCBFNpD9RO3oqIiN4CO1Y44kxqXg==",
"license": "MIT",
"dependencies": {
"@asamuzakjp/css-color": "^5.1.11",
"@asamuzakjp/dom-selector": "^7.1.1",
"@asamuzakjp/css-color": "^7.1.3",
"@asamuzakjp/dom-selector": "^10.0.3",
"@bramus/specificity": "^2.4.2",
"@csstools/css-syntax-patches-for-csstree": "^1.1.3",
"@exodus/bytes": "^1.15.0",
"@csstools/css-syntax-patches-for-csstree": "^1.1.15",
"@exodus/bytes": "^1.16.0",
"css-tree": "^3.2.1",
"data-urls": "^7.0.0",
"data-urls": "^8.0.0",
"decimal.js": "^10.6.0",
"html-encoding-sniffer": "^6.0.0",
"html-encoding-sniffer": "^7.0.0",
"is-potential-custom-element-name": "^1.0.1",
"lru-cache": "^11.3.5",
"lru-cache": "^11.5.3",
"parse5": "^8.0.1",
"saxes": "^6.0.0",
"symbol-tree": "^3.2.4",
"tough-cookie": "^6.0.1",
"undici": "^7.25.0",
"w3c-xmlserializer": "^5.0.0",
"tough-cookie": "^6.0.2",
"undici": "^8.12.1",
"w3c-xmlserializer": "^6.0.0",
"webidl-conversions": "^8.0.1",
"whatwg-mimetype": "^5.0.0",
"whatwg-url": "^16.0.1",
"whatwg-url": "^17.2.0",
"xml-name-validator": "^5.0.0"
},
"engines": {
"node": "^20.19.0 || ^22.13.0 || >=24.0.0"
"node": "^22.22.2 || ^24.15.0 || >=26.0.0"
},
"peerDependencies": {
"canvas": "^3.0.0"
"canvas": "^3.2.3"
},
"peerDependenciesMeta": {
"canvas": {
@@ -16649,15 +16520,23 @@
}
},
"node_modules/jsdom/node_modules/lru-cache": {
"version": "11.5.1",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.1.tgz",
"integrity": "sha512-RPimw/7aMdv2oqRrxKwvZXcPfwBrn/JZ2xYcY9Hus/6LaS3VOAKVWKWgNLCFSiOm1ESXinjsDlidVU7JlnCN2A==",
"dev": true,
"version": "11.5.3",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz",
"integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==",
"license": "BlueOak-1.0.0",
"engines": {
"node": "20 || >=22"
}
},
"node_modules/jsdom/node_modules/undici": {
"version": "8.12.3",
"resolved": "https://registry.npmjs.org/undici/-/undici-8.12.3.tgz",
"integrity": "sha512-+fdndUTwBP86cVjihTp21hZHo7d6oj1c/47XPA3lL8mM0XHs+C4EkcjmgRsFnFk2f/UONGDy9ItBItmXsLOQHw==",
"license": "MIT",
"engines": {
"node": ">=22.19.0"
}
},
"node_modules/jsesc": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz",
@@ -22412,13 +22291,6 @@
"@scarf/scarf": "=1.4.0"
}
},
"node_modules/symbol-tree": {
"version": "3.2.4",
"resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz",
"integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==",
"dev": true,
"license": "MIT"
},
"node_modules/tagged-tag": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/tagged-tag/-/tagged-tag-1.0.0.tgz",
@@ -22757,15 +22629,15 @@
}
},
"node_modules/tr46": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/tr46/-/tr46-6.0.0.tgz",
"integrity": "sha512-bLVMLPtstlZ4iMQHpFHTR7GAGj2jxi8Dg0s2h2MafAE4uSWF98FC/3MomU51iQAMf8/qDUbKWf5GxuvvVcXEhw==",
"version": "7.0.0",
"resolved": "https://registry.npmjs.org/tr46/-/tr46-7.0.0.tgz",
"integrity": "sha512-BcDSDW+SIGWVOns1Zm6Yg91q9AEj7eaID0QDY9oIqJD1A8dscNwMcl9Sms2DeuWCNov1X0/oXanHGYQBSLwZsg==",
"license": "MIT",
"dependencies": {
"punycode": "^2.3.1"
},
"engines": {
"node": ">=20"
"node": "^22.14.0 || >=24.0.0"
}
},
"node_modules/tree-kill": {
@@ -24160,15 +24032,15 @@
}
},
"node_modules/w3c-xmlserializer": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz",
"integrity": "sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==",
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-6.0.0.tgz",
"integrity": "sha512-4Nsy8K5Tr6SPDH9jhKJOHf7ChDrc1zufZTVSF7x72hwuEXBqxqk9G6cK+K2NRUtB3iELRJqjXb4JPDMBjMTl2Q==",
"license": "MIT",
"dependencies": {
"xml-name-validator": "^5.0.0"
},
"engines": {
"node": ">=18"
"node": "^22.22.2 || ^24.15.0 || >=26.0.0"
}
},
"node_modules/walk-up-path": {
@@ -24207,17 +24079,17 @@
}
},
"node_modules/whatwg-url": {
"version": "16.0.1",
"resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-16.0.1.tgz",
"integrity": "sha512-1to4zXBxmXHV3IiSSEInrreIlu02vUOvrhxJJH5vcxYTBDAx51cqZiKdyTxlecdKNSjj8EcxGBxNf6Vg+945gw==",
"version": "17.3.0",
"resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-17.3.0.tgz",
"integrity": "sha512-KwOAJrpf+GTgBvcBQJcP38sMF0DsQKdwtG+TxM2pW44P6E5k0hDbWrDmyuJDIF0Uef0aQq0ZoJs+5oI+k8ddhg==",
"license": "MIT",
"dependencies": {
"@exodus/bytes": "^1.11.0",
"tr46": "^6.0.0",
"@exodus/bytes": "^1.16.0",
"tr46": "^7.0.0",
"webidl-conversions": "^8.0.1"
},
"engines": {
"node": "^20.19.0 || ^22.12.0 || >=24.0.0"
"node": "^22.14.0 || >=24.0.0"
}
},
"node_modules/which": {
@@ -25005,7 +24877,7 @@
},
"server": {
"name": "@trek/server",
"version": "5.0.0",
"version": "4.3.4",
"dependencies": {
"@aws-lite/client": "^0.23.7",
"@aws-lite/s3": "^0.2.7",
@@ -25384,7 +25256,7 @@
},
"shared": {
"name": "@trek/shared",
"version": "5.0.0",
"version": "4.3.4",
"dependencies": {
"isomorphic-dompurify": "^3.23.0",
"zod": "^4.6.7"
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "@trek/root",
"private": true,
"version": "5.0.0",
"version": "4.3.4",
"engines": {
"node": "^22.22.2 || ^24.15.0 || >=26.0.0"
},
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@trek/server",
"version": "5.0.0",
"version": "4.3.4",
"engines": {
"node": "^22.22.2 || ^24.15.0 || >=26.0.0"
},
+1 -1
View File
@@ -13,7 +13,7 @@
"src/nest/doc-sync/providers/synology-drive.client.ts": 1160,
"src/nest/journey/journey-domain.service.ts": 1659,
"src/nest/places/places.service.ts": 1592,
"src/nest/plugins/plugin-runtime.service.ts": 1460,
"src/nest/plugins/plugin-runtime.service.ts": 1463,
"src/nest/plugins/runtime/plugin-sdk.ts": 1093,
"src/nest/reservations/reservations.service.ts": 1237,
"src/nest/trips/trips.service.ts": 1006,
-4
View File
@@ -35,8 +35,6 @@ export class Plugins {
update_block_version?: string | null;
trek_range?: string | null;
update_hold: number & Opt = 0;
trek_range_accepted_version?: string | null;
trek_range_accepted_host?: string | null;
}
export const PluginsSchema = defineEntity({
@@ -74,7 +72,5 @@ export const PluginsSchema = defineEntity({
update_block_version: p.text().nullable(),
trek_range: p.text().nullable(),
update_hold: p.integer().default(0),
trek_range_accepted_version: p.text().nullable(),
trek_range_accepted_host: p.text().nullable(),
},
});
+1 -1
View File
@@ -370,7 +370,7 @@ const aiProviderStateSchema = z.discriminatedUnion('adapter', [
adapter: z.literal('openai-responses'),
items: z.array(z.record(z.string(), z.unknown())),
}),
// Anthropic's content blocks of an answer that searched the web or thought, replayed as they came.
// Anthropic's content blocks of an answer that searched the web, replayed with their search results.
z.object({
adapter: z.literal('anthropic-messages'),
blocks: z.array(z.record(z.string(), z.unknown())),
-2
View File
@@ -34,6 +34,4 @@ export interface PluginsTable {
update_block_version: InsertOptional<string | null>;
trek_range: InsertOptional<string | null>;
update_hold: InsertOptional<number>;
trek_range_accepted_version: InsertOptional<string | null>;
trek_range_accepted_host: InsertOptional<string | null>;
}
@@ -1,18 +0,0 @@
import { Migration } from '@mikro-orm/migrations';
/**
* An admin can run one plugin outside the TREK versions its author declared,
* instead of switching the check off for every plugin through
* TREK_PLUGINS_IGNORE_TREK_RANGE. The consent belongs to what the admin was
* shown: `trek_range_accepted_version` is the plugin version they accepted and
* `trek_range_accepted_host` the TREK version it ran on then. An update of the
* plugin or a new TREK major asks again.
*/
export class Migration20200101046310_an_admin_can_run_a_plugin_outside_its_trek_range extends Migration {
override name = 'Migration20200101046310_an_admin_can_run_a_plugin_outside_its_trek_range';
override up(): void {
this.addSql('ALTER TABLE plugins ADD COLUMN trek_range_accepted_version TEXT');
this.addSql('ALTER TABLE plugins ADD COLUMN trek_range_accepted_host TEXT');
}
}
@@ -26,16 +26,13 @@ export interface PluginIdPermissionRow {
permissions: string | null;
}
/** PR17 — the one-row activation gate `assertActivatable` reads: grants, dependencies, the TREK range and an admin's consent to run outside it. */
/** PR17 — `SELECT permissions, granted_permissions, dependencies, trek_range, api_version FROM plugins WHERE id = ?` (`assertActivatable`'s one-row activation gate). */
export interface PluginActivationGateRow {
permissions: string;
granted_permissions: string;
dependencies: string | null;
trek_range: string | null;
api_version: number | null;
version: string | null;
trek_range_accepted_version: string | null;
trek_range_accepted_host: string | null;
}
/** PR18 — `SELECT permissions, config FROM plugins WHERE id = ?` (`spawnActivated`). */
@@ -92,8 +89,6 @@ export interface PluginAdminRow {
dependencies: string | null;
operator_egress: number;
trek_range: string | null;
trek_range_accepted_version: string | null;
trek_range_accepted_host: string | null;
author_pubkey: string | null;
update_block_code: string | null;
update_block_detail: string | null;
@@ -149,18 +144,7 @@ export class PluginsRepository extends TrekRepository<Plugins> {
async findActivationGate(id: string): Promise<PluginActivationGateRow | null> {
const row = await this.findOne(
{ id },
{
fields: [
'permissions',
'granted_permissions',
'dependencies',
'trek_range',
'api_version',
'version',
'trek_range_accepted_version',
'trek_range_accepted_host',
],
},
{ fields: ['permissions', 'granted_permissions', 'dependencies', 'trek_range', 'api_version'] },
);
return row
? {
@@ -169,9 +153,6 @@ export class PluginsRepository extends TrekRepository<Plugins> {
dependencies: row.dependencies ?? null,
trek_range: row.trek_range ?? null,
api_version: row.api_version ?? null,
version: row.version ?? null,
trek_range_accepted_version: row.trek_range_accepted_version ?? null,
trek_range_accepted_host: row.trek_range_accepted_host ?? null,
}
: null;
}
@@ -389,8 +370,6 @@ export class PluginsRepository extends TrekRepository<Plugins> {
'dependencies',
'operator_egress',
'trek_range',
'trek_range_accepted_version',
'trek_range_accepted_host',
'author_pubkey',
'update_block_code',
'update_block_detail',
@@ -417,8 +396,6 @@ export class PluginsRepository extends TrekRepository<Plugins> {
dependencies: r.dependencies ?? null,
operator_egress: r.operator_egress,
trek_range: r.trek_range ?? null,
trek_range_accepted_version: r.trek_range_accepted_version ?? null,
trek_range_accepted_host: r.trek_range_accepted_host ?? null,
author_pubkey: r.author_pubkey ?? null,
update_block_code: r.update_block_code ?? null,
update_block_detail: r.update_block_detail ?? null,
@@ -568,11 +545,6 @@ export class PluginsRepository extends TrekRepository<Plugins> {
await this.nativeUpdate({ id }, { update_hold: hold ? 1 : 0 });
}
/** An admin accepted running this plugin version outside its TREK range, on this TREK. */
async acceptTrekRange(id: string, version: string, host: string): Promise<void> {
await this.nativeUpdate({ id }, { trek_range_accepted_version: version, trek_range_accepted_host: host });
}
/**
* RG8 (`commitUpload`, sideload step 2) — `` UPDATE plugins SET source_repo = ?,
* source_commit = NULL, sha256 = NULL, reviewed_at = NULL, author_pubkey = NULL,
@@ -7,11 +7,11 @@ import { CurrentUser } from '../auth-core/current-user.decorator';
import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
import { ManagedForbidden } from '../common/managed';
import { ResponseContract } from '../common/response-contract';
import { AiAdminSettingsDto, AiInstanceConnectionDto, AiModelUpdateDto } from './ai-connections.dto';
import { AiAdminSettingsDto, AiInstanceConnectionDto } from './ai-connections.dto';
import { AiConnectionsService } from './ai-connections.service';
import { ChatgptAuthService } from './chatgpt-auth.service';
import { OpenrouterAuthService } from './openrouter-auth.service';
import { Body, Controller, Delete, Get, HttpCode, Patch, Post, Put, UseGuards } from '@nestjs/common';
import { Body, Controller, Delete, Get, HttpCode, Post, Put, UseGuards } from '@nestjs/common';
import {
aiAdminConnectionResponseSchema,
aiAdminSettingsSchema,
@@ -63,12 +63,6 @@ export class AiAdminController {
return this.connections.saveInstance(user.id, body as AiInstanceConnectionRequest);
}
@Patch('connection/model')
@ResponseContract(aiAdminConnectionResponseSchema)
setModel(@CurrentUser() user: User, @Body() body: AiModelUpdateDto) {
return this.connections.setInstanceModel(user.id, body.model);
}
@Delete('connection')
@HttpCode(200)
@ResponseContract(successResponseSchema)
@@ -23,21 +23,10 @@ const cloudFetch: AiFetch = (url, init) => safeFetch(url, { ...init, signal: ini
*/
const adminServerFetch: AiFetch = (url, init) => safeFetchLlm(url, { ...init, signal: init.signal }, 5, null);
/**
* Whether an OpenAI model behind an API key goes through the Responses API:
* the reasoning models (the o-series, GPT-5 and later) refuse function tools
* on Chat Completions with a 400 (#2792). Their `-chat` variants do not reason
* and stay on Chat Completions, like the older GPT-4 line.
*/
export function openAiWantsResponses(model: string): boolean {
return /^(o\d|gpt-([5-9]|\d{2,}))/.test(model) && !/-chat/.test(model);
}
/**
* The chat client for a resolved connection: Anthropic's Messages API, the
* Responses API for a ChatGPT plan and OpenAI's reasoning models, and Chat
* Completions for everything else OpenAI-compatible (older OpenAI models,
* Gemini, OpenRouter, an admin's own server).
* Responses API for a ChatGPT plan, and Chat Completions for everything
* OpenAI-compatible (OpenAI, Gemini, OpenRouter, an admin's own server).
*/
@Injectable()
export class AiChatClientService {
@@ -56,10 +45,6 @@ export class AiChatClientService {
cloudFetch,
);
}
if (kind === 'openai' && openAiWantsResponses(model)) {
const apiKey = credential.apiKey ?? '';
return new OpenAiResponsesClient(model, () => Promise.resolve(apiKey), cloudFetch, 'openai');
}
switch (kind) {
case 'anthropic':
return new AnthropicMessagesClient(model, credential.apiKey ?? '', cloudFetch);
@@ -328,26 +328,6 @@ export class AiConnectionsService implements SharedAiConnectionPort {
return this.modelsOf(adminId, row);
}
/**
* Picks the model of the instance's connection, one the provider offers. The
* only way to do so for a shared ChatGPT plan: saving the connection again
* needs a key, and a plan has a sign-in instead.
* @txIndependent reading the credential may renew a ChatGPT sign-in first; that write stands on its own.
*/
async setInstanceModel(adminId: number, model: string): Promise<AiAdminConnectionResponse> {
const row = await this.connections.findInstance();
if (!row) throw aiRefusal('not_found', 'No connection is set up for everyone');
const models = await this.modelsOf(adminId, row);
if (!models.some((m) => m.id === model)) throw aiRefusal('unknown_model', 'This model is not offered here');
await this.connections.setModel(row.id, model);
await this.audit.writeAudit({
userId: adminId,
action: 'ai.connection.saved',
details: { scope: 'instance', kind: row.kind, model },
});
return this.instanceConnection();
}
async removeInstance(adminId: number): Promise<void> {
const row = await this.connections.findInstance();
if (!row) throw aiRefusal('not_found', 'No connection is set up for everyone');
@@ -86,11 +86,9 @@ export function toAnthropicMessages(messages: AiChatMessage[]): AnthropicMessage
* A block of an answer as it goes back to the provider: as it came, but a text
* block without the citations it carried, which the provider checks against
* the search results and which the history needs no more than their words.
* Always a copy: the request marks its blocks for the cache in place, and a
* mark left on the stored answer would go out again on every later step.
*/
function replayed(block: ContentBlock): ContentBlock {
return block.type === 'text' ? { type: 'text', text: asText(block.text) } : { ...block };
return block.type === 'text' ? { type: 'text', text: asText(block.text) } : block;
}
/** Anthropic's own web search, a server tool; a few searches a step keep the turn short. */
@@ -116,17 +114,10 @@ export function markHistoryForCache(messages: AnthropicMessage[], breakpoints: n
last.block.cache_control = CACHED;
let question = blocks.length - 1;
while (question >= 0 && !(blocks[question]?.role === 'user' && blocks[question]?.block.type === 'text')) question--;
// A replayed thinking block goes back exactly as it came, so the mark sits on the block before it.
let mark = question - 1;
while (mark >= 0 && isThinking(blocks[mark]?.block)) mark--;
const before = mark >= 0 ? blocks[mark] : undefined;
const before = question > 0 ? blocks[question - 1] : undefined;
if (breakpoints >= 2 && before && before !== last) before.block.cache_control = CACHED;
}
function isThinking(block: ContentBlock | undefined): boolean {
return block?.type === 'thinking' || block?.type === 'redacted_thinking';
}
const STOP_REASONS: Record<string, AiFinishReason> = { tool_use: 'tool-calls', max_tokens: 'length' };
/**
@@ -216,10 +207,9 @@ interface OpenBlock {
/**
* What one streamed Messages API turn has said so far, fed one event at a
* time. It keeps every content block as it came, thinking blocks with their
* signature included, so an answer that searched the web or thought can be
* replayed as it was (state()); any other answer is rebuilt from its text and
* calls as before.
* time. It keeps every content block as it came, so an answer that searched
* the web can be replayed with its search and its results (state()); an
* answer that did not is rebuilt from its text and calls as before.
*/
class AnthropicTurn {
inputTokens = 0;
@@ -256,10 +246,6 @@ class AnthropicTurn {
if (delta.type === 'text_delta' && asText(delta.text)) {
if (open) open.block.text = asText(open.block.text) + asText(delta.text);
yield { type: 'text-delta', delta: asText(delta.text) };
} else if (delta.type === 'thinking_delta' && open) {
open.block.thinking = asText(open.block.thinking) + asText(delta.thinking);
} else if (delta.type === 'signature_delta' && open) {
open.block.signature = asText(open.block.signature) + asText(delta.signature);
} else if (delta.type === 'input_json_delta' && open) {
open.json += asText(delta.partial_json);
} else if (delta.type === 'citations_delta') {
@@ -299,17 +285,10 @@ class AnthropicTurn {
}
}
/**
* The blocks to replay, for an answer that searched the web or thought; null
* for one rebuilt from its text and calls. A model that thinks (Sonnet 5.5,
* Opus 5.5) wants its thinking blocks back unchanged with the rest of the
* turn, and writes what it says between tool calls into them: rebuilt from
* text and calls alone, the next step after a tool came back empty (#2789).
*/
/** The blocks to replay, for an answer that searched the web; null for one rebuilt from its text and calls. */
state(): AiProviderState | null {
if (!this.searched) return null;
const blocks = [...this.blocks.entries()].sort(([a], [b]) => a - b).map(([, open]) => open.block);
const thought = blocks.some(isThinking);
if (!this.searched && !thought) return null;
return { adapter: 'anthropic-messages', blocks };
}
}
@@ -130,22 +130,20 @@ function citedSources(item: Record<string, unknown>): AiSource[] {
}
/**
* OpenAI's Responses API, on a ChatGPT plan (Sign in with ChatGPT) or, for the
* reasoning models, on an OpenAI API key, which take their function tools only
* here (#2792). Within the preview's limits: nothing stored, streamed, no
* output cap or temperature, the instructions as `instructions`, the tools in
* one namespace that carries a description. On a plan, a 401 before the stream
* starts is answered once with a refreshed token; a second one means the
* sign-in has to be renewed. A key has nothing to refresh.
* OpenAI's Responses API on a ChatGPT plan (Sign in with ChatGPT). Within the
* preview's limits: nothing stored, streamed, no output cap or temperature,
* the instructions as `instructions`, the tools in one namespace that carries
* a description. A 401 before the stream starts is answered once with a
* refreshed token; a second one means the sign-in has to be renewed.
*/
export class OpenAiResponsesClient implements AiChatClient {
readonly kind = 'chatgpt' as const;
readonly webSearch = true;
constructor(
readonly model: string,
private readonly token: ChatgptTokenSource,
private readonly fetcher: AiFetch,
readonly kind: 'chatgpt' | 'openai' = 'chatgpt',
) {}
async *stream(request: AiChatRequest, signal: AbortSignal): AsyncGenerator<AiChatEvent> {
@@ -229,7 +227,7 @@ export class OpenAiResponsesClient implements AiChatClient {
try {
return await send(accessToken);
} catch (err) {
if (this.kind !== 'chatgpt' || !(err instanceof AiProviderError) || err.status !== 401) throw err;
if (!(err instanceof AiProviderError) || err.status !== 401) throw err;
return send(await this.token(accessToken));
}
}
@@ -1,4 +1,3 @@
import { intlLocale } from './assistant-words';
import { fileKeyOf } from './cards/card-values';
import type { AssistantFocus, AssistantMention } from '@trek/shared';
@@ -413,7 +412,7 @@ export function todayIn(timeZone: string, now: Date): string {
/** The English name of a locale's language, for the instruction to answer in it. */
export function languageName(locale: string): string {
try {
return new Intl.DisplayNames(['en'], { type: 'language' }).of(intlLocale(locale)) ?? locale;
return new Intl.DisplayNames(['en'], { type: 'language' }).of(locale) ?? locale;
} catch {
return locale;
}
@@ -17,15 +17,6 @@ export function supportedLocale(locale: string): string {
return SUPPORTED_LANGUAGE_CODES.includes(language) ? language : 'en';
}
/**
* The BCP 47 tag of a request's locale, for Intl: a TREK code reads as its
* language ('br' is Brazilian Portuguese here, Breton to Intl), anything else
* is passed through.
*/
export function intlLocale(locale: string): string {
return SUPPORTED_LANGUAGE_CODES.includes(locale) ? getIntlLanguage(locale) : locale;
}
/** The words of one locale's table, or none when it cannot be read. */
export async function localeTable(code: string): Promise<Table> {
try {
@@ -1,4 +1,3 @@
import { intlLocale } from '../assistant-words';
import type { PreviewContext } from './card-types';
import type { AssistantChangeLabelKey, AssistantChangeRow } from '@trek/shared';
@@ -58,7 +57,7 @@ export class Rows {
/** A locale Intl accepts, the user's when it can. */
export function localeOf(ctx: Pick<PreviewContext, 'locale'>): string {
try {
return Intl.getCanonicalLocales(intlLocale(ctx.locale))[0] ?? 'en';
return Intl.getCanonicalLocales(ctx.locale)[0] ?? 'en';
} catch {
return 'en';
}
@@ -71,7 +71,6 @@ export const MANAGED_ROUTE_ALLOW_LIST: string[] = [
'AiAdminController.removeConnection',
'AiAdminController.saveConnection',
'AiAdminController.saveSettings',
'AiAdminController.setModel',
'AiAdminController.settings',
'AiAdminController.signOutChatgpt',
'AiAdminController.startChatgpt',
+7 -88
View File
@@ -126,98 +126,18 @@ export interface TrekRangeBypass {
/** The plugin's declared range, or null when it declared none at all. */
trekRange: string | null;
hostVersion: string;
/**
* True when an admin accepted this one plugin outside its range, false when
* TREK_PLUGINS_IGNORE_TREK_RANGE lets every plugin through.
*/
acceptedByAdmin: boolean;
}
/** An admin's consent to run one plugin outside its range, as the plugins row keeps it. */
interface TrekRangeAcceptance {
/** The plugin version that was installed when the admin accepted. */
acceptedVersion: string | null;
/** The TREK version it ran on then. */
acceptedHost: string | null;
}
/**
* Whether an admin's consent still covers the plugin as it is installed now: the
* same plugin version, on the same TREK major. An update of the plugin, or a TREK
* major past the one the admin saw it run on, asks again.
*/
export function acceptanceHolds(
pluginVersion: string | null | undefined,
a: TrekRangeAcceptance | null | undefined,
): boolean {
if (!a?.acceptedVersion || !a.acceptedHost || !pluginVersion) return false;
if (a.acceptedVersion !== pluginVersion) return false;
const accepted = semver.coerce(a.acceptedHost);
const host = normalizedHost();
if (!accepted || host === null) return false;
return semver.major(accepted) === semver.major(host);
}
/**
* Non-null exactly when `range` would have been refused and only a bypass lets it
* Non-null exactly when `range` would have been refused and only the bypass lets it
* through: the marker that makes an install/activate response say "this worked, but
* only because you told TREK to run it anyway". `accepted` is this one plugin's
* consent from the admin; the environment switch covers every plugin. Null for a
* normal install (the range fits) and null when neither applies (the gate refuses).
* only because you told TREK to ignore the version check". Null for a normal install
* (the range fits) and null when the bypass is off (the gate refuses instead).
*/
export function bypassedRange(range: string | null | undefined, accepted = false): TrekRangeBypass | null {
export function bypassedRange(range: string | null | undefined): TrekRangeBypass | null {
if (hostSatisfies(range)) return null;
const everyPlugin = trekRangeBypassed();
if (!everyPlugin && !accepted) return null;
return { trekRange: range ?? null, hostVersion: hostVersion(), acceptedByAdmin: !everyPlugin };
}
/** What the activation gate reads off a plugin's row to decide whether it may run on this TREK. */
interface TrekRangeRow {
trek_range: string | null;
version: string | null;
trek_range_accepted_version: string | null;
trek_range_accepted_host: string | null;
}
/** Why the activation gate refuses a plugin on this TREK, in the shape its error carries. */
interface TrekRangeRefusal {
message: string;
code: 'TREK_VERSION_UNKNOWN' | 'TREK_VERSION_INCOMPATIBLE';
detail: { trekRange: string | null; hostVersion: string };
}
/**
* The TREK-version half of the activation gate: null when the plugin may run, else why
* not. An admin's consent (`acceptNow`, or one kept on the row for this version and TREK
* major) or TREK_PLUGINS_IGNORE_TREK_RANGE lets an outgrown plugin through, and every
* start of one says so in the log; the plugin list carries the same marker for the UI.
*/
export function trekRangeRefusal(id: string, row: TrekRangeRow, acceptNow = false): TrekRangeRefusal | null {
const accepted =
acceptNow ||
acceptanceHolds(row.version, {
acceptedVersion: row.trek_range_accepted_version,
acceptedHost: row.trek_range_accepted_host,
});
const bypass = bypassedRange(row.trek_range, accepted);
if (bypass) {
warnRangeBypass(id, bypass);
return null;
}
if (!row.trek_range) {
return {
message: `plugin ${id} does not declare which TREK versions it supports`,
code: 'TREK_VERSION_UNKNOWN',
detail: { trekRange: null, hostVersion: hostVersion() },
};
}
if (hostSatisfies(row.trek_range)) return null;
return {
message: `plugin ${id} requires TREK ${row.trek_range} — this is TREK ${hostVersion()}`,
code: 'TREK_VERSION_INCOMPATIBLE',
detail: { trekRange: row.trek_range, hostVersion: hostVersion() },
};
if (!trekRangeBypassed()) return null;
return { trekRange: range ?? null, hostVersion: hostVersion() };
}
/**
@@ -227,8 +147,7 @@ export function trekRangeRefusal(id: string, row: TrekRangeRow, acceptNow = fals
*/
export function warnRangeBypass(id: string, b: TrekRangeBypass): void {
const declared = b.trekRange ? `declares TREK ${b.trekRange}` : 'declares no TREK version range';
const because = b.acceptedByAdmin ? 'an admin chose to run it anyway' : 'TREK_PLUGINS_IGNORE_TREK_RANGE is set';
console.warn(
`[plugins] ${id} ${declared} — this is TREK ${b.hostVersion}; continuing because ${because}. The author has not verified it on this version: it may not work, and it could corrupt TREK data.`,
`[plugins] ${id} ${declared} — this is TREK ${b.hostVersion}; continuing because TREK_PLUGINS_IGNORE_TREK_RANGE is set. The author has not verified it on this version: it may not work, and it could corrupt TREK data.`,
);
}
@@ -62,7 +62,7 @@ import { scanForNativeBinaries } from './install/native-scan';
import { devLinkEnabled, DEV_LINK_SOURCE } from './dev-link';
import { pluginCodeDir, pluginDataDir } from './paths';
import { assertHostCompatible, PluginRegistryService, RegistryError } from './registry/registry.service';
import { hostSatisfies, hostVersion, trekRangeRefusal } from './install/host-compat';
import { hostSatisfies, hostVersion, bypassedRange, warnRangeBypass } from './install/host-compat';
import type { TrekRangeBypass } from './install/host-compat';
import { keyFingerprint } from './signature-status';
import { AuditService } from '../audit/audit.service';
@@ -639,10 +639,8 @@ export class PluginRuntimeService implements OnApplicationBootstrap, OnModuleDes
* freshly-installed plugin (no prior grant) is itself the consent for its
* declared set; widening an already-consented set requires `consentWiden` (the
* update consent dialog), and otherwise throws PluginConsentRequired.
* `acceptTrekRange` is the admin's "run it anyway" outside the TREK range the author
* declared: for this plugin only, never a dependency, kept on its row for this version.
*/
async activate(id: string, consentWiden = false, acceptTrekRange = false): Promise<void> {
async activate(id: string, consentWiden = false): Promise<void> {
const installed = await this.installedDepRows();
// Deps-first order over the installed graph (throws DependencyCycleError on a
// cycle). Missing deps aren't in `installed` so they don't appear here — the
@@ -654,7 +652,6 @@ export class PluginRuntimeService implements OnApplicationBootstrap, OnModuleDes
// blocked dependency never leaves the chain half-activated. Only the target
// may consent-widen; dependencies are auto-enabled at their existing grant.
const toCheck = rootInstalled ? order : [id];
if (acceptTrekRange) await this.rememberRangeAcceptance(id);
for (const nodeId of toCheck) await this.assertActivatable(nodeId, installed, nodeId === id ? consentWiden : false);
// Enable dependencies first (skip ones already enabled), then the target.
@@ -664,16 +661,6 @@ export class PluginRuntimeService implements OnApplicationBootstrap, OnModuleDes
}
}
/**
* Keeps the admin's "run it anyway" for the installed version, when it is in fact outside its range.
* @txStandalone the admin's answer to a dialog; it stands whether or not the plugin then starts.
*/
private async rememberRangeAcceptance(id: string): Promise<void> {
const row = await this.plugins.findActivationGate(id);
if (!row?.version || hostSatisfies(row.trek_range)) return;
await this.plugins.acceptTrekRange(id, row.version, hostVersion());
}
/** All plugin rows projected to what the dependency helpers reason over. */
private async installedDepRows(): Promise<Map<string, PluginDepRow>> {
const rows: PluginDepRow[] = await this.plugins.listDepRows();
@@ -695,8 +682,24 @@ export class PluginRuntimeService implements OnApplicationBootstrap, OnModuleDes
// it would not make the plugin start. It is also the gate that catches the case
// install can't — TREK was upgraded PAST the plugin's declared upper bound, so code
// that was legitimately installed no longer supports the host it's sitting on.
const refusal = trekRangeRefusal(id, row);
if (refusal) throw new PluginDependencyError(refusal.message, refusal.code, refusal.detail);
const bypass = bypassedRange(row.trek_range);
if (bypass) {
// TREK_PLUGINS_IGNORE_TREK_RANGE: the operator chose to run it anyway. Say so in the
// log every time it starts — the plugin list carries the same marker for the UI.
warnRangeBypass(id, bypass);
} else if (!row.trek_range) {
throw new PluginDependencyError(
`plugin ${id} does not declare which TREK versions it supports`,
'TREK_VERSION_UNKNOWN',
{ trekRange: null, hostVersion: hostVersion() },
);
} else if (!hostSatisfies(row.trek_range)) {
throw new PluginDependencyError(
`plugin ${id} requires TREK ${row.trek_range} — this is TREK ${hostVersion()}`,
'TREK_VERSION_INCOMPATIBLE',
{ trekRange: row.trek_range, hostVersion: hostVersion() },
);
}
// Same reasoning as the TREK-version gate above: a plugin whose manifest apiVersion
// outpaces this TREK's plugin-API surface can never run correctly, so it must be
// refused before any consent dialog is offered.
+3 -10
View File
@@ -113,15 +113,8 @@ export class PluginsController {
// compatible version and reporting addons the admin still has to enable.
// Dependency resolution pins versions internally but never DELIBERATELY, so
// only the plain path below recomputes the update hold.
const acceptTrekRange = body.acceptTrekRange === true;
if (body.withDependencies) {
return await this.registry.installWithDependencies(body.id, body.constraint, acceptTrekRange);
}
const res = await this.registry.install(body.id, {
version: body.version,
constraint: body.constraint,
acceptTrekRange,
});
if (body.withDependencies) return await this.registry.installWithDependencies(body.id, body.constraint);
const res = await this.registry.install(body.id, { version: body.version, constraint: body.constraint });
await this.registry.recomputeUpdateHold(res.id, res.version, !!body.version);
return res;
} catch (e) {
@@ -279,7 +272,7 @@ export class PluginsController {
async activate(@Param('id') id: string, @Body() body: PluginActivateDto) {
if (!pluginsEnabled()) throw new HttpException({ error: 'Plugins are disabled by server configuration' }, 503);
try {
await this.runtime.activate(id, !!body?.consent, body?.acceptTrekRange === true);
await this.runtime.activate(id, !!body?.consent);
} catch (e) {
// Re-enabling a plugin whose update widened its permissions must NOT grant
// them silently — surface a distinct code so the UI opens the consent dialog.
+5 -16
View File
@@ -25,7 +25,7 @@ import {
import { devLinkEnabled } from './dev-link';
import { readAudit } from './host/plugin-audit';
import { pluginBudgetUsage } from './host/plugin-host-state';
import { acceptanceHolds, bypassedRange, hostSatisfies, hostVersion, trekRangeBypassed } from './install/host-compat';
import { bypassedRange, hostSatisfies, hostVersion, trekRangeBypassed } from './install/host-compat';
import type { TrekRangeBypass } from './install/host-compat';
import type { PluginDependency } from './install/manifest';
import { pluginsEnabled } from './kill-switch';
@@ -71,8 +71,6 @@ interface PluginRawRow {
capabilities: string;
dependencies: string | null;
trek_range: string | null;
trek_range_accepted_version: string | null;
trek_range_accepted_host: string | null;
author_pubkey: string | null;
update_block_code: string | null;
update_block_detail: string | null;
@@ -115,10 +113,9 @@ export interface PluginListItem {
/** The running TREK, so the UI can say "needs X, you have Y" without doing semver. */
hostVersion: string;
/**
* Non-null when the plugin is outside its declared range (or declared none) and only an
* admin's "run it anyway" for this plugin, or TREK_PLUGINS_IGNORE_TREK_RANGE, lets it
* activate. The card shows it as a warning rather than a blocker: the admin chose this,
* but must keep seeing what they chose.
* Non-null when the plugin is outside its declared range (or declared none) and only
* TREK_PLUGINS_IGNORE_TREK_RANGE lets it activate. The card shows it as a warning
* rather than a blocker: the admin chose this, but must keep seeing what they chose.
*/
trekRangeBypassed: TrekRangeBypass | null;
/** The concrete blockers, so the UI can render chips + the resolve dialog. */
@@ -203,13 +200,7 @@ export class PluginsService {
const state = resolveDependencyState(deps, installed);
// Mirrors the order of assertActivatable's gate, so the card explains the same
// blocker the activate call would hit rather than a second, lesser one.
const trekBypass = bypassedRange(
r.trek_range,
acceptanceHolds(r.version, {
acceptedVersion: r.trek_range_accepted_version,
acceptedHost: r.trek_range_accepted_host,
}),
);
const trekBypass = bypassedRange(r.trek_range);
const dependencyStatus: PluginDependencyStatus =
!hostSatisfies(r.trek_range) && !trekBypass
? 'hostIncompatible'
@@ -222,8 +213,6 @@ export class PluginsService {
dependencies: _raw,
operator_egress: _oe,
trek_range,
trek_range_accepted_version: _acceptedVersion,
trek_range_accepted_host: _acceptedHost,
author_pubkey,
update_block_code,
update_block_detail,
@@ -392,11 +392,11 @@ export class PluginRegistryService {
* version (`minTrekVersion`/`maxTrekVersion`). Throws if the plugin isn't in the
* registry or nothing qualifies. Backs "download the latest compatible version".
*/
async resolveVersion(id: string, constraint?: string, acceptTrekRange = false): Promise<RegistryVersion> {
async resolveVersion(id: string, constraint?: string): Promise<RegistryVersion> {
const reg = await this.fetchRegistry();
const entry = reg.plugins.find((p) => p.id === id);
if (!entry) throw new RegistryError(`plugin ${id} not in registry`);
const v = this.latestCompatible(entry, constraint) ?? (acceptTrekRange ? this.newestOf(entry, constraint) : null);
const v = this.latestCompatible(entry, constraint);
if (!v) {
throw new RegistryError(
constraint
@@ -427,15 +427,6 @@ export class PluginRegistryService {
return [...candidates].sort((a, b) => semver.rcompare(a.version, b.version))[0];
}
/**
* The newest version that satisfies `constraint`, whatever TREK it declares: what an
* admin's "install anyway" takes when no version fits this TREK. A version that does
* fit is always preferred over this (see {@link selectVersion}).
*/
private newestOf(entry: RegistryEntry, constraint?: string): RegistryVersion | null {
return this.latestCompatible(entry, constraint, () => true);
}
/**
* Pick the version `install()` will fetch, and refuse an incompatible one — on EVERY
* path, which is the whole point. An explicit `version` and the bare "install latest"
@@ -443,15 +434,11 @@ export class PluginRegistryService {
* through resolveVersion), so the admin UI's own Install button — which sends neither —
* happily installed a plugin that declared it doesn't support this TREK.
*/
private selectVersion(
entry: RegistryEntry,
opts?: { version?: string; constraint?: string; acceptTrekRange?: boolean },
): RegistryVersion {
const accept = opts?.acceptTrekRange === true;
private selectVersion(entry: RegistryEntry, opts?: { version?: string; constraint?: string }): RegistryVersion {
if (opts?.version) {
const ver = entry.versions.find((v) => v.version === opts.version);
if (!ver) throw new RegistryError(`version ${opts.version} not found for ${entry.id}`);
if (!accept && !installable(ver, normalizedHost())) {
if (!installable(ver, normalizedHost())) {
throw new RegistryError(
`${entry.id} ${ver.version} requires TREK ${trekRequirement(ver)} — this is TREK ${hostVersion()}`,
'TREK_VERSION_INCOMPATIBLE',
@@ -459,8 +446,7 @@ export class PluginRegistryService {
}
return ver;
}
const ver =
this.latestCompatible(entry, opts?.constraint) ?? (accept ? this.newestOf(entry, opts?.constraint) : null);
const ver = this.latestCompatible(entry, opts?.constraint);
if (ver) return ver;
// Nothing compatible. Say WHY against the newest version the admin was actually
// shown, rather than a bare "not found" — the fix is a TREK upgrade, not a retry.
@@ -490,7 +476,7 @@ export class PluginRegistryService {
*/
async install(
id: string,
opts?: { version?: string; constraint?: string; retrustKey?: string; acceptTrekRange?: boolean },
opts?: { version?: string; constraint?: string; retrustKey?: string },
): Promise<{ id: string; version: string; trekRangeBypassed: TrekRangeBypass | null }> {
const reg = await this.fetchRegistry();
const entry = reg.plugins.find((p) => p.id === id);
@@ -532,7 +518,7 @@ export class PluginRegistryService {
// published entries usually carry a lower bound and no upper one at all, so a
// plugin that declares "<4.0.0" passes the pre-download filter on TREK 4 and is
// caught only here.
const trekRangeBypassed = assertHostCompatible(manifest.trekRange, id, opts?.acceptTrekRange === true);
const trekRangeBypassed = assertHostCompatible(manifest.trekRange, id);
if (scanForNativeBinaries(pluginRoot).length) throw new RegistryError('artifact contains native binaries');
// 6. atomic move into place
@@ -557,9 +543,6 @@ export class PluginRegistryService {
// The plugin is now on new code that passed every check — whatever refusal was
// recorded before no longer describes reality.
await clearUpdateBlock(this.plugins, id);
// The admin's "install anyway" for this plugin, kept for the version that landed
// so activating it later does not ask a second time.
if (trekRangeBypassed?.acceptedByAdmin) await this.plugins.acceptTrekRange(id, ver.version, hostVersion());
});
return { id, version: ver.version, trekRangeBypassed };
} finally {
@@ -577,7 +560,6 @@ export class PluginRegistryService {
async installWithDependencies(
id: string,
constraint?: string,
acceptTrekRange = false,
): Promise<{ installed: string[]; requiredAddons: string[]; trekRangeBypassed: TrekRangeBypass | null }> {
let trekRangeBypassed: TrekRangeBypass | null = null;
const installedNow = new Set(await this.plugins.listAllIds());
@@ -588,14 +570,12 @@ export class PluginRegistryService {
const visit = async (pid: string, range: string | undefined, stack: string[]): Promise<void> => {
if (done.has(pid)) return;
if (stack.includes(pid)) throw new RegistryError(`plugin dependency cycle: ${[...stack, pid].join(' -> ')}`);
// The admin's "install anyway" covers the plugin they asked for, never a dependency.
const acceptHere = acceptTrekRange && pid === id;
const ver = await this.resolveVersion(pid, range, acceptHere); // throws if not in registry / unsatisfiable
const ver = await this.resolveVersion(pid, range); // throws if not in registry / unsatisfiable
if (!installedNow.has(pid)) {
// Install the version we just RESOLVED. Passing the range back (or nothing, for
// the root) made install() re-pick on its own and land on entry.versions[0] —
// so the compatible version resolveVersion had chosen was computed and discarded.
const res = await this.install(pid, { version: ver.version, acceptTrekRange: acceptHere });
const res = await this.install(pid, { version: ver.version });
// The admin asked for the root; that is the bypass they are warned about (a
// dependency's own bypass still lands in the log).
if (pid === id) trekRangeBypassed = res.trekRangeBypassed;
@@ -837,14 +817,13 @@ function installable(v: RegistryVersion, host: string | null): boolean {
* every install front door (registry, sideload, dev-link) so they all fail the same way,
* with a code the admin UI can act on rather than prose it would have to string-match.
*
* Under TREK_PLUGINS_IGNORE_TREK_RANGE, or when the admin `accepted` this one plugin
* outside its range, the refusal becomes a log warning, and the returned marker is what
* the front door hands back so the admin is told too. Null means the range fits and
* nothing was bypassed.
* Under TREK_PLUGINS_IGNORE_TREK_RANGE the refusal becomes a log warning, and the
* returned marker is what the front door hands back so the admin is told too. Null
* means the range fits and nothing was bypassed.
*/
export function assertHostCompatible(range: string | null, id: string, accepted = false): TrekRangeBypass | null {
export function assertHostCompatible(range: string | null, id: string): TrekRangeBypass | null {
if (hostSatisfies(range)) return null;
const bypass = bypassedRange(range, accepted);
const bypass = bypassedRange(range);
if (bypass) {
warnRangeBypass(id, bypass);
return bypass;
+3 -16
View File
@@ -55,18 +55,11 @@ const tokenListSchema = z.object({
totalItems: z.number().optional(),
});
const actorSchema = z.object({ id: z.string(), is_local: z.boolean().nullish() });
/**
* A user record with the ActivityPub actors that stand for it; the local one
* authors the user's trails. PocketBase expands a back-relation as a single
* object when only one record can match and as a list otherwise, so an account
* with one actor answers with the object itself.
*/
/** A user record with the ActivityPub actors that stand for it; the local one authors the user's trails. */
const userActorsSchema = z.object({
expand: z
.object({
activitypub_actors_via_user: z.union([z.array(actorSchema), actorSchema.transform((actor) => [actor])]).nullish(),
activitypub_actors_via_user: z.array(z.object({ id: z.string(), is_local: z.boolean().nullish() })).nullish(),
})
.nullish(),
});
@@ -266,13 +259,7 @@ export class WandererClient {
const actors = (user.expand?.activitypub_actors_via_user ?? [])
.filter((actor) => actor.is_local !== false && isTrailId(actor.id))
.map((actor) => actor.id);
if (actors.length === 0) {
throw new WandererError(
'no_author',
'wanderer named no author for the token',
'no local actor in activitypub_actors_via_user',
);
}
if (actors.length === 0) throw new WandererError('invalid_response', 'wanderer named no author for the token');
return actors;
}
+1 -7
View File
@@ -2,7 +2,6 @@ import { WandererConnections } from '../../db/entities/WandererConnections.entit
import type { WandererConnectionsRepository } from '../../db/repositories/WandererConnections.repository';
import { decodePolyline, thinLine } from '../../utils/polyline';
import { checkSsrf } from '../../utils/ssrfGuard';
import { logWarn } from '../audit/audit-log.logger';
import { AuditService } from '../audit/audit.service';
import { decrypt_api_key, maybe_encrypt_api_key } from '../common/crypto/apiKeyCrypto';
import { DomainError } from '../common/domain-error';
@@ -184,14 +183,9 @@ export class WandererService {
await this.connections.recordCheck(userId, ok, code);
}
/**
* A failed call, with a rejected token noted on the connection so its card
* says so. The log gets the reason the client is not shown: which field of
* wanderer's answer did not match, or what came instead of JSON.
*/
/** A failed call, with a rejected token noted on the connection so its card says so. */
private async failed(userId: number, err: unknown): Promise<never> {
if (!(err instanceof WandererError)) throw err;
logWarn(`[wanderer] ${err.code}: ${err.message}${err.detail ? ` (${err.detail})` : ''}`);
if (err.code === 'unauthorized') await this.noteCheck(userId, false, err.code);
throw refusalOf(err);
}
@@ -204,16 +204,6 @@ describe('AI connections e2e', () => {
expect(saved.body.connection).toMatchObject({ scope: 'instance', kind: 'anthropic', hint: '…7777', baseUrl: null });
expect(saved.body.prefill).toBeNull();
// The model for everyone is switched on its own, by an admin only, to one the provider offers (#2783).
const model = (as_: number, body: object) =>
request(server).patch('/api/admin/ai/connection/model').set(as(as_)).send(body);
expect((await model(USER, { model: 'claude-haiku' })).status).toBe(403);
expect((await model(ADMIN, {})).status).toBe(400);
expect((await model(ADMIN, { model: 'nope' })).body).toMatchObject({ code: 'unknown_model' });
const switched = await model(ADMIN, { model: 'claude-haiku' });
expect(switched.status).toBe(200);
expect(switched.body.connection).toMatchObject({ kind: 'anthropic', model: 'claude-haiku', hint: '…7777' });
// A user now runs on the instance's connection, with the daily limit and a privacy notice to acknowledge.
const status = await request(server).get('/api/ai/status').set(as(USER));
expect(status.body).toMatchObject({
@@ -117,11 +117,11 @@ describe('PluginRuntimeService dev-link', () => {
try {
await expect(runtime.link(writeSource('oldplug-bypass', { trek: '>=2.0.0 <3.0.0' }))).resolves.toMatchObject({
id: 'oldplug-bypass',
trekRangeBypassed: { trekRange: '>=2.0.0 <3.0.0', hostVersion: '3.3.0', acceptedByAdmin: false },
trekRangeBypassed: { trekRange: '>=2.0.0 <3.0.0', hostVersion: '3.3.0' },
});
await expect(runtime.link(writeSource('rangeless-bypass', { trek: '' }))).resolves.toMatchObject({
id: 'rangeless-bypass',
trekRangeBypassed: { trekRange: null, hostVersion: '3.3.0', acceptedByAdmin: false },
trekRangeBypassed: { trekRange: null, hostVersion: '3.3.0' },
});
// A dir that fits is a plain link — no marker to alarm anyone with.
await expect(runtime.link(writeSource('fits-bypass'))).resolves.toMatchObject({ trekRangeBypassed: null });
@@ -24,8 +24,7 @@ const { testDb } = vi.hoisted(() => {
-- otherwise fail on the version gate before reaching the behaviour under test. The gate
-- itself is exercised in "TREK host-version gating" below, with explicit ranges.
trek_range TEXT DEFAULT '>=3.0.0',
source_repo TEXT, author_pubkey TEXT, update_block_code TEXT, update_block_detail TEXT, update_block_version TEXT,
trek_range_accepted_version TEXT, trek_range_accepted_host TEXT);
source_repo TEXT, author_pubkey TEXT, update_block_code TEXT, update_block_detail TEXT, update_block_version TEXT);
CREATE TABLE plugin_error_log (id INTEGER PRIMARY KEY AUTOINCREMENT, plugin_id TEXT, level TEXT, message TEXT, ts TEXT);
CREATE TABLE plugin_settings_fields (id INTEGER PRIMARY KEY AUTOINCREMENT, plugin_id TEXT, field_key TEXT, scope TEXT, secret INTEGER, default_value TEXT);
CREATE TABLE settings (user_id INTEGER, key TEXT, value TEXT);
@@ -819,27 +818,14 @@ describe('PluginRuntimeService.retrust', () => {
* host it declared it doesn't support — would otherwise be spawned on the next boot.
*/
describe('TREK host-version gating', () => {
const seedRanged = (
id: string,
trekRange: string | null,
enabled = 0,
accepted: { version?: string; acceptedVersion?: string; acceptedHost?: string } = {},
) => {
const seedRanged = (id: string, trekRange: string | null, enabled = 0) => {
fs.mkdirSync(path.join(codeRoot, id, 'server'), { recursive: true });
fs.writeFileSync(path.join(codeRoot, id, 'server', 'index.js'), 'module.exports = { async onLoad() {} };');
testDb
.prepare(
"INSERT INTO plugins (id, status, enabled, permissions, granted_permissions, config, trek_range, version, trek_range_accepted_version, trek_range_accepted_host) VALUES (?, ?, ?, '[]', '[]', '{}', ?, ?, ?, ?)",
"INSERT INTO plugins (id, status, enabled, permissions, granted_permissions, config, trek_range) VALUES (?, ?, ?, '[]', '[]', '{}', ?)",
)
.run(
id,
enabled ? 'active' : 'inactive',
enabled,
trekRange,
accepted.version ?? null,
accepted.acceptedVersion ?? null,
accepted.acceptedHost ?? null,
);
.run(id, enabled ? 'active' : 'inactive', enabled, trekRange);
};
const cleanup = (...ids: string[]) => {
for (const id of ids) testDb.prepare('DELETE FROM plugins WHERE id = ?').run(id);
@@ -933,43 +919,6 @@ describe('TREK host-version gating', () => {
});
});
it("runs an outgrown plugin on the admin's say-so, and does not ask a second time", async () => {
process.env.APP_VERSION = '5.0.0';
seedRanged('say-so', '>=3.2.0 <4.0.0', 0, { version: '1.0.3' });
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
const rt = await createPluginRuntime(dbConn);
await rt.activate('say-so', false, true);
expect(rt.isActive('say-so')).toBe(true);
expect(warn.mock.calls.some((c) => /say-so.*an admin chose to run it anyway/.test(String(c[0])))).toBe(true);
await rt.deactivate('say-so');
// The consent was kept with the row, so switching it on again needs no second one.
await rt.activate('say-so');
expect(rt.isActive('say-so')).toBe(true);
await rt.deactivate('say-so');
warn.mockRestore();
cleanup('say-so');
});
it("keeps the admin's consent for the version and TREK major it was given on only", async () => {
const given = { acceptedVersion: '1.0.3', acceptedHost: '5.0.0' };
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
process.env.APP_VERSION = '5.0.1';
seedRanged('kept', '>=3.2.0 <4.0.0', 0, { version: '1.0.3', ...given });
seedRanged('updated', '>=3.2.0 <4.0.0', 0, { version: '1.1.0', ...given });
const rt = await createPluginRuntime(dbConn);
await rt.activate('kept');
expect(rt.isActive('kept')).toBe(true);
await rt.deactivate('kept');
// An update of the plugin asks again.
await expect(rt.activate('updated')).rejects.toMatchObject({ code: 'TREK_VERSION_INCOMPATIBLE' });
// So does a new TREK major.
process.env.APP_VERSION = '6.0.0';
await expect(rt.activate('kept')).rejects.toMatchObject({ code: 'TREK_VERSION_INCOMPATIBLE' });
warn.mockRestore();
cleanup('kept', 'updated');
});
it('checks the version BEFORE permissions — an unrunnable plugin gets no consent dialog', async () => {
// Consenting to permissions would not make it start, so offering the dialog is a lie.
process.env.APP_VERSION = '4.0.0';
@@ -1193,43 +1193,6 @@ describe('TREK-version gating on install', () => {
expect(safeDownload).not.toHaveBeenCalled();
});
it("an admin's install-anyway takes the newest version when none fits, and keeps that consent on the row", async () => {
process.env.APP_VERSION = '4.0.0'; // both versions declare <4.0.0
stubMulti();
stageMulti('2.1.0', 0);
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
await expect(svc.install('multi', { acceptTrekRange: true })).resolves.toEqual({
id: 'multi',
version: '2.1.0',
trekRangeBypassed: { trekRange: '>=3.4.0 <4.0.0', hostVersion: '4.0.0', acceptedByAdmin: true },
});
expect(warn.mock.calls.some((c) => /multi.*an admin chose to run it anyway/.test(String(c[0])))).toBe(true);
warn.mockRestore();
const row = await findRow(t, Plugins, { id: 'multi' });
expect(row).toMatchObject({ trek_range_accepted_version: '2.1.0', trek_range_accepted_host: '4.0.0' });
});
it("an admin's install-anyway still prefers a version that fits", async () => {
process.env.APP_VERSION = '3.3.0';
stubMulti();
stageMulti('2.0.0', 1);
await expect(svc.install('multi', { acceptTrekRange: true })).resolves.toEqual({
id: 'multi',
version: '2.0.0',
trekRangeBypassed: null,
});
expect(await findRow(t, Plugins, { id: 'multi' })).toMatchObject({ trek_range_accepted_version: null });
});
it("an admin's install-anyway covers the plugin they asked for, never a dependency", async () => {
process.env.APP_VERSION = '4.0.0';
stubMulti();
await expect(svc.resolveVersion('multi', undefined, false)).rejects.toMatchObject({
code: 'TREK_VERSION_INCOMPATIBLE',
});
await expect(svc.resolveVersion('multi', undefined, true)).resolves.toMatchObject({ version: '2.1.0' });
});
it('honours an EXCLUSIVE upper bound, which minTrekVersion alone cannot express', async () => {
// Both versions declare "<4.0.0" and neither carries a maxTrekVersion — under the old
// min-only check TREK 4 looked compatible with everything.
@@ -1260,7 +1223,7 @@ describe('TREK-version gating on install', () => {
await expect(svc.install('multi')).resolves.toEqual({
id: 'multi',
version: '2.1.0',
trekRangeBypassed: { trekRange: '>=3.4.0 <4.0.0', hostVersion: '3.3.0', acceptedByAdmin: false },
trekRangeBypassed: { trekRange: '>=3.4.0 <4.0.0', hostVersion: '3.3.0' },
});
expect(warn.mock.calls.some((c) => /multi.*>=3\.4\.0 <4\.0\.0.*3\.3\.0/.test(String(c[0])))).toBe(true);
warn.mockRestore();
@@ -1272,7 +1235,7 @@ describe('TREK-version gating on install', () => {
stageMulti('2.1.0', 0);
await expect(svc.install('multi', { version: '2.1.0' })).resolves.toMatchObject({
version: '2.1.0',
trekRangeBypassed: { trekRange: '>=3.4.0 <4.0.0', hostVersion: '3.3.0', acceptedByAdmin: false },
trekRangeBypassed: { trekRange: '>=3.4.0 <4.0.0', hostVersion: '3.3.0' },
});
});
@@ -1305,7 +1268,7 @@ describe('TREK-version gating on install', () => {
safeDownload.mockResolvedValue({ bytes: artifact, sha256: sha });
await expect(svc.install('flight-tracker')).resolves.toMatchObject({
id: 'flight-tracker',
trekRangeBypassed: { trekRange: '>=3.2.0 <3.4.0', hostVersion: '3.9.0', acceptedByAdmin: false },
trekRangeBypassed: { trekRange: '>=3.2.0 <3.4.0', hostVersion: '3.9.0' },
});
expect(fs.existsSync(path.join(codeRoot, 'flight-tracker'))).toBe(true);
});
@@ -1324,7 +1287,7 @@ describe('TREK-version gating on install', () => {
REGISTRY.plugins[0].versions[0].sha256 = sha;
safeDownload.mockResolvedValue({ bytes: artifact, sha256: sha });
await expect(svc.install('flight-tracker')).resolves.toMatchObject({
trekRangeBypassed: { trekRange: null, hostVersion: '3.9.0', acceptedByAdmin: false },
trekRangeBypassed: { trekRange: null, hostVersion: '3.9.0' },
});
});
@@ -1335,15 +1298,13 @@ describe('TREK-version gating on install', () => {
);
expect(old).toMatchObject({
id: 'my-upload',
trekRangeBypassed: { trekRange: '>=3.0.0 <3.5.0', hostVersion: '3.9.0', acceptedByAdmin: false },
trekRangeBypassed: { trekRange: '>=3.0.0 <3.5.0', hostVersion: '3.9.0' },
});
fs.rmSync(old.stagingDir, { recursive: true, force: true });
const rangeless = svc.stageUpload(
makeArtifact({ id: 'my-upload', name: 'Up', version: '1.0.0', type: 'integration', trek: undefined }),
);
expect(rangeless).toMatchObject({
trekRangeBypassed: { trekRange: null, hostVersion: '3.9.0', acceptedByAdmin: false },
});
expect(rangeless).toMatchObject({ trekRangeBypassed: { trekRange: null, hostVersion: '3.9.0' } });
fs.rmSync(rangeless.stagingDir, { recursive: true, force: true });
const fits = svc.stageUpload(
makeArtifact({ id: 'my-upload', name: 'Up', version: '1.0.0', type: 'integration' }),
@@ -98,7 +98,6 @@ const UNNUMBERED = [
'Migration20200101046280_an_assistant_conversation_can_be_about_no_one_trip',
'Migration20200101046290_a_removed_member_cannot_rejoin_by_invite_link',
'Migration20200101046300_an_attached_file_stays_with_its_conversation',
'Migration20200101046310_an_admin_can_run_a_plugin_outside_its_trek_range',
];
// The last step the positional runner ever had; planLegacyBaseline refuses a
// schema_version past it.
@@ -1,79 +0,0 @@
/**
* AICL-001 to AICL-002: which chat client a resolved connection gets. An
* OpenAI reasoning model behind an API key takes its function tools only on the
* Responses API, so it goes there like a ChatGPT plan does (#2792).
*/
import { AiChatClientService, openAiWantsResponses } from '../../../../src/nest/ai-connections/ai-chat-client.service';
import { AiConnectionsModule } from '../../../../src/nest/ai-connections/ai-connections.module';
import type { ResolvedAiConnection } from '../../../../src/nest/ai-connections/ai-connections.types';
import { AnthropicMessagesClient } from '../../../../src/nest/ai-connections/providers/anthropic-messages.client';
import { OpenAiChatClient } from '../../../../src/nest/ai-connections/providers/openai-chat.client';
import { OpenAiResponsesClient } from '../../../../src/nest/ai-connections/providers/openai-responses.client';
import { AppConfigModule } from '../../../../src/nest/app-config/app-config.module';
import { DemoModule } from '../../../../src/nest/common/demo.module';
import { LlmLocalService } from '../../../../src/nest/llm-parse/llm-local.service';
import { OidcService } from '../../../../src/nest/oidc/oidc.service';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { createTestModule, type TestModule } from '../../../helpers/test-module';
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
const db = createSnapshotTestDb();
let t: TestModule;
beforeAll(async () => {
t = await createTestModule({
db,
imports: [AppConfigModule, DemoModule, AiConnectionsModule],
overrides: [
{ provide: LlmLocalService, useValue: {} },
{ provide: OidcService, useValue: {} },
],
});
});
afterAll(async () => {
await t.close();
db.close();
});
function connection(kind: ResolvedAiConnection['kind'], model: string): ResolvedAiConnection {
return {
id: 1,
scope: 'instance',
kind,
model,
baseUrl: kind === 'custom' ? 'http://ollama:11434/v1' : null,
host: 'host',
paidBy: 'instance',
status: 'ok',
credential: { type: 'api_key', apiKey: 'sk-test' },
};
}
describe('AiChatClientService', () => {
it('AICL-001: an OpenAI reasoning model on a key goes to the Responses API, an older one stays on Chat Completions', () => {
const clients = t.get(AiChatClientService);
const sol = clients.create(connection('openai', 'gpt-6.1-sol'));
expect(sol).toBeInstanceOf(OpenAiResponsesClient);
expect(sol.kind).toBe('openai');
expect(clients.create(connection('openai', 'gpt-4.1'))).toBeInstanceOf(OpenAiChatClient);
expect(clients.create(connection('anthropic', 'claude-sonnet-5-5'))).toBeInstanceOf(AnthropicMessagesClient);
expect(clients.create(connection('custom', 'gpt-6.1-sol'))).toBeInstanceOf(OpenAiChatClient);
const plan = clients.create({
...connection('chatgpt', 'gpt-6.1-sol'),
credential: { type: 'chatgpt', accessToken: 'at' },
});
expect(plan).toBeInstanceOf(OpenAiResponsesClient);
expect(plan.kind).toBe('chatgpt');
});
it('AICL-002: the reasoning lines are o-series, GPT-5 and later; their -chat variants and GPT-4 are not', () => {
for (const model of ['o3', 'o4-mini', 'gpt-5', 'gpt-5.6-sol', 'gpt-6.1-sol', 'gpt-6-sol']) {
expect(openAiWantsResponses(model), model).toBe(true);
}
for (const model of ['gpt-4.1', 'gpt-4o', 'gpt-4o-mini', 'gpt-5-chat-latest', 'omni-moderation-latest']) {
expect(openAiWantsResponses(model), model).toBe(false);
}
});
});
@@ -42,7 +42,6 @@ function services() {
writeSettings: vi.fn(async () => ({ policy: 'user' })),
instanceConnection: vi.fn(async () => ADMIN_CONNECTION),
saveInstance: vi.fn(async () => ({ connection: null, prefill: null })),
setInstanceModel: vi.fn(async () => ADMIN_CONNECTION),
removeInstance: vi.fn(async () => undefined),
listInstanceModels: vi.fn(async () => []),
},
@@ -188,7 +187,6 @@ describe('AiAdminController', () => {
'saveSettings',
'connection',
'saveConnection',
'setModel',
'removeConnection',
'models',
'startOpenrouter',
@@ -200,7 +198,6 @@ describe('AiAdminController', () => {
{ method: RequestMethod.PUT, path: 'settings', httpCode: undefined },
{ method: RequestMethod.GET, path: 'connection', httpCode: undefined },
{ method: RequestMethod.PUT, path: 'connection', httpCode: undefined },
{ method: RequestMethod.PATCH, path: 'connection/model', httpCode: undefined },
{ method: RequestMethod.DELETE, path: 'connection', httpCode: 200 },
{ method: RequestMethod.GET, path: 'models', httpCode: undefined },
{ method: RequestMethod.POST, path: 'connect/openrouter/start', httpCode: 200 },
@@ -228,9 +225,6 @@ describe('AiAdminController', () => {
baseUrl: 'http://ollama:11434/v1',
model: 'llama',
});
// A model picked for everyone, the only way to switch a shared ChatGPT plan's (#2783).
expect(await controller.setModel(admin, { model: 'gpt-6.1-sol-mini' })).toBe(ADMIN_CONNECTION);
expect(s.connections.setInstanceModel).toHaveBeenCalledWith(1, 'gpt-6.1-sol-mini');
expect(await controller.removeConnection(admin)).toEqual({ success: true });
expect(await controller.models(admin)).toEqual({ models: [] });
await controller.startOpenrouter(admin);
@@ -316,28 +316,6 @@ describe('the instance connection', () => {
expect(service().readsImages({ ...haiku, model: 'claude-sonnet' })).toBe(true);
});
it("AICS-019: a shared ChatGPT plan's model is switched on its own, to one the plan offers (#2783)", async () => {
const admin = await user();
expect((await refusal(service().setInstanceModel(admin, 'claude-haiku'))).status).toBe(404);
await orm().em.fork().insert(AiConnections, { scope: 'instance', kind: 'chatgpt', model: 'claude-sonnet' });
audit.writeAudit.mockClear();
const saved = await service().setInstanceModel(admin, 'claude-haiku');
expect(catalog.list).toHaveBeenLastCalledWith({ kind: 'chatgpt', baseUrl: null, secret: 'chatgpt-access' });
expect(saved.connection).toMatchObject({ kind: 'chatgpt', model: 'claude-haiku' });
expect(audit.writeAudit).toHaveBeenCalledWith({
userId: admin,
action: 'ai.connection.saved',
details: { scope: 'instance', kind: 'chatgpt', model: 'claude-haiku' },
});
expect(await refusal(service().setInstanceModel(admin, 'nope'))).toMatchObject({
status: 422,
body: { code: 'unknown_model' },
});
expect((await service().instanceConnection()).connection?.model).toBe('claude-haiku');
await service().removeInstance(admin);
});
it('AICS-014: settings are read with their defaults and written back', async () => {
const admin = await user();
expect(await service().readSettings()).toEqual({
@@ -295,79 +295,6 @@ describe('AnthropicMessagesClient', () => {
expect(err).not.toBeInstanceOf(AiProviderError);
expect((err as Error).name).toBe('AbortError');
});
it('ANTH-008: an answer that thought is replayed with its thinking blocks as they came, never marked for the cache (#2789)', async () => {
const thinking = { type: 'thinking', thinking: '', signature: 'sig-a1b2' };
const call = { type: 'tool_use', id: 'toolu_02', name: 'list_accommodations', input: {} };
const http = fetchAnswering(
streamResponse([
{ type: 'message_start', message: { usage: { input_tokens: 5, output_tokens: 1 } } },
{ type: 'content_block_start', index: 0, content_block: { type: 'thinking', thinking: '', signature: '' } },
{ type: 'content_block_delta', index: 0, delta: { type: 'thinking_delta', thinking: '' } },
{ type: 'content_block_delta', index: 0, delta: { type: 'signature_delta', signature: 'sig-a1b2' } },
{ type: 'content_block_stop', index: 0 },
{
type: 'content_block_start',
index: 1,
content_block: { type: 'tool_use', id: 'toolu_02', name: 'list_accommodations' },
},
{ type: 'content_block_delta', index: 1, delta: { type: 'input_json_delta', partial_json: '{}' } },
{ type: 'content_block_stop', index: 1 },
{ type: 'message_delta', delta: { stop_reason: 'tool_use' }, usage: { output_tokens: 30 } },
{ type: 'message_stop' },
]),
);
const events = await run(
new AnthropicMessagesClient('claude-sonnet-5-5', 'k', http.fetcher).stream(REQUEST, signal()),
);
// The thinking says nothing on screen; the call and the blocks to replay come back.
expect(events.filter((e) => e.type === 'text-delta')).toEqual([]);
expect(events).toContainEqual({
type: 'provider-state',
state: { adapter: 'anthropic-messages', blocks: [thinking, call] },
});
const next = toAnthropicMessages([
{ role: 'user', text: 'Where are we staying?' },
{
role: 'assistant',
text: '',
toolCalls: [{ id: 'toolu_02', name: 'list_accommodations', args: {} }],
providerState: { adapter: 'anthropic-messages', blocks: [thinking, call] },
},
{ role: 'tool', toolCallId: 'toolu_02', name: 'list_accommodations', output: '[]' },
{ role: 'user', text: 'And in Kyoto?' },
]);
expect(next[1]).toEqual({ role: 'assistant', content: [thinking, call] });
markHistoryForCache(next, 2);
expect(next[1]?.content[0]).toEqual(thinking);
// An answer that ended on a thinking block: the mark before the question skips it.
const ended = toAnthropicMessages([
{ role: 'user', text: 'Hi' },
{
role: 'assistant',
text: '',
toolCalls: [],
providerState: { adapter: 'anthropic-messages', blocks: [thinking] },
},
{ role: 'user', text: 'Still there?' },
]);
markHistoryForCache(ended, 2);
expect(ended[1]?.content[0]).toEqual(thinking);
expect(ended[0]?.content[0]?.cache_control).toEqual({ type: 'ephemeral' });
// The request is marked, the stored answer is not: a mark left on it would go out on every later step.
const stored = { adapter: 'anthropic-messages' as const, blocks: [{ ...thinking }, { ...call }] };
const marked = toAnthropicMessages([
{ role: 'user', text: 'Hi' },
{ role: 'assistant', text: '', toolCalls: [], providerState: stored },
{ role: 'user', text: 'Go on' },
]);
markHistoryForCache(marked, 2);
expect(marked[1]?.content[1]?.cache_control).toEqual({ type: 'ephemeral' });
expect(stored.blocks[1]).not.toHaveProperty('cache_control');
});
});
describe('OpenAiChatClient', () => {
@@ -616,18 +543,6 @@ describe('OpenAiResponsesClient', () => {
expect(
await failure(new OpenAiResponsesClient('m', tokens('a', 'b'), twice.fetcher).stream(REQUEST, signal())),
).toMatchObject({ code: 'needs_reauth' });
// An API key has nothing to refresh: one request, and the refusal names the key (#2792).
const keyed = fetchAnswering(jsonResponse(401, {}), streamResponse(STREAM));
const key = tokens('sk-key');
const refused = await failure(
new OpenAiResponsesClient('gpt-6.1-sol', key, keyed.fetcher, 'openai').stream(REQUEST, signal()),
);
expect(refused).toMatchObject({ code: 'invalid_key' });
expect(key).toHaveBeenCalledTimes(1);
expect(keyed.calls).toHaveLength(1);
expect(keyed.calls[0]?.url).toBe('https://api.openai.com/v1/responses');
expect(keyed.calls[0]?.init.headers).toMatchObject({ authorization: 'Bearer sk-key' });
});
it('OARS-005: a used-up plan, a failed response and a stream without completion are provider errors', async () => {
@@ -231,12 +231,6 @@ describe('the turn context', () => {
expect(languageName('!!')).toBe('!!');
});
it('ASTCTX-033: reads TREK language codes as their language, not as the BCP 47 tag they spell', () => {
expect(languageName('br')).toBe('Brazilian Portuguese');
expect(languageName('gr')).toBe('Greek');
expect(languageName('pt-BR')).toBe('Brazilian Portuguese');
});
it('ASTCTX-022: carries the date, the units the user prefers and the card', () => {
const card = buildTripCard(1, 7, SUMMARY, PLACES, null);
const context = turnContext(card, 'Asia/Tokyo', new Date('2026-06-11T23:30:00Z'), {
@@ -69,7 +69,6 @@ describe('dayLabel', () => {
expect(dayLabel(ctx, 99)).toBe('#99');
expect(dayLabel({ ...ctx, locale: 'de' }, 32)).toBe('Fr., 12. Juni');
expect(dayLabel({ ...ctx, locale: 'not a locale!' }, 32)).toBe('Fri, Jun 12');
expect(dayLabel({ ...ctx, locale: 'br' }, 32)).toBe(dayLabel({ ...ctx, locale: 'pt-BR' }, 32));
});
});
+2 -15
View File
@@ -126,32 +126,19 @@ describe('WandererClient', () => {
expect(searchBody(0).options.filter).toEqual(["author IN ['nspsn7zu7octact']"]);
});
it('RS-03b: an owner with one actor, which wanderer expands as an object rather than a list, is found', async () => {
answer({
...OWNER,
'/api/v1/user/gixauk8ukjpqabm': reply({
expand: { activitypub_actors_via_user: { id: 'nspsn7zu7octact', is_local: true } },
}),
});
await expect(client.ownActors(CREDS)).resolves.toEqual(['nspsn7zu7octact']);
});
it('RS-03: a token wanderer reads as anonymous is refused, however 200 the answer', async () => {
answer({ '/api/v1/api-token': reply({ items: [], totalItems: 0 }) });
expect((await failure(() => client.check(CREDS))).code).toBe('unauthorized');
});
it('RS-03: an owner without a local author is told as such; an odd id is an answer TREK does not trust', async () => {
it('RS-03: an owner without a local author, or with an odd id, is an answer TREK does not trust', async () => {
answer({
...OWNER,
'/api/v1/user/gixauk8ukjpqabm': reply({
expand: { activitypub_actors_via_user: [{ id: 'remote1', is_local: false }] },
}),
});
// wanderer did answer, so the reason is the missing author, not an answer from somewhere else.
expect((await failure(() => client.ownActors(CREDS))).code).toBe('no_author');
answer({ ...OWNER, '/api/v1/user/gixauk8ukjpqabm': reply({}) });
expect((await failure(() => client.ownActors(CREDS))).code).toBe('no_author');
expect((await failure(() => client.ownActors(CREDS))).code).toBe('invalid_response');
answer({ '/api/v1/api-token': reply({ items: [{ user: 'Not-An-Id!' }] }) });
expect((await failure(() => client.ownActors(CREDS))).code).toBe('invalid_response');
@@ -15,11 +15,6 @@ import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vites
const { checkSsrf } = vi.hoisted(() => ({ checkSsrf: vi.fn() }));
vi.mock('../../../src/utils/ssrfGuard', () => ({ checkSsrf, safeFetch: vi.fn() }));
const { logWarn } = vi.hoisted(() => ({ logWarn: vi.fn() }));
vi.mock('../../../src/nest/audit/audit-log.logger', async (importOriginal) => ({
...(await importOriginal<typeof import('../../../src/nest/audit/audit-log.logger')>()),
logWarn,
}));
const PUBLIC = { allowed: true, isPrivate: false };
const PRIVATE = { allowed: false, isPrivate: true, resolvedIp: '192.168.1.5', error: 'private' };
@@ -381,23 +376,6 @@ describe('WandererService reads for an import', () => {
expect((await refusal(failing.service.findTrail(1, 'trail1'))).getStatus()).toBe(404);
});
it('WAND-SVC-018b: the log gets the reason an answer was not understood, which the client is not shown', async () => {
const { service, client } = setup(savedRow());
logWarn.mockClear();
client.ownActors.mockRejectedValueOnce(
new WandererError(
'invalid_response',
'wanderer answered with something TREK does not understand',
'hits.0.difficulty: expected number, received string',
),
);
expect((await refusal(service.search(1, { q: '', page: 1 }))).getStatus()).toBe(502);
expect(logWarn).toHaveBeenCalledWith(
'[wanderer] invalid_response: wanderer answered with something TREK does not understand' +
' (hits.0.difficulty: expected number, received string)',
);
});
it('WAND-SVC-019: a failure that is not wanderer answering is rethrown as it is', async () => {
const { service, client } = setup(savedRow());
client.trail.mockRejectedValueOnce(new TypeError('bug'));
+3 -37
View File
@@ -6,7 +6,6 @@ import {
hostSatisfies,
trekRangeBypassed,
bypassedRange,
acceptanceHolds,
__resetHostWarningForTests,
} from '../../../src/nest/plugins/install/host-compat';
@@ -126,27 +125,6 @@ describe('hostSatisfies', () => {
* the truth (hostSatisfies) never changes — the UI still has to say the plugin is
* outside its range.
*/
describe('acceptanceHolds', () => {
it('holds for the same plugin version on the same TREK major only', () => {
process.env.APP_VERSION = '5.0.1';
const given = { acceptedVersion: '1.0.3', acceptedHost: '5.0.0' };
expect(acceptanceHolds('1.0.3', given)).toBe(true);
expect(acceptanceHolds('1.1.0', given)).toBe(false); // an update asks again
process.env.APP_VERSION = '6.0.0';
expect(acceptanceHolds('1.0.3', given)).toBe(false); // so does a new TREK major
});
it('holds nothing without a full consent or a version to compare', () => {
process.env.APP_VERSION = '5.0.0';
expect(acceptanceHolds('1.0.0', null)).toBe(false);
expect(acceptanceHolds('1.0.0', { acceptedVersion: '1.0.0', acceptedHost: null })).toBe(false);
expect(acceptanceHolds(null, { acceptedVersion: '1.0.0', acceptedHost: '5.0.0' })).toBe(false);
expect(acceptanceHolds('1.0.0', { acceptedVersion: '1.0.0', acceptedHost: 'not-a-version' })).toBe(false);
process.env.APP_VERSION = 'dev';
expect(acceptanceHolds('1.0.0', { acceptedVersion: '1.0.0', acceptedHost: '5.0.0' })).toBe(false);
});
});
describe('range bypass (TREK_PLUGINS_IGNORE_TREK_RANGE)', () => {
it('is off by default and only an explicit truthy value turns it on', () => {
expect(trekRangeBypassed()).toBe(false);
@@ -160,27 +138,15 @@ describe('range bypass (TREK_PLUGINS_IGNORE_TREK_RANGE)', () => {
process.env.APP_VERSION = '3.3.0';
expect(bypassedRange('>=4.0.0')).toBeNull(); // off → the gate refuses, nothing to report
process.env.TREK_PLUGINS_IGNORE_TREK_RANGE = 'true';
expect(bypassedRange('>=4.0.0')).toEqual({ trekRange: '>=4.0.0', hostVersion: '3.3.0', acceptedByAdmin: false });
expect(bypassedRange('>=4.0.0')).toEqual({ trekRange: '>=4.0.0', hostVersion: '3.3.0' });
expect(bypassedRange('>=3.2.0 <4.0.0')).toBeNull(); // fits → not a bypass, a normal install
});
it('covers a plugin that declared no range at all — the same author oversight', () => {
process.env.APP_VERSION = '3.3.0';
process.env.TREK_PLUGINS_IGNORE_TREK_RANGE = '1';
expect(bypassedRange(null)).toEqual({ trekRange: null, hostVersion: '3.3.0', acceptedByAdmin: false });
expect(bypassedRange(undefined)).toEqual({ trekRange: null, hostVersion: '3.3.0', acceptedByAdmin: false });
});
it("an admin's consent for one plugin lets it through without the switch, and says it was theirs", () => {
process.env.APP_VERSION = '5.0.0';
expect(bypassedRange('>=3.2.0 <4.0.0', true)).toEqual({
trekRange: '>=3.2.0 <4.0.0',
hostVersion: '5.0.0',
acceptedByAdmin: true,
});
expect(bypassedRange('>=5.0.0', true)).toBeNull(); // fits: nothing was set aside
process.env.TREK_PLUGINS_IGNORE_TREK_RANGE = '1';
expect(bypassedRange('>=3.2.0 <4.0.0', true)).toMatchObject({ acceptedByAdmin: false });
expect(bypassedRange(null)).toEqual({ trekRange: null, hostVersion: '3.3.0' });
expect(bypassedRange(undefined)).toEqual({ trekRange: null, hostVersion: '3.3.0' });
});
it('leaves hostSatisfies telling the truth while bypassed', () => {
@@ -145,7 +145,7 @@ async function installFixturePlugin(opts: { settings: Array<Record<string, unkno
name: 'Fixture',
version: '1.0.0',
type: 'integration',
trek: '>=4.0.0 <6.0.0',
trek: '>=4.0.0 <5.0.0',
settings: opts.settings,
}),
);
@@ -134,32 +134,10 @@ describe('PluginsService.list', () => {
expect(out.ignoreTrekRange).toBe(true);
expect(out.plugins[0]).toMatchObject({
dependencyStatus: 'ok',
trekRangeBypassed: { trekRange: '>=3.0.0 <4.0.0', hostVersion: '4.1.0', acceptedByAdmin: false },
trekRangeBypassed: { trekRange: '>=3.0.0 <4.0.0', hostVersion: '4.1.0' },
});
});
it("an admin's consent for this version lets the outgrown plugin activate and names it as theirs", async () => {
process.env.APP_VERSION = '4.1.0';
await insertRow(orm, Plugins, {
id: 'old',
name: 'Old',
type: 'widget',
status: 'inactive',
version: '1.0.0',
trek_range: '>=3.0.0 <4.0.0',
trek_range_accepted_version: '1.0.0',
trek_range_accepted_host: '4.0.0',
});
const out = await (await makeService()).list();
expect(out.ignoreTrekRange).toBe(false);
expect(out.plugins[0]).toMatchObject({
dependencyStatus: 'ok',
trekRangeBypassed: { trekRange: '>=3.0.0 <4.0.0', hostVersion: '4.1.0', acceptedByAdmin: true },
});
// The consent stays on the server: the list does not hand its columns out.
expect(out.plugins[0]).not.toHaveProperty('trek_range_accepted_version');
});
it('a plugin inside its range carries no marker even with the switch on', async () => {
process.env.APP_VERSION = '3.5.0';
process.env.TREK_PLUGINS_IGNORE_TREK_RANGE = '1';
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@trek/shared",
"version": "5.0.0",
"version": "4.3.4",
"engines": {
"node": "^22.22.2 || ^24.15.0 || >=26.0.0"
},

Some files were not shown because too many files have changed in this diff Show More