Merge branch 'main' into web-chat-create

# Conflicts:
#	web/PARITY.md
#	web/src/app.js
#	web/test/chat.test.mjs
#	web/test/ui-smoke.mjs
This commit is contained in:
2026-10-19 14:31:08 +01:00
11 changed files with 2339 additions and 80 deletions
+629 -47
View File
@@ -174,6 +174,15 @@ import {
decodeAttentionDismissals,
encodeAttentionDismissals,
} from "./attention.js";
import {
NOTIFICATION_RATIONALE,
NOTIFY_STORAGE_KEY,
createAlertLedger,
decodeNotificationSettings,
encodeNotificationSettings,
notificationEnvironment,
notificationPermissionState,
} from "./notify.js";
import {
DEFAULT_SEARCH_KIND,
DEFAULT_SEARCH_SORT,
@@ -228,6 +237,7 @@ import {
} from "./actions.js";
import {
BACKGROUND_TASKS_TITLE,
CHAT_ACTIONS_LABEL,
CHAT_ATTACH_LABEL,
CHAT_COMMAND_DISMISS_LABEL,
CHAT_COMMAND_GLYPH,
@@ -241,14 +251,23 @@ import {
CHAT_CREATE_TITLE,
CHAT_EMPTY,
CHAT_FOLLOW_THRESHOLD_PX,
CHAT_HIDE_ACTION,
CHAT_LOADING,
CHAT_NEW_ACTION,
CHAT_NO_MATCH_ACTION,
CHAT_QUEUED_NOTICE,
CHAT_REMOVED_MESSAGE,
CHAT_RENAME_ACTION,
CHAT_RENAME_DISMISS,
CHAT_RENAME_FIELD_LABEL,
CHAT_RENAME_HELPER,
CHAT_RENAME_SAVE,
CHAT_RENAME_TITLE,
CHAT_SEARCH_LABEL,
CHAT_SEND_LABEL,
CHAT_STOP_LABEL,
CHAT_TAB_TITLE,
CHAT_UNDO_ACTION,
CLOSED_CHIP_LABEL,
CLOSED_SECTION_LABEL,
CLOSE_CHAT_ACTION,
@@ -279,6 +298,7 @@ import {
SHELL_OUTPUT_UNAVAILABLE,
SHELL_ROW_LABEL,
applyChatEvent,
applyChatOverrides,
applyChatPermission,
appendChatNotice,
approvalCard,
@@ -292,7 +312,6 @@ import {
chatCommandSuggestions,
chatCreateFailed,
chatCreateSucceeded,
chatStartInLabel,
chatFirstScroll,
chatFollowsAt,
chatHeaderMeta,
@@ -300,31 +319,45 @@ import {
chatNoticeLabel,
chatOpensAtNewest,
chatShowJumpToLatest,
chatStartInLabel,
chatStreamState,
closeChatConfirmation,
composerAction,
composerCanSend,
composerSendEnabled,
composerSubmit,
decodeChatOverrides,
decodeChatSeen,
defaultDirectoryChoice,
directoryChoices,
directoryLabel,
dismissChatNotice as dismissChatNoticeModel,
emptyChatOverrides,
emptyChatSeen,
encodeChatOverrides,
encodeChatSeen,
filterSessions,
groupSessionsByDirectory,
hideChatOverride,
historyResync,
isChatSessionUnseen,
makeChatNotice,
markChatUnseen,
mergeHistoryPage,
mergeShellFrame,
newChatCreateState,
newChatThread,
parseChatInput,
queuedAfterFrame,
readChatSeen,
reasoningLabel,
renameChatOverride,
restoreChatOverride,
resumedThread,
runningAfterFrame,
runningBackgroundShells,
runningToolElapsedMillis,
seedChatSeen,
sessionActivity,
sessionActivityBadge,
sessionChipLabel,
@@ -377,6 +410,22 @@ const CHAT_SCROLL_STORAGE_KEY = "pipelines.web.chatScroll.v1";
*/
const CHAT_DRAFT_STORAGE_KEY = "pipelines.web.chatDraft.v1";
/**
* The operator's own chat changes (C13): local renames and hidden session ids,
* the web analogue of Android's `chat_overrides` preference. One JSON value:
* `{titles:{"<id>":"<title>"},hidden:["<id>"]}`. A local title wins over the
* server's on every later list refresh; a hidden id only disappears here.
*/
const CHAT_OVERRIDES_STORAGE_KEY = "pipelines.web.chatOverrides.v1";
/**
* What the operator has already seen of the session list (C13), the web analogue
* of Android's `chat_seen` preference. One JSON value:
* `{seenAt:{"<id>":<updated_at ms>},unseen:["<id>"]}`. The watermark is advanced
* only by opening a chat (or first-sight seeding), never by a stale list.
*/
const CHAT_SEEN_STORAGE_KEY = "pipelines.web.chatSeen.v1";
/** Shown where tiles exist but the configured server URL cannot resolve them. */
const ARTIFACT_SERVER_HINT =
"Set the server URL in Settings to open or copy artifact links.";
@@ -483,6 +532,10 @@ const state = {
attentionDismissed: new Set(),
attentionSheetOpen: false,
attentionSnapshot: null,
// Notifications (L5): whether the operator has already been asked, loaded once
// at boot from localStorage. The browser owns the permission itself; this flag
// only changes the honest wording in Settings and is never a claim of consent.
notifyAsked: false,
// Omni-search (S1/S2): the field/panel state, kept beside the view it never
// changes, plus the pure debounce/stale-token sequencer. Opening or closing the
// search leaves state.view, the selection and the loaded data untouched.
@@ -551,6 +604,18 @@ const state = {
// report for a refused close/reopen.
chatClose: null,
chatBusy: false,
// C13: this device's local titles/hidden ids and the seen watermarks, both
// persisted as one JSON value each. `chatMenu` is the row whose Chat actions
// menu is open, `chatRename` the session whose Rename chat dialog is open, and
// `chatSnackbar` the one in-flight hide report (`{id, sessionId}`) with the
// timer that auto-dismisses it. A new hide replaces the previous report.
chatOverrides: readChatOverridesStore(),
chatSeen: readChatSeenStore(),
chatMenu: null,
chatRename: null,
chatSnackbar: null,
chatSnackbarSeq: 0,
chatSnackbarTimer: null,
// C5: the session ids this connection currently has subscribed to their shared
// live stream. The server detaches a subscription when the connection closes
// (there is no chat_unsubscribe), so this is cleared on every socket drop and
@@ -567,6 +632,11 @@ const state = {
chatCreate: null,
};
// The run-notification ledger (L5). It is seeded from the authoritative run list
// and from the subscribe snapshot, then observes pushed `run_event` frames; it
// never feeds the runs list (that is R10's separate fold).
const runAlerts = createAlertLedger();
let runPoll = null;
// One shared live clock for the runs list: it ticks only while a shown run is
@@ -1033,6 +1103,76 @@ function loadAttentionDismissed() {
}
}
/**
* Fold one pushed `run_event` frame into the notification ledger (L5). It does
* not touch the runs list (R10's fold is separate); it only decides whether this
* transition raises exactly one notification. A run already failed/waiting when
* seeded, a duplicate frame, a non-qualifying status and a key the operator
* dismissed all produce nothing.
*/
function onRunAlertFrame(frame) {
const alert = runAlerts.observe(frame, { dismissed: state.attentionDismissed });
if (!alert || !notificationsAllowed()) return;
try {
const notification = new Notification(alert.title, { body: alert.body, tag: alert.key });
notification.onclick = () => {
window.focus();
state.view = "runs";
render();
selectRun(alert.runId);
};
} catch {
// Some browsers can throw even with permission granted; the in-page Needs
// you surface remains the only honest channel and nothing is faked.
}
}
/** True only when a real browser notification can be constructed right now. */
function notificationsAllowed() {
return (
typeof globalThis.Notification === "function" &&
globalThis.isSecureContext === true &&
globalThis.Notification.permission === "granted"
);
}
/** Persist only the asked flag; never a permission claim, endpoint or credential. */
function persistNotifyAsked(asked) {
state.notifyAsked = Boolean(asked);
try {
localStorage.setItem(NOTIFY_STORAGE_KEY, encodeNotificationSettings({ asked }));
} catch {
// Storage disabled or full: the in-memory flag still applies for this session.
}
}
/** The asked flag from storage at boot; anything unreadable means never asked. */
function loadNotifyAsked() {
try {
return decodeNotificationSettings(localStorage.getItem(NOTIFY_STORAGE_KEY)).asked;
} catch {
return false;
}
}
/**
* Start the run-event watch for this connected epoch: seed from the list that is
* already in hand, treat the subscribe snapshot as seeds too (the server writes
* it before the ack), then observe deltas. A refused subscribe only means no
* pushes; the page keeps working and Settings stays honest.
*/
async function startRunAlertWatch() {
runAlerts.seed(state.runs);
runAlerts.beginSeed();
try {
await repo.subscribeRuns();
} catch {
// No live watch: notifications simply cannot raise on this connection.
} finally {
runAlerts.endSeed();
}
}
function render() {
renderHeader();
renderBanner();
@@ -1140,7 +1280,12 @@ function tabButton(view, label) {
*/
function renderSettingsView() {
const pane = h("div", { class: "settings" });
pane.append(renderSettingsConnection(), renderSettingsWorkspace(), renderSettingsTemplates());
pane.append(
renderSettingsConnection(),
renderSettingsWorkspace(),
renderSettingsNotifications(),
renderSettingsTemplates(),
);
return pane;
}
@@ -1229,6 +1374,75 @@ function renderSettingsConnection() {
return section;
}
/**
* The Notifications section (L5). The Android rationale is shown verbatim; the
* status line is the pure permission view for this page's real browser facts.
* Only the explicit control asks for permission, never page load. When the API
* is unavailable, the page is insecure or permission is denied, the wording says
* plainly that the in-app Needs you surface is the only channel — no fake
* notification is ever drawn.
*/
function renderSettingsNotifications() {
const view = notificationPermissionState({
...notificationEnvironment(),
asked: state.notifyAsked,
});
const section = h("section", { class: "settings-section", id: "settingsNotifications" });
section.append(h("h2", { class: "settings-title", text: "Notifications" }));
section.append(h("p", { class: "settings-helper", text: NOTIFICATION_RATIONALE }));
section.append(
h("p", {
id: "settingsNotificationState",
class: `settings-notify-state settings-notify-${view.state}`,
role: "status",
text: view.body,
}),
);
if (view.canRequest) {
section.append(
h(
"div",
{ class: "settings-actions" },
h("button", {
id: "settingsEnableNotifications",
class: "primary",
type: "button",
text: view.actionLabel,
onclick: requestNotifications,
}),
),
);
}
return section;
}
/**
* Ask for notification permission from the operator's explicit click. The asked
* flag is persisted first and the page re-renders from the browser's real answer;
* a refused/dismissed prompt leaves the honest default/denied wording in place.
*/
function requestNotifications() {
persistNotifyAsked(true);
const ctor = globalThis.Notification;
if (typeof ctor !== "function" || !globalThis.isSecureContext) {
renderContent();
return;
}
try {
const result = ctor.requestPermission();
if (result && typeof result.then === "function") {
result.then(
() => renderContent(),
() => renderContent(),
);
return;
}
} catch {
// A browser that refuses the request keeps the honest fallback wording.
}
renderContent();
}
/** The trusted-network warning card, SettingsScreen.kt's TrustWarning verbatim. */
function renderTrustWarning() {
return h(
@@ -3947,6 +4161,47 @@ function readChatDraft(sessionId) {
return typeof value === "string" ? value : "";
}
/** The persisted local chat overrides; unreadable storage means no overrides. */
function readChatOverridesStore() {
try {
return decodeChatOverrides(localStorage.getItem(CHAT_OVERRIDES_STORAGE_KEY));
} catch {
return emptyChatOverrides();
}
}
/** Persist the current local overrides; storage failure leaves memory authoritative. */
function saveChatOverrides() {
try {
localStorage.setItem(CHAT_OVERRIDES_STORAGE_KEY, encodeChatOverrides(state.chatOverrides));
} catch {
// storage may be full or disabled; the in-memory overrides still hold
}
}
/** The persisted seen state; unreadable storage means nothing seen. */
function readChatSeenStore() {
try {
return decodeChatSeen(localStorage.getItem(CHAT_SEEN_STORAGE_KEY));
} catch {
return emptyChatSeen();
}
}
/**
* Persist the seen state only when it actually changed. Every frame and refresh
* would otherwise rewrite localStorage for no reason.
*/
function saveChatSeen(next) {
if (next === state.chatSeen) return;
state.chatSeen = next;
try {
localStorage.setItem(CHAT_SEEN_STORAGE_KEY, encodeChatSeen(state.chatSeen));
} catch {
// storage may be full or disabled; the in-memory state still holds
}
}
/**
* The pixels the transcript still sits above its end (0 when at the bottom), via
* the same pure decision the unit tests cover. `chatBottomDistancePx` measures
@@ -4022,6 +4277,10 @@ async function loadChatSessions(force = false) {
);
state.chatSessions = [...held, ...listed];
state.chatLoaded = true;
// Fold this device's seen state in: the active chat has been read, and every
// session seen for the first time gets a baseline so pre-existing chats are
// not all reported as new.
saveChatSeen(seedChatSeen(state.chatSeen, state.chatSessions, state.chatActiveId));
} catch (error) {
state.chatError = describeError(error);
}
@@ -4115,11 +4374,16 @@ async function openChatSession(id) {
const leaving = document.getElementById("chatTranscript");
if (leaving && state.chatActiveId) saveChatScroll(state.chatActiveId, currentChatPosition(leaving));
state.chatActiveId = id;
state.chatMenu = null;
state.chatPlaced = null;
state.chatFollowing = true;
state.chatReasoning = new Set();
state.chatToolPanels = new Set();
state.chatToolRows = new Set();
// Opening reads the conversation: advance the watermark to its current recency
// and clear the explicit unseen mark (a row that is absent has no recency).
const session = state.chatSessions.find((candidate) => candidate.id === id) ?? null;
saveChatSeen(readChatSeen(state.chatSeen, id, session?.updated_at ?? 0));
const existing = state.chatThreads.get(id);
state.chatThreads.set(id, {
...newChatThread(id),
@@ -4199,11 +4463,23 @@ function settleChatThreads() {
function onChatEvent(frame) {
const sessionId = String(frame?.session_id ?? "").trim();
if (!sessionId || !state.chatThreads.has(sessionId)) return;
markBackgroundChatUnseen(sessionId);
const thread = state.chatThreads.get(sessionId);
state.chatThreads.set(sessionId, applyChatEvent(thread, frame, Date.now()));
renderContent();
}
/**
* A frame for a conversation that is not on screen marks it explicitly unseen,
* so its live activity is visible in the list even though a pushed stream carries
* no wall-clock recency to compare. The active chat is read as it arrives and is
* never marked.
*/
function markBackgroundChatUnseen(sessionId) {
if (!sessionId || sessionId === state.chatActiveId) return;
saveChatSeen(markChatUnseen(state.chatSeen, sessionId));
}
/**
* Fold one pushed `chat_permission` frame into its conversation (C10). Only a
* conversation this client has open is folded — the server only pushes a
@@ -4415,6 +4691,7 @@ async function loadOlderChatHistory(id) {
/** Open the Close chat? confirm for [session] (the mutation only on confirm). */
function openChatClose(session) {
state.chatMenu = null;
state.chatClose = session;
renderContent();
}
@@ -4462,6 +4739,7 @@ async function acceptChatClose(session) {
async function reopenChatSession(id) {
if (state.chatBusy) return;
state.chatBusy = true;
state.chatMenu = null;
renderContent();
try {
const { session: updated } = await repo.reopenChat(id);
@@ -4480,6 +4758,136 @@ function applyChatSessionUpdate(id, updated, closed) {
);
}
// ---------------------------------------------------------------------------
// This device's chat changes (C13): local rename, hide + undo, row menu
// ---------------------------------------------------------------------------
/** The server row with this device's local title applied (for the open pane). */
function effectiveChatSession(session) {
if (!session) return null;
return applyChatOverrides([session], state.chatOverrides)[0] ?? session;
}
/** Open one row's Chat actions menu, closing any other. */
function openChatMenu(sessionId) {
state.chatMenu = state.chatMenu === sessionId ? null : sessionId;
renderContent();
// The re-render replaced the focused button; move focus into the panel so a
// keyboard operator can walk the items without hunting for the next Tab stop.
if (state.chatMenu) {
const first = document.querySelector(`#chatRows .chat-row[data-session="${CSS.escape(sessionId)}"] .chat-menu-item`);
first?.focus();
}
}
/** Open the Rename chat dialog for [session] (its current effective title). */
function openChatRename(session) {
state.chatMenu = null;
state.chatRename = session;
renderContent();
// Same re-render note as the menu: put the cursor in the Name field.
document.getElementById("chatRenameInput")?.focus();
}
function dismissChatRename() {
state.chatRename = null;
renderContent();
}
/**
* Record a local rename, persist it and reflect it at once: the row shows the
* local title on the next render (and every later refresh), and an open
* conversation's own title follows. Nothing is sent to the server — the
* brokered protocol has no chat rename.
*/
function applyLocalChatRename(sessionId, title) {
const next = renameChatOverride(state.chatOverrides, sessionId, title);
if (next === state.chatOverrides) return false;
state.chatOverrides = next;
saveChatOverrides();
const local = next.titles[String(sessionId)];
if (local != null) setThread(sessionId, { title: local });
return true;
}
/**
* The dialog's Save: trim, record the override, close the dialog and re-render.
* A blank title is ignored (Save is already disabled while trimmed-blank).
*/
function acceptChatRename(session, title) {
const trimmed = String(title ?? "").trim();
if (trimmed === "") return;
applyLocalChatRename(session.id, trimmed);
state.chatRename = null;
renderContent();
}
/**
* Hide a session on this device only. The server is not asked to delete
* anything: the row disappears from this list, its conversation closes, and the
* one snackbar says exactly that with an Undo. A new hide replaces the previous
* report (one snackbar slot), never queues behind it.
*/
function hideChatLocally(sessionId) {
const id = String(sessionId ?? "");
if (!id) return;
const next = hideChatOverride(state.chatOverrides, id);
if (next === state.chatOverrides) return;
state.chatOverrides = next;
saveChatOverrides();
state.chatMenu = null;
state.chatRename = null;
// Hiding closes the conversation, exactly as Android's remove does: the thread
// is dropped, the active id cleared and the subscription forgotten.
state.chatThreads.delete(id);
if (state.chatActiveId === id) {
state.chatActiveId = null;
state.chatPlaced = null;
}
if (state.chatSubscriptions.has(id)) {
state.chatSubscriptions = new Set(state.chatSubscriptions);
state.chatSubscriptions.delete(id);
}
installChatSnackbar(id);
renderContent();
}
/** Replace the one in-flight hide report and (re)start its auto-dismiss timer. */
function installChatSnackbar(sessionId) {
if (state.chatSnackbarTimer != null) clearTimeout(state.chatSnackbarTimer);
state.chatSnackbarSeq += 1;
const id = state.chatSnackbarSeq;
state.chatSnackbar = { id, sessionId };
state.chatSnackbarTimer = setTimeout(() => {
state.chatSnackbarTimer = null;
if (state.chatSnackbar?.id !== id) return;
state.chatSnackbar = null;
renderContent();
}, 6000);
}
/** Undo the last hide: restore its row and clear the report (nothing server-side). */
function undoHideChat() {
const sessionId = state.chatSnackbar?.sessionId;
if (!sessionId) return;
const next = restoreChatOverride(state.chatOverrides, sessionId);
if (next !== state.chatOverrides) {
state.chatOverrides = next;
saveChatOverrides();
}
clearChatSnackbar();
renderContent();
}
/** Drop the hide report and its timer (Undo, expiry, or leaving the list). */
function clearChatSnackbar() {
if (state.chatSnackbarTimer != null) {
clearTimeout(state.chatSnackbarTimer);
state.chatSnackbarTimer = null;
}
state.chatSnackbar = null;
}
// ---------------------------------------------------------------------------
// The composer and its slash commands (C8 · C9)
// ---------------------------------------------------------------------------
@@ -4666,8 +5074,9 @@ function runChatCommand(sessionId, session, text) {
/**
* Perform one command effect. `/new` creates a session in the current directory
* and opens it (the create request is C2's; until C2 lands the browser sends
* `chat_create` directly); `/close` reuses the C3 confirm; `/rename` is the local
* rename pending C13; `/stop` interrupts; `/help` shows the command list.
* `chat_create` directly); `/close` reuses the C3 confirm; `/rename` writes to
* C13's durable device-local store; `/stop` interrupts; `/help` shows the
* command list.
*/
function applyChatCommandEffect(sessionId, session, effect) {
switch (effect.kind) {
@@ -4732,16 +5141,15 @@ async function startChatSession(directory) {
}
/**
* `/rename`: rename the session on this device only. C13 owns the durable local
* rename/hide store; until it lands this renames the held row and the open
* conversation in memory and says so.
* `/rename`: rename the session on this device only, through the same durable
* store the row's Rename chat dialog uses (C13). The local title wins over the
* server's on every later refresh; nothing is sent to the server.
*/
function renameChatSessionLocally(sessionId, title) {
state.chatSessions = state.chatSessions.map((session) =>
session.id === sessionId ? { ...session, title } : session,
);
setThread(sessionId, { title });
addChatNotice(sessionId, `Renamed this session to “${title}” on this device only; the server's title is unchanged.`);
const trimmed = String(title ?? "").trim();
if (trimmed === "") return;
applyLocalChatRename(sessionId, trimmed);
addChatNotice(sessionId, `Renamed this session to “${trimmed}” on this device only; the server's title is unchanged.`);
}
/** The composer's Stop control: interrupt the session's running turn. */
@@ -4875,7 +5283,9 @@ function removeChatAttachment(sessionId, attachmentId) {
}
function renderChatList() {
const list = h("div", { class: "list chat-list" });
// The open menu must not be clipped by the list's rounded-corner overflow; the
// class is present only while a menu is open, so the normal list stays clipped.
const list = h("div", { class: `list chat-list${state.chatMenu ? " menu-open" : ""}` });
const toolbar = h("div", { class: "list-toolbar chat-toolbar" });
toolbar.append(
h("input", {
@@ -4923,7 +5333,8 @@ function fillChatRows(rows) {
rows.append(empty);
return;
}
const filtered = filterSessions(state.chatSessions, state.chatQuery);
const visible = applyChatOverrides(state.chatSessions, state.chatOverrides);
const filtered = filterSessions(visible, state.chatQuery);
if (filtered.length === 0 && state.chatQuery.trim() !== "") {
const empty = chatEmpty(chatNoMatchMessage(state.chatQuery));
empty.append(
@@ -4986,7 +5397,14 @@ function chatEmpty(message) {
function renderChatRow(session) {
const open = state.chatActiveId === session.id;
const thread = state.chatThreads.get(session.id) ?? null;
const activity = sessionActivity(thread?.running === true, false);
const unseen =
!session.closed &&
isChatSessionUnseen(session, {
activeId: state.chatActiveId,
seen: state.chatSeen,
opened: state.chatThreads.has(session.id),
});
const activity = sessionActivity(thread?.running === true, unseen);
const badge = sessionActivityBadge(activity, open);
const row = h("div", {
class: `row chat-row${open ? " selected" : ""}`,
@@ -4995,8 +5413,8 @@ function renderChatRow(session) {
"data-session": session.id,
onclick: () => openChatSession(session.id),
onkeydown: (event) => {
// Only the row itself opens on Enter/Space; a nested Close chat…/Reopen
// button handles its own keyboard activation (and must not double-fire).
// Only the row itself opens on Enter/Space; the Chat actions menu handles
// its own keyboard activation (and must not double-fire).
if (event.target !== event.currentTarget) return;
if (event.key === "Enter" || event.key === " ") {
event.preventDefault();
@@ -5024,35 +5442,7 @@ function renderChatRow(session) {
text: sessionMeta(session, sessionWorkLabel(session.busy === true, thread)),
}),
);
const actions = h("div", { class: "chat-row-actions" });
if (session.closed) {
actions.append(
h("button", {
class: "ghost chat-reopen",
type: "button",
text: REOPEN_ACTION,
disabled: state.chatBusy,
onclick: (event) => {
event.stopPropagation();
reopenChatSession(session.id);
},
}),
);
} else {
actions.append(
h("button", {
class: "ghost chat-close",
type: "button",
text: CLOSE_CHAT_ACTION,
disabled: state.chatBusy,
onclick: (event) => {
event.stopPropagation();
openChatClose(session);
},
}),
);
}
row.append(actions);
row.append(renderChatActionsMenu(session));
return row;
}
@@ -5169,6 +5559,78 @@ function renderChatCreate() {
return pane;
}
/**
* One row's Chat actions menu, with Android's items in its order: Rename…, then
* Close chat… (open) or Reopen (closed), then Hide on this device. Closing is the
* shared, server-side finish; hiding only affects this device and says so.
*/
function renderChatActionsMenu(session) {
const wrap = h("div", { class: "chat-row-actions chat-menu-wrap" });
const expanded = state.chatMenu === session.id;
wrap.append(
h("button", {
class: "ghost chat-menu-button",
type: "button",
text: "⋯",
"aria-label": CHAT_ACTIONS_LABEL,
"aria-haspopup": "menu",
"aria-expanded": expanded ? "true" : "false",
title: CHAT_ACTIONS_LABEL,
onclick: (event) => {
event.stopPropagation();
openChatMenu(session.id);
},
}),
);
if (expanded) {
const menu = h("div", { class: "chat-menu-panel", role: "menu", "aria-label": CHAT_ACTIONS_LABEL });
menu.addEventListener("click", (event) => event.stopPropagation());
menu.append(
h("button", {
class: "ghost chat-menu-item chat-menu-rename",
type: "button",
role: "menuitem",
text: CHAT_RENAME_ACTION,
onclick: () => openChatRename(session),
}),
);
if (session.closed) {
menu.append(
h("button", {
class: "ghost chat-menu-item chat-menu-reopen",
type: "button",
role: "menuitem",
text: REOPEN_ACTION,
disabled: state.chatBusy,
onclick: () => reopenChatSession(session.id),
}),
);
} else {
menu.append(
h("button", {
class: "ghost chat-menu-item chat-menu-close",
type: "button",
role: "menuitem",
text: CLOSE_CHAT_ACTION,
disabled: state.chatBusy,
onclick: () => openChatClose(session),
}),
);
}
menu.append(
h("button", {
class: "ghost chat-menu-item chat-menu-hide",
type: "button",
role: "menuitem",
text: CHAT_HIDE_ACTION,
onclick: () => hideChatLocally(session.id),
}),
);
wrap.append(menu);
}
return wrap;
}
/** The active conversation: identity, context, transcript and its controls. */
function renderChatConversation() {
const pane = h("div", { class: "detail chat-detail" });
@@ -5178,8 +5640,9 @@ function renderChatConversation() {
return pane;
}
const session = state.chatSessions.find((candidate) => candidate.id === state.chatActiveId) ?? null;
const effective = effectiveChatSession(session);
const thread = state.chatThreads.get(state.chatActiveId) ?? null;
const title = session ? sessionTitle(session) : state.chatActiveId.slice(0, 18);
const title = effective ? sessionTitle(effective) : state.chatActiveId.slice(0, 18);
// The pending approval card (C10), derived from the stored frame plus the local
// answer. While it is actionable the top bar offers a jump control and the
// running indicator stands down (a turn blocked on a decision is not generating).
@@ -5291,9 +5754,89 @@ function renderChatConversation() {
*/
function appendChatDialogs(pane) {
if (state.chatClose) pane.append(renderChatCloseDialog(state.chatClose));
if (state.chatRename) pane.append(renderChatRenameDialog(state.chatRename));
if (state.chatSnackbar) pane.append(renderChatSnackbar());
if (state.actionError) pane.append(renderActionFailedDialog());
}
/**
* The one hide report (C13): the exact Android message and an `Undo` action. It
* is a fixed overlay (so a re-render or the transcript's height never moves it)
* and it is replaced, never queued, by a newer hide.
*/
function renderChatSnackbar() {
const bar = h("div", { class: "chat-snackbar", role: "status" });
bar.append(h("span", { class: "chat-snackbar-message", text: CHAT_REMOVED_MESSAGE }));
bar.append(
h("button", {
class: "ghost chat-snackbar-undo",
type: "button",
text: CHAT_UNDO_ACTION,
onclick: () => undoHideChat(),
}),
);
return bar;
}
/**
* The Rename chat dialog (C13): a locally-kept name, with the helper that says so
* plainly. Save is disabled while the trimmed value is blank; typing toggles that
* state directly, so the transcript's scroll is never disturbed by a re-render.
* Nothing is sent to the server — there is no chat rename on the wire.
*/
function renderChatRenameDialog(session) {
const effective = effectiveChatSession(session) ?? session;
const overlay = h("div", {
class: "confirm-dialog confirm-chat-rename",
role: "dialog",
"aria-modal": "true",
"aria-label": CHAT_RENAME_TITLE,
});
overlay.addEventListener("click", (event) => {
if (event.target === overlay) dismissChatRename();
});
const panel = h("div", { class: "confirm-panel" });
panel.append(h("h2", { class: "confirm-title", text: CHAT_RENAME_TITLE }));
const field = h("div", { class: "chat-rename-field" });
field.append(h("label", { class: "chat-rename-label", for: "chatRenameInput", text: CHAT_RENAME_FIELD_LABEL }));
const input = h("input", {
id: "chatRenameInput",
class: "rename-input chat-rename-input",
type: "text",
value: sessionTitle(effective),
spellcheck: "false",
autocomplete: "off",
});
field.append(input);
panel.append(field);
panel.append(h("p", { class: "chat-rename-helper", text: CHAT_RENAME_HELPER }));
const actions = h("div", { class: "confirm-actions" });
actions.append(
h("button", {
class: "ghost confirm-dismiss chat-rename-cancel",
type: "button",
text: CHAT_RENAME_DISMISS,
onclick: dismissChatRename,
}),
);
const save = h("button", {
class: "confirm-accept chat-rename-save",
type: "button",
text: CHAT_RENAME_SAVE,
disabled: input.value.trim() === "",
onclick: () => acceptChatRename(session, input.value),
});
// Toggle Save in place on input: no renderContent, so the transcript's scroll
// position (C14) is untouched while the operator types.
input.addEventListener("input", () => {
save.disabled = input.value.trim() === "";
});
actions.append(save);
panel.append(actions);
overlay.append(panel);
return overlay;
}
/**
* The background-tasks bar (C11): the running shells this conversation still
* owns. It returns null (renders nothing) unless at least one shell is running,
@@ -6883,6 +7426,9 @@ async function onConnected() {
// local, so that path is a single render and nothing is fetched twice).
renderBanner();
await loadCurrentView();
// Seed from the authoritative list first, then watch: the subscribe snapshot
// and its ack are treated as seeds, so a reconnect gap never notifies.
await startRunAlertWatch();
}
async function loadCurrentView(force = false) {
@@ -6917,11 +7463,13 @@ async function loadCurrentView(force = false) {
// history from one that has not arrived yet.
const { runs, usage } = await repo.listRuns();
state.runs = runs;
runAlerts.seed(runs);
if (usage) state.usage = usage;
state.runsLoaded = true;
} else {
const { runs, usage } = await repo.listRuns();
state.runs = runs;
runAlerts.seed(runs);
state.usage = usage;
state.runsLoaded = true;
}
@@ -7165,6 +7713,10 @@ client.addEventListener("state", (event) => {
// gone, so no thread keeps claiming to run until a fresh frame proves it.
clearChatSubscriptions();
settleChatThreads();
// Drop the run-status baseline but keep this page session's notified keys:
// the reconnect reseeds from the fresh list before it resubscribes, so a
// transition hidden by the gap can never notify late.
runAlerts.reset();
}
// A reconnect (not a first connect): re-attach the open chat's stream and
// refresh its history wholesale, so a gap that swallowed the end of a turn is
@@ -7183,6 +7735,13 @@ client.addEventListener("state", (event) => {
client.addEventListener("frame", (event) => {
const message = event.detail;
if (!message) return;
if (message.type === Protocol.RUN_EVENT) {
// L5 only: observe the pushed transition for notifications. R10's runs-list
// fold is deliberately not implemented here.
const runFrame = message[Protocol.RUN_EVENT];
if (runFrame) onRunAlertFrame(runFrame);
return;
}
if (message.type === Protocol.CHAT_PERMISSION) {
const permission = message[ChatKeys.PERMISSION];
if (permission) onChatPermission(permission);
@@ -7218,6 +7777,11 @@ document.addEventListener("keydown", (event) => {
dismissActionError();
return;
}
if (state.chatRename) {
event.preventDefault();
dismissChatRename();
return;
}
if (state.chatClose) {
event.preventDefault();
dismissChatClose();
@@ -7238,12 +7802,29 @@ document.addEventListener("keydown", (event) => {
closeStagePane();
return;
}
if (state.chatMenu) {
event.preventDefault();
state.chatMenu = null;
renderContent();
return;
}
if (state.searchOpen) {
event.preventDefault();
closeSearch();
}
});
// A click anywhere outside an open Chat actions menu closes it, so a menu never
// lingers behind another row's selection. The wrap element (button + panel)
// keeps its own clicks from closing it.
document.addEventListener("click", (event) => {
if (!state.chatMenu) return;
const target = event.target;
if (target instanceof Element && target.closest(".chat-menu-wrap")) return;
state.chatMenu = null;
renderContent();
});
// Return-to-foreground recovery (T4): the page becomes visible again, or the
// browser reports it is back online, and the client drives its socket back
// without waiting out the backoff. DOM-only, and idempotent.
@@ -7256,4 +7837,5 @@ window.addEventListener("online", onForegroundActive);
// The attention surface's dismissed identities are loaded once here, before the
// first render, so the bell's badge is correct from the very first paint.
state.attentionDismissed = loadAttentionDismissed();
state.notifyAsked = loadNotifyAsked();
render();
+262
View File
@@ -37,6 +37,10 @@
// ui/chat/ChatFormat.kt attachmentError, attachmentFiles,
// MAX_ATTACHMENT_BYTES, attachmentDisplayName
// ui/chat/ChatAttachments.kt the attachment display name/error rules
// ui/chat/ChatOverrides.kt ChatSessionOverrides: local titles + hidden ids,
// applied over every server list refresh
// ui/chat/ChatSeen.kt ChatSeenState: the seen watermark and explicit
// unseen marks behind the row's "New" badge
//
// Nothing here touches the DOM or imports the app: every wording and decision is
// unit-tested without a browser. The caller sets each server string with
@@ -584,6 +588,264 @@ export function closeChatConfirmation(title) {
);
}
// ---------------------------------------------------------------------------
// Local overrides and seen state (ChatOverrides.kt / ChatSeen.kt)
// ---------------------------------------------------------------------------
/** The row menu and the rename dialog, verbatim from ChatListPane.kt. */
export const CHAT_RENAME_ACTION = "Rename…";
export const CHAT_HIDE_ACTION = "Hide on this device";
export const CHAT_ACTIONS_LABEL = "Chat actions";
export const CHAT_REMOVED_MESSAGE = "Hidden on this device; the chat stays on the server.";
export const CHAT_UNDO_ACTION = "Undo";
export const CHAT_RENAME_TITLE = "Rename chat";
export const CHAT_RENAME_FIELD_LABEL = "Name";
export const CHAT_RENAME_HELPER =
"The server has no rename for a chat, so this name is kept on this device.";
export const CHAT_RENAME_SAVE = "Save";
export const CHAT_RENAME_DISMISS = "Cancel";
/** The empty override model: no local titles, nothing hidden. */
export function emptyChatOverrides() {
return { titles: {}, hidden: [] };
}
/** The empty seen model: no watermarks, no explicit unseen marks. */
export function emptyChatSeen() {
return { seenAt: {}, unseen: [] };
}
/** A positive finite epoch-millisecond value, else 0 (never NaN). */
function millis(value) {
const number = Number(value);
return Number.isFinite(number) && number > 0 ? number : 0;
}
/**
* Decode a stored overrides value. Blank text, `null`, corrupt JSON, an array and
* wrong-typed fields all fall back to the empty model; nothing here throws, so a
* bad preference can never break the list.
*/
export function decodeChatOverrides(stored) {
const empty = emptyChatOverrides();
if (stored == null || stored === "") return empty;
let parsed = stored;
if (typeof stored === "string") {
if (stored.trim() === "") return empty;
try {
parsed = JSON.parse(stored);
} catch {
return empty;
}
}
if (parsed == null || typeof parsed !== "object" || Array.isArray(parsed)) return empty;
const titles = {};
const rawTitles = parsed.titles;
if (rawTitles != null) {
if (typeof rawTitles !== "object" || Array.isArray(rawTitles)) return empty;
for (const [id, title] of Object.entries(rawTitles)) {
if (isBlank(id) || typeof title !== "string" || isBlank(title)) continue;
titles[id] = title.trim();
}
}
const hidden = [];
const rawHidden = parsed.hidden;
if (rawHidden != null) {
if (!Array.isArray(rawHidden)) return empty;
for (const id of rawHidden) {
if (typeof id !== "string" || isBlank(id) || hidden.includes(id)) continue;
hidden.push(id);
}
}
return { titles, hidden };
}
/** The one-line JSON an overrides value is stored as. */
export function encodeChatOverrides(overrides) {
return JSON.stringify({
titles: { ...(overrides?.titles ?? {}) },
hidden: [...(overrides?.hidden ?? [])],
});
}
/**
* Decode a stored seen value with the same tolerance as the overrides: blank,
* corrupt or wrong-typed input is nothing seen, never an exception. Unseen ids
* are de-duplicated.
*/
export function decodeChatSeen(stored) {
const empty = emptyChatSeen();
if (stored == null || stored === "") return empty;
let parsed = stored;
if (typeof stored === "string") {
if (stored.trim() === "") return empty;
try {
parsed = JSON.parse(stored);
} catch {
return empty;
}
}
if (parsed == null || typeof parsed !== "object" || Array.isArray(parsed)) return empty;
const seenAt = {};
const rawSeenAt = parsed.seenAt;
if (rawSeenAt != null) {
if (typeof rawSeenAt !== "object" || Array.isArray(rawSeenAt)) return empty;
for (const [id, value] of Object.entries(rawSeenAt)) {
const at = millis(value);
if (isBlank(id) || at <= 0) continue;
seenAt[id] = at;
}
}
const unseen = [];
const rawUnseen = parsed.unseen;
if (rawUnseen != null) {
if (!Array.isArray(rawUnseen)) return empty;
for (const id of rawUnseen) {
if (typeof id !== "string" || isBlank(id) || unseen.includes(id)) continue;
unseen.push(id);
}
}
return { seenAt, unseen };
}
/** The one-line JSON a seen value is stored as. */
export function encodeChatSeen(seen) {
return JSON.stringify({
seenAt: { ...(seen?.seenAt ?? {}) },
unseen: [...(seen?.unseen ?? [])],
});
}
/**
* Record a local rename. A blank id or a title that is blank after trimming
* changes nothing; a recorded title is trimmed, and it wins over the server's
* own on every later refresh.
*/
export function renameChatOverride(overrides, id, title) {
const current = overrides ?? emptyChatOverrides();
const trimmed = str(title).trim();
const key = str(id);
if (isBlank(key) || trimmed === "") return current;
if (current.titles?.[key] === trimmed) return current;
return { ...current, titles: { ...(current.titles ?? {}), [key]: trimmed } };
}
/**
* Hide a session on this device. A blank id or an already-hidden id changes
* nothing, and an id is never appended twice.
*/
export function hideChatOverride(overrides, id) {
const current = overrides ?? emptyChatOverrides();
const key = str(id);
const hidden = current.hidden ?? [];
if (isBlank(key) || hidden.includes(key)) return current;
return { ...current, hidden: [...hidden, key] };
}
/** Restore a hidden session, undoing [hideChatOverride]. */
export function restoreChatOverride(overrides, id) {
const current = overrides ?? emptyChatOverrides();
const key = str(id);
const hidden = current.hidden ?? [];
if (!hidden.includes(key)) return current;
return { ...current, hidden: hidden.filter((entry) => entry !== key) };
}
/**
* The server's sessions with this device's overrides applied: hidden ids are
* removed (the set is built once, so each row is O(1)) and a local title replaces
* the server's. A blank/absent server title still falls through to
* `sessionTitle` at render time.
*/
export function applyChatOverrides(sessions, overrides) {
const list = Array.isArray(sessions) ? sessions : [];
const titles = overrides?.titles ?? {};
const hiddenIds = new Set(overrides?.hidden ?? []);
if (hiddenIds.size === 0 && Object.keys(titles).length === 0) return list;
return list
.filter((session) => !hiddenIds.has(str(session?.id)))
.map((session) => {
const local = titles[str(session?.id)];
return typeof local === "string" && local.trim() !== ""
? { ...session, title: local.trim() }
: session;
});
}
/** The newest recency the operator has seen for [id], or 0 when never seen. */
export function chatSeenWatermark(seen, id) {
const value = seen?.seenAt?.[str(id)];
return millis(value);
}
/**
* Record the first sight of every listed session, so a pre-existing chat is not
* reported as new activity. The active session is read (it is on screen); every
* other session is seeded only when it has no watermark yet and its recency is a
* real timestamp. An explicit unseen mark is never cleared by seeding.
*/
export function seedChatSeen(seen, sessions, activeId) {
let next = seen ?? emptyChatSeen();
for (const session of Array.isArray(sessions) ? sessions : []) {
const id = str(session?.id);
const updatedAt = millis(session?.updated_at);
if (isBlank(id) || updatedAt <= 0) continue;
if (id === str(activeId)) {
next = readChatSeen(next, id, updatedAt);
} else if (chatSeenWatermark(next, id) === 0) {
next = { ...next, seenAt: { ...(next.seenAt ?? {}), [id]: updatedAt } };
}
}
return next;
}
/**
* Read [id] up to [updatedAt]: the watermark advances only when the value is
* strictly newer (a stale read can never rewind it) and any explicit unseen mark
* is cleared. A blank id changes nothing.
*/
export function readChatSeen(seen, id, updatedAt) {
const current = seen ?? emptyChatSeen();
const key = str(id);
if (isBlank(key)) return current;
const at = millis(updatedAt);
const advanced = at > chatSeenWatermark(current, key);
const unseen = current.unseen ?? [];
const marked = unseen.includes(key);
if (!advanced && !marked) return current;
return {
seenAt: advanced ? { ...(current.seenAt ?? {}), [key]: at } : { ...(current.seenAt ?? {}) },
unseen: marked ? unseen.filter((entry) => entry !== key) : [...unseen],
};
}
/** Mark [id] as moved on while it was not on screen; blank ids and duplicates no-op. */
export function markChatUnseen(seen, id) {
const current = seen ?? emptyChatSeen();
const key = str(id);
const unseen = current.unseen ?? [];
if (isBlank(key) || unseen.includes(key)) return current;
return { ...current, seenAt: { ...(current.seenAt ?? {}) }, unseen: [...unseen, key] };
}
/**
* The exact `ChatState.isUnseen` rule: a session is new only when it is not the
* active one and either an explicit unseen mark exists or it has never been
* opened here and its `updated_at` is strictly newer than the stored watermark.
*/
export function isChatSessionUnseen(session, { activeId = null, seen = null, opened = false } = {}) {
const id = str(session?.id);
if (isBlank(id) || id === str(activeId)) return false;
if ((seen?.unseen ?? []).includes(id)) return true;
if (opened) return false;
return millis(session?.updated_at) > chatSeenWatermark(seen, id);
}
// ---------------------------------------------------------------------------
// Session narrowing and grouping (ChatListFilter.kt)
// ---------------------------------------------------------------------------
+315
View File
@@ -0,0 +1,315 @@
// Pure, DOM-free notification model for failed/waiting runs (L5). It mirrors
// android/.../notify/RunAlerts.kt: the same two qualifying kinds, the same
// headlines, the same run line and the same one-notification-per-run+kind rule.
//
// Everything here is pure: no DOM, no clock, no storage access. The page owns
// the Notification constructor, the permission request gesture and localStorage;
// the unit tests own the state machine. The attention model in `attention.js`
// is the single authority for which runs qualify and for the dismissal identity,
// so the in-page "Needs you" surface and the tray can never disagree.
import { AttentionKind, attentionKey, attentionKindOf } from "./attention.js";
// ---------------------------------------------------------------------------
// Kinds, headlines and the run line
// ---------------------------------------------------------------------------
/** The two run events that raise a notification (RunAlerts.kt RunAlertKind). */
export const RunAlertKind = Object.freeze({
Decision: AttentionKind.Decision,
Failed: AttentionKind.Failed,
});
/** `alertKindOf`: an attention kind is already exactly the notification kind. */
export function alertKindOf(kind) {
if (kind === AttentionKind.Decision || kind?.name === AttentionKind.Decision.name) {
return AttentionKind.Decision;
}
if (kind === AttentionKind.Failed || kind?.name === AttentionKind.Failed.name) {
return AttentionKind.Failed;
}
return null;
}
/** The short headline one kind shows (RunAlerts.alertTitle). */
export function alertTitle(kind) {
switch (alertKindOf(kind)?.name) {
case "Decision":
return "A run needs your decision";
case "Failed":
return "A run failed";
default:
return "";
}
}
/** The stable run+kind identity, the unit of dedupe (RunAlerts.alertKey). */
export function alertKey(runId, kind) {
const resolved = alertKindOf(kind);
return resolved ? attentionKey(runId, resolved) : "";
}
/**
* The line naming the run (RunAlerts.alertText): the attention label, then the
* pipeline it belongs to. The label is the run's trimmed title, falling back to
* the pipeline name; a blank or equal pipeline is never repeated, so there is no
* trailing separator.
*/
export function alertBody(run) {
const pipeline = String(run?.pipeline ?? run?.name ?? "");
const title = String(run?.label ?? run?.title ?? "").trim();
const label = title !== "" ? title : pipeline;
if (pipeline === "" || pipeline === label) return label;
return `${label} \u00b7 ${pipeline}`;
}
// ---------------------------------------------------------------------------
// The ledger: seed, observe, dedupe
// ---------------------------------------------------------------------------
/**
* Tracks the last status seen for every run and the run+kind alerts already
* raised in this page session.
*
* - `seed(runs)` records the authoritative list without raising anything, so a
* run that was already failed/waiting when the page loaded (or when the socket
* reconnected) never notifies.
* - `beginSeed()`/`endSeed()` bracket the `subscribe` snapshot: the server writes
* the current state of every watched run before its ack, and those frames are
* seeds too, not transitions.
* - `observe(frame)` raises only when a known run's status changes *into*
* `failed` or `waiting`. A duplicate frame (same status), an unchanged
* qualifying state, an unknown status and a first-seen run all return null.
* - A run+kind key is forgotten when the run leaves that qualifying state, so a
* genuinely new transition (for example failed -> running -> failed again) can
* notify once more; the same transition can never repeat.
* - A key present in the attention surface's dismissed set is suppressed. The
* dismissal is the attention model's own `{runId}:{kind}` identity.
* - `reset()` drops the status baseline on a socket drop but keeps the notified
* keys, so a gap that swallows a transition cannot raise a notification after
* the reconnect; the next seed establishes the new baseline.
*/
export function createAlertLedger() {
const lastStatus = new Map();
const notified = new Set();
let seeding = false;
function seed(runs) {
const next = new Map();
for (const run of runs ?? []) {
const runId = runIdOf(run?.id ?? run?.run_id);
if (runId == null) continue;
next.set(runId, normalizeStatus(run?.status));
}
lastStatus.clear();
for (const [runId, status] of next) lastStatus.set(runId, status);
pruneNotified(next);
}
function observe(frame, { dismissed } = {}) {
const runId = runIdOf(frame?.run_id ?? frame?.runId ?? frame?.id);
const status = normalizeStatus(frame?.status);
if (runId == null || status === "") return null;
const previous = lastStatus.get(runId);
lastStatus.set(runId, status);
const kind = attentionKindOf(status);
if (!kind) {
forget(runId, AttentionKind.Decision);
forget(runId, AttentionKind.Failed);
return null;
}
// A run can only be in one qualifying state; forget the other kind's key so
// a later transition back into it is a new event.
forget(runId, kind === AttentionKind.Decision ? AttentionKind.Failed : AttentionKind.Decision);
if (seeding) return null;
if (previous === undefined || previous === status) return null;
const key = alertKey(runId, kind);
if (notified.has(key)) return null;
notified.add(key);
const dismissedKeys =
dismissed instanceof Set ? dismissed : new Set(Array.isArray(dismissed) ? dismissed : []);
if (dismissedKeys.has(key)) return null;
return {
runId,
kind,
key,
title: alertTitle(kind),
body: alertBody(frame),
};
}
function reset() {
lastStatus.clear();
seeding = false;
}
function beginSeed() {
seeding = true;
}
function endSeed() {
seeding = false;
}
function forget(runId, kind) {
const key = alertKey(runId, kind);
if (key !== "") notified.delete(key);
}
function pruneNotified(statuses) {
for (const key of [...notified]) {
const split = key.lastIndexOf(":");
if (split < 0) continue;
const runId = runIdOf(key.slice(0, split));
const kindName = key.slice(split + 1);
const status = runId == null ? undefined : statuses.get(runId);
// A run that is absent from this read tells us nothing; keep its key.
if (status === undefined) continue;
const kind = attentionKindOf(status);
if (!kind || kind.name !== kindName) notified.delete(key);
}
}
return {
seed,
observe,
reset,
beginSeed,
endSeed,
/** Test/introspection helper; returns a copy, never the live set. */
notifiedKeys: () => [...notified],
statusOf: (runId) => lastStatus.get(runIdOf(runId)),
};
}
/** Trim/lowercase the server's status word; an absent value is "". */
function normalizeStatus(status) {
return String(status ?? "").trim().toLowerCase();
}
/** A positive run id as a number, or null for anything malformed. */
function runIdOf(value) {
const id = Number(value);
return Number.isFinite(id) && id > 0 ? id : null;
}
// ---------------------------------------------------------------------------
// Permission wording and persistence
// ---------------------------------------------------------------------------
/** Android's NOTIFICATION_RATIONALE, verbatim (RunAlerts.kt). */
export const NOTIFICATION_RATIONALE =
"Pipelines can notify you when a run is waiting for your decision or has failed. " +
"Without it, those runs still appear in the in-app Needs you surface.";
/** The explicit-gesture control's label; shown only when a request is possible. */
export const NOTIFICATION_REQUEST_LABEL = "Enable notifications";
export const NOTIFICATION_UNSUPPORTED =
"This browser does not support notifications. The in-app Needs you surface is the only channel.";
export const NOTIFICATION_INSECURE =
"Notifications need a secure context (https or localhost). This page is not secure, so the " +
"in-app Needs you surface is the only channel.";
export const NOTIFICATION_GRANTED =
"Notifications are on. Failed and waiting runs will raise a browser notification.";
export const NOTIFICATION_DENIED =
"Notifications are blocked for this site. Allow them in the browser's site settings to use them; " +
"until then the in-app Needs you surface is the only channel.";
export const NOTIFICATION_DEFAULT =
"Notifications are off. Enable them to be told when a run fails or needs your decision.";
export const NOTIFICATION_DEFAULT_ASKED =
"Notifications are still off. Your browser did not grant permission when asked; you can ask " +
"again, or the in-app Needs you surface remains the only channel.";
/**
* The total permission view for Settings. `supported` and `secureContext` are
* the browser's own facts; `permission` is the Notification API's own word
* (`default` | `granted` | `denied`, anything else treated as default).
*
* Only a supported, secure page whose permission is still `default` offers the
* request control. The request is always an explicit user gesture; nothing here
* asks on its own, and the `asked` flag only changes the honest wording.
*/
export function notificationPermissionState({
supported = true,
secureContext = true,
permission = "default",
asked = false,
} = {}) {
const state = !supported
? "unsupported"
: !secureContext
? "insecure"
: permission === "granted"
? "granted"
: permission === "denied"
? "denied"
: "default";
const canRequest = state === "default";
let body = NOTIFICATION_DEFAULT;
switch (state) {
case "unsupported":
body = NOTIFICATION_UNSUPPORTED;
break;
case "insecure":
body = NOTIFICATION_INSECURE;
break;
case "granted":
body = NOTIFICATION_GRANTED;
break;
case "denied":
body = NOTIFICATION_DENIED;
break;
default:
body = asked ? NOTIFICATION_DEFAULT_ASKED : NOTIFICATION_DEFAULT;
}
return {
state,
body,
canRequest,
actionLabel: canRequest ? NOTIFICATION_REQUEST_LABEL : null,
asked: Boolean(asked),
};
}
/**
* The browser facts the permission view needs. Pure enough to unit-test with a
* fake scope; the real page passes `globalThis`. An unrecognised permission
* value is read as `default` rather than guessed.
*/
export function notificationEnvironment(scope = globalThis) {
const ctor = scope?.Notification;
const supported = typeof ctor === "function";
const raw = supported ? ctor.permission : "default";
const permission = raw === "granted" || raw === "denied" ? raw : "default";
return { supported, secureContext: scope?.isSecureContext === true, permission };
}
/** The one localStorage key for this page's notification preference. */
export const NOTIFY_STORAGE_KEY = "pipelines.web.notify.v1";
/** Encode only the asked flag; no endpoint, credential or permission claim. */
export function encodeNotificationSettings(settings) {
return JSON.stringify({ asked: Boolean(settings?.asked) });
}
/**
* Decode the stored preference. Total: blank, unreadable JSON, a non-object, a
* non-boolean or a throwing getter all mean "never asked", so a malformed value
* can never throw into the page or claim the operator was asked.
*/
export function decodeNotificationSettings(stored) {
const text = stored == null ? "" : String(stored).trim();
if (text === "") return { asked: false };
let parsed;
try {
parsed = JSON.parse(text);
} catch {
return { asked: false };
}
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return { asked: false };
return { asked: parsed.asked === true };
}
+8
View File
@@ -27,6 +27,14 @@ export const Protocol = Object.freeze({
GET_RUN: "get_run",
RUN: "run",
// Live run state (internal/protocol/runevents.go, L5/R10). `subscribe` sends
// the current state of the watched runs as `run_event` frames and then a
// compact delta on each transition; `unsubscribe` stops the watch. The page
// uses the frames for run notifications without changing R10's runs-list fold.
SUBSCRIBE: "subscribe",
UNSUBSCRIBE: "unsubscribe",
RUN_EVENT: "run_event",
// Omni-search (internal/protocol/search.go): the command and its reply type.
// The per-kind payloads and the kind/limit vocabulary live in src/search.js.
SEARCH: "search",
+18
View File
@@ -115,6 +115,24 @@ export class PipelinesRepository {
return response.run_detail;
}
/**
* Watches run state (L5), mirroring `PipelinesRepository.subscribeRuns` for the
* blank "any workspace" scope the runs list shows: exactly `{type:'subscribe',
* workspace:''}` and no `run_ids` (an empty list would watch the whole scope,
* but omitting the field is the shape the Android client sends). The server
* replies with the current state of every matching run as unsolicited
* `run_event` frames, then an id-matched ack, then deltas. Awaiting the ack is
* how the page knows the snapshot has been delivered.
*/
async subscribeRuns() {
return this.#client.call({ type: Protocol.SUBSCRIBE, workspace: "" });
}
/** Stops this connection's run-state watch. Best effort; a disconnect drops it. */
async unsubscribeRuns() {
return this.#client.call({ type: Protocol.UNSUBSCRIBE });
}
/**
* Omni-search. Sends exactly `SearchRequest{query, kind, limit}` from
* internal/protocol/search.go: `kind` is the empty string for every kind, and