web: settings destination with connection, workspace and templates (L1)

Completes the item: the Settings view, its pure helpers and the client's
socket-replacement path, plus the fix the review required (a header-side URL
correction clears the Settings field's own error) and a smoke check for it.
This commit is contained in:
2026-10-19 11:30:19 +01:00
parent 27a1605127
commit 597151cdd1
9 changed files with 1601 additions and 49 deletions
+431 -26
View File
@@ -14,6 +14,26 @@ import {
serverBuildLabel,
stateBadge,
} from "./connection.js";
import {
SERVER_URL_HELPER,
SERVER_URL_PLACEHOLDER,
TEMPLATES_CARD_LABEL,
TEMPLATES_CARD_SECONDARY,
TRUST_BODY,
TRUST_TITLE,
WORKSPACE_HELPER,
WORKSPACE_PLACEHOLDER,
canSaveWorkspace,
connectionActionKind,
connectionActions,
connectionCard,
readServerUrl,
readWorkspace,
savedWorkspaceLine,
workspaceErrorText,
writeServerUrl,
writeWorkspace,
} from "./settings.js";
import {
ArtifactKind,
artifactCaptureNotes,
@@ -294,8 +314,6 @@ import {
} from "./chat.js";
import { codeBlockLabel, parseInline, parseMarkdown } from "./markdown.js";
const STORAGE_KEY = "pipelines.web.serverUrl.v2";
/**
* The per-session chat scroll positions (C14). Persisted in localStorage, the
* browser analogue of the Android `ChatThread.scroll`: a position the operator
@@ -333,14 +351,29 @@ function defaultServerUrl() {
const client = new PipelinesClient();
const repo = new PipelinesRepository(client);
// Read the persisted settings once: the server URL falls back to the page's own
// proxy endpoint when unset, and the workspace starts blank when unset. Both the
// configured value and the draft start from storage.
const initialWorkspace = readWorkspace(localStorage);
const state = {
view: "pipelines",
url: localStorage.getItem(STORAGE_KEY) ?? defaultServerUrl(),
url: readServerUrl(localStorage) || defaultServerUrl(),
// The server URL's own validation message (Android's `urlError`), shown as the
// Settings field's supporting text and cleared as soon as the field is edited.
urlError: "",
// The workspace the operator configured (L1), the analogue of SettingsRepository's
// `workspace` preference. `workspaceDraft` is the field's live value; Save copies
// it into `workspace` and localStorage. Both start from the persisted value.
workspace: initialWorkspace,
workspaceDraft: initialWorkspace,
connection: client.state,
// The last `pong` reply is remembered so the banner can name a stale server
// build and warn about a protocol mismatch (T5) without re-pinging.
serverBuild: null,
serverProtocol: null,
// The `pong` reply's server time (L1), shown in the Settings connection card.
serverTime: null,
pipelines: [],
runs: [],
usage: null,
@@ -549,6 +582,47 @@ function endpointConfigured() {
return validateServerUrl(state.url).valid;
}
/**
* The one server-URL draft (Android's `serverUrlDraft`). Both the header field and
* the Settings `Server URL` field edit this same value and are mirrored in place
* without a re-render, so the two can never show different endpoints while typing
* (and neither loses focus). Editing also clears the field's own error, exactly as
* AppViewModel.updateServerUrlDraft does.
*/
function setServerUrlDraft(value, sourceId) {
state.url = value;
clearServerUrlError();
for (const id of ["url", "settingsServerUrl"]) {
if (id === sourceId) continue;
const other = document.getElementById(id);
if (other && other.value !== value) other.value = value;
}
// The Settings field mirrors this value even when the edit came from the header,
// so its own supporting text, error tint and aria-invalid must be refreshed from
// the same draft state too: a corrected URL can never leave the field announced
// as invalid (or keep the stale "That is not a valid URL." message) just because
// the correction happened in the header field.
if (document.getElementById("settingsServerUrl")) refreshServerUrlError();
}
/**
* Clear the server-URL validation error, wherever it was surfaced: the Settings
* field's own error always, and — when the invalid Connect came from another view
* — the matching page-level banner too, so an edit never leaves a stale message
* claiming the URL is still bad.
*/
function clearServerUrlError() {
if (!state.urlError) return;
const message = state.urlError;
state.urlError = "";
if (state.error === message) {
state.error = "";
for (const banner of document.querySelectorAll("#content .banner.error")) {
if ((banner.textContent ?? "").includes(message)) banner.remove();
}
}
}
function renderHeader() {
const info = bannerState(state.connection, { hasEndpoint: endpointConfigured() });
const controls = [
@@ -560,7 +634,7 @@ function renderHeader() {
value: state.url,
spellcheck: "false",
oninput: (e) => {
state.url = e.target.value;
setServerUrlDraft(e.target.value, "url");
},
}),
];
@@ -932,22 +1006,29 @@ function renderContent() {
tabButton("runs", `Runs (${state.runs.length})`),
tabButton("templates", "Templates"),
tabButton("chat", CHAT_TAB_TITLE),
tabButton("settings", "Settings"),
h("span", { class: "spacer" }),
h("button", { class: "ghost", text: "Refresh", onclick: () => loadCurrentView(true) }),
),
);
const split = h("div", { class: "split" });
if (state.view === "pipelines") {
split.append(renderPipelineList(), renderPipelineDetail());
} else if (state.view === "runs") {
split.append(renderRunList(), renderRunDetail());
} else if (state.view === "chat") {
split.append(renderChatList(), renderChatConversation());
// Settings is a single-pane destination (not the list/detail split): the
// app's own settings page is one scrolled column.
if (state.view === "settings") {
nodes.push(renderSettingsView());
} else {
split.append(renderTemplateGallery(), renderTemplateDetail());
const split = h("div", { class: "split" });
if (state.view === "pipelines") {
split.append(renderPipelineList(), renderPipelineDetail());
} else if (state.view === "runs") {
split.append(renderRunList(), renderRunDetail());
} else if (state.view === "chat") {
split.append(renderChatList(), renderChatConversation());
} else {
split.append(renderTemplateGallery(), renderTemplateDetail());
}
nodes.push(split);
}
nodes.push(split);
// Capture the live transcript's position before it is replaced, so the very
// next render can put the operator back exactly where they were (a dialog, a
// refresh or a paging frame must not move them).
@@ -986,6 +1067,314 @@ function tabButton(view, label) {
});
}
// --- Settings (L1) ---------------------------------------------------------
/**
* The Settings destination: the app's three sections (Connection, Workspace,
* Templates) in one pane. It is wiring only — every string, the workspace
* validation and the connection card's lines come from the pure `settings.js`,
* and the connection controls drive the page's existing single client through
* the same handlers the header uses (no second socket or path). Every
* server-derived string is set with textContent.
*/
function renderSettingsView() {
const pane = h("div", { class: "settings" });
pane.append(renderSettingsConnection(), renderSettingsWorkspace(), renderSettingsTemplates());
return pane;
}
function renderSettingsConnection() {
const section = h("section", { class: "settings-section" });
section.append(h("h2", { class: "settings-title", text: "Connection" }));
section.append(
h(
"label",
{ class: "settings-field", for: "settingsServerUrl" },
h("span", { class: "settings-field-label", text: "Server URL" }),
h("input", {
id: "settingsServerUrl",
type: "text",
placeholder: SERVER_URL_PLACEHOLDER,
value: state.url,
spellcheck: "false",
autocomplete: "off",
"aria-describedby": "settingsUrlHelper",
"aria-invalid": state.urlError ? "true" : null,
oninput: (event) => {
setServerUrlDraft(event.target.value, "settingsServerUrl");
},
}),
),
);
// Android's `urlError ?: helper` supporting text. The error clears on the next
// edit (AppViewModel.updateServerUrlDraft) and is announced as the field's own
// invalid state rather than as a page-level banner.
section.append(
h(
"p",
{
id: "settingsUrlHelper",
class: `settings-helper${state.urlError ? " settings-helper-error" : ""}`,
role: state.urlError ? "alert" : null,
},
serverUrlSupportingText(),
),
);
const actions = connectionActions(state.connection);
section.append(
h(
"div",
{ class: "settings-actions" },
h("button", {
id: "settingsPrimary",
class: "primary",
type: "button",
text: actions.primary,
onclick: () => runConnectionAction(actions.primary),
}),
h("button", {
id: "settingsSecondary",
class: "ghost",
type: "button",
text: actions.secondary,
onclick: () => runConnectionAction(actions.secondary),
}),
),
);
const tone = bannerState(state.connection, { hasEndpoint: endpointConfigured() }).tone;
const card = h("div", { class: `settings-status status-${tone}` });
const lines = connectionCard(state.connection, {
version: state.serverBuild?.version,
commit: state.serverBuild?.commit,
serverTime: state.serverTime,
});
lines.forEach((line, index) => {
// Android's Connecting card leads its one line with a CircularProgressIndicator;
// the shared spinner is drawn only for that state, inline with the text, so the
// other three stay plain text.
if (index === 0 && state.connection.kind === "connecting") {
const row = h("div", { class: "settings-status-head" });
row.append(h("span", { class: "spinner settings-status-spinner", "aria-hidden": "true" }));
row.append(h("p", { class: "settings-status-line", text: line }));
card.append(row);
return;
}
card.append(h("p", { class: "settings-status-line", text: line }));
});
section.append(card, renderTrustWarning());
return section;
}
/** The trusted-network warning card, SettingsScreen.kt's TrustWarning verbatim. */
function renderTrustWarning() {
return h(
"div",
{ class: "settings-warning" },
h("p", { class: "settings-warning-title", text: TRUST_TITLE }),
h("p", { class: "settings-warning-body", text: TRUST_BODY }),
);
}
/**
* Route a Settings connection control through the page's existing single client,
* mirroring AppViewModel: Disconnect closes the shared socket, Connect is
* connect-only (validate + persist + open — never the header's toggle), and
* Reconnect re-opens the same validated endpoint now. Nothing here opens a second
* connection.
*/
function runConnectionAction(label) {
const kind = connectionActionKind(label);
if (kind === "disconnect") {
repo.disconnect();
stopRunPoll();
return;
}
if (kind === "reconnect") {
onReconnectClicked();
return;
}
// The `Connect` label must never fall through to the header's toggle: while
// connected that would tear the live socket down (Android's connect() is
// connect-only).
openConfiguredEndpoint();
}
/** Android's `urlError ?: helper` supporting text for the Server URL field. */
function serverUrlSupportingText() {
return state.urlError || SERVER_URL_HELPER;
}
/**
* Update the Server URL field's own error state in place (supporting text,
* aria-invalid and the error tint) so an invalid Connect never needs a full
* re-render and the field being typed in is never rebuilt.
*/
function refreshServerUrlError() {
const field = document.getElementById("settingsServerUrl");
const helper = document.getElementById("settingsUrlHelper");
if (field) {
if (state.urlError) field.setAttribute("aria-invalid", "true");
else field.removeAttribute("aria-invalid");
}
if (helper) {
helper.textContent = serverUrlSupportingText();
helper.classList.toggle("settings-helper-error", Boolean(state.urlError));
if (state.urlError) helper.setAttribute("role", "alert");
else helper.removeAttribute("role");
}
}
function renderSettingsWorkspace() {
const section = h("section", { class: "settings-section" });
section.append(h("h2", { class: "settings-title", text: "Workspace" }));
section.append(
h(
"label",
{ class: "settings-field", for: "settingsWorkspace" },
h("span", { class: "settings-field-label", text: "Workspace path (on the server)" }),
h("input", {
id: "settingsWorkspace",
type: "text",
placeholder: WORKSPACE_PLACEHOLDER,
value: state.workspaceDraft,
spellcheck: "false",
autocomplete: "off",
"aria-describedby": "workspaceHelper",
"aria-invalid": workspaceErrorText(state.workspaceDraft) ? "true" : null,
oninput: (event) => {
state.workspaceDraft = event.target.value;
refreshWorkspaceControls();
},
}),
),
);
section.append(
h(
"p",
{
id: "workspaceHelper",
class: `settings-helper${workspaceErrorText(state.workspaceDraft) ? " settings-helper-error" : ""}`,
},
workspaceSupportingText(),
),
);
section.append(
h("button", {
id: "saveWorkspace",
class: "primary settings-save",
type: "button",
text: "Save workspace",
disabled: !canSaveWorkspace(state.workspaceDraft),
onclick: saveWorkspace,
}),
);
section.append(h("p", { id: "savedWorkspace", class: "settings-saved", text: savedWorkspaceLine(state.workspace) }));
return section;
}
/** Android's `workspaceError ?: helper` supporting text for the workspace field. */
function workspaceSupportingText() {
return workspaceErrorText(state.workspaceDraft) || WORKSPACE_HELPER;
}
/**
* Update the workspace field's dependent controls in place (the helper/error line
* and the Save button's enabled state) so typing never re-renders — and so never
* blurs — the field being typed in.
*/
function refreshWorkspaceControls() {
const helper = document.getElementById("workspaceHelper");
const invalid = Boolean(workspaceErrorText(state.workspaceDraft));
if (helper) {
helper.textContent = workspaceSupportingText();
helper.classList.toggle("settings-helper-error", invalid);
}
const field = document.getElementById("settingsWorkspace");
if (field) {
if (invalid) field.setAttribute("aria-invalid", "true");
else field.removeAttribute("aria-invalid");
}
const save = document.getElementById("saveWorkspace");
if (save) save.disabled = !canSaveWorkspace(state.workspaceDraft);
}
/** Persist the workspace (trimmed) and update the `Saved workspace:` line. */
function saveWorkspace() {
if (!canSaveWorkspace(state.workspaceDraft)) return;
state.workspace = writeWorkspace(localStorage, state.workspaceDraft);
state.workspaceDraft = state.workspace;
// Show the trimmed value that was actually stored, in the field as well as the
// saved line (both updated in place so the keyboard focus is not disturbed).
const field = document.getElementById("settingsWorkspace");
if (field) field.value = state.workspace;
const saved = document.getElementById("savedWorkspace");
if (saved) saved.textContent = savedWorkspaceLine(state.workspace);
}
/**
* Reset the template detail/create state that belongs to a selection. Shared by
* selecting a template and opening the gallery from Settings, so the two lists of
* fields can never drift.
*/
function resetTemplateCreateState() {
state.templateTab = "summary";
// A different template reseeds the create dialog, so a name typed for one
// template can never be submitted against another.
state.templateCreateOpen = false;
state.templateCreateName = "";
state.templateCreateSending = false;
state.templateCreateError = "";
state.templateCreateCreated = null;
}
/** Clear the selection and everything that belongs to it. */
function resetTemplateSelection() {
state.selectedTemplateKey = null;
resetTemplateCreateState();
}
/**
* Open the existing Templates gallery (L1's one card): switch the view, clear any
* selection/detail left from a previous visit and render. The gallery itself is
* unchanged — this is the same destination the Templates tab opens.
*/
function openTemplatesFromSettings() {
state.view = "templates";
state.error = "";
resetTemplateSelection();
renderContent();
if (!state.templates.length) loadCurrentView();
}
function renderSettingsTemplates() {
const section = h("section", { class: "settings-section" });
section.append(h("h2", { class: "settings-title", text: "Templates" }));
const card = h(
"button",
{
id: "browseTemplates",
class: "card settings-card",
type: "button",
onclick: openTemplatesFromSettings,
},
// SettingsScreen.kt's row idiom: a leading glyph, the label and secondary
// line, then a forward chevron.
h("span", { class: "settings-card-glyph", "aria-hidden": "true", text: "\u25a4" }),
h(
"span",
{ class: "settings-card-text" },
h("span", { class: "card-name", text: TEMPLATES_CARD_LABEL }),
h("span", { class: "card-desc", text: TEMPLATES_CARD_SECONDARY }),
),
h("span", { class: "settings-card-chevron", "aria-hidden": "true", text: "\u203a" }),
);
section.append(card);
return section;
}
function renderPipelineList() {
const list = h("div", { class: "list" });
list.append(renderPipelineControls());
@@ -5720,21 +6109,32 @@ function setError(err) {
* same validate → persist → repo.connect path. `repo.connect` resets the
* attempt/backoff inside client.js, cancelling a pending retry delay.
*
* `surfaceError` is false for the background (foreground-recovery) caller so a
* stale, invalid URL field cannot spray an error into the UI on every
* An invalid draft is reported as the Settings field's own error (Android's
* `urlError`) and cleared on the next edit; it is never left as a page-level
* banner. `surfaceError` is false for the background (foreground-recovery)
* caller so a stale, invalid URL field cannot spray an error into the UI on every
* visibilitychange/online event.
*/
function openConfiguredEndpoint({ surfaceError = true } = {}) {
const validated = validateServerUrl(state.url);
if (!validated.valid) {
if (surfaceError) {
state.error = validated.message;
renderContent();
state.urlError = validated.message;
// On another view the field is not rendered, so the page-level error is the
// only way to say why nothing happened; on Settings it belongs under the
// field.
if (state.view === "settings") {
refreshServerUrlError();
} else {
state.error = validated.message;
renderContent();
}
}
return;
}
state.error = "";
localStorage.setItem(STORAGE_KEY, state.url.trim());
state.urlError = "";
writeServerUrl(localStorage, state.url);
repo.connect(validated);
}
@@ -5785,11 +6185,23 @@ async function onConnected() {
// and warn about a protocol mismatch (T5); the ping is the only source.
state.serverProtocol = reply?.protocol ?? null;
state.serverBuild = reply?.build ?? null;
// The pong carries the server's own time (internal/protocol/message.go `Time`),
// shown in the Settings connection card.
state.serverTime = reply?.time ?? null;
// Update the banner at once; the content render that shows the build/time in
// the Settings card is the one `loadCurrentView` already performs (Settings is
// local, so that path is a single render and nothing is fetched twice).
renderBanner();
await loadCurrentView();
}
async function loadCurrentView(force = false) {
// Settings is local: it has no server-backed list to (re)load, so switching to
// or refreshing it must never raise the "connect first" error.
if (state.view === "settings") {
renderContent();
return;
}
if (state.connection.kind !== "connected") {
state.error = "Connect to the server first.";
renderContent();
@@ -5872,14 +6284,7 @@ async function validateTemplate(entry) {
function selectTemplate(key) {
state.selectedTemplateKey = key;
state.templateTab = "summary";
// A different template reseeds the create dialog, so a name typed for one
// template can never be submitted against another.
state.templateCreateOpen = false;
state.templateCreateName = "";
state.templateCreateSending = false;
state.templateCreateError = "";
state.templateCreateCreated = null;
resetTemplateCreateState();
renderContent();
}
+21 -1
View File
@@ -159,13 +159,33 @@ export class PipelinesClient extends EventTarget {
retrying: false,
});
const socket = new this.#WebSocketImpl(current);
const superseded = this.#ws;
this.#ws = socket;
// Replace the current socket, then close the one it superseded (mirrors
// PipelinesClient.openLocked). Its callbacks are ignored from then on, so a
// failure the old socket reports late can neither clear the new socket nor
// schedule a reconnect that would undo it. A request already sent on the old
// socket cannot receive a reply from the replacement, so fail it now rather
// than leaving a view waiting for the ordinary request timeout.
if (superseded) {
this.#failPending("Connection replaced");
try {
superseded.close(NORMAL_CLOSURE, "superseded");
} catch {
/* already closed */
}
}
socket.onopen = () => {
if (this.#ws !== socket) return;
this.#attempt = 0;
this.#setState({ kind: CONNECTED, attempt: 0, reason: "", retrying: false });
};
socket.onmessage = (event) => this.#onMessage(event.data);
socket.onmessage = (event) => {
if (this.#ws !== socket) return;
this.#onMessage(event.data);
};
socket.onclose = (event) => {
if (this.#ws !== socket) return;
this.#handleClosed(`Connection closed (${event.code ?? "?"})`);
};
socket.onerror = () => {
+10 -1
View File
@@ -14,6 +14,15 @@
/** The reconnect affordance, exactly as ConnectionBanner.kt names it. */
export const RECONNECT_LABEL = "Reconnect";
/**
* The one definition of the connecting line: `Connecting (attempt N)…`, shared by
* the persistent banner and the Settings status card so the same app sentence can
* never drift between the two.
*/
export function connectingLabel(attempt) {
return `Connecting (attempt ${attempt ?? 0})\u2026`;
}
/** Idle banner copy, verbatim from ConnectionBanner.kt. */
export const IDLE_BANNER_TEXT =
"Not connected. Enter the server URL in Settings, then connect.";
@@ -54,7 +63,7 @@ export function bannerState(connection, { hasEndpoint = false } = {}) {
case "connecting":
return {
tone: "connecting",
text: `Connecting (attempt ${c.attempt ?? 0})\u2026`,
text: connectingLabel(c.attempt),
action: null,
};
case "disconnected": {
+215
View File
@@ -0,0 +1,215 @@
// The Settings destination's pure logic and copy (L1): the exact strings the
// Android SettingsScreen.kt shows, the workspace-path validation rules
// (AppViewModel.validateWorkspace), the connection status card's lines, and the
// two localStorage keys that stand in for SettingsRepository's preferences.
//
// Deliberately free of DOM, sockets and timers, so every branch is unit-testable
// in Node and renders identically in the page. Wording authority:
// ui/screens/SettingsScreen.kt — the fields, helper lines, warning, status card
// and the TrustWarning / Templates row
// ui/AppViewModel.kt — validateWorkspace / saveWorkspace
// data/SettingsRepository.kt — the two persisted preferences (server URL, workspace)
// ui/screens/SettingsScreen.kt — the ConnectionStatusCard's connected build line
//
// The Android store persists the server URL and the workspace under `server_url`
// and `workspace`; the browser's analogue is localStorage. Only these two keys
// are ever written — never a credential, because the server has no authentication.
import { connectingLabel, serverBuildLabel } from "./connection.js";
/**
* The persisted server-URL key. It is the browser analogue of
* SettingsRepository's `KEY_SERVER_URL` and the single source of truth the page
* already used (`app.js`); kept here so the module owns both settings keys.
*/
export const SERVER_URL_STORAGE_KEY = "pipelines.web.serverUrl.v2";
/** The persisted workspace key (SettingsRepository's `KEY_WORKSPACE` analogue). */
export const WORKSPACE_STORAGE_KEY = "pipelines.web.workspace.v1";
/** Server-URL field copy, verbatim from SettingsScreen.kt. */
export const SERVER_URL_PLACEHOLDER = "ws://192.168.1.20:8081/connect";
export const SERVER_URL_HELPER =
"ws:// on a trusted LAN/VPN, or wss:// through a proxy/VPN. No authentication is used.";
/** Workspace field copy, verbatim from SettingsScreen.kt. */
export const WORKSPACE_PLACEHOLDER = "/Users/you/repos/pipelines";
export const WORKSPACE_HELPER =
"An absolute directory that already exists on the execution server. For Docker, " +
"mount the host directory at the same absolute path with its owner's UID/GID. " +
"This is not the phone's storage.";
/** The one workspace validation failure, verbatim from AppViewModel.validateWorkspace. */
export const WORKSPACE_ERROR =
"The workspace must be an absolute path that exists on the execution server.";
/** The trusted-network warning, verbatim from SettingsScreen.kt's TrustWarning. */
export const TRUST_TITLE = "Trusted LAN/VPN only";
export const TRUST_BODY =
"The Pipelines API has no authentication and is not internet-safe. Do not " +
"expose it to untrusted networks, and never enter provider credentials here \u2014 " +
"the app stores none.";
/** The templates entry, verbatim from SettingsScreen.kt. */
export const TEMPLATES_CARD_LABEL = "Browse templates";
export const TEMPLATES_CARD_SECONDARY = "Reusable pipeline definitions offered by the server.";
/**
* AppViewModel.validateWorkspace: a blank draft is not an error (the field is
* simply untouched), a non-absolute path names the failure, an absolute path is
* accepted. Returns the error string or null.
*/
export function validateWorkspacePath(value) {
const trimmed = String(value ?? "").trim();
if (trimmed === "") return null;
if (!trimmed.startsWith("/")) return WORKSPACE_ERROR;
return null;
}
/**
* The supporting text under the workspace field: the validation error when the
* draft is invalid, otherwise the helper line (Android's `workspaceError ?: helper`).
*/
export function workspaceErrorText(value) {
return validateWorkspacePath(value) ?? "";
}
/**
* Whether `Save workspace` is enabled. The page deliberately refuses a blank
* field (there is nothing to save) as well as a relative path, so the only
* enabled state is a trimmed absolute path. This is stricter than Android's
* `workspaceError == null` (which also enables Save on a blank field) and is
* recorded in web/PARITY.md.
*/
export function canSaveWorkspace(value) {
const trimmed = String(value ?? "").trim();
return trimmed !== "" && validateWorkspacePath(trimmed) === null;
}
/** The `Saved workspace:` line (Android's `configuredWorkspace.ifBlank { "(none)" }`). */
export function savedWorkspaceLine(value) {
const trimmed = String(value ?? "").trim();
return `Saved workspace: ${trimmed || "(none)"}`;
}
/**
* Read the persisted workspace. Tolerant and blank-on-unreadable: a missing
* storage, a throwing `getItem` or a non-string value all read as "".
*/
export function readWorkspace(storage) {
try {
const raw = storage?.getItem?.(WORKSPACE_STORAGE_KEY);
return typeof raw === "string" ? raw : "";
} catch {
return "";
}
}
/**
* Persist the workspace trimmed, exactly as SettingsRepository.setWorkspace
* does, and return the stored value so the caller can show the same line. Never
* throws: an unavailable/full storage leaves the in-memory value authoritative.
*/
export function writeWorkspace(storage, value) {
const trimmed = String(value ?? "").trim();
try {
storage?.setItem?.(WORKSPACE_STORAGE_KEY, trimmed);
} catch {
// A read-only or full localStorage must not break saving in memory.
}
return trimmed;
}
/**
* Read the persisted server URL. The same tolerant contract as `readWorkspace`:
* a missing storage, a throwing `getItem` or a non-string value all read as "".
* (The page treats "" as "use the default endpoint", exactly as before.)
*/
export function readServerUrl(storage) {
try {
const raw = storage?.getItem?.(SERVER_URL_STORAGE_KEY);
return typeof raw === "string" ? raw : "";
} catch {
return "";
}
}
/**
* Persist the server URL trimmed, mirroring SettingsRepository.setServerUrl.
* Never throws: an unavailable/full storage leaves the in-memory value
* authoritative. Returns the stored value.
*/
export function writeServerUrl(storage, value) {
const trimmed = String(value ?? "").trim();
try {
storage?.setItem?.(SERVER_URL_STORAGE_KEY, trimmed);
} catch {
// A read-only or full localStorage must not break connecting.
}
return trimmed;
}
/**
* The connection status card's lines, exactly per SettingsScreen.kt's
* ConnectionStatusCard:
* idle -> "Not connected"
* connecting -> "Connecting (attempt N)…"
* connected -> "Connected", the build line when present, "Server time t" when present
* disconnected -> "Disconnected", the message, "Retrying with backoff…" only while retrying
*
* The connecting and build lines reuse `connection.js`, so each sentence has one
* definition shared with the header banner.
*/
export function connectionCard(state, { version, commit, serverTime } = {}) {
const c = state ?? {};
switch (c.kind) {
case "connected": {
const lines = ["Connected"];
const build = serverBuildLabel({ version, commit });
if (build) lines.push(build);
const time = String(serverTime ?? "").trim();
if (time) lines.push(`Server time ${time}`);
return lines;
}
case "connecting":
return [connectingLabel(c.attempt)];
case "disconnected": {
const lines = ["Disconnected"];
const reason = String(c.reason ?? "").trim();
if (reason) lines.push(reason);
if (c.retrying) lines.push("Retrying with backoff\u2026");
return lines;
}
default:
return ["Not connected"];
}
}
/**
* The emphasised primary action and the de-emphasised secondary one, mirroring
* SettingsScreen.kt's `active` branch: while connected (or connecting) the
* meaningful action is Disconnect, otherwise Connect, with Reconnect offered
* while idle/disconnected. The labels are the app's own.
*/
export function connectionActions(state) {
const kind = (state ?? {}).kind;
const active = kind === "connected" || kind === "connecting";
return active
? { primary: "Disconnect", secondary: "Connect" }
: { primary: "Connect", secondary: "Reconnect" };
}
/**
* Which existing client operation an action label drives. The mapping is pure so
* the page cannot accidentally send `Connect` through the header's toggle (which
* disconnects while connected): Android's `AppViewModel.connect()` is
* connect-only, `reconnect()` re-opens the saved endpoint and `disconnect()` is
* the only thing that closes the socket. Returns one of
* `"disconnect" | "reconnect" | "connect"`; anything that is not a known
* disconnect/reconnect label is a connect.
*/
export function connectionActionKind(label) {
if (label === "Disconnect") return "disconnect";
if (label === "Reconnect") return "reconnect";
return "connect";
}