Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

Red dots for Skill updates, preset-model updates and unexpected errors — and a way to clear them (#510)

Yaowei Zheng25432e8078ee
diff --git a/changelog/unreleased/2026-08-27-todo-badges.md b/changelog/unreleased/2026-08-27-todo-badges.md
new file mode 100644
index 00000000..d211bac2
--- /dev/null
+++ b/changelog/unreleased/2026-08-27-todo-badges.md
@@ -0,0 +1,82 @@
+# Red dots for Skill updates, preset-model updates and unexpected errors — and a way to clear them
+
+- **Date:** 2026-08-27
+- **Type:** feature
+- **Scope:** `web`, `server`
+- **PR:** [#510](https://github.com/Prism-Shadow/penguin-harness/pull/510)
+
+[中文版](2026-08-27-todo-badges.zh.md)
+
+The phone-style red dot that marked a software or Agent-kernel update gained three more trails,
+for things the user is expected to act on but might reasonably choose not to: **Skill library**
+updates, **model library** preset updates, and **unexpected errors** in the cost center. Each dot
+leads down an unbroken path to the control that deals with it, and each one can be put down.
+
+## The three trails
+
+- **Skill library** — the sidebar's Skills entry and the collapsed rail's Skills icon, ending at
+ the cards whose "update installs" button reinstalls the library copy on every Agent that is
+ behind. The gate reads a new `skillUpdates` field on the Agent list, so it added no request of
+ its own; running the update reloads that list, and the dot goes down with it.
+- **Model library** — the Models entry, ending at the "sync presets" button, which carries the
+ dot on the control that acts. Gated on ownership like that button: a member never sees the
+ badge, and the probe behind it was not requested at all.
+- **Cost center** — the Cost Center entry, ending at the errors panel. The probe counted
+ `unexpected` errors only (a business 4xx is the server saying no on purpose), over a trailing
+ 7-day window.
+
+The mobile menu button kept carrying one dot for everything; with an unexpected error in the mix
+its wording widened from "updates are available" to "something needs attention", because an error
+is not an update by any reading.
+
+## Clearing a dot
+
+Acting cleared a dot: updating the Skills, syncing the presets. For the case where the user looks
+and decides not to act, all three pages got the **same notice in the same place** — directly under
+the page title, an `attention`-toned block carrying the red dot the user followed, the trail's own
+sentence, and **Mark as handled** (**Mark as read** in the cost center).
+
+A dismissal stored the **signature** of what was waved away: the Skill names with the library
+versions on offer, the model references that would change, the newest error's timestamp. The dot
+came back only once what was waiting had grown beyond that — a later Skill version, a catalog
+release touching a different model, a newer error. Dismissing a batch and then acting on one of
+its items left the rest dismissed, and rows leaving the error window — the row cap evicting the
+oldest, an Agent deletion taking its rows out from anywhere — never raised the dot again.
+
+The markers were stored per user in `ui_prefs` under `todoDismissed`, keyed by Project, beside
+`initialPasswordBannerDismissed`. They therefore follow the account rather than the browser: on a
+shared workstation one person's dismissal no longer puts the dots down for the next, and a second
+device or a second tab picks up what the first one cleared.
+
+## Details
+
+- `lib/todo-badges.ts` added the three gates and the dismissal rule as pure functions, unit
+ tested: distinct-Skill counting across Agents, order independence, the highest library version
+ winning when two Agents are behind by different amounts, an Agent list from a server too old to
+ send the field, a preset delta separating two same-sized changes, an error window whose oldest
+ rows were evicted, and the rest of a dismissed batch staying down after one of it was updated.
+- `features/models/catalog-sync.ts` gained `catalogDelta`, which asks the sync action's own
+ question of a **saved** model table rather than the page's row state. The badge and the button
+ therefore cannot disagree about whether there is anything to do, and a test replays every table
+ shape through both to keep it that way — a dot leading to a button that answers "already up to
+ date" is the failure this avoids.
+- `AgentSummary.skillUpdates` was added: the installed Skills the bundled library has moved past,
+ each with the version on offer, computed in the pass that already counted them. Reading them was
+ bounded to the first 4 KB of each `SKILL.md`, which is where the frontmatter block sits — the
+ preinstalled library runs to roughly 180 KB of `SKILL.md` per Agent, and the Agent list is
+ reloaded after every Skill update. Skills the library does not carry — installed from a zip or a
+ picked directory — were never listed, since there is no library version for them to be behind.
+- `GET /usage/errors` took an optional `kind` (`unexpected` / `expected`), which is how the badge
+ asks for one row instead of pulling the whole dashboard aggregate for two numbers. A `kind`
+ outside that set answered 400 rather than a silently empty page, which would read as "no errors".
+- The two probes were cached per Project at module level and fetched once per browser session from
+ the same single eager owner as the update check, fail-soft in the same way: an unreachable probe
+ leaves the gate closed and says nothing. Refreshing after a sync or a Skill update bumps a
+ per-Project generation, so a probe still in flight from before the action cannot land on top of
+ the answer from after it.
+- The Agents list's "Kernel update needed" capsule got paler. Its fill was measured against the
+ plain gray `Badge` sharing the row — 1.09 : 1 against the card in light and 1.11 : 1 in dark,
+ where that neighbour shows 1.10 : 1 and 1.18 : 1 — instead of sitting a fifth louder than it.
+ The ink was left unchanged and still clears 7.67 : 1 in light and 9.13 : 1 in dark.
+- Six new bilingual strings: one sentence per trail (carried unchanged from the dot's tooltip down
+ to the page notice), the widened combined wording, and the two clearing labels.
diff --git a/changelog/unreleased/2026-08-27-todo-badges.zh.md b/changelog/unreleased/2026-08-27-todo-badges.zh.md
new file mode 100644
index 00000000..380640c6
--- /dev/null
+++ b/changelog/unreleased/2026-08-27-todo-badges.zh.md
@@ -0,0 +1,36 @@
+# 技能更新、预置模型更新与未预期错误都有了红点,并且可以解除
+
+- **Date:** 2026-08-27
+- **Type:** feature
+- **Scope:** `web`, `server`
+- **PR:** [#510](https://github.com/Prism-Shadow/penguin-harness/pull/510)
+
+[English](2026-08-27-todo-badges.md)
+
+原先标记软件更新与 Agent 内核更新的手机式红点,新增了三条路径,对应三件「该处理、但用户也可能合理地选择不处理」的事:**技能库**的技能更新、**模型库**的预置模型更新,以及**成本中心**的未预期错误。每个红点都沿一条不断裂的路径指向真正处理它的控件,并且每个红点都能被放下。
+
+## 三条路径
+
+- **技能库**——侧栏的「技能库」入口与收起态侧栏的技能图标,终点是卡片上的「更新安装」按钮:它会在所有落后的 Agent 上重装库中副本。判定依据是 Agent 列表新增的 `skillUpdates` 字段,因此没有多发一次请求;执行更新会重新拉取该列表,红点随之消失。
+- **模型库**——「模型库」入口,终点是「同步预置」按钮,红点就落在这个真正执行操作的控件上。与该按钮一样按 Owner 判定:成员不会看到红点,其背后的探测请求也根本不会发出。
+- **成本中心**——「成本中心」入口,终点是异常面板。探测只统计 `unexpected`(业务 4xx 是服务端有意拒绝,不算),窗口是最近 7 天。
+
+移动端菜单按钮仍然对全部路径显示同一个红点;当其中混有未预期错误时,措辞由「有可用更新」放宽为「有待处理事项」——错误怎么读都不是一次更新。
+
+## 如何解除
+
+真正去做就会解除:更新技能、同步预置。而对于「看过之后决定不做」的情形,三个页面都换上了**同一个提示、同一个位置**——紧贴页面标题下方,一块 `attention` 色调的提示区,里面是用户一路跟过来的那个红点、这条路径自己的那句话,以及**标记为已处理**(成本中心为**标记为已读**)。
+
+解除时保存的是被放下的那件事的**签名**:技能名加库中版本、会被改动的模型引用、最新一条错误的时间戳。只有当等待的东西超出了那一份,红点才会重新亮起——更高的技能版本、改动了别的模型的目录发布、更新的一条错误。整批解除后再处理其中一件,剩下的仍然保持熄灭;错误行离开窗口——行数上限淘汰最旧的、删除 Agent 连带删掉它的行——也不会让红点重新亮起。
+
+标记按用户存在 `ui_prefs` 的 `todoDismissed` 下、按 Project 分键,与 `initialPasswordBannerDismissed` 并列。因此它跟着账号而不是跟着浏览器:共用一台机器时,一个人的解除不会替下一个人把红点熄灭;换一台设备或另开一个标签页,也能看到先前放下的结果。
+
+## 细节
+
+- `lib/todo-badges.ts` 以纯函数写下三条判定与解除规则,并附单元测试:跨 Agent 按技能去重计数、与顺序无关、两个 Agent 落后程度不同时取较高的库版本、来自过旧服务端而没有该字段的 Agent 列表、两个规模相同但内容不同的预置差异、最旧行已被淘汰的错误窗口,以及整批解除后其中一件被更新、其余仍保持熄灭。
+- `features/models/catalog-sync.ts` 新增 `catalogDelta`:把同步动作自己的问题问在**已保存**的模型表上,而不是页面的行状态。这样红点与按钮不可能对「是否有事可做」给出不同答案,并有测试把各种表形态同时喂给两者以维持这一点——红点指向一个回答「已是最新」的按钮,正是这里要避免的失败。
+- 新增 `AgentSummary.skillUpdates`:内置库已经超过的已安装技能,并带上可用的版本号,在原本就要走一遍的那次扫描里算出。读取被限制在每个 `SKILL.md` 的前 4 KB,frontmatter 块正在那里——预装的库每个 Agent 约有 180 KB 的 `SKILL.md`,而每次技能更新后都会重新拉取 Agent 列表。库中没有的技能——来自 zip 或用户选择的目录——不会被列出,因为它们没有可落后的库版本。
+- `GET /usage/errors` 新增可选的 `kind`(`unexpected` / `expected`),红点据此只取一行,而不是为了两个数字去拉整份看板聚合。超出该集合的 `kind` 返回 400,而不是一页悄悄为空——那会被读成「没有错误」。
+- 两个探测请求按 Project 缓存在模块层,由与更新检查同一个 eager 拥有者在每个浏览器会话中各取一次,并且同样 fail-soft:探测不可达时判定保持关闭,什么也不说。同步或更新技能之后的刷新会推进一个按 Project 的代号,因此动作之前发出、尚未返回的探测不会盖掉动作之后的答案。
+- Agents 列表上的「内核需要更新」胶囊变淡了。其底色以同行的灰色 `Badge` 为标尺——浅色下相对卡片 1.09 : 1、深色下 1.11 : 1,而那枚邻居是 1.10 : 1 与 1.18 : 1——不再比它响亮五分之一。文字颜色未变,浅色 7.67 : 1、深色 9.13 : 1,余量充足。
+- 新增六条双语文案:每条路径一句(从红点的 tooltip 一路原样带到页面提示)、放宽后的合并措辞,以及两个解除操作的标签。
diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.md
index 71eee425..a6a263d6 100644
--- a/packages/docs/content/server-api.en.md
+++ b/packages/docs/content/server-api.en.md
@@ -211,7 +211,7 @@ On Session creation, `modelId` and `provider` are both-or-neither: send the comp
| Method | Path | Description |
| --- | --- | --- |
| GET | /usage | Usage statistics; query parameters `from`, `to`, `fromTs`/`toTs` (ISO timestamps bounding a trailing window, given together; required for `minute`), `groupBy`, `granularity` (`minute` / `hour` / `day` / `week` / `month` time-series precision, default `day`; oversized range × precision combinations are rejected), `agentId`, `provider`, `modelId` |
-| GET | /usage/errors | One page of the error detail table (newest first): `offset`, `limit`, plus the same `from` / `to` / `agentId` filter → `{items, total}` |
+| GET | /usage/errors | One page of the error detail table (newest first): `offset`, `limit`, plus the same `from` / `to` / `agentId` filter and an optional `kind` (`unexpected` / `expected`) → `{items, total}` |
| GET | /agents/:agentId/traces | Date → Session drill-down structure of Trace files |
| GET | /agents/:agentId/traces/:sessionId/:index | Read Trace events (`offset` / `limit` pagination) |
| GET | /agents/:agentId/traces/:sessionId/:index/analysis | Trace performance analysis |
diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.md
index f8233733..05252d76 100644
--- a/packages/docs/content/server-api.zh.md
+++ b/packages/docs/content/server-api.zh.md
@@ -211,7 +211,7 @@ Schedule 写操作仅限 Owner。新建 Session 模式的任务,`modelId` 与
| 方法 | 路径 | 说明 |
| --- | --- | --- |
| GET | /usage | 用量统计,查询参数 `from`、`to`、`fromTs`/`toTs`(ISO 时间戳界定的滑动窗口,须成对给出;`minute` 精度必需)、`groupBy`、`granularity`(时间序列精度 `minute` / `hour` / `day` / `week` / `month`,默认 `day`;范围 × 精度过大的组合会被拒绝)、`agentId`、`provider`、`modelId` |
-| GET | /usage/errors | 异常明细表分页(按时间倒序):`offset`、`limit`,以及与看板一致的 `from` / `to` / `agentId` 过滤 → `{items, total}` |
+| GET | /usage/errors | 异常明细表分页(按时间倒序):`offset`、`limit`,以及与看板一致的 `from` / `to` / `agentId` 过滤,另可选 `kind`(`unexpected` / `expected`)→ `{items, total}` |
| GET | /agents/:agentId/traces | Trace 文件的日期 → Session 下钻结构 |
| GET | /agents/:agentId/traces/:sessionId/:index | 读取 Trace 事件(`offset` / `limit` 分页) |
| GET | /agents/:agentId/traces/:sessionId/:index/analysis | Trace 性能分析结果 |
diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.ts
index b7f0bbb3..a92f4abc 100644
--- a/packages/server/src/api/types.ts
+++ b/packages/server/src/api/types.ts
@@ -270,6 +270,14 @@ export interface UiPrefs {
credentialGuideSeen?: boolean;
/** The initial-password notice banner (app layout) was permanently dismissed by the user. */
initialPasswordBannerDismissed?: boolean;
+ /**
+ * "I have dealt with this" markers for the dismissible to-do badges, per Project id and then
+ * per trail (`skills` / `models` / `errors`). Each value is the SIGNATURE of what was waved
+ * away rather than a hidden flag, so anything new raises the dot again (web's
+ * `lib/todo-badges.ts`). Replaced whole on every write, like `draftShortcuts`: the merge is
+ * shallow, so this whole map is one field.
+ */
+ todoDismissed?: Record<string, Record<string, string>>;
/**
* The draft screen's user-defined shortcuts, in display order. Replaced whole on every write
* (the merge is shallow, so the array is one field like any other) and bounded on write by
@@ -806,6 +814,14 @@ export interface VaultUpdateRequest {
// Agent and its config (system_config.yaml + AGENTS.md)
// ---------------------------------------------------------------------------
+/** One installed Skill the library carries a higher version of (see {@link AgentSummary.skillUpdates}). */
+export interface SkillUpdateRef {
+ /** Skill directory name — the identity install / uninstall address it by. */
+ name: string;
+ /** The LIBRARY's version, i.e. what installing again would bring, not what is on disk. */
+ version: number;
+}
+
export interface AgentSummary {
agentId: string;
name?: string;
@@ -831,6 +847,14 @@ export interface AgentSummary {
scheduleCount: number;
/** Installed Skill count (number of agent_state/skills/<name>/ directories with a SKILL.md). */
skillCount: number;
+ /**
+ * Installed Skills the built-in library has moved past, each with the library version on
+ * offer — the Skill-library update gate, riding along on the Agent list so a badge over
+ * that page costs no request of its own. Empty when nothing is behind. Skills that are not
+ * in the library (installed from a zip or a picked directory) are never listed: there is no
+ * library version for them to be behind.
+ */
+ skillUpdates: SkillUpdateRef[];
/** Memory count (topic files summed over the scope directories under agent_state/memory/, independent of the memory switch). */
memoryCount: number;
}
@@ -2578,6 +2602,13 @@ export interface UsageModelSeries extends UsageEntitySeriesCounts {
modelId: string;
}
+/**
+ * The two categories an error record is filed under: `unexpected` is a 500 or an unforeseen
+ * runtime exception, `expected` an HttpError / business 4xx. The panel separates them by
+ * colour, and `GET /usage/errors` takes one of them as its `kind` filter.
+ */
+export type UsageErrorKind = "unexpected" | "expected";
+
/** Occurrence count of an error for a given source · code (the "most common" metric in the stats center's error panel). */
export interface UsageErrorCount {
source: string;
@@ -2617,7 +2648,10 @@ export interface UsageErrors {
* GET /api/projects/:projectId/usage/errors — one page of the error detail table, newest
* first. The dashboard response above already carries the first page; this exists so
* "show me earlier ones" does not have to refetch the whole aggregate. It takes the same
- * date/agent filter as the dashboard, so a page never widens what the summary counted.
+ * date/agent filter as the dashboard, so a page never widens what the summary counted, plus
+ * an optional `kind` ({@link UsageErrorKind}) narrowing to one of the two categories — which
+ * is how the cost-center badge asks "are there unexpected errors, and how new is the newest"
+ * with `limit=1` instead of pulling the whole dashboard aggregate.
*/
export interface UsageErrorsPage {
items: UsageErrorItem[];
diff --git a/packages/server/src/db/repos/errors.ts b/packages/server/src/db/repos/errors.ts
index 1de52b84..c7e06d36 100644
--- a/packages/server/src/db/repos/errors.ts
+++ b/packages/server/src/db/repos/errors.ts
@@ -53,6 +53,8 @@ export interface ErrorFilter {
from?: string;
to?: string;
agentId?: string;
+ /** One error category (`unexpected` / `expected`); absent counts both, which is what the panel shows. */
+ kind?: string;
/** Whether to include unattributed errors (`project_id IS NULL`): admins only, defaults to false (see file header). */
includeGlobal?: boolean;
}
@@ -156,6 +158,10 @@ export class ErrorsRepo {
conds.push("agent_id = :agentId");
params.agentId = f.agentId;
}
+ if (f.kind !== undefined) {
+ conds.push("kind = :kind");
+ params.kind = f.kind;
+ }
return { where: conds.join(" AND "), params };
}
diff --git a/packages/server/src/http/routes/usage.ts b/packages/server/src/http/routes/usage.ts
index 9c00cadc..a363863f 100644
--- a/packages/server/src/http/routes/usage.ts
+++ b/packages/server/src/http/routes/usage.ts
@@ -5,11 +5,11 @@
* sets the time-series precision, defaulting to day; fromTs/toTs bound a
* trailing window down to instants — required for minute — and must be given
* together);
- * GET /api/projects/:p/usage/errors?offset&limit&from&to&agentId — one page of the error
+ * GET /api/projects/:p/usage/errors?offset&limit&from&to&agentId&kind — one page of the error
* detail table, for paging back past the first page the dashboard already returns.
*/
import { Hono } from "hono";
-import type { UsageGranularity, UsageGroupBy } from "../../api/types.js";
+import type { UsageErrorKind, UsageGranularity, UsageGroupBy } from "../../api/types.js";
import type { AppEnv } from "../../auth/middleware.js";
import { badRequest, optionalDateParam, paginationQuery, requireValidId } from "../validate.js";
import type { AppDeps } from "../../app.js";
@@ -18,6 +18,9 @@ const GROUP_BYS: readonly UsageGroupBy[] = ["date", "agent", "model", "session"]
const GRANULARITIES: readonly UsageGranularity[] = ["minute", "hour", "day", "week", "month"];
+/** The two categories `error_records.kind` is ever written with (ErrorRecorder's own vocabulary). */
+const ERROR_KINDS: readonly UsageErrorKind[] = ["unexpected", "expected"];
+
/**
* Parse an optional ISO-8601 timestamp parameter, normalized to the UTC ISO
* form the usage rows record — string comparison against `usage_records.ts`
@@ -91,6 +94,17 @@ export function usageRoutes(deps: AppDeps): Hono<AppEnv> {
const from = optionalDateParam(c.req.query("from"), "from");
const to = optionalDateParam(c.req.query("to"), "to");
const agentId = c.req.query("agentId");
+ const kindRaw = c.req.query("kind");
+ // `kind` narrows to one of the two categories the panel's stats already separate. It is
+ // validated against that closed set rather than passed through, so a typo asks for
+ // nothing instead of silently matching no rows and reading as "no errors".
+ if (
+ kindRaw !== undefined &&
+ kindRaw !== "" &&
+ !(ERROR_KINDS as readonly string[]).includes(kindRaw)
+ ) {
+ throw badRequest(`kind must be one of ${ERROR_KINDS.join(" / ")}.`);
+ }
return c.json(
deps.usageService.queryErrors(projectId, {
offset,
@@ -101,6 +115,7 @@ export function usageRoutes(deps: AppDeps): Hono<AppEnv> {
...(from !== undefined ? { from } : {}),
...(to !== undefined ? { to } : {}),
...(agentId !== undefined && agentId !== "" ? { agentId } : {}),
+ ...(kindRaw !== undefined && kindRaw !== "" ? { kind: kindRaw } : {}),
}),
);
});
diff --git a/packages/server/src/services/agent-service.ts b/packages/server/src/services/agent-service.ts
index 06783ad6..cf9bfe94 100644
--- a/packages/server/src/services/agent-service.ts
+++ b/packages/server/src/services/agent-service.ts
@@ -27,14 +27,38 @@ import {
skillsDir,
systemConfigPath,
} from "@prismshadow/penguin-core";
+import { librarySkill, parseSkillFrontmatter } from "@prismshadow/penguin-skills";
import type { AgentsRepo } from "../db/repos/agents.js";
import { SEMANTIC_ID_PATTERN, SEMANTIC_ID_RULE } from "./ids.js";
import type { AgentConfigService } from "./agent-config-service.js";
import type { SnapshotService } from "./snapshot-service.js";
import { isTopicFileName } from "./memory-service.js";
+import type { SkillUpdateRef } from "../api/types.js";
import { resolveLibrarySkills } from "./skill-library.js";
import { resolveDirectorySkills } from "./directory-skills.js";
+/**
+ * How much of a SKILL.md is read to answer "which version is installed" (see `installedSkills`).
+ * Generous against the largest frontmatter block the library ships (under 1 KB) and still a
+ * bounded read of a file whose body can be tens of kilobytes.
+ */
+const SKILL_HEAD_BYTES = 4096;
+
+/**
+ * The first `bytes` of a file as UTF-8. A truncation can split a multi-byte character at the
+ * tail, which is harmless for every caller here: what is parsed out of the head is ASCII.
+ */
+async function readHead(file: string, bytes: number): Promise<string> {
+ const handle = await fs.open(file, "r");
+ try {
+ const buffer = Buffer.alloc(bytes);
+ const { bytesRead } = await handle.read(buffer, 0, bytes, 0);
+ return buffer.toString("utf8", 0, bytesRead);
+ } finally {
+ await handle.close();
+ }
+}
+
export interface AgentListItem {
agentId: string;
name?: string;
@@ -54,6 +78,8 @@ export interface AgentListItem {
scheduleCount: number;
/** Number of installed Skills (count of skills/<name>/ directories that contain a SKILL.md). */
skillCount: number;
+ /** Installed Skills the library has a newer version of, each carrying that library version. */
+ skillUpdates: SkillUpdateRef[];
/** Number of memory topic files across every scope directory under memory/ (independent of the memory switch, like skillCount). */
memoryCount: number;
}
@@ -102,13 +128,13 @@ export class AgentService {
);
return Promise.all(
sorted.map(async (row) => {
- const [meta, updatedAt, vaultKeyCount, scheduleCount, skillCount, memoryCount] =
+ const [meta, updatedAt, vaultKeyCount, scheduleCount, skills, memoryCount] =
await Promise.all([
this.agentConfig.readCardMeta(projectId, row.agentId),
this.configUpdatedAt(projectId, row.agentId),
this.vaultKeyCount(projectId, row.agentId),
this.scheduleCount(projectId, row.agentId),
- this.skillCount(projectId, row.agentId),
+ this.installedSkills(projectId, row.agentId),
this.memoryCount(projectId, row.agentId),
]);
return {
@@ -118,7 +144,8 @@ export class AgentService {
...(updatedAt !== undefined ? { updatedAt } : {}),
vaultKeyCount,
scheduleCount,
- skillCount,
+ skillCount: skills.count,
+ skillUpdates: skills.updates,
memoryCount,
};
}),
@@ -144,29 +171,64 @@ export class AgentService {
}
}
- /** Number of installed Skills: count of skills/<name>/ directories containing a SKILL.md (0 if the directory doesn't exist). */
- private async skillCount(projectId: string, agentId: string): Promise<number> {
+ /**
+ * One pass over `skills/`, answering both card questions: how many Skills are installed
+ * (directories containing a SKILL.md) and which of them the library has moved past.
+ *
+ * The two are read together because the second needs what the first was already opening:
+ * counting only asked whether SKILL.md exists, and the version lives in its frontmatter.
+ * Splitting them into two passes would walk the same directories twice.
+ *
+ * Only the HEAD of each SKILL.md is read, and that bound is load-bearing rather than a
+ * micro-optimization: a preinstalled library is ~180 KB of SKILL.md across seventeen files
+ * per Agent, so a Project of ten Agents would move ~2 MB through every `GET /agents` — and
+ * the Skills page reloads that list after each update. The frontmatter block is at the head
+ * by definition (the parser's regex is anchored there) and the largest one in the library is
+ * under 1 KB, so {@link SKILL_HEAD_BYTES} covers it many times over; a block that somehow
+ * overran it would be truncated, fail to parse, and read as version 1 — the same fallback an
+ * unparseable file already takes.
+ *
+ * The directory name is the Skill's identity (core's `listInstalledSkills` says so, and
+ * install/uninstall address by it), so that — not the frontmatter's `name` — is what the
+ * library is looked up by. A Skill the library does not carry (installed from a zip or from a
+ * picked directory) has no library version to be behind and is never an update; an
+ * unparseable or version-less SKILL.md reads as version 1, the same fallback the parser
+ * applies everywhere else. Every failure degrades to "not installed" / "no update": a card
+ * hint must not be the thing that makes the Agent list fail.
+ */
+ private async installedSkills(
+ projectId: string,
+ agentId: string,
+ ): Promise<{ count: number; updates: SkillUpdateRef[] }> {
const base = skillsDir(this.root, projectId, agentId);
let dirents: Dirent[];
try {
dirents = await fs.readdir(base, { withFileTypes: true });
} catch {
- return 0;
+ return { count: 0, updates: [] };
}
- const present = await Promise.all(
+ const installed = await Promise.all(
dirents
// Dot-prefixed directories are install staging, never a Skill (a Skill name has no dot).
.filter((d) => d.isDirectory() && !d.name.startsWith("."))
.map(async (d) => {
try {
- await fs.access(path.join(base, d.name, "SKILL.md"));
- return true;
+ const head = await readHead(path.join(base, d.name, "SKILL.md"), SKILL_HEAD_BYTES);
+ return { name: d.name, version: parseSkillFrontmatter(head)?.version ?? 1 };
} catch {
- return false;
+ return null;
}
}),
);
- return present.filter(Boolean).length;
+ const updates: SkillUpdateRef[] = [];
+ for (const skill of installed) {
+ if (skill === null) continue;
+ const version = librarySkill(skill.name)?.version;
+ if (version !== undefined && version > skill.version) {
+ updates.push({ name: skill.name, version });
+ }
+ }
+ return { count: installed.filter((s) => s !== null).length, updates };
}
/** Number of memory topic files: regular `*.md` files (minus each scope's MEMORY.md index) summed over the scope directories under memory/ (0 if the directory doesn't exist). */
@@ -335,6 +397,7 @@ export class AgentService {
const meta = await this.agentConfig.readCardMeta(projectId, agentId);
const cardName = archive !== undefined ? (meta.name ?? agentId) : displayName;
const cardDescription = archive !== undefined ? meta.description : description;
+ const skills = await this.installedSkills(projectId, agentId);
return {
agentId,
name: cardName,
@@ -348,7 +411,8 @@ export class AgentService {
// are real reads because a package may carry any of them.
vaultKeyCount: 0,
scheduleCount: await this.scheduleCount(projectId, agentId),
- skillCount: await this.skillCount(projectId, agentId),
+ skillCount: skills.count,
+ skillUpdates: skills.updates,
memoryCount: await this.memoryCount(projectId, agentId),
};
}
diff --git a/packages/server/src/services/usage-service.ts b/packages/server/src/services/usage-service.ts
index 0678a77f..2246ecd4 100644
--- a/packages/server/src/services/usage-service.ts
+++ b/packages/server/src/services/usage-service.ts
@@ -96,6 +96,8 @@ export interface UsageErrorsQuery {
from?: string;
to?: string;
agentId?: string;
+ /** Narrow to one category — `unexpected` (500s / runtime exceptions) or `expected`; absent counts both. */
+ kind?: string;
/** Admin only: include errors with no Project attribution (see the ErrorsRepo file header). */
includeGlobalErrors?: boolean;
}
@@ -266,6 +268,7 @@ export class UsageService {
...(q.agentId !== undefined ? { agentId: q.agentId } : {}),
...(q.from !== undefined ? { from: q.from } : {}),
...(q.to !== undefined ? { to: q.to } : {}),
+ ...(q.kind !== undefined ? { kind: q.kind } : {}),
...(q.includeGlobalErrors === true ? { includeGlobal: true } : {}),
};
return {
diff --git a/packages/server/test/errors.test.ts b/packages/server/test/errors.test.ts
index 7745e259..418dd883 100644
--- a/packages/server/test/errors.test.ts
+++ b/packages/server/test/errors.test.ts
@@ -1124,6 +1124,50 @@ describe("HTTP onError persistence (integration)", () => {
expect((await api.get(`/api/projects/${projectId}/usage/errors?from=2026-13-01`)).status).toBe(
400,
);
+ // A `kind` outside the two categories is a bad request, not a silently empty page: the
+ // cost-center badge reads `total` as "is anything waiting", and a typo answering 0 would
+ // read as "nothing is".
+ expect((await api.get(`/api/projects/${projectId}/usage/errors?kind=oops`)).status).toBe(400);
+ });
+
+ it("the paged error route narrows to one category on request, counting only that one", async () => {
+ // What the cost-center badge asks: one row of `unexpected`, for the count and the newest
+ // timestamp its dismissal is stamped against. Seeded directly, so the interleaving is exact.
+ const repo = new ErrorsRepo(t.deps.db);
+ const seed = (kind: string, code: string, ts: string) =>
+ repo.insert({
+ ts,
+ date: ts.slice(0, 10),
+ projectId,
+ agentId: "a1",
+ sessionId: "s1",
+ source: "http",
+ kind,
+ code,
+ status: kind === "unexpected" ? 500 : 404,
+ message: code,
+ });
+ seed("expected", "expected_0", "2026-07-27T00:00:00.000Z");
+ seed("unexpected", "unexpected_0", "2026-07-27T01:00:00.000Z");
+ seed("expected", "expected_1", "2026-07-27T02:00:00.000Z");
+ seed("unexpected", "unexpected_1", "2026-07-27T03:00:00.000Z");
+
+ const probe = (await (
+ await api.get(`/api/projects/${projectId}/usage/errors?offset=0&limit=1&kind=unexpected`)
+ ).json()) as UsageErrorsPage;
+ expect(probe.total).toBe(2); // only the unexpected ones are counted
+ expect(probe.items.map((e) => e.code)).toEqual(["unexpected_1"]); // newest first, one row
+
+ const expectedOnly = (await (
+ await api.get(`/api/projects/${projectId}/usage/errors?offset=0&limit=20&kind=expected`)
+ ).json()) as UsageErrorsPage;
+ expect(expectedOnly.items.map((e) => e.code)).toEqual(["expected_1", "expected_0"]);
+
+ // No `kind` still counts both, so the panel the badge leads to is unchanged.
+ const all = (await (
+ await api.get(`/api/projects/${projectId}/usage/errors?offset=0&limit=20`)
+ ).json()) as UsageErrorsPage;
+ expect(all.total).toBe(4);
});
it("Project deletion cascade-cleans that Project's error records", async () => {
diff --git a/packages/server/test/skills.test.ts b/packages/server/test/skills.test.ts
index 0f3a6691..cdc068ce 100644
--- a/packages/server/test/skills.test.ts
+++ b/packages/server/test/skills.test.ts
@@ -7,7 +7,8 @@
* while a newly created plain Agent has none, Agent creation seeding the Skills picked in the
* create dialog (unknown name = 404 with no Agent created), and the zip
* archive install/export (layouts, zip-slip and limit rejections, 409
- * skill_exists + overwrite replace, byte-identical export round-trip).
+ * skill_exists + overwrite replace, byte-identical export round-trip), and the Agent list's
+ * `skillUpdates` — the Skill-library badge gate, which rides along on that list.
*/
import fs from "node:fs/promises";
import path from "node:path";
@@ -17,6 +18,7 @@ import { skillsDir } from "@prismshadow/penguin-core";
import { librarySkill, loadPreinstalledSkills } from "@prismshadow/penguin-skills";
import type {
AgentCreateResponse,
+ AgentsResponse,
AgentSkillsResponse,
ProjectCreateResponse,
SkillLibraryResponse,
@@ -515,4 +517,69 @@ describe("skills api", () => {
"attachment; filename*=UTF-8''nover-skill.zip",
);
});
+
+ /**
+ * The Skill-library badge gate. It is computed from the files on disk against the bundled
+ * library, so the cases that matter are the three ways a directory can fail to be an update:
+ * already current, not in the library at all, and unreadable.
+ */
+ describe("skillUpdates on the Agent list", () => {
+ const listAgents = async (): Promise<AgentsResponse["agents"]> =>
+ ((await (await owner.get(`/api/projects/${projectId}/agents`)).json()) as AgentsResponse)
+ .agents;
+ /** Rewrites an installed SKILL.md's frontmatter version, which is what "behind" means. */
+ const setInstalledVersion = async (agentId: string, name: string, version: number) => {
+ const file = path.join(skillsDir(t.root, projectId, agentId), name, "SKILL.md");
+ const raw = await fs.readFile(file, "utf8");
+ await fs.writeFile(file, raw.replace(/^version:.*$/m, `version: ${version}`), "utf8");
+ };
+
+ it("is empty for a freshly installed Skill, and names the library version once it falls behind", async () => {
+ await createPlainAgent("bare_updates");
+ expect((await owner.post(base("bare_updates"), { names: ["penguin-sdk"] })).status).toBe(201);
+
+ const fresh = (await listAgents()).find((a) => a.agentId === "bare_updates")!;
+ expect(fresh.skillCount).toBe(1);
+ expect(fresh.skillUpdates).toEqual([]);
+
+ // Age the installed copy: the library now carries a higher version than the disk does.
+ await setInstalledVersion("bare_updates", "penguin-sdk", 0);
+ const behind = (await listAgents()).find((a) => a.agentId === "bare_updates")!;
+ expect(behind.skillUpdates).toEqual([
+ { name: "penguin-sdk", version: librarySkill("penguin-sdk")!.version },
+ ]);
+ // Reinstalling IS the update, so the badge clears with the same request the trail ends on.
+ expect((await owner.post(base("bare_updates"), { names: ["penguin-sdk"] })).status).toBe(201);
+ expect((await listAgents()).find((a) => a.agentId === "bare_updates")!.skillUpdates).toEqual(
+ [],
+ );
+ });
+
+ it("never lists a Skill the library does not carry, however old it looks", async () => {
+ await createPlainAgent("byo_updates");
+ const zip = zipSync({
+ "SKILL.md": strToU8(
+ "---\nname: byo-skill\ndescription: hand written\nversion: 1\n---\nbody\n",
+ ),
+ });
+ const res = await owner.post(`${base("byo_updates")}/archive`, {
+ dataBase64: Buffer.from(zip).toString("base64"),
+ });
+ expect(res.status).toBe(201);
+ const agent = (await listAgents()).find((a) => a.agentId === "byo_updates")!;
+ expect(agent.skillCount).toBe(1);
+ // Nothing to be behind: there is no library copy to reinstall over it.
+ expect(agent.skillUpdates).toEqual([]);
+ });
+
+ it("counts a directory with no readable SKILL.md as neither installed nor an update", async () => {
+ await createPlainAgent("broken_updates");
+ await fs.mkdir(path.join(skillsDir(t.root, projectId, "broken_updates"), "penguin-sdk"), {
+ recursive: true,
+ });
+ const agent = (await listAgents()).find((a) => a.agentId === "broken_updates")!;
+ expect(agent.skillCount).toBe(0);
+ expect(agent.skillUpdates).toEqual([]);
+ });
+ });
});
diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.ts
index 473bc6b4..7a72924a 100644
--- a/packages/web/src/api/endpoints.ts
+++ b/packages/web/src/api/endpoints.ts
@@ -121,6 +121,7 @@ import type {
UpdateCheckResponse,
UpdateRunResponse,
DesktopUpdateStatusResponse,
+ UsageErrorKind,
UsageErrorsPage,
UsageGranularity,
UsageGroupBy,
@@ -819,7 +820,15 @@ export const importAgentTrace = (projectId: string, agentId: string, body: Trace
*/
export const getUsageErrors = (
projectId: string,
- params: { offset: number; limit: number; from?: string; to?: string; agentId?: string },
+ params: {
+ offset: number;
+ limit: number;
+ from?: string;
+ to?: string;
+ agentId?: string;
+ /** Narrow to one category; the cost-center badge asks for `unexpected` with `limit: 1`. */
+ kind?: UsageErrorKind;
+ },
) =>
apiFetch<UsageErrorsPage>(`/api/projects/${encodeURIComponent(projectId)}/usage/errors`, {
query: {
@@ -828,6 +837,7 @@ export const getUsageErrors = (
from: params.from,
to: params.to,
agentId: params.agentId,
+ kind: params.kind,
},
});
diff --git a/packages/web/src/components/layout/app-layout.tsx b/packages/web/src/components/layout/app-layout.tsx
index cc6c66c3..c9ca6db8 100644
--- a/packages/web/src/components/layout/app-layout.tsx
+++ b/packages/web/src/components/layout/app-layout.tsx
@@ -9,7 +9,7 @@ import { NavLink, Outlet, useMatch, useNavigate } from "react-router";
import * as api from "../../api/endpoints";
import { S } from "../../lib/strings";
import { latestConversation } from "../../lib/session-grouping";
-import { useUpdateBadges } from "../../lib/use-update-badges";
+import { navNoteFor, useUpdateBadges } from "../../lib/use-update-badges";
import { useAuth } from "../../state/auth";
import { useProject } from "../../state/project";
import { useSessions } from "../../state/sessions";
@@ -50,9 +50,9 @@ function CollapsedRail({ onExpand }: { onExpand: () => void }) {
const { sessions, loading } = useSessions();
/**
* Passive: the layout above owns the one fetch per session, so the rail only reads the
- * shared caches — and gets pushed a result that lands while it is mounted. Two badges here:
- * the avatar mirrors the pinned sidebar's software dot (the user menu behind it holds the
- * update row), and the Agents entry leads to the outdated Agent's kernel action.
+ * shared caches — and gets pushed a result that lands while it is mounted. The avatar
+ * mirrors the pinned sidebar's software dot (the user menu behind it holds the update row);
+ * every other badge here rides on a page entry, which is where its trail continues.
*/
const badges = useUpdateBadges();
const activeSessionId = useMatch("/chat/:sessionId")?.params.sessionId ?? null;
@@ -134,10 +134,11 @@ function CollapsedRail({ onExpand }: { onExpand: () => void }) {
</button>
{/* 3-8. Page entries */}
{pages.map((item) => {
- /* Agents is the one entry on a badge trail: an outdated kernel is fixed on the
- Agent settings page this entry leads to. The dot itself is decorative — the
- tooltip and the accessible name say what is updatable. */
- const note = item.to === "/agents" ? badges.kernelNote : null;
+ /* Four entries sit on a badge trail — Agents (an outdated kernel), Skills, Models and
+ the Cost Center. The dot itself is decorative: the tooltip and the accessible name
+ say what is waiting, and this rail's icons have no visible label, so they carry
+ both the entry's name and that sentence. */
+ const note = navNoteFor(badges, item.to);
return (
<NavLink
key={item.to}
diff --git a/packages/web/src/components/layout/sidebar.tsx b/packages/web/src/components/layout/sidebar.tsx
index 64a2c59c..6b8dd77c 100644
--- a/packages/web/src/components/layout/sidebar.tsx
+++ b/packages/web/src/components/layout/sidebar.tsx
@@ -164,7 +164,7 @@ import { UpdateDialog } from "../account/update-dialog";
import { offersClientUpdate } from "../../lib/desktop-update";
import { requestClientInstall, useDesktopUpdate } from "../../lib/use-desktop-update";
import { forceUpdateCheck, updateCheckOutcome, useVersionInfo } from "../../lib/use-version-info";
-import { useUpdateBadges } from "../../lib/use-update-badges";
+import { navNoteFor, useUpdateBadges } from "../../lib/use-update-badges";
import { releaseUpdate } from "../../lib/update-badges";
import { SettingsDialog } from "../../features/settings/settings-dialog";
import { ICON_SIZE } from "../../lib/icon-scale";
@@ -1628,12 +1628,13 @@ export function Sidebar({
}`}
>
{navItems.map((item) => {
- /* Agents is the one nav entry on a badge trail: an outdated kernel is fixed
- on the Agent settings page two clicks down. The dot is anchored to the row,
- not to the label text (where it would float over whatever follows the word):
- at the row's right edge, on the same inset as its horizontal padding, and
- vertically centred on the row rather than on the line of text. */
- const note = item.to === "/agents" ? badges.kernelNote : null;
+ /* Four nav entries sit on a badge trail — Agents (an outdated kernel, fixed on
+ the Agent settings page two clicks down), Skills, Models and the Cost Center
+ (each cleared on the page itself). The dot is anchored to the row, not to the
+ label text (where it would float over whatever follows the word): at the
+ row's right edge, on the same inset as its horizontal padding, and vertically
+ centred on the row rather than on the line of text. */
+ const note = navNoteFor(badges, item.to);
return (
<NavLink
key={item.to}
diff --git a/packages/web/src/components/ui/todo-notice.tsx b/packages/web/src/components/ui/todo-notice.tsx
new file mode 100644
index 00000000..26c96f3a
--- /dev/null
+++ b/packages/web/src/components/ui/todo-notice.tsx
@@ -0,0 +1,65 @@
+/**
+ * The last stop on each of the three DISMISSIBLE trails: a notice directly under the page
+ * title saying what is waiting, plus the control that puts the dot down.
+ *
+ * It exists because those trails, unlike the software and kernel ones, can end in a decision
+ * NOT to act — a model table kept off the catalog, an error read and understood — and a dot
+ * with no way down is a dot that stops meaning anything. What the trail was already saying in
+ * every tooltip above is repeated here verbatim, so arriving confirms rather than re-explains.
+ *
+ * **One shape on all three pages**, owner-specified: same block, same place, directly below the
+ * `<h1>`. The Skills library, the model library and the cost center were three different
+ * shapes before, and a reader who had learned one had learned nothing about the next.
+ *
+ * `toneStrip.attention` is the tone by its own definition — "unfinished: waiting on time, a
+ * queue, or the user" is exactly what all three trails are — and by its own shape, since
+ * `toneStrip` is the map for a bordered notice that owns a row. Not `danger`, which means
+ * failed, destructive or over a limit: a Skill with a newer copy in the library is none of
+ * those. The class string is the one the other attention strips already use
+ * (`prompt-injection-controls.tsx`, `memory-tab.tsx`).
+ *
+ * The 6px red dot stays INSIDE the block, in the same fill it carried down the trail
+ * (`update-dot.tsx`), so the notice reads as "this is that dot": red is the trail's identity
+ * and amber is the notice's shape. It is decorative — the sentence beside it is the carrier,
+ * and the button folds that sentence into its own accessible name, keeping its visible label as
+ * the prefix.
+ *
+ * The top margin is built in rather than left to the caller: three pages place this and all
+ * three want the same gap under their title. A page whose container spaces its children (the
+ * cost center's `space-y-4`) overrides it, which is the right answer there too.
+ */
+import { Button } from "./button";
+import { UPDATE_DOT_INLINE } from "./update-dot";
+import { ICON_GAP } from "../../lib/icon-scale";
+import { toneStrip } from "../../lib/tone";
+
+export function TodoNotice({
+ text,
+ dismissLabel,
+ onDismiss,
+}: {
+ /** What is waiting — the trail's own sentence, unchanged from the dot's tooltip. */
+ text: string;
+ /** The clearing action's wording; "mark as read" where nothing is being updated. */
+ dismissLabel: string;
+ onDismiss: () => void;
+}) {
+ return (
+ <div
+ className={`mt-3 flex items-center justify-between gap-4 rounded-lg border px-4 py-3 ${toneStrip.attention}`}
+ >
+ <p className={`flex min-w-0 items-center text-xs ${ICON_GAP.menu}`}>
+ <span aria-hidden className={`shrink-0 ${UPDATE_DOT_INLINE}`} />
+ <span className="min-w-0">{text}</span>
+ </p>
+ <Button
+ size="sm"
+ className="shrink-0"
+ aria-label={`${dismissLabel} · ${text}`}
+ onClick={onDismiss}
+ >
+ {dismissLabel}
+ </Button>
+ </div>
+ );
+}
diff --git a/packages/web/src/components/ui/update-dot.tsx b/packages/web/src/components/ui/update-dot.tsx
index 8ad08172..c9965439 100644
--- a/packages/web/src/components/ui/update-dot.tsx
+++ b/packages/web/src/components/ui/update-dot.tsx
@@ -9,6 +9,10 @@
* says is "there is something new further down this path", a category `tone.ts` explicitly
* keeps out of scope. So the badge colour lives here instead, written once, and every dot on
* an update trail renders through this component rather than spelling a palette class inline.
+ * The carve-out is about the MARK. The block one of these dots sits inside on a page
+ * (`todo-notice.tsx`) is an ordinary `toneStrip.attention` notice: a bordered strip with a
+ * ground of its own is a shape `tone.ts` does own, and what it says there — unfinished, waiting
+ * on the user — is one of its five meanings.
*
* Red, because that is what a notification badge is everywhere else a user has seen one, and
* `red-400`, the pale rung, so the mark reads as news rather than as an alarm. WCAG 2.x contrast
@@ -65,6 +69,13 @@ const DOT_SIZE = {
export type UpdateDotSize = keyof typeof DOT_SIZE;
+/**
+ * The dot's fill and inline size without the positioning — for the one mark on an update trail
+ * that sits in normal flow rather than over an anchor (`todo-notice.tsx`). Exported so the red
+ * stays written once, here, for the reason the header gives.
+ */
+export const UPDATE_DOT_INLINE = `rounded-full bg-red-400 ${DOT_SIZE.inline}`;
+
export function UpdateDot({
size = "chrome",
position = "-right-0.5 -top-0.5",
@@ -96,9 +107,16 @@ export function UpdateDot({
*
* A tinted capsule, not the dot's flat fill: this one has an interior, so its label owes WCAG
* 1.4.3's 4.5 : 1 against its own background, and a surface pale enough to belong beside the
- * dots can only pay that with a dark ink. Measured red-800 on red-100 6.85 : 1 in light and
- * red-300 on red-950 8.42 : 1 in dark, with the hover fills (red-200 / red-900) still at
- * 5.75 : 1 and 5.22 : 1 under the same ink. Tint against card rather than ink against card is
+ * dots can only pay that with a dark ink.
+ *
+ * **How pale is set by the capsule beside it, not by taste.** The fill is measured against the
+ * card it sits on — white in light, gray-900 (`#0d0d0d` here) in dark — and aimed at the plain
+ * gray `Badge` sharing the row, which shows at 1.10 : 1 in light and 1.18 : 1 in dark. red-50
+ * lands at 1.09 : 1 and red-950/70 at 1.11 : 1, so the capsule now reads as red without
+ * reading as an alarm; the earlier red-100 / red-950 pair sat a fifth louder than its
+ * neighbour, which is what made it shout. The ink is unchanged and keeps a wide margin:
+ * red-800 on red-50 7.67 : 1 (hover red-100 6.86 : 1) in light, red-300 on red-950/70
+ * 9.13 : 1 (hover red-950 8.40 : 1) in dark. Tint against card rather than ink against card is
* what the neighbouring gray `Badge` also runs on: the capsule is found by its text.
* The badge colours stay in this module, with the dot's, for the reason the header gives — an
* update mark is not a `tone.ts` status.
@@ -108,7 +126,7 @@ export function UpdatePill({ onClick, children }: { onClick: () => void; childre
<button
type="button"
onClick={onClick}
- className="inline-flex shrink-0 items-center whitespace-nowrap rounded-full bg-red-100 px-2 py-0.5 text-[11px] font-semibold text-red-800 transition-colors duration-150 hover:bg-red-200 dark:bg-red-950 dark:text-red-300 dark:hover:bg-red-900"
+ className="inline-flex shrink-0 items-center whitespace-nowrap rounded-full bg-red-50 px-2 py-0.5 text-[11px] font-semibold text-red-800 transition-colors duration-150 hover:bg-red-100 dark:bg-red-950/70 dark:text-red-300 dark:hover:bg-red-950"
>
{children}
</button>
diff --git a/packages/web/src/features/models/catalog-sync.ts b/packages/web/src/features/models/catalog-sync.ts
index eb2b9dac..d18895fc 100644
--- a/packages/web/src/features/models/catalog-sync.ts
+++ b/packages/web/src/features/models/catalog-sync.ts
@@ -8,10 +8,17 @@
* PUT keeps the stored key) and existing rows keep their credential display state.
*/
import { presetModelEntries } from "@prismshadow/penguin-core/model-catalog";
+import type { ModelsResponse } from "@prismshadow/penguin-server/api";
import type { RowState } from "./models-page";
type PresetEntry = ReturnType<typeof presetModelEntries>[number];
+/** One saved model entry, as the models endpoint sends it. */
+type ModelDto = ModelsResponse["models"][number];
+
+/** The catalog-owned fields, in the string-typed form both sides are compared in. */
+type CatalogFields = ReturnType<typeof presetFields>;
+
/** The catalog-owned fields of a row, in RowState's string-typed form (mirrors toRow). */
function presetFields(p: PresetEntry) {
return {
@@ -43,6 +50,67 @@ function presetToRow(p: PresetEntry): RowState {
};
}
+/**
+ * The saved entry's form of those same fields, straight from the DTO. It mirrors the subset of
+ * `models-page.tsx`'s `toRow` the catalog owns — deliberately, so the badge below can read a
+ * model table the page has not loaded into row state. `test/catalog-sync.test.ts` pins the two
+ * together: whatever `toRow` does to a DTO, this must do to the same DTO, or the badge and the
+ * sync button would disagree about whether anything is out of date.
+ */
+function savedFields(m: ModelDto): CatalogFields {
+ return {
+ vision: m.vision !== false,
+ contextWindow: m.contextWindow !== undefined ? String(m.contextWindow) : "",
+ clientType: m.clientType ?? "",
+ cacheRead: m.pricing ? String(m.pricing.cacheRead) : "",
+ cacheWrite: m.pricing ? String(m.pricing.cacheWrite) : "",
+ output: m.pricing ? String(m.pricing.output) : "",
+ baseUrl: m.credential?.baseUrl ?? "",
+ };
+}
+
+/** What syncing would change, and which entries it would touch (see {@link catalogDelta}). */
+export interface CatalogDelta {
+ added: number;
+ updated: number;
+ /** `provider/modelId` of every entry that would be added or rewritten, in catalog order. */
+ refs: string[];
+}
+
+/**
+ * What "sync presets" would change if it ran right now, read off a **saved** model table rather
+ * than the page's row state — the gate behind the Models nav badge, which has to answer before
+ * anyone opens the page.
+ *
+ * The same union `syncRowsWithCatalog` applies, so the two cannot disagree about whether there
+ * is anything to do: catalog entries the table does not carry are additions, entries it does
+ * carry whose catalog-owned fields differ are updates, and locally added models are invisible
+ * to both. `refs` is what a dismissal is stamped against, so a later catalog release touching a
+ * different model raises the badge again (see `lib/todo-badges.ts`).
+ */
+export function catalogDelta(
+ models: readonly ModelDto[],
+ preset: PresetEntry[] = presetModelEntries(),
+): CatalogDelta {
+ const saved = new Map(models.map((m) => [`${m.provider}\0${m.modelId}`, m]));
+ const delta: CatalogDelta = { added: 0, updated: 0, refs: [] };
+ for (const p of preset) {
+ const entry = saved.get(`${p.provider}\0${p.model_id}`);
+ if (entry === undefined) {
+ delta.added += 1;
+ delta.refs.push(`${p.provider}/${p.model_id}`);
+ continue;
+ }
+ const fields = savedFields(entry);
+ const target = presetFields(p);
+ if ((Object.keys(target) as (keyof CatalogFields)[]).some((k) => fields[k] !== target[k])) {
+ delta.updated += 1;
+ delta.refs.push(`${p.provider}/${p.model_id}`);
+ }
+ }
+ return delta;
+}
+
/**
* Merges the current rows with the built-in catalog. Existing rows keep their identity,
* credential state, and list position (fields are updated in place); catalog-only entries
diff --git a/packages/web/src/features/models/models-page.tsx b/packages/web/src/features/models/models-page.tsx
index 4995a459..3f352c7a 100644
--- a/packages/web/src/features/models/models-page.tsx
+++ b/packages/web/src/features/models/models-page.tsx
@@ -111,6 +111,11 @@ import {
} from "./model-group-expansion";
import { clearDraftModelRef } from "../chat/draft-cache";
import { syncRowsWithCatalog } from "./catalog-sync";
+import { useUpdateBadges } from "../../lib/use-update-badges";
+import { dismissTodo } from "../../lib/todo-dismissals";
+import { refreshProjectTodos } from "../../lib/use-project-todos";
+import { UpdateDot } from "../../components/ui/update-dot";
+import { TodoNotice } from "../../components/ui/todo-notice";
import { buildImportedRows } from "./group-import";
import { tpsTone, ttftTone } from "./speed-test";
import type { SpeedResult, SpeedTone } from "./speed-test";
@@ -529,6 +534,10 @@ export function ModelsPage() {
const { currentProject } = useProject();
const projectId = currentProject?.projectId ?? null;
const isOwner = currentProject?.role === "owner";
+ /** The Models trail's raised badge, or undefined — the header's two marks appear with it. */
+ const todo = useUpdateBadges().todos.models;
+ /** What the trail says, read at render time: `S` is a live binding swapped on locale change. */
+ const syncNote = todo ? S.todo.presetUpdates(todo.count) : "";
const userId = useAuth().user?.userId ?? null;
/** Per-model speed results (in-memory, reset on every project switch; "pending" while that model's turn is running). */
const [speedResults, setSpeedResults] = useState<Map<string, SpeedResult | "pending">>(new Map());
@@ -697,6 +706,10 @@ export function ModelsPage() {
visionModel,
S.models.syncDone(merged.added, merged.updated),
);
+ // The Models nav badge is gated on the SAVED table, which this page holds only as row
+ // state: re-probe it so the dot goes down on the server's answer rather than on the
+ // assumption that the write covered everything the catalog offered.
+ refreshProjectTodos(projectId);
};
/**
@@ -872,34 +885,66 @@ export function ModelsPage() {
return (
<div className="h-full overflow-y-auto p-4 md:p-6">
<div className="mx-auto max-w-5xl">
- <div className="mb-4 flex flex-wrap items-center justify-between gap-2">
- <h1 className="flex items-center gap-1.5 text-xl font-semibold">
- {S.models.title}
- {!isOwner && <InfoPopover label={S.models.title}>{S.models.readOnlyHint}</InfoPopover>}
- </h1>
- {/* The header holds search plus the owner-only "sync presets" action (add-model
- entry points live in each group header); on narrow screens (flex-wrap wraps it
- to its own line) the search box shrinks flexibly, fixed width at >=sm. */}
- <div className="flex min-w-0 max-w-full grow items-center gap-2 sm:grow-0">
- <div className="min-w-0 flex-1 sm:w-56 sm:flex-none">
- <Input
- size="sm"
- value={query}
- onChange={(e) => setQuery(e.target.value)}
- placeholder={S.models.searchPlaceholder}
- />
+ <div className="mb-4">
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <h1 className="flex items-center gap-1.5 text-xl font-semibold">
+ {S.models.title}
+ {!isOwner && (
+ <InfoPopover label={S.models.title}>{S.models.readOnlyHint}</InfoPopover>
+ )}
+ </h1>
+ {/* The header holds search plus the owner-only "sync presets" action (add-model
+ entry points live in each group header); on narrow screens (flex-wrap wraps it
+ to its own line) the search box shrinks flexibly, fixed width at >=sm. */}
+ <div className="flex min-w-0 max-w-full grow items-center gap-2 sm:grow-0">
+ <div className="min-w-0 flex-1 sm:w-56 sm:flex-none">
+ <Input
+ size="sm"
+ value={query}
+ onChange={(e) => setQuery(e.target.value)}
+ placeholder={S.models.searchPlaceholder}
+ />
+ </div>
+ {/* The dot stays on the control that ACTS, not on the notice below: it marks the
+ button the trail ends at, and a mark that moved off it would point at nothing.
+ Owner-only, like the button — the gate never raises this for a member. The dot
+ straddles the button's top-right corner (update-dot.tsx's rule for a button)
+ and is decorative: the sr-only sentence folds what is waiting into the button's
+ accessible name, in the wording the trail carried down. */}
+ {isOwner && (
+ <Button
+ size="sm"
+ className="relative"
+ onClick={() => void syncPresets()}
+ disabled={busy || rows === null}
+ title={
+ todo ? `${S.models.syncCatalogHint} · ${syncNote}` : S.models.syncCatalogHint
+ }
+ >
+ {S.models.syncCatalog}
+ {todo && (
+ <>
+ <UpdateDot
+ size="inline"
+ position="right-0.5 top-0.5 -translate-y-1/2 translate-x-1/2"
+ />
+ <span className="sr-only"> · {syncNote}</span>
+ </>
+ )}
+ </Button>
+ )}
</div>
- {isOwner && (
- <Button
- size="sm"
- onClick={() => void syncPresets()}
- disabled={busy || rows === null}
- title={S.models.syncCatalogHint}
- >
- {S.models.syncCatalog}
- </Button>
- )}
</div>
+ {/* Last stop on the Models trail, in the one shape all three dismissible trails use:
+ directly under the title, naming what is waiting and carrying the way down for
+ someone who has looked and decided to stay off the catalog. */}
+ {isOwner && todo && (
+ <TodoNotice
+ text={syncNote}
+ dismissLabel={S.todo.dismiss}
+ onDismiss={() => dismissTodo(projectId, "models", todo.signature)}
+ />
+ )}
</div>
{rows === null ? (
diff --git a/packages/web/src/features/skills/skills-page.tsx b/packages/web/src/features/skills/skills-page.tsx
index e397a234..162b6029 100644
--- a/packages/web/src/features/skills/skills-page.tsx
+++ b/packages/web/src/features/skills/skills-page.tsx
@@ -44,6 +44,8 @@ import { S } from "../../lib/strings";
import { apiErrorText } from "../../lib/api-error";
import { formatRelativeDate } from "../../lib/format";
import { useDocumentTitle } from "../../lib/use-document-title";
+import { useUpdateBadges } from "../../lib/use-update-badges";
+import { dismissTodo } from "../../lib/todo-dismissals";
import { useAuth } from "../../state/auth";
import { useLocale } from "../../state/locale";
import { agentDisplayName, useProject } from "../../state/project";
@@ -52,6 +54,8 @@ import { Button } from "../../components/ui/button";
import { Chevron } from "../../components/ui/chevron";
import { GlyphIcon } from "../../components/ui/glyph-icon";
import { Modal } from "../../components/ui/modal";
+import { TodoNotice } from "../../components/ui/todo-notice";
+import { UpdateDot } from "../../components/ui/update-dot";
import { ConfirmModal } from "../../components/ui/confirm-modal";
import { Skeleton, SkeletonCard } from "../../components/ui/skeleton";
import { toastError, toastSuccess } from "../../components/ui/toast";
@@ -96,9 +100,12 @@ export function SkillsPage() {
const navigate = useNavigate();
const { locale } = useLocale();
const userId = useAuth().user?.userId ?? null;
- const { currentProject, agents, currentAgent, setCurrentAgentId } = useProject();
+ const { currentProject, agents, currentAgent, setCurrentAgentId, reloadAgents } = useProject();
const projectId = currentProject?.projectId ?? null;
+ /** The Skills trail's raised badge, or undefined — the notice under the title clears it. */
+ const todo = useUpdateBadges().todos.skills;
+
const [groups, setGroups] = useState<SkillGroupItem[] | null>(null);
const [error, setError] = useState<string | null>(null);
const [installed, setInstalled] = useState<InstalledMap>(new Map());
@@ -222,6 +229,10 @@ export function SkillsPage() {
const failed = results.find((r): r is PromiseRejectedResult => r.status === "rejected");
if (!failed) toastSuccess(S.skills.updatedToast(name, agentIds.length));
else toastError(apiErrorText(failed.reason));
+ // The Skills nav badge is gated on `AgentSummary.skillUpdates`, which this page's own
+ // install map does not feed: without reloading the Agent list the dot would survive the
+ // very update it led the user to. Runs after a partial failure too — some Agent moved.
+ void reloadAgents();
};
/**
@@ -262,6 +273,16 @@ export function SkillsPage() {
{S.skills.pageTitle}
<InfoPopover label={S.skills.pageTitle}>{S.skills.pageDesc}</InfoPopover>
</h1>
+ {/* Last stop on the Skills trail: what the sidebar's dot was pointing at, in its own
+ wording, plus the way to clear it for someone who has looked and decided to stay on
+ the installed copies. The per-card update buttons below are the action itself. */}
+ {todo && (
+ <TodoNotice
+ text={S.todo.skillUpdates(todo.count)}
+ dismissLabel={S.todo.dismiss}
+ onDismiss={() => dismissTodo(projectId, "skills", todo.signature)}
+ />
+ )}
{error ? (
<div className="mt-6 flex items-center gap-3">
@@ -454,17 +475,25 @@ function SkillCard({
{/* Actions: equal-square light icon buttons in a single row, vertically centered at the
card's right edge (copy goes into aria-label and title). */}
<div className="flex shrink-0 items-center justify-center gap-1.5">
- {/* Light (secondary): an update nudge, not the card's primary action. */}
+ {/* Light (secondary): an update nudge, not the card's primary action. The last stop on
+ the Skills trail, so it carries the dot itself — straddling the top-right corner of
+ the button's border, the anchoring rule update-dot.tsx states for a button. The mark
+ is decorative; what is waiting is already in this button's own title and accessible
+ name, which is why no sr-only sentence is added beside it. */}
{outdated.length > 0 && (
<Button
size="sm"
variant="secondary"
- className="h-8 w-8 shrink-0 justify-center p-0"
+ className="relative h-8 w-8 shrink-0 justify-center p-0"
aria-label={`${S.skills.updateOutdated(outdated.length)} ${skill.name}`}
title={S.skills.updateOutdated(outdated.length)}
onClick={() => setPendingUpdate(outdated)}
>
<GlyphIcon d={UPDATE_ICON} size={ICON_SIZE.iconButton} />
+ <UpdateDot
+ size="inline"
+ position="right-0.5 top-0.5 -translate-y-1/2 translate-x-1/2"
+ />
</Button>
)}
<Button
diff --git a/packages/web/src/features/usage/usage-page.tsx b/packages/web/src/features/usage/usage-page.tsx
index 60451118..876be6d4 100644
--- a/packages/web/src/features/usage/usage-page.tsx
+++ b/packages/web/src/features/usage/usage-page.tsx
@@ -32,6 +32,9 @@ import * as api from "../../api/endpoints";
import { S } from "../../lib/strings";
import { apiErrorText } from "../../lib/api-error";
import { useDocumentTitle } from "../../lib/use-document-title";
+import { useUpdateBadges } from "../../lib/use-update-badges";
+import { dismissTodo } from "../../lib/todo-dismissals";
+import { TodoNotice } from "../../components/ui/todo-notice";
import { formatMoney, humanizeTokens } from "../../lib/format";
import { catalogEntryFor } from "@prismshadow/penguin-core/model-catalog";
import { useProject } from "../../state/project";
@@ -132,6 +135,8 @@ export function UsagePage() {
useDocumentTitle(S.usage.title);
const { currency } = useTheme();
const { currentProject } = useProject();
+ /** The Cost Center trail's raised badge, or undefined — the errors panel's notice clears it. */
+ const todo = useUpdateBadges().todos.errors;
const projectId = currentProject?.projectId ?? null;
// ?agentId= deep link (from the Agents page's "cost" entry point): the URL
@@ -331,6 +336,19 @@ export function UsagePage() {
</div>
</div>
+ {/* Last stop on the Cost Center trail, in the one shape all three dismissible trails
+ use: directly under the title, not down against the errors table. It counts the
+ probe's own trailing window (use-project-todos.ts), which is not the filters above
+ it, so it states what the badge is about rather than what any one panel is showing.
+ "Read", not "done" — nothing is being updated here, the user has simply looked. */}
+ {todo && (
+ <TodoNotice
+ text={S.todo.unexpectedErrors(todo.count)}
+ dismissLabel={S.todo.markRead}
+ onDismiss={() => dismissTodo(projectId, "errors", todo.signature)}
+ />
+ )}
+
{/* Summary cards (today / last 7 days / cumulative) */}
{data ? (
<div className="grid grid-cols-1 gap-3 sm:grid-cols-3">
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index 0c12b368..40e19be7 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -220,6 +220,24 @@ export const en: Strings = {
"Only the AppImage build updates itself on Linux — update a package install through your package manager",
},
+ /**
+ * The three DISMISSIBLE badge trails (Skill library / model library / cost center) and the
+ * controls that clear them. One sentence per trail, carried unchanged from the dot's tooltip
+ * down to the notice on the page it leads to — the same discipline the kernel trail keeps.
+ */
+ todo: {
+ skillUpdates: (n: number) => (n === 1 ? "1 skill update" : `${n} skill updates`),
+ presetUpdates: (n: number) =>
+ n === 1 ? "1 preset model to sync" : `${n} preset models to sync`,
+ unexpectedErrors: (n: number) => (n === 1 ? "1 unexpected error" : `${n} unexpected errors`),
+ /** Combined anchor whose trails are not all updates — an unexpected error is not one. */
+ pending: "Something needs attention",
+ /** Clears an update the user has decided not to take now (a later one raises the badge again). */
+ dismiss: "Mark as handled",
+ /** The cost center's wording: nothing is being updated there, the errors are simply read. */
+ markRead: "Mark as read",
+ },
+
/** Desktop task-completion notifications (window unfocused; desktop-shell sessions only). */
notify: {
taskCompleteTitle: "Task completed",
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index ace8430a..932f15d3 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -224,6 +224,23 @@ export const zh = {
clientUnsupportedNonAppImage: "Linux 上只有 AppImage 版本支持自更新——包安装请通过包管理器更新",
},
+ /**
+ * The three DISMISSIBLE badge trails (Skill library / model library / cost center) and the
+ * controls that clear them. One sentence per trail, carried unchanged from the dot's tooltip
+ * down to the notice on the page it leads to — the same discipline the kernel trail keeps.
+ */
+ todo: {
+ skillUpdates: (n: number) => `${n} 个技能有更新`,
+ presetUpdates: (n: number) => `${n} 个预置模型可同步`,
+ unexpectedErrors: (n: number) => `${n} 条未预期错误`,
+ /** Combined anchor whose trails are not all updates — an unexpected error is not one. */
+ pending: "有待处理事项",
+ /** Clears an update the user has decided not to take now (a later one raises the badge again). */
+ dismiss: "标记为已处理",
+ /** The cost center's wording: nothing is being updated there, the errors are simply read. */
+ markRead: "标记为已读",
+ },
+
/** Desktop task-completion notifications (window unfocused; desktop-shell sessions only). */
notify: {
taskCompleteTitle: "任务完成",
diff --git a/packages/web/src/lib/todo-badges.ts b/packages/web/src/lib/todo-badges.ts
new file mode 100644
index 00000000..deb72c8d
--- /dev/null
+++ b/packages/web/src/lib/todo-badges.ts
@@ -0,0 +1,129 @@
+/**
+ * The three DISMISSIBLE badge trails, and what a dismissal is stamped against.
+ *
+ * `update-badges.ts` next door covers the two trails that clear themselves — a software
+ * release and an Agent kernel — where there is nothing to dismiss: the badge is gone the
+ * moment the update is installed. These three are different in one way that decides the
+ * whole design: the user may reasonably look at what is waiting and choose to leave it
+ * there. A model table deliberately kept off the catalog, a Skill deliberately pinned to an
+ * older copy, an error already read and understood — none of those should keep a red dot lit
+ * forever, and none of them changes any state a gate could read.
+ *
+ * So each trail produces a **signature**: a string naming exactly WHAT is waiting. Dismissing
+ * stores that string (`todo-dismissals.ts`); the badge is raised again only when what is
+ * waiting has grown BEYOND it. Acting on the trail therefore clears the badge on its own (the
+ * signature becomes null), and so does dismissing — but something *new* arriving raises it
+ * again, which a plain "hidden forever" flag could not do.
+ *
+ * Containment, never equality: the user dismisses two Skill updates, installs one of them, and
+ * the remaining one must stay dismissed — it is the thing they already waved away. What
+ * "beyond" means differs by the shape of what is waiting, which is what {@link TodoMatch}
+ * names.
+ *
+ * Pure decisions only (vitest runs node-only here, so nothing renders and nothing fetches);
+ * `use-project-todos.ts` wires them to the live stores and turns a count into localized copy.
+ */
+import type { AgentSummary, UsageErrorsPage } from "@prismshadow/penguin-server/api";
+import type { CatalogDelta } from "../features/models/catalog-sync";
+
+/** The three trails, in sidebar order. Also the key each dismissal is stored under. */
+export type TodoKey = "skills" | "models" | "errors";
+
+/**
+ * How a dismissal is compared against what is waiting now.
+ *
+ * - `set` — the items are independent things (a Skill, a model reference). One of them absent
+ * from what was dismissed raises the badge; a smaller set never does.
+ * - `watermark` — the signature is an ordered high-water mark (the newest error's timestamp),
+ * and only a HIGHER one raises the badge. Rows leave the window from either end — the row cap
+ * evicts the oldest, deleting an Agent removes its rows wherever they sit — so a signature
+ * that moved DOWN is not news.
+ */
+export type TodoMatch = "set" | "watermark";
+
+/** What one trail has waiting. */
+export interface Todo {
+ /** What is waiting, as one string: {@link items} joined by `,`. This is what a dismissal stores. */
+ signature: string;
+ /**
+ * The individual things waiting, one string each — what a stored signature is compared
+ * against under {@link match}. Two runs that would show the user the same thing must produce
+ * the same items, in the same order.
+ */
+ items: string[];
+ /** How many things are waiting; the only number the copy names. */
+ count: number;
+ /** Which containment rule {@link raisedTodo} applies to this trail. */
+ match: TodoMatch;
+}
+
+/**
+ * Library Skills some Agent in this Project has fallen behind on. The flag rides along on the
+ * Project's Agent list, so this costs no request of its own — the same trick `kernelOutdated`
+ * plays for the kernel trail.
+ *
+ * Counted by distinct Skill, not per Agent: the trail ends on the Skills page, which lists the
+ * library once, so "3 Skills can be updated" is what the user will see there even if the three
+ * are spread over five Agents. The signature carries the library VERSION alongside each name,
+ * so a Skill dismissed at v2 raises the badge again when the library reaches v3 — dismissing
+ * answers "not this update", not "never tell me about this Skill".
+ */
+export function skillUpdateTodo(
+ agents: ReadonlyArray<Pick<AgentSummary, "skillUpdates">>,
+): Todo | null {
+ const latest = new Map<string, number>();
+ for (const agent of agents) {
+ for (const update of agent.skillUpdates ?? []) {
+ const known = latest.get(update.name);
+ if (known === undefined || update.version > known) latest.set(update.name, update.version);
+ }
+ }
+ if (latest.size === 0) return null;
+ const items = [...latest].map(([name, version]) => `${name}@${version}`).sort();
+ return { signature: items.join(","), items, count: latest.size, match: "set" };
+}
+
+/**
+ * Built-in catalog entries the Project's model table does not match. The delta is the sync
+ * action's own (`catalog-sync.ts`), not a second opinion about it: a badge that leads to a
+ * button which then reports "already up to date" is worse than no badge.
+ *
+ * The signature is the list of references that would change, so syncing part of the table by
+ * hand and dismissing the rest behaves the way the user would expect, and a catalog release
+ * touching a different model raises the badge again even when the count happens to match.
+ */
+export function presetUpdateTodo(delta: CatalogDelta): Todo | null {
+ if (delta.refs.length === 0) return null;
+ return {
+ signature: delta.refs.join(","),
+ items: [...delta.refs],
+ count: delta.refs.length,
+ match: "set",
+ };
+}
+
+/**
+ * Unexpected errors (500s and runtime exceptions) the cost center is holding. Expected errors
+ * — an HttpError, a business 4xx — are deliberately not a to-do: they are the server saying no
+ * on purpose, and there is nothing for the user to do about them.
+ *
+ * The page is the one-row probe `use-project-todos.ts` fetches, so `items[0]` is the newest
+ * error and `total` the count in the window. The signature is that newest timestamp alone, and
+ * it is a `watermark` rather than a set: the newest row can move DOWN as well as up — the row
+ * cap evicts the oldest, and deleting an Agent takes its rows out from wherever they sit,
+ * newest included — and a dot the user already cleared must not come back because rows left.
+ */
+export function unexpectedErrorTodo(page: UsageErrorsPage): Todo | null {
+ const newest = page.items[0];
+ if (newest === undefined || page.total === 0) return null;
+ return { signature: newest.ts, items: [newest.ts], count: page.total, match: "watermark" };
+}
+
+/** The trail's badge: what is waiting, or null when nothing is or the user already waved this away. */
+export function raisedTodo(todo: Todo | null, dismissed: string | null): Todo | null {
+ if (todo === null) return null;
+ if (dismissed === null) return todo;
+ if (todo.match === "watermark") return todo.signature > dismissed ? todo : null;
+ const seen = new Set(dismissed.split(","));
+ return todo.items.some((item) => !seen.has(item)) ? todo : null;
+}
diff --git a/packages/web/src/lib/todo-dismissals.ts b/packages/web/src/lib/todo-dismissals.ts
new file mode 100644
index 00000000..92e8ef34
--- /dev/null
+++ b/packages/web/src/lib/todo-dismissals.ts
@@ -0,0 +1,126 @@
+/**
+ * "I have dealt with this" markers for the three dismissible badge trails, per Project.
+ *
+ * What is stored is not a hidden flag but the SIGNATURE the trail carried when it was
+ * dismissed (`todo-badges.ts` explains why): the badge stays down while what is waiting is
+ * still contained in what the user waved away, and anything new raises it again.
+ *
+ * **Per account, not per browser.** A marker says what one PERSON has already looked at, so
+ * `localStorage` would be wrong in both directions: on a shared workstation the owner's
+ * dismissal would put the dots down for a member who was never shown what was waiting, and the
+ * same user on a second device would keep clearing a dot they had already cleared. The markers
+ * therefore live in `ui_prefs` under `todoDismissed`, following the precedent
+ * `initialPasswordBannerDismissed` set (app-layout.tsx) — the store is free-form JSON, so this
+ * needs no schema or API change — and reloading any tab picks up what another one dismissed.
+ *
+ * `PUT /me/prefs` merges only at the TOP level, which is why the store holds every Project's
+ * markers and writes the whole map: sending one Project's slice would drop the others.
+ *
+ * Until that read lands the map is `null` and every trail reads as down. That is the same
+ * fail-soft direction the probes take (`use-project-todos.ts`) — an unreachable read leaves
+ * the gate closed and says nothing — and it also keeps a dot from appearing on load only to
+ * disappear a moment later.
+ */
+import { useEffect } from "react";
+import { createStore } from "zustand/vanilla";
+import { useStore } from "zustand/react";
+import * as api from "../api/endpoints";
+import type { TodoKey } from "./todo-badges";
+
+/** The `ui_prefs` key the whole map is stored under. */
+export const TODO_PREFS_KEY = "todoDismissed";
+
+/** One Project's markers: the dismissed signature per trail, absent where nothing was dismissed. */
+export type TodoDismissals = Partial<Record<TodoKey, string>>;
+
+/** Every Project's markers, keyed by Project id — the shape held under {@link TODO_PREFS_KEY}. */
+export type TodoDismissMap = Record<string, TodoDismissals>;
+
+/** The three keys, listed once so parsing cannot drift from the union. */
+const TODO_KEYS: readonly TodoKey[] = ["skills", "models", "errors"];
+
+const EMPTY: TodoDismissals = {};
+
+/**
+ * Reads the markers out of the free-form prefs blob. Anything malformed degrades to "nothing
+ * dismissed", which shows a dot the user can clear again — the failure direction that loses no
+ * information. Non-string values are dropped per key rather than failing the whole record: a
+ * signature is always a string, and one bad key must not resurrect the other two trails' dots.
+ */
+export function parseTodoDismissMap(raw: unknown): TodoDismissMap {
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return {};
+ const out: TodoDismissMap = {};
+ for (const [projectId, value] of Object.entries(raw)) {
+ if (typeof value !== "object" || value === null || Array.isArray(value)) continue;
+ const record: TodoDismissals = {};
+ for (const key of TODO_KEYS) {
+ const signature = (value as Record<string, unknown>)[key];
+ if (typeof signature === "string") record[key] = signature;
+ }
+ out[projectId] = record;
+ }
+ return out;
+}
+
+/** The whole map after dismissing one Project's trail at `signature` (pure; the caller persists it). */
+export function withDismissal(
+ map: TodoDismissMap,
+ projectId: string,
+ key: TodoKey,
+ signature: string,
+): TodoDismissMap {
+ return { ...map, [projectId]: { ...(map[projectId] ?? EMPTY), [key]: signature } };
+}
+
+// —— Module-level store: one read per browser session, every subscriber re-renders on change ——
+
+/** `null` until the stored markers arrive; every trail reads as down while it is. */
+const dismissStore = createStore<{ map: TodoDismissMap | null }>(() => ({ map: null }));
+
+let hydrating = false;
+
+function hydrate(): void {
+ if (hydrating || dismissStore.getState().map !== null) return;
+ hydrating = true;
+ void api
+ .getPrefs()
+ .then(({ prefs }) => {
+ dismissStore.setState({ map: parseTodoDismissMap(prefs[TODO_PREFS_KEY]) });
+ })
+ .catch(() => {
+ // Left unhydrated on purpose, so a later mount retries: writing an empty map here would
+ // both raise every dot and let the next dismissal overwrite the Projects it never read.
+ hydrating = false;
+ });
+}
+
+/**
+ * Reactive read of one Project's markers, or `null` while they are unknown.
+ *
+ * `eager` marks the single owner that actually reads them — `AppLayout`, through
+ * `use-update-badges.ts`, the same owner that activates the probes. Every other anchor passes
+ * false and is pushed the result when it lands.
+ */
+export function useTodoDismissals(projectId: string | null, eager = false): TodoDismissals | null {
+ useEffect(() => {
+ if (eager) hydrate();
+ }, [eager]);
+ return useStore(dismissStore, (s) =>
+ s.map === null || projectId === null ? null : (s.map[projectId] ?? EMPTY),
+ );
+}
+
+/** Dismisses one trail at the signature it is showing right now, and persists it (best-effort). */
+export function dismissTodo(projectId: string | null, key: TodoKey, signature: string): void {
+ if (projectId === null) return;
+ const { map } = dismissStore.getState();
+ // No markers means no dot was raised, so there is nothing to wave away — and writing now
+ // would persist a map missing every Project this session never read.
+ if (map === null) return;
+ if (map[projectId]?.[key] === signature) return; // No-op: skip the write and the re-render.
+ const next = withDismissal(map, projectId, key, signature);
+ dismissStore.setState({ map: next });
+ // Fire-and-forget, the initial-password banner's pattern: a lost write only costs
+ // persistence, the dot is already down in this tab.
+ void api.putPrefs({ [TODO_PREFS_KEY]: next }).catch(() => undefined);
+}
diff --git a/packages/web/src/lib/update-badges.ts b/packages/web/src/lib/update-badges.ts
index b7db8b3c..621aed18 100644
--- a/packages/web/src/lib/update-badges.ts
+++ b/packages/web/src/lib/update-badges.ts
@@ -4,7 +4,9 @@
* Two independent trails end in two different controls, so they are two independent gates:
* a *software* update, actionable in the sidebar user menu, and an *Agent kernel* update,
* actionable on the Agent settings page. The outermost chrome (the mobile menu button) shows
- * one dot for either.
+ * one dot for either — and, since `todo-badges.ts` joined them, for the three dismissible
+ * trails as well; `badgeNote` at the bottom is what every anchor covering more than one of
+ * them speaks through.
*
* Every gate here is written as "is there a control the user can reach": a badge over a path
* with nothing actionable at the end of it is worse than no badge. That is why the software
@@ -77,20 +79,32 @@ export function anyKernelOutdated(
}
/**
- * What an anchor covering BOTH trails says. `mixed` is the combined case: two different
- * things are updatable and the anchor leads to both, so it must not claim to be either.
+ * One thing a dot can stand for. The first two are the self-clearing trails above; the last
+ * three are the dismissible ones in `todo-badges.ts`, which carry a count because the anchors
+ * that name them have room to say how many.
*/
-export type UpdateBadgeNote =
- | { kind: "none" }
- | { kind: "release"; version: string }
- | { kind: "client"; version: string | null }
+export type BadgeSource =
+ | SoftwareUpdate
| { kind: "kernel" }
- | { kind: "mixed" };
+ | { kind: "skills"; count: number }
+ | { kind: "models"; count: number }
+ | { kind: "errors"; count: number };
+
+/**
+ * What an anchor says. A single source speaks for itself; several make it `mixed`, because an
+ * anchor leading to all of them must not claim to be one — naming one of five would point the
+ * user down the wrong trail.
+ *
+ * `updatesOnly` splits the two combined wordings apart. Four of the five sources ARE updates
+ * and can be summed up as "something can be updated"; unexpected errors are not an update by
+ * any reading, so a mix containing them needs the wider "something is waiting for you".
+ */
+export type UpdateBadgeNote =
+ { kind: "none" } | BadgeSource | { kind: "mixed"; updatesOnly: boolean };
-/** Classifies what one anchor over both trails should say (see {@link UpdateBadgeNote}). */
-export function updateBadgeNote(software: SoftwareUpdate | null, kernel: boolean): UpdateBadgeNote {
- if (software !== null && kernel) return { kind: "mixed" };
- if (software !== null) return software;
- if (kernel) return { kind: "kernel" };
- return { kind: "none" };
+/** Classifies what one anchor over `sources` should say (see {@link UpdateBadgeNote}). */
+export function badgeNote(sources: readonly BadgeSource[]): UpdateBadgeNote {
+ if (sources.length === 0) return { kind: "none" };
+ if (sources.length === 1) return sources[0]!;
+ return { kind: "mixed", updatesOnly: sources.every((s) => s.kind !== "errors") };
}
diff --git a/packages/web/src/lib/use-project-todos.ts b/packages/web/src/lib/use-project-todos.ts
new file mode 100644
index 00000000..e9fb3570
--- /dev/null
+++ b/packages/web/src/lib/use-project-todos.ts
@@ -0,0 +1,186 @@
+/**
+ * The two Project-scoped probes behind the dismissible badges, and their shared cache.
+ *
+ * The Skills trail needs no request at all — `AgentSummary.skillUpdates` rides along on the
+ * Agent list the Project context already loads. The other two do:
+ *
+ * - **models** — the built-in catalog lives in the client bundle, so the only missing half is
+ * the Project's saved model table. It is read through the models endpoint the page itself
+ * uses, and the delta is computed by the sync action's own code (`catalog-sync.ts`), which is
+ * what keeps the badge from ever leading to a button that answers "already up to date".
+ * - **errors** — a one-row page of unexpected errors (`limit: 1`), which is all a badge needs:
+ * `total` is the count and `items[0]` the newest, i.e. the signature a dismissal is stamped
+ * against. The alternative was the cost center's whole dashboard aggregate, for two numbers.
+ *
+ * The window the error probe asks for is the cost center's OWN default range, not all of
+ * history, and that is load-bearing rather than a saving: the page opens on the last 7 days, so
+ * counting anything wider would raise a dot leading to a table with no rows in it.
+ *
+ * Both are cached per Project at module level and fetched once per browser session from the
+ * single eager owner (`AppLayout`, through `use-update-badges.ts`); every other anchor reads
+ * the cache passively and is pushed the result when it lands. Failures resolve to "nothing
+ * known", clear the shared promise so a later activation retries, and surface nothing: an
+ * unreachable probe leaves the gate closed and says nothing, exactly like the update check.
+ * `refreshProjectTodos` is the acting user: after a sync or a Skill update the answer has
+ * changed, and the badge must not wait for a reload to notice. It bumps a per-Project
+ * generation so an in-flight probe from before the action cannot land on top of the answer
+ * from after it.
+ */
+import { useEffect, useState } from "react";
+import type { ModelsResponse, UsageErrorsPage } from "@prismshadow/penguin-server/api";
+import * as api from "../api/endpoints";
+import { presetRange } from "../features/usage/usage-controls";
+
+/** The unexpected-error probe's window: the cost center's own default preset (see the header). */
+const ERROR_RANGE_PRESET = "7d";
+
+/** What the probes know about one Project; `null` means "not fetched, or the fetch failed". */
+export interface ProjectTodoData {
+ models: ModelsResponse | null;
+ errors: UsageErrorsPage | null;
+}
+
+const EMPTY: ProjectTodoData = { models: null, errors: null };
+
+const modelsCache = new Map<string, ModelsResponse>();
+const modelsPromise = new Map<string, Promise<ModelsResponse>>();
+const errorsCache = new Map<string, UsageErrorsPage>();
+const errorsPromise = new Map<string, Promise<UsageErrorsPage>>();
+/**
+ * The composed pair, kept so a Project's snapshot keeps ONE identity between changes. Consumers
+ * memoize the catalog diff on it, and a fresh object on every read would recompute that on every
+ * keystroke in the model page's search box. Dropped whenever either half moves.
+ */
+const snapshotCache = new Map<string, ProjectTodoData>();
+/**
+ * Refresh generation per Project, bumped by {@link refreshProjectTodos}. A fetch captures the
+ * generation it started under and drops its result if a refresh has happened since: without
+ * that, a first probe resolving after the post-sync one would reinstate the pre-sync answer and
+ * raise a dot over a button that then reports "already up to date" — the case this whole module
+ * exists to prevent.
+ */
+const generation = new Map<string, number>();
+
+/**
+ * Mounted hooks subscribe here so any refresh of the module cache reaches every consumer at
+ * once — the sidebar's nav dots, the collapsed rail's icons, the mobile menu button and the
+ * page notices all react without a remount. Active hooks await the shared promise themselves;
+ * passive ones only ever read the cache, and without this push they would miss a result that
+ * lands while they are mounted.
+ */
+const listeners = new Set<() => void>();
+
+function notifyAll(): void {
+ for (const notify of listeners) notify();
+}
+
+/** Reads the module cache for one Project (the shared EMPTY when nothing is known yet). */
+function snapshot(projectId: string | null): ProjectTodoData {
+ if (projectId === null) return EMPTY;
+ const hit = snapshotCache.get(projectId);
+ if (hit) return hit;
+ const models = modelsCache.get(projectId) ?? null;
+ const errors = errorsCache.get(projectId) ?? null;
+ if (models === null && errors === null) return EMPTY;
+ const composed = { models, errors };
+ snapshotCache.set(projectId, composed);
+ return composed;
+}
+
+/** Whether a fetch started at `at` still owns its Project's answer (see {@link generation}). */
+function current(projectId: string, at: number): boolean {
+ return (generation.get(projectId) ?? 0) === at;
+}
+
+function fetchModels(projectId: string): void {
+ if (modelsPromise.has(projectId)) return;
+ const at = generation.get(projectId) ?? 0;
+ const promise = api.getModels(projectId).then((res) => {
+ if (!current(projectId, at)) return res;
+ modelsCache.set(projectId, res);
+ snapshotCache.delete(projectId);
+ notifyAll();
+ return res;
+ });
+ modelsPromise.set(projectId, promise);
+ // Guarded too: a superseded fetch's rejection would otherwise clear the promise the refresh
+ // put in its place, and the next mount would fetch a third time.
+ promise.catch(() => {
+ if (current(projectId, at)) modelsPromise.delete(projectId);
+ });
+}
+
+function fetchErrors(projectId: string): void {
+ if (errorsPromise.has(projectId)) return;
+ const at = generation.get(projectId) ?? 0;
+ const range = presetRange(ERROR_RANGE_PRESET, new Date());
+ const promise = api
+ .getUsageErrors(projectId, { offset: 0, limit: 1, kind: "unexpected", ...range })
+ .then((res) => {
+ if (!current(projectId, at)) return res;
+ errorsCache.set(projectId, res);
+ snapshotCache.delete(projectId);
+ notifyAll();
+ return res;
+ });
+ errorsPromise.set(projectId, promise);
+ promise.catch(() => {
+ if (current(projectId, at)) errorsPromise.delete(projectId);
+ });
+}
+
+/**
+ * The probes for one Project.
+ *
+ * `eager` marks the single owner that actually fetches; every other consumer passes false and
+ * reads the cache. `wantModels` is the model probe's own gate: syncing presets is an owner-only
+ * action, so a member has no control at the end of that trail and the request is not made at
+ * all — a badge over a path with nothing actionable on it is worse than no badge.
+ */
+export function useProjectTodos(
+ projectId: string | null,
+ eager: boolean,
+ wantModels: boolean,
+): ProjectTodoData {
+ const [data, setData] = useState<ProjectTodoData>(() => snapshot(projectId));
+
+ // Re-sync from the module cache whenever a fetch or a refresh pushes a fresh result.
+ useEffect(() => {
+ const sync = () => setData(snapshot(projectId));
+ listeners.add(sync);
+ sync();
+ return () => {
+ listeners.delete(sync);
+ };
+ }, [projectId]);
+
+ useEffect(() => {
+ if (!eager || projectId === null) return;
+ if (wantModels) fetchModels(projectId);
+ fetchErrors(projectId);
+ }, [eager, projectId, wantModels]);
+
+ return data;
+}
+
+/**
+ * Drops one Project's cached probes and re-runs the ones already known, then pushes the result.
+ * Called after an action that changes what is waiting — syncing presets, updating a Skill — so
+ * the badge clears (or does not) on the strength of the server's answer rather than a guess.
+ * Only probes that had already run are re-run: refreshing must not make a request a gate had
+ * deliberately declined.
+ */
+export function refreshProjectTodos(projectId: string | null): void {
+ if (projectId === null) return;
+ const hadModels = modelsPromise.has(projectId);
+ const hadErrors = errorsPromise.has(projectId);
+ generation.set(projectId, (generation.get(projectId) ?? 0) + 1);
+ modelsPromise.delete(projectId);
+ errorsPromise.delete(projectId);
+ modelsCache.delete(projectId);
+ errorsCache.delete(projectId);
+ snapshotCache.delete(projectId);
+ notifyAll();
+ if (hadModels) fetchModels(projectId);
+ if (hadErrors) fetchErrors(projectId);
+}
diff --git a/packages/web/src/lib/use-update-badges.ts b/packages/web/src/lib/use-update-badges.ts
index 53b46254..451e3fb5 100644
--- a/packages/web/src/lib/use-update-badges.ts
+++ b/packages/web/src/lib/use-update-badges.ts
@@ -1,45 +1,62 @@
/**
- * The live update badges, read by every anchor on the two update trails: the mobile menu
- * button, the sidebar avatar and its collapsed-rail twin, and both Agents nav entries.
+ * The live badges, read by every anchor on the five trails: the mobile menu button, the
+ * sidebar avatar and its collapsed-rail twin, and the Agents / Skills / Models / Cost Center
+ * nav entries in both the pinned sidebar and the rail.
*
* One owner activates the fetches. `AppLayout` calls this with `eager` on, which is what makes
* a badge appear on a fresh load at all — the anchors below it stay passive and read the shared
- * caches (`use-version-info.ts`, `use-desktop-update.ts`), which push every consumer when a
- * result lands. Both caches are module level, so "eager" still costs one request per browser
- * session, and both are fail-soft: an unreachable check leaves every gate closed and says
- * nothing.
+ * caches (`use-version-info.ts`, `use-desktop-update.ts`, `use-project-todos.ts`, and the
+ * dismissal markers in `todo-dismissals.ts`), which push every consumer when a result lands.
+ * All of them are module level, so "eager" still costs one request per browser session per
+ * Project, and all of them are fail-soft: an unreachable check leaves every gate closed and
+ * says nothing.
*
- * The gates themselves are pure and unit tested in `update-badges.ts`; this file only wires
- * them to the stores and turns the note into localized copy.
+ * The gates themselves are pure and unit tested in `update-badges.ts` and `todo-badges.ts`;
+ * this file only wires them to the stores and turns each into localized copy. Two rules it
+ * enforces on the way, both of them the same rule: a badge only appears where the user can
+ * reach a control. The desktop shell hides the server-release row, so a newer release raises
+ * nothing there; syncing presets is owner-only, so a member never sees the Models dot (and
+ * `use-project-todos.ts` does not even make that request).
*/
-import { useEffect } from "react";
+import { useEffect, useMemo } from "react";
import { S } from "./strings";
import { offersClientUpdate } from "./desktop-update";
import { refreshDesktopUpdate, useDesktopUpdate } from "./use-desktop-update";
import { useVersionInfo } from "./use-version-info";
-import { anyKernelOutdated, softwareUpdate, updateBadgeNote } from "./update-badges";
-import type { SoftwareUpdate, UpdateBadgeNote } from "./update-badges";
+import { anyKernelOutdated, badgeNote, softwareUpdate } from "./update-badges";
+import type { BadgeSource, SoftwareUpdate, UpdateBadgeNote } from "./update-badges";
+import { presetUpdateTodo, raisedTodo, skillUpdateTodo, unexpectedErrorTodo } from "./todo-badges";
+import type { Todo, TodoKey } from "./todo-badges";
+import { useTodoDismissals } from "./todo-dismissals";
+import { useProjectTodos } from "./use-project-todos";
+import { catalogDelta } from "../features/models/catalog-sync";
import { useAuth } from "../state/auth";
import { useProject } from "../state/project";
+/** The nav routes that can carry a dot, and what each one's dot leads to. */
+export type BadgedRoute = "/agents" | "/skills" | "/models" | "/usage";
+
export interface UpdateBadges {
/** A software update this mode can act on, or null. */
software: SoftwareUpdate | null;
/** What the software anchors (the avatars) say — the update row's own wording; null with no update. */
softwareNote: string | null;
- /** Whether any Agent in the current Project has an outdated kernel. */
- kernel: boolean;
- /** What the Agents anchors say; null when no kernel is outdated. */
- kernelNote: string | null;
+ /** What each badged nav entry says; a route absent from the map carries no dot. */
+ navNotes: Partial<Record<BadgedRoute, string>>;
+ /** The raised to-do of each dismissible trail, for the page that clears it; absent when down. */
+ todos: Partial<Record<TodoKey, Todo>>;
/** Whether the outermost chrome shows a dot at all. */
any: boolean;
- /** What an anchor covering both trails says — the combined case names neither. Null when there is nothing. */
+ /** What an anchor covering everything says — a combined case names none of them. Null when there is nothing. */
note: string | null;
}
export function useUpdateBadges(eager = false): UpdateBadges {
const { desktopMode, sessionVia } = useAuth();
- const { agents } = useProject();
+ const { agents, currentProject } = useProject();
+ const projectId = currentProject?.projectId ?? null;
+ // Syncing presets is owner-only, so that trail has no control at its end for a member.
+ const ownsProject = currentProject?.role === "owner";
const clientRowOffered = offersClientUpdate({ desktopMode, sessionVia });
const { update } = useVersionInfo(eager);
// Passive: the shell's snapshot is polled by the sidebar's own hook instance while the user
@@ -49,6 +66,8 @@ export function useUpdateBadges(eager = false): UpdateBadges {
useEffect(() => {
if (eager && clientRowOffered) refreshDesktopUpdate();
}, [eager, clientRowOffered]);
+ const probes = useProjectTodos(projectId, eager, ownsProject);
+ const dismissed = useTodoDismissals(projectId, eager);
const software = softwareUpdate({
releaseRowOffered: !desktopMode,
@@ -57,19 +76,62 @@ export function useUpdateBadges(eager = false): UpdateBadges {
clientStatus: status,
});
const kernel = anyKernelOutdated(agents);
- const kernelNote = kernel ? S.agent.kernelOutdatedHint : null;
- const softwareNote = software === null ? null : noteText(software);
+ // Memoized on the cached response's identity: this walks the whole built-in catalog, and the
+ // hook re-runs on every render of the pages that read it (a keystroke in the model search box).
+ const presetTodo = useMemo(
+ () => (probes.models === null ? null : presetUpdateTodo(catalogDelta(probes.models.models))),
+ [probes.models],
+ );
+ // Markers still in flight (`null`) close every gate: raising a dot and putting it down a
+ // moment later, on a trail the user had already dealt with, is worse than a late dot.
+ const raise = (todo: Todo | null, key: TodoKey): Todo | null =>
+ dismissed === null ? null : raisedTodo(todo, dismissed[key] ?? null);
+ const skills = raise(skillUpdateTodo(agents), "skills");
+ const models = raise(presetTodo, "models");
+ const errors = raise(
+ probes.errors === null ? null : unexpectedErrorTodo(probes.errors),
+ "errors",
+ );
+
+ // Every raised source, in the order the trails appear in the nav. `badgeNote` reads the list;
+ // the per-route map below is what each individual anchor says.
+ const sources: BadgeSource[] = [];
+ if (software !== null) sources.push(software);
+ if (kernel) sources.push({ kind: "kernel" });
+ if (skills !== null) sources.push({ kind: "skills", count: skills.count });
+ if (models !== null) sources.push({ kind: "models", count: models.count });
+ if (errors !== null) sources.push({ kind: "errors", count: errors.count });
+
+ const navNotes: Partial<Record<BadgedRoute, string>> = {};
+ if (kernel) navNotes["/agents"] = S.agent.kernelOutdatedHint;
+ if (skills !== null) navNotes["/skills"] = S.todo.skillUpdates(skills.count);
+ if (models !== null) navNotes["/models"] = S.todo.presetUpdates(models.count);
+ if (errors !== null) navNotes["/usage"] = S.todo.unexpectedErrors(errors.count);
return {
software,
- softwareNote,
- kernel,
- kernelNote,
- any: software !== null || kernel,
- note: noteText(updateBadgeNote(software, kernel)),
+ softwareNote: software === null ? null : noteText(software),
+ navNotes,
+ todos: {
+ ...(skills !== null ? { skills } : {}),
+ ...(models !== null ? { models } : {}),
+ ...(errors !== null ? { errors } : {}),
+ },
+ any: sources.length > 0,
+ note: noteText(badgeNote(sources)),
};
}
+/**
+ * The note one nav route's dot carries, or null. Routes off every trail are simply absent from
+ * the map, so the lookup widens the key type rather than each caller asserting its own route
+ * into {@link BadgedRoute} — the nav rows are built from a route manifest and only ever hold
+ * strings.
+ */
+export function navNoteFor(badges: UpdateBadges, route: string): string | null {
+ return (badges.navNotes as Partial<Record<string, string>>)[route] ?? null;
+}
+
/**
* The localized sentence for one note. Read at call time, never hoisted: `S` is a live binding
* swapped on locale change.
@@ -84,7 +146,13 @@ function noteText(note: UpdateBadgeNote): string | null {
return S.update.clientRestartToInstall(note.version);
case "kernel":
return S.agent.kernelOutdatedHint;
+ case "skills":
+ return S.todo.skillUpdates(note.count);
+ case "models":
+ return S.todo.presetUpdates(note.count);
+ case "errors":
+ return S.todo.unexpectedErrors(note.count);
default:
- return S.update.updatesAvailable;
+ return note.updatesOnly ? S.update.updatesAvailable : S.todo.pending;
}
}
diff --git a/packages/web/test/agent-handoff.test.ts b/packages/web/test/agent-handoff.test.ts
index d3e441e6..e27f961e 100644
--- a/packages/web/test/agent-handoff.test.ts
+++ b/packages/web/test/agent-handoff.test.ts
@@ -28,6 +28,7 @@ const agent = (agentId: string, name?: string): AgentSummary => ({
kernelOutdated: false,
vaultKeyCount: 0,
scheduleCount: 0,
+ skillUpdates: [],
skillCount: 0,
memoryCount: 0,
});
diff --git a/packages/web/test/catalog-sync.test.ts b/packages/web/test/catalog-sync.test.ts
index 549b612f..24041110 100644
--- a/packages/web/test/catalog-sync.test.ts
+++ b/packages/web/test/catalog-sync.test.ts
@@ -1,12 +1,20 @@
/**
* catalog-sync.ts unit tests: the "sync presets" merge — union of the local model table and
* the built-in catalog, catalog winning on differing preset entries, local additions and
- * credentials untouched.
+ * credentials untouched — plus `catalogDelta`, the same question asked of a saved table so the
+ * Models nav badge can answer it before the page has loaded any rows.
+ *
+ * The last block is the one that matters most: the badge and the button must never disagree
+ * about whether there is anything to do, so every case above is replayed through both.
*/
import { describe, expect, it } from "vitest";
-import { syncRowsWithCatalog } from "../src/features/models/catalog-sync";
+import type { ModelsResponse } from "@prismshadow/penguin-server/api";
+import { catalogDelta, syncRowsWithCatalog } from "../src/features/models/catalog-sync";
+import { toRow } from "../src/features/models/models-page";
import type { RowState } from "../src/features/models/models-page";
+type ModelDto = ModelsResponse["models"][number];
+
type PresetEntry = Parameters<typeof syncRowsWithCatalog>[1] extends (infer E)[] | undefined
? E
: never;
@@ -169,3 +177,91 @@ describe("syncRowsWithCatalog", () => {
expect(rows.every((r) => r.apiKeyInput === "" && !r.clearApiKey)).toBe(true);
});
});
+
+/** A saved entry, in the shape the models endpoint sends. */
+function makeDto(partial: Partial<ModelDto> & Pick<ModelDto, "provider" | "modelId">): ModelDto {
+ return { ...partial } as ModelDto;
+}
+
+describe("catalogDelta", () => {
+ it("reports nothing when the saved table already matches the catalog", () => {
+ const saved = PRESET.map((p) =>
+ makeDto({
+ provider: p.provider,
+ modelId: p.model_id,
+ vision: p.vision !== false,
+ ...(p.context_window !== undefined ? { contextWindow: p.context_window } : {}),
+ ...(p.client_type !== undefined ? { clientType: p.client_type } : {}),
+ ...(p.pricing
+ ? {
+ pricing: {
+ cacheRead: p.pricing.cache_read,
+ cacheWrite: p.pricing.cache_write,
+ output: p.pricing.output,
+ } as ModelDto["pricing"],
+ }
+ : {}),
+ ...(p.base_url !== undefined
+ ? { credential: { baseUrl: p.base_url } as ModelDto["credential"] }
+ : {}),
+ }),
+ );
+ expect(catalogDelta(saved, PRESET)).toEqual({ added: 0, updated: 0, refs: [] });
+ });
+
+ it("names every entry it would add or rewrite, in catalog order", () => {
+ const stale = makeDto({ provider: "deepseek", modelId: "deepseek-v4-pro", vision: true });
+ expect(catalogDelta([stale], PRESET)).toEqual({
+ added: 2,
+ updated: 1,
+ refs: [
+ "deepseek/deepseek-v4-pro",
+ "qwen-token-plan/glm-5.2",
+ "qwen-token-plan/qwen3.8-max-preview",
+ ],
+ });
+ });
+
+ it("ignores locally added models, exactly as the merge does", () => {
+ const local = makeDto({ provider: "custom", modelId: "my-own" });
+ expect(catalogDelta([local], PRESET).refs).not.toContain("custom/my-own");
+ });
+
+ /**
+ * The badge reads a saved table; the button reads row state. They are two conversions of the
+ * same data, so this pins them together: whatever `toRow` does to a DTO, `catalogDelta` must
+ * read the same way, or a dot would lead to a button answering "already up to date".
+ */
+ it("agrees with the sync merge on every table shape, against the real catalog", () => {
+ const tables: ModelDto[][] = [
+ [],
+ [makeDto({ provider: "deepseek", modelId: "deepseek-v4-pro" })],
+ [makeDto({ provider: "deepseek", modelId: "deepseek-v4-pro", contextWindow: 1000000 })],
+ [
+ makeDto({
+ provider: "qwen-token-plan",
+ modelId: "glm-5.2",
+ clientType: "openai-chat",
+ credential: { baseUrl: "http://my-proxy" } as ModelDto["credential"],
+ }),
+ ],
+ [makeDto({ provider: "custom", modelId: "my-own", contextWindow: 8192 })],
+ ];
+ for (const table of tables) {
+ const merged = syncRowsWithCatalog(table.map(toRow), PRESET);
+ const delta = catalogDelta(table, PRESET);
+ expect([delta.added, delta.updated], JSON.stringify(table)).toEqual([
+ merged.added,
+ merged.updated,
+ ]);
+ expect(delta.refs.length).toBe(merged.added + merged.updated);
+ }
+ });
+
+ it("agrees with the merge on an empty table against the shipped catalog", () => {
+ const merged = syncRowsWithCatalog([]);
+ const delta = catalogDelta([]);
+ expect([delta.added, delta.updated]).toEqual([merged.added, merged.updated]);
+ expect(delta.refs.length).toBeGreaterThan(30);
+ });
+});
diff --git a/packages/web/test/todo-badges.test.ts b/packages/web/test/todo-badges.test.ts
new file mode 100644
index 00000000..d6dbce41
--- /dev/null
+++ b/packages/web/test/todo-badges.test.ts
@@ -0,0 +1,189 @@
+/**
+ * Gate + dismissal unit tests for the three DISMISSIBLE badge trails.
+ *
+ * The rule every case here defends is the one that makes a dismissal safe: what the badge is
+ * dismissed against is WHAT is waiting, not the fact that something was. So dismissing hides
+ * exactly the things that were waved away — including the rest of a batch after one of them is
+ * dealt with — acting on the trail clears it on its own, and anything new — a later Skill
+ * version, a different model, a newer error — raises it again.
+ */
+import { describe, expect, it } from "vitest";
+import type { AgentSummary, UsageErrorsPage } from "@prismshadow/penguin-server/api";
+import {
+ presetUpdateTodo,
+ raisedTodo,
+ skillUpdateTodo,
+ unexpectedErrorTodo,
+} from "../src/lib/todo-badges";
+import type { Todo } from "../src/lib/todo-badges";
+import { parseTodoDismissMap, withDismissal } from "../src/lib/todo-dismissals";
+
+/** Just the field the Skills gate reads (the gate takes a Pick, so the fixture can be one too). */
+function agent(
+ ...updates: Array<{ name: string; version: number }>
+): Pick<AgentSummary, "skillUpdates"> {
+ return { skillUpdates: updates };
+}
+
+function errorPage(total: number, ...timestamps: string[]): UsageErrorsPage {
+ return {
+ total,
+ items: timestamps.map((ts) => ({
+ ts,
+ source: "runtime",
+ code: "boom",
+ kind: "unexpected",
+ message: "boom",
+ })),
+ };
+}
+
+describe("skillUpdateTodo", () => {
+ it("is null when no Agent is behind", () => {
+ expect(skillUpdateTodo([agent(), agent()])).toBeNull();
+ });
+
+ it("counts distinct Skills, not Agents: the trail ends on a list that shows each once", () => {
+ const todo = skillUpdateTodo([
+ agent({ name: "web-design", version: 3 }),
+ agent({ name: "web-design", version: 3 }, { name: "vllm", version: 2 }),
+ ]);
+ expect(todo).toEqual({
+ signature: "vllm@2,web-design@3",
+ items: ["vllm@2", "web-design@3"],
+ count: 2,
+ match: "set",
+ });
+ });
+
+ it("is order-independent, so two loads of the same state dismiss alike", () => {
+ const a = skillUpdateTodo([agent({ name: "b", version: 1 }, { name: "a", version: 2 })]);
+ const b = skillUpdateTodo([agent({ name: "a", version: 2 }), agent({ name: "b", version: 1 })]);
+ expect(a).toEqual(b);
+ });
+
+ it("keeps the highest library version when Agents disagree", () => {
+ // One Agent behind v2 and another behind v3 is one Skill to update, at v3.
+ const todo = skillUpdateTodo([
+ agent({ name: "vllm", version: 2 }),
+ agent({ name: "vllm", version: 3 }),
+ ]);
+ expect(todo).toEqual({ signature: "vllm@3", items: ["vllm@3"], count: 1, match: "set" });
+ });
+
+ it("survives an Agent list from a server that does not send the field", () => {
+ // A newer web against an older runtime: no skillUpdates key at all, and no crash.
+ expect(skillUpdateTodo([{} as Pick<AgentSummary, "skillUpdates">])).toBeNull();
+ });
+});
+
+describe("presetUpdateTodo", () => {
+ it("is null when the table already matches the catalog", () => {
+ expect(presetUpdateTodo({ added: 0, updated: 0, refs: [] })).toBeNull();
+ });
+
+ it("counts the entries that would change and signs itself with them", () => {
+ const todo = presetUpdateTodo({
+ added: 1,
+ updated: 1,
+ refs: ["anthropic/claude-opus-5", "openai/gpt-5"],
+ });
+ expect(todo).toEqual({
+ signature: "anthropic/claude-opus-5,openai/gpt-5",
+ items: ["anthropic/claude-opus-5", "openai/gpt-5"],
+ count: 2,
+ match: "set",
+ });
+ });
+
+ it("separates two deltas of the same size, so a different model still raises the dot", () => {
+ const first = presetUpdateTodo({ added: 1, updated: 0, refs: ["a/one"] });
+ const second = presetUpdateTodo({ added: 1, updated: 0, refs: ["b/two"] });
+ expect(first!.count).toBe(second!.count);
+ expect(first!.signature).not.toBe(second!.signature);
+ });
+});
+
+describe("unexpectedErrorTodo", () => {
+ it("is null on an empty window", () => {
+ expect(unexpectedErrorTodo(errorPage(0))).toBeNull();
+ });
+
+ it("is null when the count is zero even if a row came back", () => {
+ // Defensive: a total of 0 is the answer to "is anything waiting", and it wins.
+ expect(unexpectedErrorTodo(errorPage(0, "2026-08-26T10:00:00.000Z"))).toBeNull();
+ });
+
+ it("signs itself with the newest error and counts the whole window", () => {
+ expect(unexpectedErrorTodo(errorPage(7, "2026-08-26T10:00:00.000Z"))).toEqual({
+ signature: "2026-08-26T10:00:00.000Z",
+ items: ["2026-08-26T10:00:00.000Z"],
+ count: 7,
+ match: "watermark",
+ });
+ });
+
+ it("does not move when only older rows are evicted", () => {
+ // The row cap evicts oldest-first, so the newest timestamp — and the dismissal — holds.
+ const before = unexpectedErrorTodo(errorPage(20000, "2026-08-26T10:00:00.000Z"));
+ const after = unexpectedErrorTodo(errorPage(19800, "2026-08-26T10:00:00.000Z"));
+ expect(after!.signature).toBe(before!.signature);
+ });
+});
+
+describe("raisedTodo", () => {
+ const todo: Todo = { signature: "vllm@2", items: ["vllm@2"], count: 1, match: "set" };
+
+ it("is down when nothing is waiting", () => {
+ expect(raisedTodo(null, null)).toBeNull();
+ expect(raisedTodo(null, "vllm@2")).toBeNull();
+ });
+
+ it("is up when nothing was dismissed", () => {
+ expect(raisedTodo(todo, null)).toEqual(todo);
+ });
+
+ it("is down for exactly what was dismissed", () => {
+ expect(raisedTodo(todo, "vllm@2")).toBeNull();
+ });
+
+ it("comes back for a later version of the same thing", () => {
+ // "Not this update" — never "never tell me about this Skill again".
+ const later: Todo = { signature: "vllm@3", items: ["vllm@3"], count: 1, match: "set" };
+ expect(raisedTodo(later, "vllm@2")).toEqual(later);
+ });
+
+ it("stays down for the rest of a batch after one of it was acted on", () => {
+ // Two Skills dismissed together, then one updated: what is left is a SUBSET of what the
+ // user waved away, and a shrinking set is not news.
+ const rest: Todo = { signature: "b@3", items: ["b@3"], count: 1, match: "set" };
+ expect(raisedTodo(rest, "a@2,b@3")).toBeNull();
+ });
+});
+
+describe("todo dismissal markers", () => {
+ it("reads nothing out of an absent, malformed or wrongly shaped record", () => {
+ expect(parseTodoDismissMap(undefined)).toEqual({});
+ expect(parseTodoDismissMap("skills")).toEqual({});
+ expect(parseTodoDismissMap([])).toEqual({});
+ expect(parseTodoDismissMap({ p1: "a@1" })).toEqual({});
+ });
+
+ it("keeps the string signatures and drops everything else, key by key", () => {
+ // One bad value must not resurrect the other trails' dots.
+ expect(parseTodoDismissMap({ p1: { skills: "a@1", models: 7, nope: "x" } })).toEqual({
+ p1: { skills: "a@1" },
+ });
+ });
+
+ it("merges into what a Project already dismissed and leaves other Projects alone", () => {
+ // The whole map is what gets written back (PUT /me/prefs merges only at the top level),
+ // so a dismissal must carry every other Project through untouched.
+ expect(
+ withDismissal({ p1: { skills: "a@1" }, p2: { errors: "t" } }, "p1", "models", "b/two"),
+ ).toEqual({
+ p1: { skills: "a@1", models: "b/two" },
+ p2: { errors: "t" },
+ });
+ });
+});
diff --git a/packages/web/test/update-badges.test.ts b/packages/web/test/update-badges.test.ts
index 214c6b7e..73fe6720 100644
--- a/packages/web/test/update-badges.test.ts
+++ b/packages/web/test/update-badges.test.ts
@@ -1,6 +1,6 @@
/**
- * Update-badge gate unit tests: what raises a notification dot, and what an anchor over both
- * trails says. The rule every case here defends is that a dot must end in a control the user
+ * Update-badge gate unit tests: what raises a notification dot, and what an anchor over
+ * several trails says. The rule every case here defends is that a dot must end in a control the user
* can actually reach — so the release gate is closed wherever the sidebar does not offer the
* release row, a fail-soft check raises nothing, and a download still in flight is not a badge.
*/
@@ -8,9 +8,9 @@ import { describe, expect, it } from "vitest";
import type { DesktopUpdateStatus, UpdateCheckResponse } from "@prismshadow/penguin-server/api";
import {
anyKernelOutdated,
+ badgeNote,
releaseUpdate,
softwareUpdate,
- updateBadgeNote,
} from "../src/lib/update-badges";
function check(overrides: Partial<UpdateCheckResponse>): UpdateCheckResponse {
@@ -156,30 +156,41 @@ describe("anyKernelOutdated", () => {
});
});
-describe("updateBadgeNote", () => {
+describe("badgeNote", () => {
const release = { kind: "release", version: "0.2.0" } as const;
+ const kernel = { kind: "kernel" } as const;
+ const errors = { kind: "errors", count: 2 } as const;
- it("says nothing when nothing is updatable", () => {
- expect(updateBadgeNote(null, false)).toEqual({ kind: "none" });
+ it("says nothing when nothing is waiting", () => {
+ expect(badgeNote([])).toEqual({ kind: "none" });
});
it("names the release when only software is updatable", () => {
- expect(updateBadgeNote(release, false)).toEqual(release);
+ expect(badgeNote([release])).toEqual(release);
});
it("carries a client build's version through, null included", () => {
- expect(updateBadgeNote({ kind: "client", version: null }, false)).toEqual({
+ expect(badgeNote([{ kind: "client", version: null }])).toEqual({
kind: "client",
version: null,
});
});
- it("says kernel when only an Agent is behind", () => {
- expect(updateBadgeNote(null, true)).toEqual({ kind: "kernel" });
+ it("names a single to-do trail, count included", () => {
+ expect(badgeNote([{ kind: "skills", count: 3 }])).toEqual({ kind: "skills", count: 3 });
});
- it("names neither when both trails have something", () => {
- // The combined anchor leads to both; naming one of the two would point at the wrong trail.
- expect(updateBadgeNote(release, true)).toEqual({ kind: "mixed" });
+ it("names none of them when several trails have something", () => {
+ // The combined anchor leads to all of them; naming one would point at the wrong trail.
+ expect(badgeNote([release, kernel])).toEqual({ kind: "mixed", updatesOnly: true });
+ });
+
+ it("keeps the combined case an update only while every source is one", () => {
+ expect(badgeNote([kernel, { kind: "models", count: 1 }])).toEqual({
+ kind: "mixed",
+ updatesOnly: true,
+ });
+ // An unexpected error is not an update by any reading, so the wider wording is required.
+ expect(badgeNote([kernel, errors])).toEqual({ kind: "mixed", updatesOnly: false });
});
});