Compare commits

...

20 Commits

Author SHA1 Message Date
Maurice d589da59f2 fix(wanderer): find the author of an account whose one actor wanderer expands as an object
PocketBase answers a back-relation with a single record as the object itself,
not a list, so the user lookup failed as an answer TREK did not understand and
every search with it.

Closes #2799
2026-10-26 01:03:35 +01:00
Allan Braun 69ff295184 fix(assistant): answer Brazilian Portuguese users in Portuguese, not Breton
TREK's code for Brazilian Portuguese is 'br', which Intl reads as Breton.
The assistant passed it straight to Intl.DisplayNames for the system
prompt's answer language and to the card formatters, so the model was told
to answer in Breton. Convert TREK codes to their BCP-47 tag with
getIntlLanguage before handing them to Intl.

Closes #2800
2026-10-26 00:04:56 +01:00
Maurice d07c17ded6 fix(assistant): finish an OpenRouter sign-in whose code came back after a second question mark
The return address already carries a query, so a code appended with ? instead
of & ended up inside the ai marker and the page did nothing, without a word.
2026-10-25 19:36:00 +01:00
Maurice 44509723fd fix(bookings): keep the review's map status within the complexity and strict-null budgets
The status hides itself for a stay linked to a trip place instead of each form
branching around it, and a lookup takes a missing name.
2026-10-25 18:59:55 +01:00
Maurice b80fdf27f2 fix(bookings): show where an imported stay lands on the map before it is saved
An imported hotel was looked up once, by its name and its address together.
A booking site's romanized address (Agoda for a stay in Japan) often matches
nothing and sank the hotel's name with it, so the place was created without
coordinates and silently never showed on the map.

The review now finds the stay right away (name and address, then the name,
then the address) and says under the address whether it is on the map and
where, or that it is not yet, with a way to search again. Picking an address
suggestion sets the spot by hand. The save uses that spot, falls back the same
way when there is none, and a stay saved without a spot says so in a toast.
Desktop dialog and phone sheet share the lookup through useReservationForm.
2026-10-25 18:59:55 +01:00
Maurice a0b7b4d196 chore(lint): lower the complexity baseline the route store move took down 2026-10-25 18:59:49 +01:00
Maurice aa24a9eff7 fix(map): keep routed roads on the device so a whole-trip route opens drawn
With "Show whole trip" on, every leg of every day went to the router one at a
time, a second apart, and the route cache lived in memory only, so each visit
started over: a trip of a month took 30 to 45 seconds before its route was
drawn, on every open.

Routes the router answered are now also kept on the device (Dexie v14,
routeCache by RouteCalculator's cache key, a month at most, the oldest give way
past 3000). A leg found there needs no request and no pause, so a trip whose
legs did not change opens with its roads at once; only new or changed legs are
routed. Plugin routes stay in memory only, since they depend on trip and day.
The cache moves out of RouteCalculator into routeStore.ts.

Closes #2794
2026-10-25 18:59:49 +01:00
Maurice de5417f9f0 style(i18n): wrap the wanderer no_author line in the CJK locales 2026-10-25 18:59:43 +01:00
Maurice a48dd7645f fix(wanderer): say so when wanderer names no author for the token's account
A token whose account has no local ActivityPub author was reported as
invalid_response, which the settings show as 'The answer did not come from
wanderer', although wanderer had answered fine. It now has its own code,
no_author, with a message in every language that says what is missing.
2026-10-25 18:59:43 +01:00
Maurice 217a576e16 fix(wanderer): log why an answer from wanderer was not understood
A failed wanderer call kept its reason in WandererError.detail (the field that
did not match, or what came instead of JSON), and the client comment said it
stays in the log, but nothing wrote it anywhere. The log only had the generic
'wanderer answered with something TREK does not understand', so neither an
admin nor we could tell what wanderer had sent. Every refusal now logs its
code, message and detail.
2026-10-25 18:59:43 +01:00
Maurice f6976d5cec fix(assistant): send OpenAI reasoning models on an API key to the Responses API
gpt-5.6-sol, gpt-6.1-sol and the other reasoning models refuse function tools
on Chat Completions, so every assistant message on such a model came back as
HTTP 400. An OpenAI connection whose model is from the o-series or GPT-5 and
later now goes through the Responses API, the client a ChatGPT plan already
uses, with the key as its bearer token and no token refresh on a 401. Older
models and the -chat variants stay on Chat Completions.

Closes #2792
2026-10-25 16:55:39 +01:00
Maurice c1c2bbf146 fix(assistant): replay an Anthropic answer that thought with its thinking blocks
Sonnet 5.5 and Opus 5.5 think by default and write what they say between tool
calls into thinking blocks, which they want back unchanged with the rest of
the turn. The client dropped those blocks (and their signatures) and rebuilt
the turn from its text and calls, so after a tool result the next step came
back empty and the assistant gave up with empty_answer. A turn that thought
is now replayed block by block like one that searched the web; the cache mark
before the question skips a thinking block, and replayed blocks are copies so
a mark never sticks to the stored answer.

Closes #2789
2026-10-25 16:49:46 +01:00
Maurice c05349f7c4 fix(docker): let dumb-init forward the stop signal in the shipped compose file
The compose file drops every capability and adds back CHOWN, SETUID and
SETGID. dumb-init runs as root and node as the node user, and signalling a
process of another user needs KILL, so docker stop never reached node and
always ended in SIGKILL (exit 137). KILL only reaches processes inside the
container's own PID namespace. CI starts the image with the same set and now
checks that docker stop exits 0 after a logged SIGTERM.

Closes #2790
2026-10-25 16:47:22 +01:00
Maurice a5342df648 fix(assistant): list the admin model switch among the routes a managed install withholds
The boot check pins every @ManagedForbidden route; the new
AiAdminController.setModel was missing, so the server refused to start.
2026-10-25 16:29:31 +01:00
Maurice f44b143371 fix(assistant): send a pasted ChatGPT callback once, and only for this sign-in
The server takes a sign-in only once. The clipboard read on return and a paste
of one's own could send the same address twice within one render, and an
address left over from an earlier attempt used up the one in progress, so the
real address came back as 'took too long'.
2026-10-25 16:29:31 +01:00
Maurice d911122a37 fix(assistant): let an admin switch the model of a shared ChatGPT plan
The model picker in Admin > Addons did nothing for a ChatGPT connection: the
only way to change the instance's model was saving the connection again, which
needs an API key a plan does not have. A PATCH /api/admin/ai/connection/model
now switches it on its own, to a model the provider offers.

Closes #2783
2026-10-25 16:29:31 +01:00
Maurice a69eee191c test(plugins): let the instance-settings fixture run on TREK 5
The fixture plugin declared trek >=4.0.0 <5.0.0, so since the version bump to
5.0.0 the host refuses to spawn it and INS-012 fails on dev.
2026-10-25 15:59:59 +01:00
Maurice 90f31d3f07 fix(assistant): give the phone home chat its own m-root so it is not see-through
The home chat outside a trip mounts beside MobileShell, so none of the --m-*
tokens it paints with resolved and the dashboard showed through the chat.
2026-10-25 15:59:59 +01:00
Maurice d4da05bbc9 docs(readme): name the container and allow plain-HTTP login in the quickstart
docker logs trek found nothing because the run command gave no --name, and
over plain HTTP the browser dropped the Secure session cookie, so the printed
admin login did not stick.
2026-10-25 15:41:45 +01:00
github-actions[bot] bd1de9e1d5 chore: bump version to 5.0.0 [skip ci] 2026-10-25 11:07:55 +00:00
121 changed files with 1567 additions and 134 deletions
+12 -1
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-drop ALL --cap-add CHOWN --cap-add SETUID --cap-add SETGID --cap-add KILL \
-v "$RUNNER_TEMP/trek/data:/app/data" \
-v "$RUNNER_TEMP/trek/uploads:/app/uploads" \
-e ENCRYPTION_KEY="$(openssl rand -hex 32)" \
@@ -1194,6 +1194,17 @@ 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
+5 -2
View File
@@ -234,12 +234,15 @@ the details.
## Get started in 30 seconds
```bash
ENCRYPTION_KEY=$(openssl rand -hex 32) docker run -d -p 3000:3000 \
ENCRYPTION_KEY=$(openssl rand -hex 32) docker run -d --name trek -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`. 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`).
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.
<div align="center">
+2 -2
View File
@@ -1,5 +1,5 @@
apiVersion: v2
name: trek
version: 4.3.4
version: 5.0.0
description: Minimal Helm chart for TREK app
appVersion: "4.3.4"
appVersion: "5.0.0"
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@trek/client",
"version": "4.3.4",
"version": "5.0.0",
"engines": {
"node": "^22.22.2 || ^24.15.0 || >=26.0.0"
},
+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": 221,
"complexity": 220,
"@typescript-eslint/no-explicit-any": 146,
"trek/no-swallowed-catch": 130,
"max-params": 32,
-1
View File
@@ -150,7 +150,6 @@
"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
@@ -8,7 +8,7 @@
"src/components/Map/MapView.tsx": 1385,
"src/components/Map/MapViewGL.test.tsx": 2919,
"src/components/Map/MapViewGL.tsx": 2290,
"src/components/Map/RouteCalculator.ts": 1076,
"src/components/Map/RouteCalculator.ts": 1063,
"src/components/PDF/TripPDF.tsx": 1082,
"src/components/Planner/DayDetailPanel.test.tsx": 2333,
"src/components/Planner/DayPlanSidebar.test.tsx": 5349,
+2
View File
@@ -229,6 +229,8 @@ 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,5 +1,6 @@
import { useState } from 'react';
import { useSearchParams } from 'react-router';
import { openrouterReturnCode } from '../../Settings/ai/aiConnectModel';
import type { Addon } from './addonModel';
import { usesConnection } from './aiAddons';
@@ -11,7 +12,7 @@ import { usesConnection } from './aiAddons';
*/
export function useAiAddonTile(aiAddons: Addon[]) {
const [params] = useSearchParams();
const [open, setOpen] = useState(() => params.get('ai') === 'openrouter');
const [open, setOpen] = useState(() => openrouterReturnCode(params) !== undefined);
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-007: the AI assistant's settings and connection for everyone.
// FE-HOOK-AI-ADMIN-001 to FE-HOOK-AI-ADMIN-008: 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,6 +16,7 @@ const repo = vi.hoisted(() => ({
saveAdminSettings: vi.fn(),
adminConnection: vi.fn(),
saveAdminConnection: vi.fn(),
setAdminModel: vi.fn(),
removeAdminConnection: vi.fn(),
adminModels: vi.fn(),
}));
@@ -157,6 +158,29 @@ 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,9 +124,16 @@ function useInstanceConnection(onChanged: () => void) {
}
};
/** Another model on the same connection: the stored key is kept by sending the mask in its place. */
/**
* 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).
*/
const setModel = (model: string) => {
if (!live || live.kind === 'chatgpt') return;
if (!live) return;
if (live.kind === 'chatgpt') {
void act(() => aiConnectionsRepo.setAdminModel(model), 'common.saved');
return;
}
const request: AiInstanceConnectionRequest =
live.kind === 'custom'
? { kind: 'custom', baseUrl: live.baseUrl ?? '', model, ...(live.hint ? { apiKey: MASKED_SETTING_VALUE } : {}) }
@@ -426,6 +426,23 @@ 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()
+7 -20
View File
@@ -4,6 +4,7 @@ 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'
@@ -196,10 +197,6 @@ 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
@@ -540,7 +537,10 @@ export async function calculateRouteWithLegs(
const avoidScope = avoiding.length ? `:avoid=${avoiding.join(',')}` : ''
const plainKey = `${profile}:${getDistanceUnit()}:${coords}${pluginScope}`
const cacheKey = `${plainKey}${avoidScope}`
const cached = routeCache.get(cacheKey)
// 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)
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 = routeCache.get(plainKey) ?? await osrmWithLegs(waypoints, coords, profile, signal)
const plain = (await storedRoute(plainKey)) ?? await osrmWithLegs(waypoints, coords, profile, signal)
cacheRoute(plainKey, plain)
return { ...plain, avoidance: { asked: avoiding, achieved: [], fellBack: true } }
}
@@ -591,11 +591,7 @@ export async function calculateRouteWithLegs(
legs,
...(route.viaPoints.length ? { vias: route.viaPoints } : {}),
}
routeCache.set(cacheKey, result)
if (routeCache.size > ROUTE_CACHE_MAX) {
const oldest = routeCache.keys().next().value
if (oldest !== undefined) routeCache.delete(oldest)
}
rememberRoute(cacheKey, result)
return result
}
@@ -638,15 +634,6 @@ 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
@@ -0,0 +1,41 @@
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,19 +5,22 @@ 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 }: Props) {
export default function AddressInput({ value, onChange, placeholder, className, onPick }: Props) {
const { locale } = useTranslation()
const placeLang = usePlaceLanguage()
// Ohne Reisekontext ist der Hinweis leer, und die Suche laeuft wie bisher.
@@ -60,6 +63,9 @@ 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,6 +29,7 @@ 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',
@@ -81,7 +82,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, saveData: buildSaveData,
pickPlace, pickHotelPlace, pickHotelStart, pickHotelEnd, stayPin, saveData: buildSaveData,
} = useReservationForm(EMPTY_FORM, days, places)
const attach = useBookingFileAttach({ reservation, files, onFileUpload, setPendingFiles, toast, t })
@@ -102,17 +103,22 @@ 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: matchPlaceId(prefill._venue?.name || prefill.title),
hotel_place_id: hotelPlaceId,
})
// 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 {
@@ -362,8 +368,14 @@ 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)}
/>
</>
)}
@@ -0,0 +1,54 @@
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);
});
});
@@ -0,0 +1,62 @@
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,6 +287,8 @@ 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 };
@@ -344,7 +346,11 @@ 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 }
? {
name: form.title,
address: form.hotel_address || null,
...(opts.venuePin ? { lat: opts.venuePin.lat, lng: opts.venuePin.lng } : {}),
}
: 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,6 +19,7 @@ import {
withStartDate,
withStartTime,
} from './reservationFormModel';
import { useStayPin } from './useStayPin';
/**
* The booking form behind the desktop ReservationModal and the phone's booking
@@ -39,6 +40,8 @@ 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.
@@ -71,6 +74,7 @@ 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)),
saveData: (opts: ReservationSaveOptions) => reservationSaveData(form, opts),
stayPin,
saveData: (opts: ReservationSaveOptions) => reservationSaveData(form, { ...opts, venuePin: stayPin.match }),
};
}
@@ -0,0 +1,74 @@
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();
});
});
@@ -0,0 +1,69 @@
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-007: the pure rules behind connecting an AI provider.
// FE-AI-CONNECT-MODEL-001 to FE-AI-CONNECT-MODEL-008: 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,6 +6,7 @@ import {
connectErrorKey,
httpHostOf,
isPublicHttpsUrl,
openrouterReturnCode,
refusalCode,
rememberOpenrouterFlow,
repairModeOf,
@@ -93,4 +94,14 @@ 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,6 +56,26 @@ 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';
@@ -79,6 +99,21 @@ 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-013: pasting a key, an own server, the ChatGPT sign-in and the OpenRouter return.
// 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.
import { act, fireEvent, renderHook, waitFor } from '@testing-library/react';
import { createElement, type ReactNode } from 'react';
import { MemoryRouter, useLocation } from 'react-router';
@@ -249,6 +249,52 @@ 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', () => {
@@ -280,4 +326,19 @@ 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,7 +5,15 @@ import { useTranslation } from '../../../i18n';
import { aiConnectionsRepo } from '../../../repo/aiConnectionsRepo';
import { detectKeyKind, isChatgptCallback, providerLabel } from '../../Assistant/providerCatalog';
import { useToast } from '../../shared/Toast';
import { connectErrorKey, httpHostOf, refusalCode, rememberOpenrouterFlow, takeOpenrouterFlow } from './aiConnectModel';
import {
callbackMatchesFlow,
connectErrorKey,
httpHostOf,
openrouterReturnCode,
refusalCode,
rememberOpenrouterFlow,
takeOpenrouterFlow,
} from './aiConnectModel';
/**
* The ways to connect a provider, one hook each, behind `AiConnectPanel`: a
@@ -205,6 +213,10 @@ 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;
@@ -232,8 +244,8 @@ export function useChatgptConnect({
const finish = async (raw: string) => {
const url = raw.trim();
if (!flow || busy) return;
if (!isChatgptCallback(url)) {
if (!flow || finishing.current) return;
if (!isChatgptCallback(url) || !callbackMatchesFlow(url, flow.authorizeUrl)) {
setError({ messageKey: 'assistant.connect.chatgptWrong', code: 'wrong_url' });
return;
}
@@ -242,6 +254,7 @@ export function useChatgptConnect({
restart();
return;
}
finishing.current = true;
setBusy(true);
setError(null);
try {
@@ -253,6 +266,7 @@ export function useChatgptConnect({
setError({ messageKey: connectErrorKey(err), code });
if (code === 'expired') restart();
} finally {
finishing.current = false;
setBusy(false);
}
};
@@ -280,10 +294,12 @@ 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 (!paste(text)) focusField();
if (flow && !callbackMatchesFlow(text, flow.authorizeUrl)) focusField();
else if (!paste(text)) focusField();
}, focusField);
});
@@ -351,9 +367,9 @@ export function useOpenrouterReturn(onConnected: () => void) {
});
useEffect(() => {
if (handled.current || params.get('ai') !== 'openrouter') return;
const code = openrouterReturnCode(params);
if (handled.current || code === undefined) return;
handled.current = true;
const code = params.get('code');
setParams(
(prev) => {
const next = new URLSearchParams(prev);
+19
View File
@@ -70,6 +70,19 @@ 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
@@ -279,6 +292,7 @@ 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);
@@ -366,6 +380,11 @@ 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' });
}
}
@@ -50,13 +50,17 @@ 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 (
<AssistantScreen
tripId={chat.id}
tripTitle={chat.title}
hidden={false}
hops={hops}
onOpenTripChat={journal ? undefined : home.openTripChat}
/>
<div className="m-root">
<AssistantScreen
tripId={chat.id}
tripTitle={chat.title}
hidden={false}
hops={hops}
onOpenTripChat={journal ? undefined : home.openTripChat}
/>
</div>
);
}
@@ -15,6 +15,7 @@ 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'
@@ -60,7 +61,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, saveData: buildSaveData,
pickPlace, pickHotelPlace, pickHotelStart, pickHotelEnd, stayPin, saveData: buildSaveData,
} = useReservationForm(EMPTY, days, places)
const assignmentOptions = useMemo(
() => buildAssignmentOptions(days, assignments, t, locale),
@@ -85,6 +86,7 @@ export default function MReservationSheet({ planner, onOpenExpense }: MReservati
expense.reset()
setPendingFiles([])
setTravelerIds(travelerIdsOf(editingReservation))
stayPin.reset()
const res = editingReservation
if (res) {
@@ -93,6 +95,8 @@ 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
@@ -335,6 +339,13 @@ 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 }; address?: string }
type ImportedStay = { place_id?: number; venue?: { name?: string; address?: string | null; lat?: number; lng?: number }; address?: string }
const toast = { success: vi.fn(), error: vi.fn(), warning: vi.fn(), info: vi.fn() }
const t = ((key: string) => key) as Translate
@@ -231,6 +231,32 @@ 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()
+25 -18
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,7 +63,10 @@ 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) {
acc.place_id = (await resolveImportedPlace(acc.venue)) ?? undefined
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'))
delete acc.venue
}
// A hotel's address lives on the linked place. Write an edited address
@@ -141,9 +144,13 @@ export function useBookingEdits(options: BookingEditsOptions) {
}
// ── Review-before-save booking import ───────────────────────────────────────
// 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> => {
// 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> => {
const name = (venue.name || '').trim()
const n = name.toLowerCase()
if (n) {
@@ -153,23 +160,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 existing.id
if (existing && (existing.id > 0 || isEffectivelyOffline())) return { id: existing.id, placed: existing.lat != null && existing.lng != null }
}
let lat: number | null = null
let lng: number | null = null
let lat: number | null = venue.lat ?? null
let lng: number | null = venue.lng ?? null
let address: string | null = venue.address ?? null
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) {
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) {
lat = hit.lat; lng = hit.lng
if (!address && hit.address) address = hit.address
}
}
} catch { /* geocode failure is non-fatal: create the place without coords */ }
} catch { /* geocode failure is non-fatal: create the place without coords, and say so */ }
}
try {
// Through the store, not placesApi directly: the API answers { place },
// and reading .id off that wrapper linked nothing. Every save of the
@@ -178,7 +185,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()) ? place.id : null
return place && (place.id > 0 || isEffectivelyOffline()) ? { id: place.id, placed: lat != null && lng != null } : null
} catch { return null }
}
+5
View File
@@ -104,6 +104,11 @@ 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
@@ -0,0 +1,69 @@
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
@@ -0,0 +1,47 @@
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
@@ -0,0 +1,35 @@
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
@@ -0,0 +1,48 @@
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,6 +56,7 @@ 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)
@@ -136,6 +137,7 @@ 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));
@@ -344,6 +346,24 @@ 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-005
// FE-MOB-ASSIST-HOME-001 to FE-MOB-ASSIST-HOME-006
//
// 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,4 +141,9 @@ 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();
});
});
+4
View File
@@ -11,6 +11,10 @@ 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:
+51 -28
View File
@@ -1,12 +1,12 @@
{
"name": "@trek/root",
"version": "4.3.4",
"version": "5.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@trek/root",
"version": "4.3.4",
"version": "5.0.0",
"workspaces": [
"client",
"server",
@@ -29,7 +29,7 @@
},
"client": {
"name": "@trek/client",
"version": "4.3.4",
"version": "5.0.0",
"dependencies": {
"@assistant-ui/react": "0.15.25",
"@fontsource/abril-fatface": "^5.3.0",
@@ -9370,7 +9370,8 @@
"optional": true,
"os": [
"android"
]
],
"peer": true
},
"node_modules/@rollup/rollup-android-arm64": {
"version": "4.62.0",
@@ -9384,7 +9385,8 @@
"optional": true,
"os": [
"android"
]
],
"peer": true
},
"node_modules/@rollup/rollup-darwin-arm64": {
"version": "4.62.0",
@@ -9398,7 +9400,8 @@
"optional": true,
"os": [
"darwin"
]
],
"peer": true
},
"node_modules/@rollup/rollup-darwin-x64": {
"version": "4.62.0",
@@ -9412,7 +9415,8 @@
"optional": true,
"os": [
"darwin"
]
],
"peer": true
},
"node_modules/@rollup/rollup-freebsd-arm64": {
"version": "4.62.0",
@@ -9426,7 +9430,8 @@
"optional": true,
"os": [
"freebsd"
]
],
"peer": true
},
"node_modules/@rollup/rollup-freebsd-x64": {
"version": "4.62.0",
@@ -9440,7 +9445,8 @@
"optional": true,
"os": [
"freebsd"
]
],
"peer": true
},
"node_modules/@rollup/rollup-linux-arm-gnueabihf": {
"version": "4.62.0",
@@ -9454,7 +9460,8 @@
"optional": true,
"os": [
"linux"
]
],
"peer": true
},
"node_modules/@rollup/rollup-linux-arm-musleabihf": {
"version": "4.62.0",
@@ -9468,7 +9475,8 @@
"optional": true,
"os": [
"linux"
]
],
"peer": true
},
"node_modules/@rollup/rollup-linux-arm64-gnu": {
"version": "4.62.0",
@@ -9482,7 +9490,8 @@
"optional": true,
"os": [
"linux"
]
],
"peer": true
},
"node_modules/@rollup/rollup-linux-arm64-musl": {
"version": "4.62.0",
@@ -9509,7 +9518,8 @@
"optional": true,
"os": [
"linux"
]
],
"peer": true
},
"node_modules/@rollup/rollup-linux-loong64-musl": {
"version": "4.62.0",
@@ -9523,7 +9533,8 @@
"optional": true,
"os": [
"linux"
]
],
"peer": true
},
"node_modules/@rollup/rollup-linux-ppc64-gnu": {
"version": "4.62.0",
@@ -9537,7 +9548,8 @@
"optional": true,
"os": [
"linux"
]
],
"peer": true
},
"node_modules/@rollup/rollup-linux-ppc64-musl": {
"version": "4.62.0",
@@ -9551,7 +9563,8 @@
"optional": true,
"os": [
"linux"
]
],
"peer": true
},
"node_modules/@rollup/rollup-linux-riscv64-gnu": {
"version": "4.62.0",
@@ -9565,7 +9578,8 @@
"optional": true,
"os": [
"linux"
]
],
"peer": true
},
"node_modules/@rollup/rollup-linux-riscv64-musl": {
"version": "4.62.0",
@@ -9579,7 +9593,8 @@
"optional": true,
"os": [
"linux"
]
],
"peer": true
},
"node_modules/@rollup/rollup-linux-s390x-gnu": {
"version": "4.62.0",
@@ -9593,7 +9608,8 @@
"optional": true,
"os": [
"linux"
]
],
"peer": true
},
"node_modules/@rollup/rollup-linux-x64-gnu": {
"version": "4.62.0",
@@ -9607,7 +9623,8 @@
"optional": true,
"os": [
"linux"
]
],
"peer": true
},
"node_modules/@rollup/rollup-linux-x64-musl": {
"version": "4.62.0",
@@ -9634,7 +9651,8 @@
"optional": true,
"os": [
"openbsd"
]
],
"peer": true
},
"node_modules/@rollup/rollup-openharmony-arm64": {
"version": "4.62.0",
@@ -9648,7 +9666,8 @@
"optional": true,
"os": [
"openharmony"
]
],
"peer": true
},
"node_modules/@rollup/rollup-win32-arm64-msvc": {
"version": "4.62.0",
@@ -9662,7 +9681,8 @@
"optional": true,
"os": [
"win32"
]
],
"peer": true
},
"node_modules/@rollup/rollup-win32-ia32-msvc": {
"version": "4.62.0",
@@ -9676,7 +9696,8 @@
"optional": true,
"os": [
"win32"
]
],
"peer": true
},
"node_modules/@rollup/rollup-win32-x64-gnu": {
"version": "4.62.0",
@@ -9690,7 +9711,8 @@
"optional": true,
"os": [
"win32"
]
],
"peer": true
},
"node_modules/@rollup/rollup-win32-x64-msvc": {
"version": "4.62.0",
@@ -9704,7 +9726,8 @@
"optional": true,
"os": [
"win32"
]
],
"peer": true
},
"node_modules/@scarf/scarf": {
"version": "1.4.0",
@@ -24982,7 +25005,7 @@
},
"server": {
"name": "@trek/server",
"version": "4.3.4",
"version": "5.0.0",
"dependencies": {
"@aws-lite/client": "^0.23.7",
"@aws-lite/s3": "^0.2.7",
@@ -25361,7 +25384,7 @@
},
"shared": {
"name": "@trek/shared",
"version": "4.3.4",
"version": "5.0.0",
"dependencies": {
"isomorphic-dompurify": "^3.23.0",
"zod": "^4.6.7"
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "@trek/root",
"private": true,
"version": "4.3.4",
"version": "5.0.0",
"engines": {
"node": "^22.22.2 || ^24.15.0 || >=26.0.0"
},
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@trek/server",
"version": "4.3.4",
"version": "5.0.0",
"engines": {
"node": "^22.22.2 || ^24.15.0 || >=26.0.0"
},
+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, replayed with their search results.
// Anthropic's content blocks of an answer that searched the web or thought, replayed as they came.
z.object({
adapter: z.literal('anthropic-messages'),
blocks: z.array(z.record(z.string(), z.unknown())),
@@ -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 } from './ai-connections.dto';
import { AiAdminSettingsDto, AiInstanceConnectionDto, AiModelUpdateDto } 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, Post, Put, UseGuards } from '@nestjs/common';
import { Body, Controller, Delete, Get, HttpCode, Patch, Post, Put, UseGuards } from '@nestjs/common';
import {
aiAdminConnectionResponseSchema,
aiAdminSettingsSchema,
@@ -63,6 +63,12 @@ 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,10 +23,21 @@ 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 Chat Completions for everything
* OpenAI-compatible (OpenAI, Gemini, OpenRouter, an admin's own server).
* 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).
*/
@Injectable()
export class AiChatClientService {
@@ -45,6 +56,10 @@ 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,6 +328,26 @@ 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,9 +86,11 @@ 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. */
@@ -114,10 +116,17 @@ 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--;
const before = question > 0 ? blocks[question - 1] : undefined;
// 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;
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' };
/**
@@ -207,9 +216,10 @@ 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, 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.
* 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.
*/
class AnthropicTurn {
inputTokens = 0;
@@ -246,6 +256,10 @@ 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') {
@@ -285,10 +299,17 @@ class AnthropicTurn {
}
}
/** The blocks to replay, for an answer that searched the web; null for one rebuilt from its text and calls. */
/**
* 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).
*/
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,20 +130,22 @@ function citedSources(item: Record<string, unknown>): AiSource[] {
}
/**
* 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.
* 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.
*/
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> {
@@ -227,7 +229,7 @@ export class OpenAiResponsesClient implements AiChatClient {
try {
return await send(accessToken);
} catch (err) {
if (!(err instanceof AiProviderError) || err.status !== 401) throw err;
if (this.kind !== 'chatgpt' || !(err instanceof AiProviderError) || err.status !== 401) throw err;
return send(await this.token(accessToken));
}
}
@@ -1,3 +1,4 @@
import { intlLocale } from './assistant-words';
import { fileKeyOf } from './cards/card-values';
import type { AssistantFocus, AssistantMention } from '@trek/shared';
@@ -412,7 +413,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(locale) ?? locale;
return new Intl.DisplayNames(['en'], { type: 'language' }).of(intlLocale(locale)) ?? locale;
} catch {
return locale;
}
@@ -17,6 +17,15 @@ 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,3 +1,4 @@
import { intlLocale } from '../assistant-words';
import type { PreviewContext } from './card-types';
import type { AssistantChangeLabelKey, AssistantChangeRow } from '@trek/shared';
@@ -57,7 +58,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(ctx.locale)[0] ?? 'en';
return Intl.getCanonicalLocales(intlLocale(ctx.locale))[0] ?? 'en';
} catch {
return 'en';
}
@@ -71,6 +71,7 @@ export const MANAGED_ROUTE_ALLOW_LIST: string[] = [
'AiAdminController.removeConnection',
'AiAdminController.saveConnection',
'AiAdminController.saveSettings',
'AiAdminController.setModel',
'AiAdminController.settings',
'AiAdminController.signOutChatgpt',
'AiAdminController.startChatgpt',
+16 -3
View File
@@ -55,11 +55,18 @@ const tokenListSchema = z.object({
totalItems: z.number().optional(),
});
/** A user record with the ActivityPub actors that stand for it; the local one authors the user's trails. */
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.
*/
const userActorsSchema = z.object({
expand: z
.object({
activitypub_actors_via_user: z.array(z.object({ id: z.string(), is_local: z.boolean().nullish() })).nullish(),
activitypub_actors_via_user: z.union([z.array(actorSchema), actorSchema.transform((actor) => [actor])]).nullish(),
})
.nullish(),
});
@@ -259,7 +266,13 @@ 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('invalid_response', 'wanderer named no author for the token');
if (actors.length === 0) {
throw new WandererError(
'no_author',
'wanderer named no author for the token',
'no local actor in activitypub_actors_via_user',
);
}
return actors;
}
+7 -1
View File
@@ -2,6 +2,7 @@ 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';
@@ -183,9 +184,14 @@ 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. */
/**
* 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.
*/
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,6 +204,16 @@ 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({
@@ -0,0 +1,79 @@
/**
* 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,6 +42,7 @@ 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 () => []),
},
@@ -187,6 +188,7 @@ describe('AiAdminController', () => {
'saveSettings',
'connection',
'saveConnection',
'setModel',
'removeConnection',
'models',
'startOpenrouter',
@@ -198,6 +200,7 @@ 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 },
@@ -225,6 +228,9 @@ 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,6 +316,28 @@ 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,6 +295,79 @@ 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', () => {
@@ -543,6 +616,18 @@ 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,6 +231,12 @@ 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,6 +69,7 @@ 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));
});
});
+15 -2
View File
@@ -126,19 +126,32 @@ 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, or with an odd id, is an answer TREK does not trust', async () => {
it('RS-03: an owner without a local author is told as such; 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 }] },
}),
});
expect((await failure(() => client.ownActors(CREDS))).code).toBe('invalid_response');
// 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');
answer({ '/api/v1/api-token': reply({ items: [{ user: 'Not-An-Id!' }] }) });
expect((await failure(() => client.ownActors(CREDS))).code).toBe('invalid_response');
@@ -15,6 +15,11 @@ 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' };
@@ -376,6 +381,23 @@ 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'));
@@ -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 <5.0.0',
trek: '>=4.0.0 <6.0.0',
settings: opts.settings,
}),
);
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@trek/shared",
"version": "4.3.4",
"version": "5.0.0",
"engines": {
"node": "^22.22.2 || ^24.15.0 || >=26.0.0"
},
+7
View File
@@ -139,6 +139,13 @@ const reservations: TranslationStrings = {
'reservations.import.cta': 'استيراد من ملف',
'reservations.import.dropHere': 'أسقط ملفات تأكيد الحجز هنا أو انقر للتحديد',
'reservations.import.dropActive': 'أسقط الملفات للاستيراد',
'reservations.import.pinSearching': 'جارٍ البحث على الخريطة…',
'reservations.import.pinFound': 'على الخريطة',
'reservations.import.pinMissingTitle': 'ليس على الخريطة بعد',
'reservations.import.pinMissingBody':
'لم يعثر TREK على مكان الإقامة هذا على الخريطة. تحقّق من الاسم والعنوان أعلاه وابحث مجددًا، أو احفظه دون دبوس.',
'reservations.import.pinRetry': 'ابحث مجددًا',
'reservations.import.savedWithoutPin': 'حُفظ دون دبوس على الخريطة. عدّل المكان وحدّد موقعه لتراه على الخريطة.',
'reservations.import.acceptedFormats':
'المقبول: EML، PDF، PKPass، HTML، TXT (بحد أقصى 10 ميغابايت لكل ملف، حتى 5 ملفات)',
'reservations.import.acceptedPhotos': 'يقرأ نموذج الذكاء الاصطناعي الصور (JPG وPNG وWEBP).',
+2
View File
@@ -38,6 +38,8 @@ const wanderer: TranslationStrings = {
'wanderer.error.not_found': 'لم يعد هذا الدرب موجودًا في wanderer.',
'wanderer.error.not_own_trail': 'يمكن استيراد دروبك الخاصة في wanderer فقط.',
'wanderer.error.invalid_response': 'لم يأتِ الرد من wanderer. تحقق من أن العنوان يشير إلى wanderer نفسه.',
'wanderer.error.no_author':
'ردّ wanderer، لكنه لا يذكر أي مؤلف للدروب لحساب رمز API هذا، لذلك لا يستطيع TREK معرفة الدروب التي تخصّك.',
'wanderer.error.too_large': 'ملف الدرب أكبر من 10 MB.',
'wanderer.error.server_error': 'ردّ wanderer بخطأ. حاول مرة أخرى لاحقًا.',
'wanderer.error.offline': 'أنت غير متصل بالإنترنت. لا يمكن البحث في wanderer إلا عند الاتصال.',
+8
View File
@@ -170,6 +170,14 @@ const reservations: TranslationStrings = {
'reservations.import.dropHere':
'Rezervasiya təsdiqi fayllarını buraya sürükləyib buraxın və ya seçmək üçün klikləyin',
'reservations.import.dropActive': 'İdxal etmək üçün faylları buraya buraxın',
'reservations.import.pinSearching': 'Xəritədə axtarılır…',
'reservations.import.pinFound': 'Xəritədə',
'reservations.import.pinMissingTitle': 'Hələ xəritədə deyil',
'reservations.import.pinMissingBody':
'TREK bu yaşayış yerini xəritədə tapa bilmədi. Yuxarıdakı adı və ünvanı yoxlayın və yenidən axtarın, ya da onu sancaqsız yadda saxlayın.',
'reservations.import.pinRetry': 'Yenidən axtar',
'reservations.import.savedWithoutPin':
'Xəritə sancağı olmadan yadda saxlanıldı. Xəritədə görmək üçün yeri redaktə edin və mövqeyini təyin edin.',
'reservations.import.acceptedFormats':
'Qəbul edilən formatlar: EML, PDF, PKPass, HTML, TXT (hər biri maksimum 10 MB, 5 fayladək)',
'reservations.import.acceptedPhotos': 'Fotoları (JPG, PNG, WEBP) süni intellekt modeli oxuyur.',
+2
View File
@@ -35,6 +35,8 @@ const wanderer: TranslationStrings = {
'wanderer.error.not_found': 'Bu cığır artıq wanderer-də yoxdur.',
'wanderer.error.not_own_trail': 'Yalnız öz wanderer cığırlarınızı idxal edə bilərsiniz.',
'wanderer.error.invalid_response': 'Cavab wanderer-dən gəlməyib. Ünvanın birbaşa wanderer-ə yönəldiyini yoxlayın.',
'wanderer.error.no_author':
'wanderer cavab verdi, lakin bu API tokeninin hesabı üçün heç bir cığır müəllifi göstərmir, buna görə TREK hansı cığırların sizə aid olduğunu bilə bilmir.',
'wanderer.error.too_large': 'Cığır faylı 10 MB-dan böyükdür.',
'wanderer.error.server_error': 'wanderer xəta ilə cavab verdi. Sonra yenidən cəhd edin.',
'wanderer.error.offline': 'Oflaynsınız. wanderer-də yalnız onlayn axtarış etmək olar.',
+8
View File
@@ -139,6 +139,14 @@ const reservations: TranslationStrings = {
'reservations.import.cta': 'Importar de arquivo',
'reservations.import.dropHere': 'Solte os arquivos de confirmação de reserva aqui ou clique para selecionar',
'reservations.import.dropActive': 'Solte os arquivos para importar',
'reservations.import.pinSearching': 'Procurando no mapa…',
'reservations.import.pinFound': 'No mapa',
'reservations.import.pinMissingTitle': 'Ainda não está no mapa',
'reservations.import.pinMissingBody':
'O TREK não encontrou esta hospedagem no mapa. Confira o nome e o endereço acima e pesquise de novo, ou salve sem alfinete.',
'reservations.import.pinRetry': 'Pesquisar de novo',
'reservations.import.savedWithoutPin':
'Salvo sem alfinete no mapa. Edite o lugar e defina a localização para vê-lo no mapa.',
'reservations.import.acceptedFormats': 'Aceitos: EML, PDF, PKPass, HTML, TXT (máx. 10 MB cada, até 5 arquivos)',
'reservations.import.acceptedPhotos': 'As fotos (JPG, PNG, WEBP) são lidas pelo modelo de IA.',
'reservations.import.parsing': 'Analisando arquivos…',
+2
View File
@@ -36,6 +36,8 @@ const wanderer: TranslationStrings = {
'wanderer.error.not_own_trail': 'Só suas próprias trilhas do wanderer podem ser importadas.',
'wanderer.error.invalid_response':
'A resposta não veio do wanderer. Confira se o endereço aponta para o próprio wanderer.',
'wanderer.error.no_author':
'O wanderer respondeu, mas não indica nenhum autor de trilhas para a conta deste token de API, então o TREK não consegue saber quais trilhas são suas.',
'wanderer.error.too_large': 'O arquivo da trilha tem mais de 10 MB.',
'wanderer.error.server_error': 'O wanderer respondeu com um erro. Tente de novo mais tarde.',
'wanderer.error.offline': 'Você está offline. O wanderer só pode ser pesquisado online.',
+8
View File
@@ -139,6 +139,14 @@ const reservations: TranslationStrings = {
'reservations.import.cta': "Importa des d'un fitxer",
'reservations.import.dropHere': 'Deixa anar els fitxers de confirmació de reserva aquí o fes clic per seleccionar',
'reservations.import.dropActive': 'Deixa anar els fitxers per importar',
'reservations.import.pinSearching': "S'està cercant al mapa…",
'reservations.import.pinFound': 'Al mapa',
'reservations.import.pinMissingTitle': 'Encara no és al mapa',
'reservations.import.pinMissingBody':
"TREK no ha trobat aquest allotjament al mapa. Revisa el nom i l'adreça de dalt i torna a cercar, o desa'l sense xinxeta.",
'reservations.import.pinRetry': 'Torna a cercar',
'reservations.import.savedWithoutPin':
"Desat sense xinxeta al mapa. Edita el lloc i fixa'n la ubicació per veure'l al mapa.",
'reservations.import.acceptedFormats':
'Acceptats: EML, PDF, PKPass, HTML, TXT (màx. 10 MB per fitxer, fins a 5 fitxers)',
'reservations.import.acceptedPhotos': "El model d'IA llegeix les fotos (JPG, PNG, WEBP).",
+2
View File
@@ -35,6 +35,8 @@ const wanderer: TranslationStrings = {
'wanderer.error.not_found': 'Aquest sender ja no existeix a wanderer.',
'wanderer.error.not_own_trail': 'Només es poden importar els teus propis senders de wanderer.',
'wanderer.error.invalid_response': "La resposta no ve de wanderer. Comprova que l'adreça apunti al mateix wanderer.",
'wanderer.error.no_author':
"wanderer ha respost, però no indica cap autor de senders per al compte d'aquest token d'API, així que TREK no pot saber quins senders són teus.",
'wanderer.error.too_large': 'El fitxer del sender ocupa més de 10 MB.',
'wanderer.error.server_error': 'wanderer ha respost amb un error. Torna-ho a provar més tard.',
'wanderer.error.offline': 'No tens connexió. Només es pot cercar a wanderer amb connexió.',
+8
View File
@@ -139,6 +139,14 @@ const reservations: TranslationStrings = {
'reservations.import.cta': 'Importovat ze souboru',
'reservations.import.dropHere': 'Přetáhněte soubory s potvrzením rezervace sem nebo klikněte pro výběr',
'reservations.import.dropActive': 'Pusťte soubory pro import',
'reservations.import.pinSearching': 'Hledání na mapě…',
'reservations.import.pinFound': 'Na mapě',
'reservations.import.pinMissingTitle': 'Zatím není na mapě',
'reservations.import.pinMissingBody':
'TREK toto ubytování na mapě nenašel. Zkontrolujte název a adresu výše a vyhledejte znovu, nebo ho uložte bez špendlíku.',
'reservations.import.pinRetry': 'Hledat znovu',
'reservations.import.savedWithoutPin':
'Uloženo bez špendlíku na mapě. Upravte místo a nastavte jeho polohu, aby se zobrazilo na mapě.',
'reservations.import.acceptedFormats':
'Přijímané formáty: EML, PDF, PKPass, HTML, TXT (max. 10 MB každý, až 5 souborů)',
'reservations.import.acceptedPhotos': 'Fotografie (JPG, PNG, WEBP) čte model AI.',
+2
View File
@@ -36,6 +36,8 @@ const wanderer: TranslationStrings = {
'wanderer.error.not_own_trail': 'Importovat lze pouze vaše vlastní trasy z aplikace wanderer.',
'wanderer.error.invalid_response':
'Odpověď nepřišla z aplikace wanderer. Zkontrolujte, zda adresa vede přímo na wanderer.',
'wanderer.error.no_author':
'wanderer odpověděl, ale pro účet tohoto API tokenu neuvádí žádného autora tras, takže TREK nepozná, které trasy jsou vaše.',
'wanderer.error.too_large': 'Soubor trasy je větší než 10 MB.',
'wanderer.error.server_error': 'wanderer odpověděl chybou. Zkuste to později.',
'wanderer.error.offline': 'Jste offline. V aplikaci wanderer lze vyhledávat jen online.',
+8
View File
@@ -143,6 +143,14 @@ const reservations: TranslationStrings = {
'reservations.import.cta': 'Aus Datei importieren',
'reservations.import.dropHere': 'Buchungsbestätigungsdateien hier ablegen oder klicken zum Auswählen',
'reservations.import.dropActive': 'Dateien zum Importieren ablegen',
'reservations.import.pinSearching': 'Wird auf der Karte gesucht …',
'reservations.import.pinFound': 'Auf der Karte',
'reservations.import.pinMissingTitle': 'Noch nicht auf der Karte',
'reservations.import.pinMissingBody':
'TREK hat diese Unterkunft nicht auf der Karte gefunden. Prüf Name und Adresse oben und such erneut, oder speichere sie ohne Kartenpunkt.',
'reservations.import.pinRetry': 'Erneut suchen',
'reservations.import.savedWithoutPin':
'Ohne Kartenpunkt gespeichert. Bearbeite den Ort und setze seine Position, damit er auf der Karte erscheint.',
'reservations.import.acceptedFormats':
'Akzeptiert: EML, PDF, PKPass, HTML, TXT (max. 10 MB pro Datei, bis zu 5 Dateien)',
'reservations.import.acceptedPhotos': 'Fotos (JPG, PNG, WEBP) liest das KI-Modell.',
+2
View File
@@ -37,6 +37,8 @@ const wanderer: TranslationStrings = {
'wanderer.error.not_own_trail': 'Nur deine eigenen wanderer-Trails können importiert werden.',
'wanderer.error.invalid_response':
'Die Antwort kam nicht von wanderer. Prüfe, ob die Adresse auf wanderer selbst zeigt.',
'wanderer.error.no_author':
'wanderer hat geantwortet, nennt für das Konto dieses API-Tokens aber keinen Trail-Autor. TREK kann deshalb nicht erkennen, welche Trails deine sind.',
'wanderer.error.too_large': 'Die Trail-Datei ist größer als 10 MB.',
'wanderer.error.server_error': 'wanderer hat mit einem Fehler geantwortet. Versuche es später noch einmal.',
'wanderer.error.offline': 'Du bist offline. wanderer lässt sich nur online durchsuchen.',
+8
View File
@@ -144,6 +144,14 @@ const reservations: TranslationStrings = {
'reservations.import.cta': 'Import from file',
'reservations.import.dropHere': 'Drop booking confirmation files here, or click to select',
'reservations.import.dropActive': 'Drop files to import',
'reservations.import.pinSearching': 'Looking for it on the map…',
'reservations.import.pinFound': 'On the map',
'reservations.import.pinMissingTitle': 'Not on the map yet',
'reservations.import.pinMissingBody':
"TREK couldn't find this stay on the map. Check the name and address above and search again, or save it without a pin.",
'reservations.import.pinRetry': 'Search again',
'reservations.import.savedWithoutPin':
'Saved without a map pin. Edit the place and set its location to see it on the map.',
'reservations.import.acceptedFormats': 'Accepted: EML, PDF, PKPass, HTML, TXT (max 10 MB each, up to 5 files)',
'reservations.import.acceptedPhotos': 'Photos (JPG, PNG, WEBP) are read by the AI model.',
'reservations.import.parsing': 'Parsing files…',
+2
View File
@@ -35,6 +35,8 @@ const wanderer: TranslationStrings = {
'wanderer.error.not_own_trail': 'Only your own wanderer trails can be imported.',
'wanderer.error.invalid_response':
'The answer did not come from wanderer. Check that the address points at wanderer itself.',
'wanderer.error.no_author':
'wanderer answered, but names no trail author for the account of this API token, so TREK cannot tell which trails are yours.',
'wanderer.error.too_large': 'The trail file is larger than 10 MB.',
'wanderer.error.server_error': 'wanderer answered with an error. Try again later.',
'wanderer.error.offline': 'You are offline. wanderer can only be searched online.',
+8
View File
@@ -141,6 +141,14 @@ const reservations: TranslationStrings = {
'reservations.import.cta': 'Importar desde archivo',
'reservations.import.dropHere': 'Suelta los archivos de confirmación de reserva aquí o haz clic para seleccionar',
'reservations.import.dropActive': 'Suelta los archivos para importar',
'reservations.import.pinSearching': 'Buscando en el mapa…',
'reservations.import.pinFound': 'En el mapa',
'reservations.import.pinMissingTitle': 'Todavía no está en el mapa',
'reservations.import.pinMissingBody':
'TREK no ha encontrado este alojamiento en el mapa. Revisa el nombre y la dirección de arriba y vuelve a buscar, o guárdalo sin chincheta.',
'reservations.import.pinRetry': 'Buscar de nuevo',
'reservations.import.savedWithoutPin':
'Guardado sin chincheta en el mapa. Edita el lugar y fija su ubicación para verlo en el mapa.',
'reservations.import.acceptedFormats':
'Aceptados: EML, PDF, PKPass, HTML, TXT (máx. 10 MB por archivo, hasta 5 archivos)',
'reservations.import.acceptedPhotos': 'El modelo de IA lee las fotos (JPG, PNG, WEBP).',
+2
View File
@@ -37,6 +37,8 @@ const wanderer: TranslationStrings = {
'wanderer.error.not_own_trail': 'Solo se pueden importar tus propios senderos de wanderer.',
'wanderer.error.invalid_response':
'La respuesta no viene de wanderer. Comprueba que la dirección apunta al propio wanderer.',
'wanderer.error.no_author':
'wanderer ha respondido, pero no indica ningún autor de senderos para la cuenta de este token de API, así que TREK no puede saber qué senderos son tuyos.',
'wanderer.error.too_large': 'El archivo del sendero ocupa más de 10 MB.',
'wanderer.error.server_error': 'wanderer ha respondido con un error. Inténtalo de nuevo más tarde.',
'wanderer.error.offline': 'Estás sin conexión. Solo se puede buscar en wanderer con conexión.',
+8
View File
@@ -144,6 +144,14 @@ const reservations: TranslationStrings = {
'reservations.import.cta': 'Impordi failist',
'reservations.import.dropHere': 'Lohista broneeringukinnituse failid siia või klõpsa valimiseks',
'reservations.import.dropActive': 'Impordiks lohista failid siia',
'reservations.import.pinSearching': 'Kaardilt otsimine…',
'reservations.import.pinFound': 'Kaardil',
'reservations.import.pinMissingTitle': 'Veel pole kaardil',
'reservations.import.pinMissingBody':
'TREK ei leidnud seda majutust kaardilt. Kontrolli ülal nime ja aadressi ning otsi uuesti või salvesta see ilma nõelata.',
'reservations.import.pinRetry': 'Otsi uuesti',
'reservations.import.savedWithoutPin':
'Salvestatud ilma kaardinõelata. Muuda kohta ja määra selle asukoht, et seda kaardil näha.',
'reservations.import.acceptedFormats': 'Lubatud: EML, PDF, PKPass, HTML, TXT (kuni 10 MB faili kohta, kuni 5 faili)',
'reservations.import.acceptedPhotos': 'Fotosid (JPG, PNG, WEBP) loeb tehisintellekti mudel.',
'reservations.import.parsing': 'Failide töötlemine…',
+2
View File
@@ -36,6 +36,8 @@ const wanderer: TranslationStrings = {
'wanderer.error.not_own_trail': 'Importida saab ainult oma wanderer-matkaradu.',
'wanderer.error.invalid_response':
'Vastus ei tulnud wanderer-rakendusest. Kontrolli, et aadress viitab otse wanderer-rakendusele.',
'wanderer.error.no_author':
'wanderer vastas, kuid ei nimeta selle API-tõendi konto jaoks ühtegi matkaraja autorit, seega ei saa TREK aru, millised matkarajad on sinu omad.',
'wanderer.error.too_large': 'Matkaraja fail on suurem kui 10 MB.',
'wanderer.error.server_error': 'wanderer vastas veaga. Proovi hiljem uuesti.',
'wanderer.error.offline': 'Oled võrguühenduseta. wanderer-rakendusest saab otsida ainult võrgus olles.',
+8
View File
@@ -142,6 +142,14 @@ const reservations: TranslationStrings = {
'reservations.import.dropHere':
'Déposez les fichiers de confirmation de réservation ici ou cliquez pour sélectionner',
'reservations.import.dropActive': 'Déposez les fichiers pour importer',
'reservations.import.pinSearching': 'Recherche sur la carte…',
'reservations.import.pinFound': 'Sur la carte',
'reservations.import.pinMissingTitle': 'Pas encore sur la carte',
'reservations.import.pinMissingBody':
"TREK n'a pas trouvé cet hébergement sur la carte. Vérifiez le nom et l'adresse ci-dessus et relancez la recherche, ou enregistrez-le sans repère.",
'reservations.import.pinRetry': 'Rechercher à nouveau',
'reservations.import.savedWithoutPin':
'Enregistré sans repère sur la carte. Modifiez le lieu et définissez sa position pour le voir sur la carte.',
'reservations.import.acceptedFormats':
"Acceptés : EML, PDF, PKPass, HTML, TXT (max. 10 Mo chacun, jusqu'à 5 fichiers)",
'reservations.import.acceptedPhotos': "Les photos (JPG, PNG, WEBP) sont lues par le modèle d'IA.",
+2
View File
@@ -36,6 +36,8 @@ const wanderer: TranslationStrings = {
'wanderer.error.not_own_trail': 'Seuls vos propres sentiers wanderer peuvent être importés.',
'wanderer.error.invalid_response':
"La réponse ne vient pas de wanderer. Vérifiez que l'adresse pointe bien vers wanderer lui-même.",
'wanderer.error.no_author':
"wanderer a répondu, mais n'indique aucun auteur de sentiers pour le compte de ce jeton API, TREK ne peut donc pas savoir quels sentiers sont les vôtres.",
'wanderer.error.too_large': 'Le fichier du sentier dépasse 10 MB.',
'wanderer.error.server_error': 'wanderer a répondu par une erreur. Réessayez plus tard.',
'wanderer.error.offline': "Vous êtes hors ligne. wanderer ne peut être consulté qu'en ligne.",
+8
View File
@@ -142,6 +142,14 @@ const reservations: TranslationStrings = {
'reservations.import.cta': 'Εισαγωγή από αρχείο',
'reservations.import.dropHere': 'Αποθέστε αρχεία επιβεβαίωσης κράτησης εδώ ή κάντε κλικ για επιλογή',
'reservations.import.dropActive': 'Αποθέστε αρχεία για εισαγωγή',
'reservations.import.pinSearching': 'Αναζήτηση στον χάρτη…',
'reservations.import.pinFound': 'Στον χάρτη',
'reservations.import.pinMissingTitle': 'Δεν είναι ακόμη στον χάρτη',
'reservations.import.pinMissingBody':
'Το TREK δεν βρήκε αυτό το κατάλυμα στον χάρτη. Ελέγξτε το όνομα και τη διεύθυνση παραπάνω και αναζητήστε ξανά ή αποθηκεύστε το χωρίς καρφίτσα.',
'reservations.import.pinRetry': 'Νέα αναζήτηση',
'reservations.import.savedWithoutPin':
'Αποθηκεύτηκε χωρίς καρφίτσα στον χάρτη. Επεξεργαστείτε το μέρος και ορίστε τη θέση του για να εμφανιστεί στον χάρτη.',
'reservations.import.acceptedFormats':
'Αποδεκτά: EML, PDF, PKPass, HTML, TXT (μέγιστο 10 MB το καθένα, έως 5 αρχεία)',
'reservations.import.acceptedPhotos': 'Τις φωτογραφίες (JPG, PNG, WEBP) τις διαβάζει το μοντέλο ΤΝ.',
+2
View File
@@ -38,6 +38,8 @@ const wanderer: TranslationStrings = {
'wanderer.error.not_own_trail': 'Μπορούν να εισαχθούν μόνο τα δικά σας μονοπάτια του wanderer.',
'wanderer.error.invalid_response':
'Η απάντηση δεν προήλθε από το wanderer. Ελέγξτε ότι η διεύθυνση οδηγεί στο ίδιο το wanderer.',
'wanderer.error.no_author':
'Το wanderer απάντησε, αλλά δεν αναφέρει κανέναν δημιουργό μονοπατιών για τον λογαριασμό αυτού του API token, οπότε το TREK δεν μπορεί να ξέρει ποια μονοπάτια είναι δικά σας.',
'wanderer.error.too_large': 'Το αρχείο του μονοπατιού είναι μεγαλύτερο από 10 MB.',
'wanderer.error.server_error': 'Το wanderer απάντησε με σφάλμα. Δοκιμάστε ξανά αργότερα.',
'wanderer.error.offline': 'Είστε εκτός σύνδεσης. Η αναζήτηση στο wanderer γίνεται μόνο με σύνδεση.',
+8
View File
@@ -140,6 +140,14 @@ const reservations: TranslationStrings = {
'reservations.import.cta': 'Importálás fájlból',
'reservations.import.dropHere': 'Dobja ide a foglalási visszaigazolás fájlokat, vagy kattintson a kiválasztáshoz',
'reservations.import.dropActive': 'Dobja ide a fájlokat az importáláshoz',
'reservations.import.pinSearching': 'Keresés a térképen…',
'reservations.import.pinFound': 'A térképen',
'reservations.import.pinMissingTitle': 'Még nincs a térképen',
'reservations.import.pinMissingBody':
'A TREK nem találta meg ezt a szállást a térképen. Ellenőrizd a fenti nevet és címet, és keress újra, vagy mentsd el tű nélkül.',
'reservations.import.pinRetry': 'Keresés újra',
'reservations.import.savedWithoutPin':
'Térképtű nélkül mentve. Szerkeszd a helyet, és állítsd be a pozícióját, hogy megjelenjen a térképen.',
'reservations.import.acceptedFormats':
'Elfogadott: EML, PDF, PKPass, HTML, TXT (max. 10 MB darabonként, legfeljebb 5 fájl)',
'reservations.import.acceptedPhotos': 'A fotókat (JPG, PNG, WEBP) az MI-modell olvassa be.',
+2
View File
@@ -36,6 +36,8 @@ const wanderer: TranslationStrings = {
'wanderer.error.not_own_trail': 'Csak a saját wanderer-túraútvonalaid importálhatók.',
'wanderer.error.invalid_response':
'A válasz nem a wanderer alkalmazástól érkezett. Ellenőrizd, hogy a cím magára a wanderer alkalmazásra mutat-e.',
'wanderer.error.no_author':
'A wanderer válaszolt, de ennek az API-tokennek a fiókjához nem nevez meg túraútvonal-szerzőt, így a TREK nem tudja, mely túraútvonalak a tieid.',
'wanderer.error.too_large': 'A túraútvonal fájlja nagyobb 10 MB-nál.',
'wanderer.error.server_error': 'A wanderer hibával válaszolt. Próbáld újra később.',
'wanderer.error.offline': 'Offline vagy. A wanderer csak online kereshető.',
+8
View File
@@ -140,6 +140,14 @@ const reservations: TranslationStrings = {
'reservations.import.cta': 'Impor dari file',
'reservations.import.dropHere': 'Seret file konfirmasi pemesanan ke sini atau klik untuk memilih',
'reservations.import.dropActive': 'Lepaskan file untuk mengimpor',
'reservations.import.pinSearching': 'Mencari di peta…',
'reservations.import.pinFound': 'Di peta',
'reservations.import.pinMissingTitle': 'Belum ada di peta',
'reservations.import.pinMissingBody':
'TREK tidak menemukan penginapan ini di peta. Periksa nama dan alamat di atas lalu cari lagi, atau simpan tanpa pin.',
'reservations.import.pinRetry': 'Cari lagi',
'reservations.import.savedWithoutPin':
'Disimpan tanpa pin peta. Edit tempatnya dan atur lokasinya agar muncul di peta.',
'reservations.import.acceptedFormats': 'Diterima: EML, PDF, PKPass, HTML, TXT (maks. 10 MB per file, hingga 5 file)',
'reservations.import.acceptedPhotos': 'Foto (JPG, PNG, WEBP) dibaca oleh model AI.',
'reservations.import.parsing': 'Memproses file…',
+2
View File
@@ -35,6 +35,8 @@ const wanderer: TranslationStrings = {
'wanderer.error.not_own_trail': 'Hanya jalur wanderer milik Anda sendiri yang dapat diimpor.',
'wanderer.error.invalid_response':
'Jawaban tidak berasal dari wanderer. Pastikan alamat mengarah ke wanderer itu sendiri.',
'wanderer.error.no_author':
'wanderer menjawab, tetapi tidak menyebutkan penulis jalur untuk akun token API ini, sehingga TREK tidak bisa mengetahui jalur mana yang milik Anda.',
'wanderer.error.too_large': 'Berkas jalur lebih besar dari 10 MB.',
'wanderer.error.server_error': 'wanderer menjawab dengan galat. Coba lagi nanti.',
'wanderer.error.offline': 'Anda sedang offline. Pencarian di wanderer hanya bisa dilakukan saat online.',
+8
View File
@@ -140,6 +140,14 @@ const reservations: TranslationStrings = {
'reservations.import.cta': 'Importa da file',
'reservations.import.dropHere': 'Trascina i file di conferma prenotazione qui o clicca per selezionare',
'reservations.import.dropActive': 'Rilascia i file per importare',
'reservations.import.pinSearching': 'Ricerca sulla mappa…',
'reservations.import.pinFound': 'Sulla mappa',
'reservations.import.pinMissingTitle': 'Non ancora sulla mappa',
'reservations.import.pinMissingBody':
"TREK non ha trovato questo alloggio sulla mappa. Controlla il nome e l'indirizzo qui sopra e cerca di nuovo, oppure salvalo senza segnaposto.",
'reservations.import.pinRetry': 'Cerca di nuovo',
'reservations.import.savedWithoutPin':
'Salvato senza segnaposto sulla mappa. Modifica il luogo e imposta la sua posizione per vederlo sulla mappa.',
'reservations.import.acceptedFormats': 'Accettati: EML, PDF, PKPass, HTML, TXT (max 10 MB ciascuno, fino a 5 file)',
'reservations.import.acceptedPhotos': 'Le foto (JPG, PNG, WEBP) vengono lette dal modello di IA.',
'reservations.import.parsing': 'Analisi dei file in corso…',
+2
View File
@@ -37,6 +37,8 @@ const wanderer: TranslationStrings = {
'wanderer.error.not_own_trail': 'Si possono importare solo i tuoi sentieri di wanderer.',
'wanderer.error.invalid_response':
"La risposta non proviene da wanderer. Controlla che l'indirizzo punti proprio a wanderer.",
'wanderer.error.no_author':
"wanderer ha risposto, ma non indica alcun autore di sentieri per l'account di questo token API, quindi TREK non può sapere quali sentieri sono tuoi.",
'wanderer.error.too_large': 'Il file del sentiero supera i 10 MB.',
'wanderer.error.server_error': 'wanderer ha risposto con un errore. Riprova più tardi.',
'wanderer.error.offline': 'Sei offline. In wanderer si può cercare solo online.',
+8
View File
@@ -139,6 +139,14 @@ const reservations: TranslationStrings = {
'reservations.import.cta': 'ファイルからインポート',
'reservations.import.dropHere': '予約確認ファイルをここにドロップするか、クリックして選択',
'reservations.import.dropActive': 'ファイルをドロップしてインポート',
'reservations.import.pinSearching': '地図で検索しています…',
'reservations.import.pinFound': '地図上の場所',
'reservations.import.pinMissingTitle': 'まだ地図にありません',
'reservations.import.pinMissingBody':
'TREK はこの宿泊先を地図上で見つけられませんでした。上の名前と住所を確認して再検索するか、ピンなしで保存してください。',
'reservations.import.pinRetry': '再検索',
'reservations.import.savedWithoutPin':
'地図のピンなしで保存しました。地図に表示するには、場所を編集して位置を設定してください。',
'reservations.import.acceptedFormats': '対応形式:EML、PDF、PKPass、HTML、TXT(各最大 10 MB、最大 5 ファイル)',
'reservations.import.acceptedPhotos': '写真(JPG、PNG、WEBP)は AI モデルが読み取ります。',
'reservations.import.parsing': 'ファイルを解析中…',
+2
View File
@@ -36,6 +36,8 @@ const wanderer: TranslationStrings = {
'wanderer.error.not_own_trail': 'インポートできるのは自分のwandererトレイルのみです。',
'wanderer.error.invalid_response':
'応答がwandererから返されたものではありません。アドレスがwanderer自体を指しているか確認してください。',
'wanderer.error.no_author':
'wandererは応答しましたが、このAPIトークンのアカウントにトレイルの作成者が示されていないため、TREKはどのトレイルがあなたのものか判断できません。',
'wanderer.error.too_large': 'トレイルのファイルが10 MBを超えています。',
'wanderer.error.server_error': 'wandererがエラーを返しました。しばらくしてからもう一度お試しください。',
'wanderer.error.offline': 'オフラインです。wandererはオンライン時のみ検索できます。',
+8
View File
@@ -139,6 +139,14 @@ const reservations: TranslationStrings = {
'reservations.import.cta': '파일에서 가져오기',
'reservations.import.dropHere': '예약 확인 파일을 여기에 끌어다 놓거나 클릭하여 선택',
'reservations.import.dropActive': '가져올 파일을 여기에 놓으세요',
'reservations.import.pinSearching': '지도에서 찾는 중…',
'reservations.import.pinFound': '지도에 있음',
'reservations.import.pinMissingTitle': '아직 지도에 없음',
'reservations.import.pinMissingBody':
'TREK이 지도에서 이 숙소를 찾지 못했습니다. 위의 이름과 주소를 확인하고 다시 검색하거나, 핀 없이 저장하세요.',
'reservations.import.pinRetry': '다시 검색',
'reservations.import.savedWithoutPin':
'지도 핀 없이 저장했습니다. 지도에 표시하려면 장소를 편집해 위치를 설정하세요.',
'reservations.import.acceptedFormats': '허용 형식: EML, PDF, PKPass, HTML, TXT (파일당 최대 10 MB, 최대 5개)',
'reservations.import.acceptedPhotos': '사진(JPG, PNG, WEBP)은 AI 모델이 읽습니다.',
'reservations.import.parsing': '파일 분석 중…',
+2
View File
@@ -34,6 +34,8 @@ const wanderer: TranslationStrings = {
'wanderer.error.not_found': 'wanderer에 이 트레일이 더 이상 없습니다.',
'wanderer.error.not_own_trail': '자신의 wanderer 트레일만 가져올 수 있습니다.',
'wanderer.error.invalid_response': 'wanderer의 응답이 아닙니다. 주소가 wanderer 자체를 가리키는지 확인하세요.',
'wanderer.error.no_author':
'wanderer가 응답했지만 이 API 토큰의 계정에 대한 트레일 작성자를 알려 주지 않아, TREK이 어떤 트레일이 내 것인지 알 수 없습니다.',
'wanderer.error.too_large': '트레일 파일이 10 MB보다 큽니다.',
'wanderer.error.server_error': 'wanderer가 오류로 응답했습니다. 나중에 다시 시도하세요.',
'wanderer.error.offline': '오프라인 상태입니다. wanderer는 온라인에서만 검색할 수 있습니다.',
+8
View File
@@ -140,6 +140,14 @@ const reservations: TranslationStrings = {
'reservations.import.cta': 'Importeren vanuit bestand',
'reservations.import.dropHere': 'Zet hier bevestigingsbestanden neer of klik om te selecteren',
'reservations.import.dropActive': 'Laat bestanden los om te importeren',
'reservations.import.pinSearching': 'Zoeken op de kaart…',
'reservations.import.pinFound': 'Op de kaart',
'reservations.import.pinMissingTitle': 'Nog niet op de kaart',
'reservations.import.pinMissingBody':
'TREK kon dit verblijf niet op de kaart vinden. Controleer de naam en het adres hierboven en zoek opnieuw, of sla het op zonder speld.',
'reservations.import.pinRetry': 'Opnieuw zoeken',
'reservations.import.savedWithoutPin':
'Opgeslagen zonder speld op de kaart. Bewerk de plek en stel de locatie in om hem op de kaart te zien.',
'reservations.import.acceptedFormats':
'Geaccepteerd: EML, PDF, PKPass, HTML, TXT (max. 10 MB per stuk, tot 5 bestanden)',
'reservations.import.acceptedPhotos': "Foto's (JPG, PNG, WEBP) worden door het AI-model gelezen.",
+2
View File
@@ -37,6 +37,8 @@ const wanderer: TranslationStrings = {
'wanderer.error.not_own_trail': 'Alleen je eigen wanderer-wandelroutes kunnen worden geïmporteerd.',
'wanderer.error.invalid_response':
'Het antwoord kwam niet van wanderer. Controleer of het adres naar wanderer zelf wijst.',
'wanderer.error.no_author':
'wanderer heeft geantwoord, maar noemt geen auteur van wandelroutes voor het account van dit API-token, dus TREK kan niet zien welke wandelroutes van jou zijn.',
'wanderer.error.too_large': 'Het bestand van de wandelroute is groter dan 10 MB.',
'wanderer.error.server_error': 'wanderer antwoordde met een fout. Probeer het later opnieuw.',
'wanderer.error.offline': 'Je bent offline. wanderer kan alleen online worden doorzocht.',
+8
View File
@@ -141,6 +141,14 @@ const reservations: TranslationStrings = {
'reservations.import.cta': 'Importuj z pliku',
'reservations.import.dropHere': 'Upuść pliki potwierdzeń rezerwacji tutaj lub kliknij, aby wybrać',
'reservations.import.dropActive': 'Upuść pliki, aby zaimportować',
'reservations.import.pinSearching': 'Szukanie na mapie…',
'reservations.import.pinFound': 'Na mapie',
'reservations.import.pinMissingTitle': 'Jeszcze nie na mapie',
'reservations.import.pinMissingBody':
'TREK nie znalazł tego noclegu na mapie. Sprawdź nazwę i adres powyżej i wyszukaj ponownie albo zapisz go bez pinezki.',
'reservations.import.pinRetry': 'Szukaj ponownie',
'reservations.import.savedWithoutPin':
'Zapisano bez pinezki na mapie. Edytuj miejsce i ustaw jego położenie, aby zobaczyć je na mapie.',
'reservations.import.acceptedFormats': 'Akceptowane: EML, PDF, PKPass, HTML, TXT (maks. 10 MB każdy, do 5 plików)',
'reservations.import.acceptedPhotos': 'Zdjęcia (JPG, PNG, WEBP) odczytuje model AI.',
'reservations.import.parsing': 'Przetwarzanie plików…',

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