Files
DriverVault/Phone App/lib/screens/servers_sheet.dart
T
tajniak81andClaude Opus 5 12ec10a797 Phone App: more than one server, and a session for each
The web app can be pointed at two DriverVault stacks and switch between them in
a click. The phone had one address and one session: reaching a second garage
meant retyping the API base in Server settings and signing in again, losing the
first server's token on the way — the same act, undone, every time you switched
back.

So lib/servers.dart is the web's servers.js ported rather than reinvented, down
to the storage keys: cc_servers holds the list, cc_active_server the one being
read, cc_session_<id> the token minted by that server and no other. The two apps
describe the same thing the same way, and the upgrade path falls out of it —
cc_token, cc_user and cc_server_url are read once at boot and folded onto the
home entry, so the build carrying this signs nobody out.

Home is the address the build ships with (kDefaultApiBase, still overridable per
device from the login screen) and cannot be removed: it is what a dropped session
falls back to. Any other server is added by address, with /api appended if the
path is left off, because a server a phone can reach is internet-facing already.

The part worth reading twice is which session a rejection ends. ApiClient no
longer holds a base or a token — it pins the active server's id, base and token
at the moment a request goes out, so a 401 arriving after a switch clears the
session of the server that actually refused it rather than whichever one is
active by then. The fallback is the web's: a remote server timing out drops its
own token, the app returns to home while home is still signed in, and only when
nothing is left to fall back to does the login screen come back. Log out still
clears every server at once, since leaving the app means leaving all of them.

Switching rebuilds the shell, keyed on the active id, because record ids belong
to the server that issued them — a garage, a charging page and a settings panel
still holding the other server's rows would each have to be told to forget them
separately. The appearance prefs come across with the profile of whoever owns
the account on the server now active.

Where the picker lives is the one place the phone cannot copy the web. There is
no app rail here, so it became the first button in the Garage header, beside the
theme toggle and log out, which is that same cluster. It names the active server
once there is a choice and goes straight to adding the second when there isn't;
the eyebrow reads GARAGE · Work for the reason the rail names it — two garages
otherwise look identical. The login screen gets its own way in, because a remote
session can expire and land you there with that server still active, and a
picker reachable only from inside the app would leave nowhere to go.

One judgment call inside the sheet: saving a connected server at a new address
saves and stops, rather than falling through to the sign-in it now needs. The
token was minted by the PocketBase behind the old address and is dropped with
it, but the credentials to replace it were never asked for, so treating the save
as a login would report an empty password as the error.

The strings are copied out of Web App/web/src/i18n/ like the rest of the shared
wording. Two are not the web's: home reads "the address this app ships with"
rather than "served with this app", since the phone has no origin to be served
from, and sameOrigin has no meaning here at all and was dropped.

Biometric sign-in stays global. It was never per-server and replays its stored
credentials against whichever server is active; making it per-server is a change
of its own, and the login screen now names the server it is about to sign into.

Nothing changes on the API Server. On Android there is no origin to allow, so
the CORS list the web app has to satisfy to reach a second server doesn't enter
into it.

Verified: flutter analyze is clean and flutter test passes, 35 tests to 46. The
new ones cover the registry — a bare origin gaining its /api, a fresh install
knowing one unnamed server on the built-in address, the legacy keys landing on
home and being cleared, two servers holding their tokens apart, a rename keeping
a session where a move drops it, removing the active server falling back to a
home that is still signed in, home refusing to be removed, and a restart reading
the list, the active id and every session back.

Not verified: none of it has been run. There is no device or emulator on this
machine and no API Server to answer, so the picker, the add sheet, a real
connect, the 401 fallback and the shell rebuild on a switch exist only as code
the analyzer is happy with — the tests reach the registry, not a screen. No APK
was built. The legacy migration was exercised against mocked SharedPreferences,
which is not a phone that had the old build on it: that is the first thing to
check on a device, since the failure mode is a silent sign-out.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-23 21:47:01 +02:00

358 lines
13 KiB
Dart

import "package:flutter/material.dart";
import "../config.dart";
import "../i18n.dart";
import "../main.dart";
import "../servers.dart";
import "../theme.dart";
/// The server picker and the add/edit/sign-in sheet behind it — the phone's
/// half of the web app's rail server switcher.
///
/// The picker names the server you are reading right now, which matters most
/// when two of them hold different cars and the screens otherwise look
/// identical, and switches between them in one tap once each has been signed
/// into.
/// Opens the picker. With only one server known there is nothing to pick
/// between, so it goes straight to adding the second one.
Future<void> showServerPicker(BuildContext context) {
if (serverRegistry.list.length < 2) return showServerEditor(context);
return showModalBottomSheet<void>(
context: context,
isScrollControlled: true,
builder: (_) => const _ServerPickerSheet(),
);
}
/// Add a server, edit one, or sign into it — one sheet, because for a server you
/// have just typed in they are the same act: an address is only worth keeping
/// once something has answered at it.
Future<void> showServerEditor(BuildContext context, {ServerEntry? server}) {
return showModalBottomSheet<void>(
context: context,
isScrollControlled: true,
builder: (_) => _ServerEditorSheet(server: server),
);
}
/// Each server carries its own profile, so the appearance prefs come from
/// whichever one is now active. Failures are ignored: the screens behind this
/// sheet report their own load errors.
void adoptActiveServerProfile() {
apiClient.getMe().then((profile) {
appSettings.applyFromProfile(profile);
authService.adoptRole(profile);
}).catchError((_) {});
}
class _ServerPickerSheet extends StatefulWidget {
const _ServerPickerSheet();
@override
State<_ServerPickerSheet> createState() => _ServerPickerSheetState();
}
class _ServerPickerSheetState extends State<_ServerPickerSheet> {
Future<void> _choose(ServerEntry server) async {
if (serverRegistry.isConnected(server.id)) {
serverRegistry.setActive(server.id);
adoptActiveServerProfile();
Navigator.pop(context);
return;
}
// No session for it yet — the same sheet that adds a server signs you in.
await showServerEditor(context, server: server);
if (mounted) setState(() {});
}
Future<void> _edit(ServerEntry server) async {
await showServerEditor(context, server: server);
if (mounted) setState(() {});
}
Future<void> _add() async {
await showServerEditor(context);
if (mounted) setState(() {});
}
@override
Widget build(BuildContext context) {
final muted = DriverVault.muted(context);
return Padding(
padding: EdgeInsets.only(
left: 16,
right: 16,
top: 16,
bottom: DriverVault.sheetBottomInset(context),
),
child: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(t("servers.title"),
style: const TextStyle(fontSize: 18, fontWeight: FontWeight.w600)),
Padding(
padding: const EdgeInsets.only(top: 2, bottom: 8),
child: Text(t("servers.switchHint"),
style: TextStyle(fontSize: 12, color: muted)),
),
for (final server in serverRegistry.list)
ListTile(
contentPadding: EdgeInsets.zero,
// Green once this server has a session of its own; muted means
// picking it will ask for credentials rather than switch.
leading: Tooltip(
message: serverRegistry.isConnected(server.id)
? t("servers.connected")
: t("servers.notConnected"),
child: Icon(Icons.circle,
size: 10,
color: serverRegistry.isConnected(server.id)
? DriverVault.success
: muted.withValues(alpha: 0.4)),
),
title: Text(serverRegistry.displayName(server),
style: const TextStyle(fontWeight: FontWeight.w600)),
subtitle: Text(serverRegistry.baseFor(server),
style: DriverVault.mono(context, size: 11, color: muted),
overflow: TextOverflow.ellipsis),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
if (server.id == serverRegistry.activeId)
Icon(Icons.check, size: 18, color: Theme.of(context).colorScheme.primary),
IconButton(
icon: const Icon(Icons.edit_outlined, size: 18),
tooltip: t("common.edit"),
onPressed: () => _edit(server),
),
],
),
onTap: () => _choose(server),
),
const Divider(),
TextButton.icon(
onPressed: _add,
icon: const Icon(Icons.add),
label: Text(t("servers.add")),
),
],
),
),
);
}
}
class _ServerEditorSheet extends StatefulWidget {
// An existing server to edit/connect to, or null to add a new one.
final ServerEntry? server;
const _ServerEditorSheet({this.server});
@override
State<_ServerEditorSheet> createState() => _ServerEditorSheetState();
}
class _ServerEditorSheetState extends State<_ServerEditorSheet> {
late final TextEditingController _name;
late final TextEditingController _url;
final _email = TextEditingController();
final _password = TextEditingController();
bool _showPassword = false;
bool _busy = false;
String? _error;
bool get _isNew => widget.server == null;
bool get _isHome => widget.server?.isHome == true;
bool get _connected =>
widget.server != null && serverRegistry.isConnected(widget.server!.id);
@override
void initState() {
super.initState();
_name = TextEditingController(text: widget.server?.name ?? "");
_url = TextEditingController(text: widget.server?.url ?? "");
}
@override
void dispose() {
_name.dispose();
_url.dispose();
_email.dispose();
_password.dispose();
super.dispose();
}
Future<void> _submit() async {
setState(() {
_busy = true;
_error = null;
});
// Keep the server added in this attempt, so a second try after a bad
// password edits that entry instead of stacking up duplicates.
var target = widget.server;
// Read before the save: moving a connected server to a new address drops
// the token minted by the old one, and that is a save, not a sign-in — the
// credentials to replace it were never asked for.
final wasConnected = _connected;
try {
if (target == null) {
target = serverRegistry.add(name: _name.text, url: _url.text);
} else {
serverRegistry.update(target.id, name: _name.text, url: _url.text);
}
if (!wasConnected) {
await authService.connect(target.id, _email.text.trim(), _password.text);
adoptActiveServerProfile();
}
if (mounted) Navigator.pop(context);
} catch (e) {
// A server that never answered is not worth keeping in the list.
if (_isNew && target != null) serverRegistry.remove(target.id);
if (mounted) setState(() => _error = e.toString());
} finally {
if (mounted) setState(() => _busy = false);
}
}
void _signOut() {
authService.disconnect(widget.server!.id);
Navigator.pop(context);
}
Future<void> _remove() async {
final name = serverRegistry.displayName(widget.server);
final ok = await showDialog<bool>(
context: context,
builder: (ctx) => AlertDialog(
content: Text(t("servers.removeConfirm", params: {"name": name})),
actions: [
TextButton(onPressed: () => Navigator.pop(ctx, false), child: Text(t("common.cancel"))),
FilledButton(onPressed: () => Navigator.pop(ctx, true), child: Text(t("common.remove"))),
],
),
);
if (ok != true || !mounted) return;
serverRegistry.remove(widget.server!.id);
if (mounted) Navigator.pop(context);
}
@override
Widget build(BuildContext context) {
final muted = DriverVault.muted(context);
return Padding(
padding: EdgeInsets.only(
left: 16,
right: 16,
top: 16,
bottom: DriverVault.sheetBottomInset(context),
),
child: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(_isNew ? t("servers.addTitle") : serverRegistry.displayName(widget.server),
style: const TextStyle(fontSize: 18, fontWeight: FontWeight.w600)),
const SizedBox(height: 12),
if (_error != null)
Padding(
padding: const EdgeInsets.only(bottom: 8),
child: Text(_error!, style: const TextStyle(color: DriverVault.danger)),
),
TextField(
controller: _name,
textCapitalization: TextCapitalization.words,
decoration: InputDecoration(
labelText: t("servers.name"),
hintText: t("servers.namePlaceholder"),
border: const OutlineInputBorder(),
isDense: true,
),
),
const SizedBox(height: 10),
TextField(
controller: _url,
keyboardType: TextInputType.url,
autocorrect: false,
decoration: InputDecoration(
labelText: t("servers.url"),
hintText: _isHome ? kDefaultApiBase : "https://garage.example.com",
border: const OutlineInputBorder(),
isDense: true,
helperText: _isHome ? t("servers.urlHomeHint") : t("servers.urlHint"),
helperMaxLines: 3,
),
),
// Credentials only while this server has no session: each server is
// its own PocketBase, so signing in happens once per server.
if (!_connected) ...[
const SizedBox(height: 14),
const Divider(height: 1),
const SizedBox(height: 14),
TextField(
controller: _email,
keyboardType: TextInputType.emailAddress,
autocorrect: false,
decoration: InputDecoration(
labelText: t("login.email"),
border: const OutlineInputBorder(),
isDense: true,
),
),
const SizedBox(height: 10),
TextField(
controller: _password,
obscureText: !_showPassword,
decoration: InputDecoration(
labelText: t("login.password"),
border: const OutlineInputBorder(),
isDense: true,
suffixIcon: IconButton(
icon: Icon(_showPassword ? Icons.visibility_off : Icons.visibility),
tooltip: _showPassword ? t("login.hidePassword") : t("login.showPassword"),
onPressed: () => setState(() => _showPassword = !_showPassword),
),
),
onSubmitted: (_) => _submit(),
),
],
const SizedBox(height: 14),
SizedBox(
width: double.infinity,
child: FilledButton(
onPressed: _busy ? null : _submit,
child: Text(_busy
? t("servers.connecting")
: _connected
? t("common.save")
: t("servers.connect")),
),
),
if (_connected || (!_isNew && !_isHome))
Padding(
padding: const EdgeInsets.only(top: 4),
child: Row(
children: [
if (_connected)
TextButton(
onPressed: _signOut,
style: TextButton.styleFrom(foregroundColor: muted),
child: Text(t("servers.signOut")),
),
const Spacer(),
if (!_isNew && !_isHome)
TextButton(
onPressed: _remove,
style: TextButton.styleFrom(foregroundColor: DriverVault.danger),
child: Text(t("common.remove")),
),
],
),
),
],
),
),
);
}
}