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();
}