Merge branch 'main' into web-routes
Resolve the L6 routes against the newer C2/C13/L5/R10 shell: keep both sides (single client imports, the run-alert watch inside the reconnect path, the boot route + popstate wiring alongside loadNotifyAsked, main's L5 row and L6 done).
This commit is contained in:
+908
-63
File diff suppressed because it is too large
Load Diff
+416
-1
@@ -16,11 +16,19 @@
|
||||
// toolLongRunning (the chip and its panel)
|
||||
// ui/chat/ChatListFilter.kt sessionMatchesQuery, filterChatSessions,
|
||||
// groupChatSessionsByDirectory
|
||||
// ui/chat/ChatDirectories.kt HOME_DIRECTORY, directoryChoices,
|
||||
// defaultDirectoryChoice (the create picker)
|
||||
// ui/chat/ChatCreatePane.kt the create flow's wording, NewChatActions footer
|
||||
// and the create state transitions
|
||||
// ui/chat/ChatScroll.kt chatBottomDistancePx, chatFollowsAt,
|
||||
// chatShowJumpToLatest, chatOpensAtNewest,
|
||||
// chatFirstScroll
|
||||
// ui/chat/ChatStore.kt the history page merge (dedupe by id, prepend an
|
||||
// older page, replace nextCursor/hasMore)
|
||||
// older page, replace nextCursor/hasMore) and the
|
||||
// local command notices (append, dismiss one,
|
||||
// take an offer; ChatCommandNotice)
|
||||
// ui/chat/ChatCommandUi.kt the Command / Command failed labels and the
|
||||
// terminal glyph of one local notice line
|
||||
// ui/chat/ChatComposer.kt composerAction, composerCanSend/composerSendEnabled,
|
||||
// the submit routing (command vs prompt)
|
||||
// ui/chat/ChatCommands.kt CHAT_COMMANDS, parseChatInput, chatCommandSuggestions,
|
||||
@@ -29,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
|
||||
@@ -110,6 +122,25 @@ export const CONVERSATION_EMPTY = "This chat has no messages yet. Ask something
|
||||
export const LOAD_OLDER_ACTION = "Load older messages";
|
||||
export const SELECT_CHAT_HINT = "Select a chat to open it.";
|
||||
|
||||
// The create flow (C2, ChatCreatePane.kt), verbatim. The home choice's row is
|
||||
// `Home (~)` while chat_create sends the `~` the server documents; the footer
|
||||
// names the value that will be sent (see chatStartInLabel).
|
||||
export const HOME_DIRECTORY = "~";
|
||||
export const HOME_LABEL = `Home (${HOME_DIRECTORY})`;
|
||||
export const CHAT_CREATE_TITLE = "Start a chat";
|
||||
export const CHAT_CREATE_BACK_LABEL = "Cancel new chat";
|
||||
export const CHAT_CREATE_LOADING = "Loading directories…";
|
||||
export const CHAT_CREATE_PROMPT = "Where should this chat live?";
|
||||
export const CHAT_CREATE_MODEL_NOTE =
|
||||
"This server has no request for choosing a chat's model, so a new chat uses the server's default.";
|
||||
export const CHAT_CREATE_CONFIRM = "New chat";
|
||||
export const CHAT_CREATE_CANCEL = "Cancel";
|
||||
|
||||
/** The create footer's line: `Start in {directory}` with the value that is sent. */
|
||||
export function chatStartInLabel(directory) {
|
||||
return `Start in ${str(directory)}`;
|
||||
}
|
||||
|
||||
/** The listing's narrowed-to-nothing message: `No chats match "{query}".` */
|
||||
export function chatNoMatchMessage(query) {
|
||||
return `No chats match "${str(query).trim()}".`;
|
||||
@@ -557,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)
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -606,6 +895,78 @@ export function directoryLabel(directory) {
|
||||
return isBlank(directory) ? NO_DIRECTORY_LABEL : str(directory);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// The create flow's directory choices (ChatDirectories.kt)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* The picker's choices from the server's reported directories. The first entry is
|
||||
* the operator's home — the one entry the server always returns first — and the
|
||||
* rest keep the server's most-recently-used order. A blank entry is dropped, and a
|
||||
* reply with nothing in it still yields the home choice, so the picker is never
|
||||
* empty. A recent's `label` is its full path; only the home row carries the path
|
||||
* as `secondary`, because its own label is `Home (~)`.
|
||||
*/
|
||||
export function directoryChoices(directories) {
|
||||
const cleaned = (directories ?? []).map((entry) => str(entry)).filter((entry) => !isBlank(entry));
|
||||
const home = cleaned.length > 0 ? cleaned[0] : HOME_DIRECTORY;
|
||||
return [
|
||||
{
|
||||
label: HOME_LABEL,
|
||||
path: home,
|
||||
home: true,
|
||||
createDirectory: HOME_DIRECTORY,
|
||||
secondary: home,
|
||||
},
|
||||
...cleaned.slice(1).map((path) => ({
|
||||
label: path,
|
||||
path,
|
||||
home: false,
|
||||
createDirectory: path,
|
||||
secondary: null,
|
||||
})),
|
||||
];
|
||||
}
|
||||
|
||||
/** The choice a freshly opened picker starts on: home, first. */
|
||||
export function defaultDirectoryChoice(choices) {
|
||||
return (choices ?? [])[0] ?? null;
|
||||
}
|
||||
|
||||
/** A fresh create state: home selected, the caller's operation id, not sending. */
|
||||
export function newChatCreateState(operationId) {
|
||||
return {
|
||||
directory: HOME_DIRECTORY,
|
||||
operationId: str(operationId),
|
||||
creating: false,
|
||||
error: "",
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Choose one directory for the create. Kept pure so the view can re-render from a
|
||||
* single state object; the error a previous refusal left is cleared because it
|
||||
* described the old choice, not this one.
|
||||
*/
|
||||
export function selectChatDirectory(create, choice) {
|
||||
const directory =
|
||||
typeof choice === "string" ? choice : str(choice?.createDirectory ?? "");
|
||||
if (isBlank(directory)) return { ...create };
|
||||
return { ...create, directory, error: "" };
|
||||
}
|
||||
|
||||
/** The create failed: stop sending and keep the server's own reason in the pane. */
|
||||
export function chatCreateFailed(create, message) {
|
||||
return { ...create, creating: false, error: str(message) };
|
||||
}
|
||||
|
||||
/** The create succeeded: the new session goes to the head of the list, deduped by id. */
|
||||
export function chatCreateSucceeded(sessions, session) {
|
||||
const list = sessions ?? [];
|
||||
if (!session) return list;
|
||||
return [session, ...list.filter((entry) => entry?.id !== session.id)];
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Transcript (ChatFormat.kt)
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -1362,6 +1723,60 @@ export const CHAT_QUEUED_NOTICE = "Queued — it will send when the current turn
|
||||
*/
|
||||
export const CHAT_COMMAND_GLYPH = ">_";
|
||||
|
||||
/** The two labels a local command line can carry (ChatCommandUi.kt). */
|
||||
export const CHAT_COMMAND_LABEL = "Command";
|
||||
export const CHAT_COMMAND_FAILED_LABEL = "Command failed";
|
||||
|
||||
/** The accessible name of an offerless notice's dismiss control. */
|
||||
export const CHAT_COMMAND_DISMISS_LABEL = "Dismiss command notice";
|
||||
|
||||
/**
|
||||
* The label for one command notice: `Command failed` when the command could not
|
||||
* be honoured, else `Command` (ChatCommandUi.kt's own choice). The same flag
|
||||
* selects the error tint on the caller's row.
|
||||
*/
|
||||
export function chatNoticeLabel(failed) {
|
||||
return failed === true ? CHAT_COMMAND_FAILED_LABEL : CHAT_COMMAND_LABEL;
|
||||
}
|
||||
|
||||
/**
|
||||
* One local command line, the app's `ChatCommandNotice` shape: it lives beside a
|
||||
* conversation, never inside its messages, so it is never sent to the agent.
|
||||
* [offer] is set only for an unrecognised command, whose draft the operator can
|
||||
* still choose to send as a message.
|
||||
*/
|
||||
export function makeChatNotice(id, text, { failed = false, offer = null } = {}) {
|
||||
return {
|
||||
id: str(id),
|
||||
text: str(text),
|
||||
failed: failed === true,
|
||||
offer: offer == null ? null : str(offer),
|
||||
};
|
||||
}
|
||||
|
||||
/** Append one notice to a conversation's list, preserving order. */
|
||||
export function appendChatNotice(notices, notice) {
|
||||
return [...(notices ?? []), notice];
|
||||
}
|
||||
|
||||
/** Drop one notice by id, leaving every other notice and its order untouched. */
|
||||
export function dismissChatNotice(notices, noticeId) {
|
||||
return (notices ?? []).filter((notice) => notice?.id !== noticeId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Take the draft an unrecognised-command notice offers, removing the notice
|
||||
* first (mirrors `ChatStore.takeNoticeOffer`). Returns `{notices, offer}`:
|
||||
* `offer` is null — and the list is returned untouched — when the notice is
|
||||
* missing, already taken or carries no offer, so a stale tap sends nothing.
|
||||
*/
|
||||
export function takeChatNoticeOffer(notices, noticeId) {
|
||||
const list = notices ?? [];
|
||||
const notice = list.find((entry) => entry?.id === noticeId);
|
||||
if (!notice || notice.offer == null) return { notices: list, offer: null };
|
||||
return { notices: dismissChatNotice(list, noticeId), offer: notice.offer };
|
||||
}
|
||||
|
||||
/** The two values of [composerAction]. */
|
||||
export const COMPOSER_SEND = "send";
|
||||
export const COMPOSER_STOP = "stop";
|
||||
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -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",
|
||||
@@ -64,6 +72,10 @@ export const Protocol = Object.freeze({
|
||||
CHAT_PROMPT: "chat_prompt",
|
||||
CHAT_INTERRUPT: "chat_interrupt",
|
||||
CHAT_CREATE: "chat_create",
|
||||
// The create flow's directory choices (C2): `chat_directories` has no body and
|
||||
// replies in the `chat_directories` field, home first then recent operator
|
||||
// directories (internal/protocol/chat.go ChatDirectories).
|
||||
CHAT_DIRECTORIES: "chat_directories",
|
||||
// The approval card (C10): the server pushes `chat_permission` frames (one
|
||||
// pending request, later re-pushed with the resolution) and the phone answers
|
||||
// with `chat_reply` (internal/protocol/chat.go ChatPermission/ChatReply).
|
||||
@@ -102,6 +114,9 @@ export const ChatKeys = Object.freeze({
|
||||
// separate field name here would put it on the wrong part of the envelope.
|
||||
PROMPT: "chat_prompt",
|
||||
CREATE: "chat_create",
|
||||
// The `chat_directories` reply (C2), home first then recents; mirrors
|
||||
// internal/protocol/message.go `ChatDirectories []string`.
|
||||
DIRECTORIES: "chat_directories",
|
||||
QUEUED: "chat_queued",
|
||||
// C10: the pushed approval frame (`chat_permission`) and the answer body
|
||||
// (`chat_reply`), both distinct Message fields in internal/protocol/message.go.
|
||||
|
||||
+37
-2
@@ -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
|
||||
@@ -383,17 +401,34 @@ export class PipelinesRepository {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Lists the directories a new chat can live in (C2), mirroring
|
||||
* `PipelinesRepository.chatDirectories`: a bare `{type:'chat_directories'}` with
|
||||
* no body, replying in `chat_directories` (home first, then recent operator
|
||||
* directories). An older server that returns no field answers with an empty
|
||||
* list; the view still offers home so the picker is never empty.
|
||||
*/
|
||||
async chatDirectories() {
|
||||
const response = await this.#client.call({ type: Protocol.CHAT_DIRECTORIES });
|
||||
return response[ChatKeys.DIRECTORIES] ?? [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates one session in an explicit directory (mirrors
|
||||
* `PipelinesRepository.chatCreate`). The directory is always sent, so a chat is
|
||||
* never created in whatever directory the server happens to be running in. The
|
||||
* reply's `chat_session` is returned, or a `ProtocolError` when the server did
|
||||
* not return one.
|
||||
*
|
||||
* `ephemeral` creates a verification chat: the server makes and bootstraps the
|
||||
* session but records no operator-registry row, so the chat never appears in
|
||||
* `chat_sessions` for the operator. Automated checks that drive this real page
|
||||
* set it, so a run can never leave a stray "New chat" in the operator's list.
|
||||
*/
|
||||
async chatCreate(title, directory, operationId = newChatOperationId()) {
|
||||
async chatCreate(title, directory, operationId = newChatOperationId(), { ephemeral = false } = {}) {
|
||||
const response = await this.#client.call({
|
||||
type: Protocol.CHAT_CREATE,
|
||||
[ChatKeys.CREATE]: { title, directory, operation_id: operationId },
|
||||
[ChatKeys.CREATE]: { title, directory, operation_id: operationId, ...(ephemeral ? { ephemeral: true } : {}) },
|
||||
});
|
||||
const session = response[ChatKeys.SESSION];
|
||||
if (!session) {
|
||||
|
||||
Reference in New Issue
Block a user