A local-first multi-agent app development platform, built on PenguinHarness
fix(web): live Session run status with a three-state row glyph (#302)
Yiru Dong91a1bd22a13b
diff --git a/changelog/unreleased/2026-08-16-chat-completion-status.md b/changelog/unreleased/2026-08-16-chat-completion-status.mdnew file mode 100644index 00000000..a062fe53--- /dev/null+++ b/changelog/unreleased/2026-08-16-chat-completion-status.md@@ -0,0 +1,44 @@+# Web App: chat rows say whether a Session is working, and whether it finished with something unread++- **Date:** 2026-08-16+- **Type:** feature+- **Scope:** `web`, `server`, `docs`+- **PR:** [#302](https://github.com/Prism-Shadow/penguin-harness/pull/302)+- **Issue:** [#291](https://github.com/Prism-Shadow/penguin-harness/issues/291)++[中文版](2026-08-16-chat-completion-status.zh.md)++A running conversation was marked by a small pulsing dot that simply vanished when the run ended, so "still working" and "finished" looked the same once the dot was gone — and a run that finished while the user was looking elsewhere left no trace at all. Sidebar rows now carry an hourglass that turns over while the Session is busy, and a green dot afterwards for as long as the last reply has not been read.++## The glyphs++Three states, two shapes:++- **Busy** — an hourglass, turning 180 degrees twice per three-second cycle with a long hold between turns. Compaction is busy work like any other and reuses the same hourglass, keeping the amber tone compaction already carries elsewhere in the app; a run in progress is gray. The two live states therefore differ by colour alone, and each names itself in its tooltip and accessible name.+- **Finished, unread** — a small green dot. It is a notification rather than a status: it says there is a reply here you have not seen. It uses the emerald the Session status dot has always used, one tone in both themes.+- **Nothing at all** — a Session whose last reply has been read shows no glyph, and neither does one that has never run (the server's existing `hasTrace` flag is what tells them apart internally). The marker is removed rather than muted, so the only marks left in the list are the ones worth acting on. Every row reserves the glyph's width whatever its state, so nothing re-flows as a run starts, finishes, and is read.+- The chat header carries the hourglass alone: the conversation on screen is by definition read, so it has no dot to show.+- Both live states and the dot carry their exact state as tooltip and accessible name in both locales, so nothing is reachable only by seeing a colour. Live states announce as a `status`; the dot is a plain labelled image. The read state announces nothing because it renders nothing, which is correct — there is no state to report.++## Live for every row++- Run status used to be live only for the conversation the tab had open. The Session channel's `task_state` event is session-scoped and carries no id, so every other row kept whatever status the last list fetch returned: a Session left running while the user moved on stayed on its hourglass indefinitely, and one that began running in the background — a scheduled task, a subagent, another tab, or the conversation just navigated away from — never grew one at all.+- The server publishes the same flip a second time on the user-level event stream (`GET /api/events`) as `session_state`, carrying the `sessionId` plus the two row fields the glyph is drawn from: `lastActiveAt` as just stamped, and `hasTrace`. The per-Session `task_state` event is unchanged: the queued follow-up count and the undelivered-steering mirror belong to the conversation being watched, and the list event carries neither.+- `hasTrace` rides along because the glyph is drawn from three fields, not one. A Session running its first Task still carries the `false` its list row was fetched with, so the hourglass would show and then the moment it stopped the row would go blank instead of showing the unread dot. The event reports it as true whenever the state is running or compacting, since a Session that is running has by definition started a Task, and the client treats it as one-way for the same reason. The flag stays load-bearing even though read and never-ran now look identical: a conversation created after this browser first saw the Project has no read marker of its own and its creation time is later than the baseline, so without the flag every brand-new row would wear the dot before it had ever run.+- The event reaches the user channels of the Project's owner and its members and no one else, and only channels a client has actually opened.+- Carrying the server's own row stamp is what makes a background completion legible: a run that finished while the user was elsewhere shows the dot, instead of settling silently as though it had already been read.+- A status naming a Session no loaded page holds is dropped rather than turned into a row — the same drop that keeps another Project's Sessions out of the list.+- Nothing polls. A reconnect landing outside the channel's replay buffer already reports `resync_required`; the list refetches once on that event, so a gap in delivery cannot strand a row mid-run.+- The conversation currently open is never drawn as unread — the user is looking at it — so no dot flashes onto its row while the chat page and the user channel report the same completion.++## Read and unread++- Read state is tracked in the browser, per Project, under `penguin.sessionSeen.<projectId>`. The API models no read receipt — there is no notifications table and no read column on a Session — so this follows the precedent already set for pinned Sessions, which persist client-side for the same reason.+- A marker records when the user last had a Session open; a Session counts as unread when its `lastActiveAt` is newer. Opening a Session stamps it, and so does a run finishing while the user is watching it. The marker takes the later of the wall clock and the Session's own `lastActiveAt`, so opening a Session marks it read even when the browser's clock lags the server's.+- The first marker written for a Project also records a baseline: conversations that last ran before it count as read, so turning the feature on does not light up every historical conversation at once.+- Markers are capped at 500 per Project, evicting the least recently seen, and a deleted Session's marker is pruned.+- Being browser-side, read state does not travel: the same account on a second device or browser starts with its own markers, and a second tab keeps its own view until it reloads.++## Reduced motion++Under `prefers-reduced-motion` the repository's global `animation: none !important` rule disables the turn, with no override of its own: the `hourglass-turn` keyframes only ever set `transform`, so the glyph stays exactly where it renders at rest — an upright, fully visible hourglass — rather than disappearing.diff --git a/changelog/unreleased/2026-08-16-chat-completion-status.zh.md b/changelog/unreleased/2026-08-16-chat-completion-status.zh.mdnew file mode 100644index 00000000..b66cef55--- /dev/null+++ b/changelog/unreleased/2026-08-16-chat-completion-status.zh.md@@ -0,0 +1,44 @@+# Web App:会话行显示是否在运行,以及跑完后有没有未读回复++- **Date:** 2026-08-16+- **Type:** feature+- **Scope:** `web`, `server`, `docs`+- **PR:** [#302](https://github.com/Prism-Shadow/penguin-harness/pull/302)+- **Issue:** [#291](https://github.com/Prism-Shadow/penguin-harness/issues/291)++[English](2026-08-16-chat-completion-status.md)++运行中的会话此前只有一个小小的呼吸圆点,运行结束后圆点直接消失,于是"还在跑"和"已经跑完"在圆点消失后看起来毫无差别;而在用户看别处时跑完的任务,更是什么痕迹都不会留下。现在侧边栏的会话行在会话忙碌时显示一个来回翻转的沙漏,跑完之后只要最后一条回复还没读,就显示一个绿色圆点。++## 图标++三种状态,两种形状:++- **忙碌** —— 沙漏,每三秒翻转 180 度两次,两次翻转之间有较长的停顿。压缩上下文同样属于忙碌,因此复用同一个沙漏,并沿用应用中压缩一贯的琥珀色;运行中则是灰色。也就是说这两个实时状态仅靠颜色区分,而每个图标都会在悬停提示和无障碍名称中说明自己是哪一种。+- **已完成且未读** —— 一个小小的绿色圆点。它更像通知而非状态:意思是"这里有一条你还没看过的回复"。颜色沿用会话状态点一直以来的那个绿色,两种主题下同一个色值。+- **不显示图标** —— 最后一条回复已读的会话不显示任何图标,从未运行过的会话同样不显示(内部靠服务端已有的 `hasTrace` 标记区分两者)。标记是直接移除而不是调淡,这样列表里剩下的每一个标记都值得处理。无论处于哪种状态,每一行都为图标预留同样的宽度,因此会话开始运行、跑完、被读过的整个过程中都不会重排。+- 聊天页头部只保留沙漏:正在看的这个会话本来就算已读,没有圆点可显示。+- 两种实时状态和圆点都在两种语言下把自己的确切状态写进悬停提示和无障碍名称,所以没有任何状态只能靠看颜色获知。实时状态以 `status` 播报,圆点则是一张带标签的普通图像。已读状态什么都不渲染,因此也什么都不播报 —— 这是对的,此时并没有需要汇报的状态。++## 每一行都实时++- 运行状态此前只对标签页当前打开的那个会话是实时的。Session 通道的 `task_state` 事件以会话为界,且不带 id,因此其余每一行都停留在上次拉取列表时的状态:用户离开后仍在运行的会话会一直挂着沙漏,而在后台开始运行的会话 —— 定时任务、子 Agent、另一个标签页,或者用户刚刚离开的那个会话 —— 则根本不会出现沙漏。+- 服务端会把同一次状态翻转再发一次,走用户级事件流(`GET /api/events`),事件名为 `session_state`,除 `sessionId` 外还携带绘制图标所需的两个行字段:刚刚写入的 `lastActiveAt`,以及 `hasTrace`。Session 级的 `task_state` 保持原样:排队的后续任务计数和未投递的 steering 镜像属于正在观看的那个会话,列表事件两者都不带。+- 之所以要带上 `hasTrace`,是因为图标由三个字段决定而不是一个。首次运行的会话,其列表行上仍是拉取时的 `false` —— 于是沙漏会正常转动,可一旦停下,那一行不会显示未读圆点,而是直接变成空白。状态为 running 或 compacting 时该字段一律报 true,因为正在运行的会话必然已经启动过 Task;前端出于同样的理由把它当作只增不减的标志。即便现在"已读"与"从未运行"看起来完全一样,这个字段依然不可省略:在本浏览器首次看到该 Project 之后才创建的会话没有自己的已读标记,其创建时间又晚于基准时间,因此若没有这个字段,每一个刚建的会话都会在从未运行过的情况下先挂上圆点。+- 该事件只发往该 Project 拥有者与成员的用户通道,不发给其他任何人,并且只发往客户端确实已经打开的通道。+- 携带服务端自己的行时间戳,正是后台完成得以被看见的关键:用户在别处时跑完的任务会显示圆点,而不是像早已读过一样悄无声息地安定下来。+- 若事件指向的会话不在任何已加载的分页中,则直接丢弃,而不是凭空造出一行 —— 其他 Project 的会话也是被同一条规则挡在列表之外的。+- 全程没有轮询。重连若落在通道重放缓冲区之外,本就会收到 `resync_required`;列表在该事件上重新拉取一次,因此投递缺口不会让某一行永远卡在运行中。+- 当前打开的会话永远不会画成未读 —— 用户正在看它 —— 所以在聊天页与用户通道先后报告同一次完成时,它那一行不会闪出圆点。++## 已读与未读++- 已读状态记录在浏览器本地,按 Project 划分,键名为 `penguin.sessionSeen.<projectId>`。API 中并没有已读回执这一概念 —— 既没有通知表,Session 上也没有已读字段 —— 因此这里沿用置顶会话出于同样原因而采取的做法,持久化在前端。+- 标记记录用户最后一次打开该会话的时间;当会话的 `lastActiveAt` 更新于该时间时即视为未读。打开会话会写入标记,用户正在观看时任务跑完也会写入。标记取墙上时钟与会话自身 `lastActiveAt` 中较晚的一个,因此即使浏览器时钟慢于服务端,打开会话也一定会被标记为已读。+- 每个 Project 首次写入标记时还会记录一个基准时间:在此之前最后运行过的会话一律算作已读,这样启用该功能不会让所有历史会话同时亮起未读。+- 每个 Project 最多保留 500 个标记,超出时淘汰最久未看的;会话被删除时其标记也会一并清除。+- 由于记录在浏览器本地,已读状态不会跟随账号流转:同一账号在另一台设备或另一个浏览器上从各自的标记开始,另一个标签页在重新加载之前也保持自己的视图。++## 减弱动态效果++在 `prefers-reduced-motion` 下,仓库全局的 `animation: none !important` 规则会直接关闭翻转,这里无需任何额外覆盖:`hourglass-turn` 关键帧只设置 `transform`,因此图标停留在静止时本来的样子 —— 一个竖直摆放、完整可见的沙漏 —— 而不会消失。diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.mdindex d92c5bd9..4fd9008b 100644--- a/packages/docs/content/server-api.en.md+++ b/packages/docs/content/server-api.en.md@@ -300,7 +300,7 @@ Real-time delivery uses Server-Sent Events, not WebSocket, on two channels (the| Channel | Path | Contents || --- | --- | --- || Per Session | GET /api/sessions/:sessionId/stream | The Session's message stream and run events |-| Per user | GET /api/events | `hello` handshake and cross-Session notifications (schedule_fired / schedule_queued / session_created) |+| Per user | GET /api/events | `hello` handshake and cross-Session notifications (session_state / schedule_fired / schedule_queued / session_created) |### Wire Format@@ -311,6 +311,7 @@ export type ServerEvent =| { type: "approval_request"; toolCall: OmniMessage<ToolCallPayload>; origin?: string[] }| { type: "task_state"; state: "idle" | "running" | "compacting" }| { type: "session_title"; sessionId: string; title: string }+ | { type: "session_state"; sessionId: string; state: "idle" | "running" | "compacting"; lastActiveAt: string; hasTrace: boolean }| { type: "resync_required" }| { type: "credentials_updated" }| { type: "hello" }@@ -324,6 +325,7 @@ export type ServerEvent =| approval_request | A tool call escalated to human approval: every call under always-ask, plus rw / unknown-permission calls under read-only; pending approvals are resent on reconnect || task_state | The Session's run state flips (idle / running / compacting) || session_title | The model-generated title after the first turn has been persisted |+| session_state | The user-channel counterpart of `task_state`: the same run-state flip, named by `sessionId`, so a Session list stays live for every row and not only the conversation a client has open. Carries the row fields needed to redraw it without refetching — `lastActiveAt` as just stamped, and `hasTrace` (true whenever the state is running or compacting, since a Session that is running has by definition started a Task). Published to the user channels of the Project's owner and members || resync_required | The Last-Event-ID was evicted from the buffer; the client must refetch history || credentials_updated | The Project's model credentials changed (`PUT /models`): cached runtimes were invalidated, so the client clears any auth-dead composer state || hello | Handshake on the user channel |diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.mdindex c18f68e1..608427aa 100644--- a/packages/docs/content/server-api.zh.md+++ b/packages/docs/content/server-api.zh.md@@ -297,7 +297,7 @@ Web 的 `/model` 模型切换没有专用接口:它按 `/agent` 交接的方| 通道 | 路径 | 内容 || --- | --- | --- || Session 级 | GET /api/sessions/:sessionId/stream | 该 Session 的消息流与运行事件 |-| 用户级 | GET /api/events | `hello` 握手与跨 Session 通知(schedule_fired / schedule_queued / session_created) |+| 用户级 | GET /api/events | `hello` 握手与跨 Session 通知(session_state / schedule_fired / schedule_queued / session_created) |### 传输格式@@ -308,6 +308,7 @@ export type ServerEvent =| { type: "approval_request"; toolCall: OmniMessage<ToolCallPayload>; origin?: string[] }| { type: "task_state"; state: "idle" | "running" | "compacting" }| { type: "session_title"; sessionId: string; title: string }+ | { type: "session_state"; sessionId: string; state: "idle" | "running" | "compacting"; lastActiveAt: string; hasTrace: boolean }| { type: "resync_required" }| { type: "credentials_updated" }| { type: "hello" }@@ -321,6 +322,7 @@ export type ServerEvent =| approval_request | 工具调用升级为人工审批时发出:always-ask 下的所有调用,以及 read-only 下 rw / 未知权限的调用;重连时未决审批会重发 || task_state | Session 运行状态翻转(idle / running / compacting) || session_title | 首轮后模型生成的标题已持久化 |+| session_state | `task_state` 在用户通道上的对应事件:同一次运行状态翻转,带上 `sessionId`,因此会话列表的每一行都能保持实时,而不只是客户端当前打开的那个会话。事件还携带重绘该行所需的行字段,无需重新拉取列表 —— 刚刚写入的 `lastActiveAt`,以及 `hasTrace`(状态为 running 或 compacting 时必为 true,因为正在运行的会话必然已经启动过 Task)。仅发往该 Project 拥有者与成员的用户通道 || resync_required | Last-Event-ID 已被缓冲区淘汰,客户端须重新拉取历史 || credentials_updated | Project 模型凭据已变更(`PUT /models`):缓存运行时已失效,客户端应清除鉴权失败的输入框禁用态 || hello | 用户通道连接握手 |diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.tsindex 0ba8cb69..53bcefe7 100644--- a/packages/server/src/api/types.ts+++ b/packages/server/src/api/types.ts@@ -1270,6 +1270,32 @@ export type ServerEvent =}/** The model-generated title after the first turn has been persisted (for in-place list updates). */| { type: "session_title"; sessionId: string; title: string }+ /**+ * The user-channel counterpart of `task_state`: the same run-state flip, named by+ * `sessionId`, delivered on GET /api/events.+ *+ * `task_state` is session-scoped and deliberately carries no id, so it only ever reaches the+ * one conversation a tab has subscribed to — every OTHER row in that tab's Session list would+ * otherwise keep whatever status its last list fetch returned. This event exists so the list+ * can stay live without polling; the per-Session contract is unchanged.+ *+ * `lastActiveAt` and `hasTrace` are the row's own fields as they stand after the flip, both+ * written just before publishing (`markDriven` at run start sets has_trace and stamps+ * last_active_at; `touchLastActive` stamps again at run end). They are what let a list act on+ * the flip without refetching: the stamp separates "this finished while I was looking+ * elsewhere" from "this finished before I last looked", and `hasTrace` separates a Session+ * that has now run from one that never has — a first run would otherwise settle back into the+ * blank "never ran" row the client still believes in.+ *+ * Published only to the user channels of the Project's owner and members.+ */+ | {+ type: "session_state";+ sessionId: string;+ state: SessionStatus;+ lastActiveAt: string;+ hasTrace: boolean;+ }/** Last-Event-ID has been evicted from the buffer: the frontend should re-fetch the history endpoint before continuing to consume this connection. */| { type: "resync_required" }/**diff --git a/packages/server/src/app.ts b/packages/server/src/app.tsindex b99d79ea..6f39f1b9 100644--- a/packages/server/src/app.ts+++ b/packages/server/src/app.ts@@ -241,6 +241,22 @@ export function buildAppDeps(config: ServerConfig, overrides: BuildDepsOverridestitles,log,goals: goalsRepo,+ // Run-state flips reach the whole login session, not just the tab watching that one+ // conversation. Audience = the Project's owner plus its members, i.e. exactly who+ // ProjectsRepo.listAccessible would grant the Project to — nobody learns that a Session+ // they cannot open changed state.+ //+ // `peek`, deliberately not `get`: a user who has never opened an event stream has no+ // channel, and conjuring one to buffer badge updates nobody is listening to is pure waste+ // (their next connection fetches the list, which carries the same statuses anyway).+ notifyProjectUsers: (projectId, event) => {+ const ownerUserId = projectsRepo.findById(projectId)?.ownerUserId;+ if (ownerUserId === undefined) return;+ const audience = new Set([ownerUserId, ...membersRepo.list(projectId).map((m) => m.userId)]);+ for (const userId of audience) {+ channels.peek(userChannelKey(userId))?.publish(event, "server_event");+ }+ },...(overrides.now ? { now: overrides.now } : {}),});managerRef = manager;diff --git a/packages/server/src/runtime/session-manager.ts b/packages/server/src/runtime/session-manager.tsindex 16f7bc84..9b646f5e 100644--- a/packages/server/src/runtime/session-manager.ts+++ b/packages/server/src/runtime/session-manager.ts@@ -236,6 +236,14 @@ export interface SessionManagerDeps {log?: (line: string) => void;/** Goal run-state persistence (optional like `titles`: without it, goals run but leave no restorable record). */goals?: GoalsRepo;+ /**+ * Publishes a Session-scoped event on the user-level channel of everyone who can see the+ * Project. The audience lookup (owner + members) and the `user:<id>` channel binding stay in+ * the app layer, the same split the scheduler's `notify` uses — this class holds no Project+ * membership repos. Optional: without it only the per-Session channel is served, which is+ * what unit tests that don't wire it get.+ */+ notifyProjectUsers?: (projectId: string, event: ServerEvent) => void;/*** Clock for persisted timestamps (last_active_at). Injected like the other services' so a* stubbed clock moves this and `usage_records.ts` together — the pairing the legacy@@ -1716,6 +1724,40 @@ export class SessionManager {? { pendingFollowUps: entry.followUps.map(followUpInfo) }: {}),});+ // The same flip again, this time on the user channel and carrying the Session id: a tab+ // subscribes to the ONE conversation it has open, so the event above can never move any+ // other row's badge. Only the queued/steering hints stay session-scoped — they belong to+ // the composer of the conversation being watched, not to a list row.+ const notify = this.deps.notifyProjectUsers;+ if (!notify) return;+ let lastActiveAt: string;+ let hasTrace: boolean;+ try {+ // Read the stamp back rather than reconstruct it: the run-end flip is published right+ // after the write that stamps it (touchLastActive in drive's finally), so this is what a+ // list fetch would return right now and no clock of ours has to agree with the one that+ // wrote it.+ const row = this.deps.sessions.findById(entry.sessionId);+ if (!row) return; // Row already deleted: no list row left to light up.+ lastActiveAt = row.lastActiveAt;+ // A running Session has by definition started a Task, whatever the row cache says yet:+ // markDriven (which sets has_trace) runs inside drive(), and startTask has already+ // published the first "running" by then. Reporting the raw flag there would tell a client+ // the Session has never run at the exact moment it visibly is running — and a client that+ // believed it would draw the hourglass, then nothing at all once the run settled.+ hasTrace = row.hasTrace === true || state !== "idle";+ } catch {+ // Same failure touchRow guards against (DB handle closed by shutdown while a run+ // outlives its drain window). A list badge is never worth breaking a run's finally over.+ return;+ }+ notify(entry.projectId, {+ type: "session_state",+ sessionId: entry.sessionId,+ state,+ lastActiveAt,+ hasTrace,+ });}private publishEvent(entry: RuntimeEntry, event: ServerEvent): void {diff --git a/packages/server/test/session-state-events.test.ts b/packages/server/test/session-state-events.test.tsnew file mode 100644index 00000000..aa28a6a2--- /dev/null+++ b/packages/server/test/session-state-events.test.ts@@ -0,0 +1,161 @@+/**+ * `session_state` on the user channel: the run-state flip a Session list can act on.+ *+ * The per-Session `task_state` event is session-scoped and deliberately carries no id, so it+ * only ever reaches the one conversation a client has subscribed to. This is its user-channel+ * counterpart — named by `sessionId`, carrying the row stamp — and what these tests pin is its+ * SCOPE: it reaches the Project's owner and its members, and nobody else, not even a logged-in+ * user with a live channel of their own.+ *+ * The unchanged shape of `task_state` itself is pinned by sse-stream.test.ts, which compares+ * the frame with `toEqual` and would fail the moment an id appeared on it.+ */+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { assistantText } from "@prismshadow/penguin-core";+import type { ServerEvent } from "../src/api/types.js";+import type { SessionRow } from "../src/db/repos/sessions.js";+import { userChannelKey } from "../src/http/routes/events.js";+import type { RuntimeSession } from "../src/runtime/session-manager.js";+import { apiClient, createTestApp, provisionUser, waitFor } from "./helpers.js";+import type { TestApp } from "./helpers.js";++const SID = "session-2026-08-19-10-00-00-abcd0001";+const PROJECT = "owner-default_project";+/** Comfortably before the run: the run-end stamp must be visibly later than this. */+const INSERTED_AT = "2026-08-19T09:00:00.000Z";++/** Fake Session that answers once and returns, so a run is one clean running → idle pair. */+function quickFakeSession(sessionId: string): RuntimeSession {+ return {+ sessionId,+ toolPermission: () => "rw",+ generateTitle: async () => ({ title: null, usage: null }),+ compactability: () => "ok" as const,+ steer: () => false,+ skipReconnectWait: () => false,+ async *run() {+ yield assistantText("done");+ },+ async *compact() {},+ };+}++/** Everything one user's channel received, as a connected client would see it. */+function inbox(t: TestApp, userId: string) {+ const events: ServerEvent[] = [];+ // `get`, not `peek`: this stands in for a client that has opened GET /api/events, which is+ // exactly the condition the publish side checks for.+ t.deps.channels.get(userChannelKey(userId)).subscribe((evt) => {+ if (evt.event === "server_event") events.push(JSON.parse(evt.data) as ServerEvent);+ });+ const states = () => events.flatMap((e) => (e.type === "session_state" ? [e] : []));+ return { events, states, run: () => states().map((e) => e.state) };+}++describe("session_state on the user channel", () => {+ let t: TestApp;+ let owner: { cookie: string };+ let boxes: { owner: ReturnType<typeof inbox>; member: ReturnType<typeof inbox> };+ let stranger: ReturnType<typeof inbox>;++ beforeEach(async () => {+ t = await createTestApp();+ owner = await provisionUser(t.app, "owner");+ await provisionUser(t.app, "member");+ // A logged-in user with their own Project and their own live channel, granted nothing here.+ await provisionUser(t.app, "stranger");+ expect(+ (+ await apiClient(t.app, owner.cookie).post(`/api/projects/${PROJECT}/members`, {+ userId: "member",+ })+ ).status,+ ).toBe(201);++ const row: SessionRow = {+ sessionId: SID,+ projectId: PROJECT,+ agentId: "default_agent",+ provider: "custom",+ modelId: "m1",+ workspace: "/tmp/w",+ approvalMode: "allow-all",+ title: null,+ createdAt: INSERTED_AT,+ lastActiveAt: INSERTED_AT,+ };+ t.deps.sessionsRepo.insert(row);+ t.deps.manager.adopt(row, quickFakeSession(SID));++ // Subscribe before anything runs: `peek` on the publish side means a channel that does not+ // exist is skipped, so the test has to be listening the way a real client would be.+ boxes = { owner: inbox(t, "owner"), member: inbox(t, "member") };+ stranger = inbox(t, "stranger");+ });+ afterEach(async () => {+ await t.cleanup();+ });++ const runTask = async () => {+ const res = await apiClient(t.app, owner.cookie).post(`/api/sessions/${SID}/tasks`, {+ input: [{ type: "text", text: "go" }],+ });+ expect(res.status).toBe(202);+ await waitFor(() => boxes.owner.run().at(-1) === "idle");+ };++ it("reaches the Project's owner and its members, and no other user", async () => {+ await runTask();+ expect(boxes.owner.run()).toEqual(["running", "idle"]);+ expect(boxes.member.run()).toEqual(["running", "idle"]);+ // The stranger's channel exists and is being listened to — it simply is never published to.+ expect(stranger.events).toEqual([]);+ });++ it("names the Session and carries the row stamp a list fetch would return", async () => {+ await runTask();+ const settled = boxes.owner.states().at(-1)!;+ expect(settled.sessionId).toBe(SID);+ expect(settled.state).toBe("idle");+ // Read back from the DB, not reconstructed: a client can trust this against its read+ // marker, which is what makes "finished while I was elsewhere" legible as unread.+ expect(settled.lastActiveAt).toBe(t.deps.sessionsRepo.findById(SID)!.lastActiveAt);+ expect(Date.parse(settled.lastActiveAt)).toBeGreaterThan(Date.parse(INSERTED_AT));+ });++ it("carries hasTrace true from the very first flip of a Session that had never run", async () => {+ // The row is inserted without has_trace, exactly as a freshly created conversation is. The+ // "running" flip is published by startTask BEFORE drive's markDriven sets the column, so+ // the raw cache would say false at that moment; the event reports the truth instead. A+ // client that believed the raw flag would draw the hourglass and then nothing at all.+ expect(t.deps.sessionsRepo.findById(SID)!.hasTrace).toBe(false);+ await runTask();+ expect(boxes.owner.states().map((e) => e.hasTrace)).toEqual([true, true]);+ expect(t.deps.sessionsRepo.findById(SID)!.hasTrace).toBe(true);+ });++ it("says nothing about the composer state the Session channel owns", async () => {+ await runTask();+ // queued / pendingSteering / pendingFollowUps belong to the conversation being watched,+ // not to a list row.+ for (const e of boxes.owner.states()) {+ expect(Object.keys(e).sort()).toEqual([+ "hasTrace",+ "lastActiveAt",+ "sessionId",+ "state",+ "type",+ ]);+ }+ });++ it("a member removed from the Project stops hearing about its Sessions", async () => {+ expect(+ (await apiClient(t.app, owner.cookie).delete(`/api/projects/${PROJECT}/members/member`))+ .status,+ ).toBe(204);+ await runTask();+ expect(boxes.owner.run()).toEqual(["running", "idle"]);+ expect(boxes.member.events).toEqual([]);+ });+});diff --git a/packages/web/src/components/layout/sidebar.tsx b/packages/web/src/components/layout/sidebar.tsxindex 2650bd86..4c31049f 100644--- a/packages/web/src/components/layout/sidebar.tsx+++ b/packages/web/src/components/layout/sidebar.tsx@@ -31,6 +31,9 @@ import type {import * as api from "../../api/endpoints";import { S } from "../../lib/strings";import { formatMonthDay, formatRelativeShort } from "../../lib/format";+import { sessionRowActivity } from "../../lib/session-activity";+import type { SessionActivity } from "../../lib/session-activity";+import { forgetSession, noteSessionSeen, useSessionSeen } from "../../lib/session-seen";import { apiErrorText } from "../../lib/api-error";import { useAuth } from "../../state/auth";import { useLocale } from "../../state/locale";@@ -103,6 +106,7 @@ import type { GroupMode } from "../ui/group-list";import { toastError, toastInfo, toastSuccess } from "../ui/toast";import { Truncated } from "../ui/truncated";import { Badge } from "../ui/badge";+import { SessionActivityIcon } from "../ui/session-activity-icon";import { Modal } from "../ui/modal";import { ConfirmModal } from "../ui/confirm-modal";import { Button } from "../ui/button";@@ -269,25 +273,17 @@ const folderKey = (groupKey: string, category: FolderCategory) => `${category}\0/** Collapse-state key of the parked-drafts group ("\0" keeps it clear of Agent ids and Workspace paths). */const DRAFTS_GROUP_KEY = "\0drafts";-/** Session status dot: running pulses green, compacting shows an amber dot; idle shows nothing. */-function StatusDot({ session }: { session: SessionInfo }) {- if (session.status === "running") {- return (- <span- title={S.chat.statusRunning}- className="h-1.5 w-1.5 shrink-0 animate-pulse rounded-full bg-emerald-500"- />- );- }- if (session.status === "compacting") {- return (- <span- title={S.chat.statusCompacting}- className="h-1.5 w-1.5 shrink-0 rounded-full bg-amber-500"- />- );- }- return null;+/**+ * Session status glyph: a turning hourglass while the Session is busy, a green dot once it has+ * finished with a reply the user has not seen, and nothing once that reply has been read — or+ * if the Session never ran at all. See sessionActivity.+ */+function StatusGlyph({ activity }: { activity: SessionActivity }) {+ // Reserve the glyph's box even when there is no glyph: the row is a flex line whose title+ // truncates into whatever space is left, so letting the slot collapse would re-flow the title+ // of every never-run row (and again the moment its first run starts).+ if (activity === null) return <span aria-hidden="true" className="block h-3 w-3 shrink-0" />;+ return <SessionActivityIcon activity={activity} />;}export function Sidebar({@@ -381,6 +377,8 @@ export function Sidebar({*/const [proxySettingsOpen, setProxySettingsOpen] = useState(false);const currentProjectId = currentProject?.projectId ?? null;+ /** This Project's read markers; re-renders the rows whenever one is stamped. */+ const sessionSeen = useSessionSeen(currentProjectId);const collapseStoreKey = currentProjectId === null ? null : collapsedGroupsKey(currentProjectId);const pinStoreKey = currentProjectId === null ? null : pinnedGroupsKey(currentProjectId);/** Collapsed page-nav group (the 智能体 → 评估中心 entries; expanded by default, the choice persists across sessions). */@@ -714,6 +712,7 @@ export function Sidebar({setPinnedSessions(prunedPins);savePinnedSessions(currentProjectId, prunedPins);}+ forgetSession(currentProjectId, target.sessionId);const prunedOrder = removeFromSessionOrder(sessionOrder, target.sessionId);if (prunedOrder !== sessionOrder) {setSessionOrder(prunedOrder);@@ -843,6 +842,8 @@ export function Sidebar({};const openSession = (s: SessionInfo) => {+ // Opening is what "read" means here: stamp the marker before navigating.+ noteSessionSeen(currentProjectId, s.sessionId, s.lastActiveAt);// Cross-group click: the current Agent follows this Session's own Agent.setCurrentAgentId(s.agentId);go(`/chat/${s.sessionId}`);@@ -934,6 +935,9 @@ export function Sidebar({key={s.sessionId}s={s}active={s.sessionId === activeSessionId}+ // Busy / settled / read / never-ran, decided in one place (session-activity.ts) so+ // the whole transition sequence is testable without a DOM.+ activity={sessionRowActivity(s, sessionSeen, activeSessionId)}pinned={pinnedSessions.has(s.sessionId)}// Pinning is an ACTIVE-list priority: folder rows (subagent / scheduled /// archived) are ordered chronologically inside their folder and never pass@@ -942,8 +946,8 @@ export function Sidebar({canPin={activeList}// Last ACTIVITY, not creation: the server stamps lastActiveAt when a run// starts and again when it ends, so a running row shows its run-start time- // (it recedes while the run continues — the pulsing status dot beside it is- // what says "active right now"). CLI-adopted and subagent rows are not+ // (it recedes while the run continues — the hourglass beside it is what says+ // "active right now"). CLI-adopted and subagent rows are not// driven by this server, so theirs stays at createdAt.lastActive={formatRelativeShort(s.lastActiveAt, locale)}{...(withAgentHint ? { agentHint: agentNameById.get(s.agentId) ?? s.agentId } : {})}@@ -2128,6 +2132,7 @@ function GroupPinButton({ pinned, onToggle }: { pinned: boolean; onToggle: () =>function SessionRow({s,active,+ activity,pinned,canPin = false,lastActive,@@ -2147,6 +2152,8 @@ function SessionRow({}: {s: SessionInfo;active: boolean;+ /** Busy / settled-read / settled-unread / never-ran, already resolved by sessionRowActivity. */+ activity: SessionActivity;/** Row is pinned (bubbled to its group's top; small pin glyph on the title). */pinned: boolean;/** Whether pinning can actually reorder this row — active-list rows only; folder rows hide the action (see renderRows). */@@ -2243,7 +2250,7 @@ function SessionRow({</span>)}{/* No per-row source tag: subagent / scheduled Sessions live in their own labelled, collapsed folders, so a badge on the title would just repeat the folder. */}- <StatusDot session={s} />+ <StatusGlyph activity={activity} />{s.pendingApprovalCount > 0 && (<span title={S.chat.pendingApprovals(s.pendingApprovalCount)}><Badge tone="amber">{s.pendingApprovalCount}</Badge>diff --git a/packages/web/src/components/ui/session-activity-icon.tsx b/packages/web/src/components/ui/session-activity-icon.tsxnew file mode 100644index 00000000..bb100916--- /dev/null+++ b/packages/web/src/components/ui/session-activity-icon.tsx@@ -0,0 +1,102 @@+import { S } from "../../lib/strings";+import type { SessionActivity } from "../../lib/session-activity";++type Activity = Exclude<SessionActivity, null>;++/**+ * Session-level activity glyphs (sidebar rows + chat header).+ *+ * Three states, two shapes:+ *+ * - **busy** — an hourglass, turning over on a loop, the motion a real hourglass makes.+ * Compaction is busy work like any other, so it reuses the hourglass rather than owning a+ * third shape; it keeps the amber tone compaction already carries elsewhere in the app (the+ * stream's compaction banner), so the two live states differ by colour alone.+ * - **finished, unread** — a small green dot. It is a notification, not a status: it says+ * "there is a reply here you have not seen".+ * - **finished, read** — nothing. The dot is removed rather than muted, so the only marks left+ * in the list are the ones worth acting on. A Session that has never run renders nothing for+ * the same reason (see sessionActivity), which makes the two visually identical by design.+ *+ * The colour-only split between the live states is a deliberate exception, not the house style:+ * each glyph names its exact state in its accessible name and tooltip, so nothing here is+ * legible only to a sighted user with full colour vision. The read state announces nothing+ * because it renders nothing, which is correct — there is no state to report.+ */+export const ACTIVITY_GLYPH: Record<"running" | "compacting", string> = {+ // Hourglass: frame top and bottom, sand funnelling to the waist.+ running: "M6 3h12M6 21h12M8 3v3.5L12 10l4-3.5V3M8 21v-3.5L12 14l4 3.5V21",+ compacting: "M6 3h12M6 21h12M8 3v3.5L12 10l4-3.5V3M8 21v-3.5L12 14l4 3.5V21",+};++/**+ * Ink for the two busy states, measured against the surfaces they actually sit on — white and+ * gray-950 — as WCAG 2.x ratios:+ *+ * - running gray-500 / gray-400 …… 4.83 : 1 light, 7.93 : 1 dark+ * - compacting amber-600 / amber-400 … 3.19 : 1 light, 12.06 : 1 dark+ *+ * The unread dot takes the emerald the Session status dot has always used — `bg-emerald-500`,+ * one tone in both themes (sidebar.tsx's StatusDot, and its twin in the chat header). It is the+ * same kind of marker in the same place, so it stays the same green.+ */+const APPEARANCE: Record<"running" | "compacting", string> = {+ running: "hourglass-turn text-gray-500 dark:text-gray-400",+ compacting: "hourglass-turn text-amber-600 dark:text-amber-400",+};++/** Localized status label (read at render time: `S` is a live binding swapped per locale). */+export function sessionActivityLabel(activity: Activity): string {+ if (activity === "running") return S.chat.statusRunning;+ if (activity === "compacting") return S.chat.statusCompacting;+ return S.chat.statusCompletedUnread;+}++export function SessionActivityIcon({+ activity,+ size = 12,+}: {+ activity: Activity;+ size?: number;+}) {+ const label = sessionActivityLabel(activity);+ if (activity === "completedUnread") {+ // The dot itself is exactly the Session status dot's geometry — `h-1.5 w-1.5`, 6px, the same+ // at both surfaces on main. It is centred inside the same `size` box the hourglass occupies+ // rather than sitting in the row's flow directly, which is what keeps a row from shifting as+ // the glyph appears, swaps shape, or goes away entirely. Centring changes where the 6px sits,+ // never how big it is: the box is the reservation, the dot is the mark.+ return (+ <span+ role="img"+ aria-label={label}+ title={label}+ style={{ width: size, height: size }}+ className="flex shrink-0 items-center justify-center"+ >+ <span className="block h-1.5 w-1.5 rounded-full bg-emerald-500" />+ </span>+ );+ }+ return (+ <svg+ width={size}+ height={size}+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="1.7"+ strokeLinecap="round"+ strokeLinejoin="round"+ // Live states announce as a status; the unread dot is a plain labelled image (run+ // completion is already announced by the notification path, not this glyph).+ role="status"+ aria-label={label}+ className={`block shrink-0 ${APPEARANCE[activity]}`}+ >+ {/* The svg <title> child doubles as the hover tooltip (svg has no HTML title attribute). */}+ <title>{label}</title>+ <path d={ACTIVITY_GLYPH[activity]} />+ </svg>+ );+}diff --git a/packages/web/src/features/chat/chat-page.tsx b/packages/web/src/features/chat/chat-page.tsxindex 5e7da319..1fdcb52a 100644--- a/packages/web/src/features/chat/chat-page.tsx+++ b/packages/web/src/features/chat/chat-page.tsx@@ -42,6 +42,8 @@ import {humanizeTokens,} from "../../lib/format";import { latestConversation } from "../../lib/session-grouping";+import { sessionActivity } from "../../lib/session-activity";+import { noteSessionSeen } from "../../lib/session-seen";import {approvalKey,createStreamModel,@@ -64,6 +66,10 @@ import { Truncated } from "../../components/ui/truncated";import { Dropdown } from "../../components/ui/dropdown";import { CopyButton, ROW_COPY_CLASS } from "../../components/ui/copy-button";import { EmptyState } from "../../components/ui/empty-state";+import {+ SessionActivityIcon,+ sessionActivityLabel,+} from "../../components/ui/session-activity-icon";import { toastError, toastInfo, toastSuccess } from "../../components/ui/toast";import { MessageStream } from "./message-stream";import type { StreamRenderContext } from "./message-stream";@@ -615,9 +621,17 @@ export function ChatPage() {}, [sessionsLoading, draft, routeSessionId, probeFailedId, sessions, navigate]);// Sync task_state to the sidebar list badge.+ //+ // Keyed on the session ID, not the `selected` row: the row object is replaced whenever+ // anything about it changes — including by the user channel's own `session_state` event for+ // this very Session, which arrives on a second connection with no ordering guarantee against+ // this one. Depending on the object re-ran this effect on that replacement and re-asserted+ // whatever `stream.taskState` still held, so a run that ended could be pushed back to+ // "running" until this tab's Session stream caught up. Depending on the id means only a real+ // state change writes, and the two sources agree instead of overwriting each other.useEffect(() => {- if (selected) setStatus(selected.sessionId, stream.taskState);- }, [stream.taskState, selected, setStatus]);+ if (selectedSessionId !== null) setStatus(selectedSessionId, stream.taskState);+ }, [stream.taskState, selectedSessionId, setStatus]);// Task returns from running/compacting to idle ON THE SAME SESSION: this turn may have// spawned a sub-session or auto-created a new Agent — reload both lists so they appear in@@ -647,6 +661,18 @@ export function ChatPage() {}}, [stream.taskState, selectedSessionId, reloadSessions, reloadAgents]);+ // Looking at a settled Session is what marks it read (session-seen.ts): stamped on open, and+ // again when a run finishes under the user's eyes, so the sidebar row left behind is not+ // flagged unread. Depending on lastActiveAt is what keeps the marker honest across clock skew+ // — the effect above reloads the list on that same active→idle edge, and the refreshed+ // server timestamp re-runs this one.+ const selectedLastActiveAt = selected?.lastActiveAt ?? null;+ useEffect(() => {+ if (selectedSessionId === null || selectedLastActiveAt === null) return;+ if (stream.taskState !== "idle") return; // Still working: nothing settled to have read yet.+ noteSessionSeen(projectId, selectedSessionId, selectedLastActiveAt);+ }, [projectId, selectedSessionId, selectedLastActiveAt, stream.taskState]);+// Positive-only existence cache for file summary cards (session-level): normalized relative// path -> true, or the shared in-flight lookup. Missing files aren't retained — a later Task may// create the same path, so its summary must re-check instead of inheriting stale false state.@@ -1520,6 +1546,14 @@ export function ChatPage() {/>);+ /**+ * Header glyph state. Never unread: this is the Session on screen, so its last reply is being+ * read right now — the read/unread split is a sidebar affordance, and passing the live marker+ * here would only flash the unread tone for the frame before the effect above stamps it.+ */+ const headerActivity =+ selected === null ? null : sessionActivity(stream.taskState, selected.hasTrace, false);+return (<div className="flex h-full flex-col bg-white dark:bg-gray-950">{/* Thin top toolbar */}@@ -1529,15 +1563,18 @@ export function ChatPage() {<h1 className="flex min-w-0 text-[15px] font-semibold"><Truncated text={selected.title ?? S.chat.defaultSessionTitle} /></h1>- {/* Running indicator (placed to the right of the title); the compacting state is shown separately by the compaction banner within the message stream, not repeated here.- Below sm only the pulsing dot remains (title carries the wording) — the text would eat the title's room on phones. */}- {stream.taskState === "running" && (+ {/* Session-level state: a turning hourglass while the run is active, and nothing at+ all once it settles — the conversation on screen is by definition read, and the+ unread dot is a sidebar affordance for the rows you are NOT looking at. The+ compacting state stays in the stream banner rather than being repeated here.+ Below sm only the glyph remains so the title keeps its room. */}+ {headerActivity === "running" && (<span- title={S.chat.statusRunning}+ title={sessionActivityLabel(headerActivity)}className="flex shrink-0 items-center gap-1.5 text-xs text-gray-500 dark:text-gray-400">- <span className="h-1.5 w-1.5 animate-pulse rounded-full bg-emerald-500" />- <span className="hidden sm:inline">{S.chat.statusRunning}</span>+ <SessionActivityIcon activity={headerActivity} />+ <span className="hidden sm:inline">{sessionActivityLabel(headerActivity)}</span></span>)}</div>diff --git a/packages/web/src/lib/session-activity.ts b/packages/web/src/lib/session-activity.tsnew file mode 100644index 00000000..f27ede0f--- /dev/null+++ b/packages/web/src/lib/session-activity.ts@@ -0,0 +1,64 @@+import type { SessionInfo, SessionStatus } from "@prismshadow/penguin-server/api";+import { isSessionUnread } from "./session-seen";+import type { SessionSeenState } from "./session-seen";++/**+ * Visual state carried by a Session row / chat header. Three states, and `null` for "say+ * nothing at all" — which is the resting state of every row the user has nothing to act on.+ */+export type SessionActivity = "running" | "compacting" | "completedUnread" | null;++/**+ * The Session's glyph state.+ *+ * Live execution comes from the server (`running` / `compacting` / `idle`). A settled Session+ * only has something to say while its last reply is UNREAD — that read/unread distinction is+ * the client's, because the API models no read receipt (see session-seen.ts). Once read it+ * falls silent: the glyph is a notification, and a list where every finished row carries a+ * permanent marker tells the user nothing about where to look next.+ *+ * `hasTrace` is the server's own "a Task has been started" flag, already on every list row, and+ * it is still load-bearing even though read and never-ran now render identically. Unread is a+ * timestamp comparison against the read marker, and a Session created AFTER this browser first+ * saw the Project has no marker of its own — it falls back to the baseline, and its creation+ * time is later, so it reads as unread. Without this guard every brand-new conversation would+ * wear the "finished, go look" dot before it had ever run.+ */+export function sessionActivity(+ status: SessionStatus,+ hasTrace: boolean,+ unread: boolean,+): SessionActivity {+ // Status first: a live run reports itself even in the window before its Trace is recorded.+ if (status === "running") return "running";+ if (status === "compacting") return "compacting";+ if (!hasTrace) return null;+ return unread ? "completedUnread" : null;+}++/** The subset of a row this function needs (a whole SessionInfo satisfies it). */+export type SessionActivityRow = Pick<+ SessionInfo,+ "sessionId" | "status" | "hasTrace" | "lastActiveAt"+>;++/**+ * The glyph one Session ROW draws: `sessionActivity` plus the two things only the list knows —+ * whether the user has looked at this Session since it last ran, and whether it is the+ * conversation currently open.+ *+ * The open conversation is never unread: the user is looking at it. The chat page reaches the+ * same conclusion by stamping the seen marker once a run settles under the user's eyes, but it+ * does so in an effect, one tick after the run-end event moved the row's `lastActiveAt` —+ * deciding it here from what is on screen keeps the glyph from flashing unread for that tick.+ */+export function sessionRowActivity(+ session: SessionActivityRow,+ seen: SessionSeenState,+ activeSessionId: string | null,+): SessionActivity {+ const unread =+ session.sessionId !== activeSessionId &&+ isSessionUnread(seen, session.sessionId, session.lastActiveAt);+ return sessionActivity(session.status, session.hasTrace, unread);+}diff --git a/packages/web/src/lib/session-seen.ts b/packages/web/src/lib/session-seen.tsnew file mode 100644index 00000000..4cb823dd--- /dev/null+++ b/packages/web/src/lib/session-seen.ts@@ -0,0 +1,215 @@+import { createStore } from "zustand/vanilla";+import { useStore } from "zustand/react";++/**+ * Per-Session "the user has seen the latest reply" markers — the read/unread half of the+ * sidebar's completion glyph.+ *+ * The server has no notion of a read receipt: there is no notifications table, no read/seen+ * column on `sessions`, and `SessionInfo` carries no such field, so a server-side marker would+ * need schema + API changes. This follows the precedent pinned-sessions.ts already set for a+ * per-Session flag the API does not model: persist it per Project in localStorage under the+ * `penguin.…` key naming, with injectable storage (vitest runs in Node, no localStorage).+ *+ * Consequences, deliberately accepted:+ * - per BROWSER, not per user — the same account on another device starts with its own markers;+ * - no cross-tab sync — the repo has no `storage` listener anywhere and says so on purpose+ * (chat-defaults-event.ts: "Same-tab only by design"), so a second tab keeps its own view+ * until it reloads.+ *+ * "Read" is a timestamp comparison rather than a flag, because the question is not "was this+ * Session ever opened" but "was it opened SINCE its last reply": the marker holds when the user+ * last looked, and `SessionInfo.lastActiveAt` (stamped by the server at run start and again at+ * run end) holds when the Session last did anything. Later activity than the marker = unread.+ */++/** Minimal storage interface (the subset of localStorage used here); tests inject an in-memory implementation. */+export interface SessionSeenStorage {+ getItem(key: string): string | null;+ setItem(key: string, value: string): void;+}++/** Storage key of one Project's seen markers (sidebar key-naming convention, `penguin.pinnedSessions.<projectId>` &c.). */+export const sessionSeenKey = (projectId: string): string => `penguin.sessionSeen.${projectId}`;++/**+ * Cap on remembered markers per Project. Only Sessions the user actually opened get one, so+ * this is generous; past it the least recently seen are dropped, and a dropped Session falls+ * back to `seededAt` — i.e. reads as read, not as a surprise unread.+ */+const MAX_MARKERS = 500;++/** One Project's markers: when the user last looked at each Session, plus the baseline below. */+export interface SessionSeenState {+ /**+ * Epoch ms first written for this Project. Everything that last ran at or before it counts as+ * read without its own marker — otherwise enabling the feature would light up every historical+ * conversation at once, which is noise, not information.+ */+ seededAt: number;+ /** sessionId → epoch ms the user last had it open. */+ seen: ReadonlyMap<string, number>;+}++const EMPTY: SessionSeenState = { seededAt: 0, seen: new Map() };++function storageOf(injected?: SessionSeenStorage): SessionSeenStorage | null {+ if (injected) return injected;+ try {+ // localStorage is resolved INSIDE the try, never as a default parameter: merely touching it+ // throws a SecurityError when site data is blocked (or in a partitioned iframe).+ return localStorage;+ } catch {+ return null; // No storage at all (privacy mode edge): every finished Session reads as read.+ }+}++/** Parses one Project's stored blob; anything malformed degrades to "nothing remembered". */+export function parseSessionSeen(raw: string | null): SessionSeenState {+ if (raw === null) return EMPTY;+ try {+ const parsed: unknown = JSON.parse(raw);+ if (typeof parsed !== "object" || parsed === null) return EMPTY;+ const o = parsed as { seededAt?: unknown; seen?: unknown };+ const seededAt = typeof o.seededAt === "number" && Number.isFinite(o.seededAt) ? o.seededAt : 0;+ const seen = new Map<string, number>();+ if (typeof o.seen === "object" && o.seen !== null) {+ for (const [id, at] of Object.entries(o.seen as Record<string, unknown>)) {+ if (typeof at === "number" && Number.isFinite(at)) seen.set(id, at);+ }+ }+ return { seededAt, seen };+ } catch {+ return EMPTY;+ }+}++/** Serializes one Project's markers, keeping only the `MAX_MARKERS` most recently seen. */+export function serializeSessionSeen(state: SessionSeenState): string {+ let entries = [...state.seen];+ if (entries.length > MAX_MARKERS) {+ entries.sort((a, b) => b[1] - a[1]);+ entries = entries.slice(0, MAX_MARKERS);+ }+ return JSON.stringify({ seededAt: state.seededAt, seen: Object.fromEntries(entries) });+}++/**+ * Records that the user is looking at a Session now.+ *+ * The marker is the LATER of the wall clock and the Session's own `lastActiveAt`, so opening a+ * Session always marks it read even when this browser's clock lags the server's — a stuck unread+ * badge is the failure users actually notice.+ */+export function markSessionSeen(+ state: SessionSeenState,+ sessionId: string,+ lastActiveAt: string,+ now: number = Date.now(),+): SessionSeenState {+ const activeAt = Date.parse(lastActiveAt);+ const at = Number.isNaN(activeAt) ? now : Math.max(now, activeAt);+ if (state.seen.get(sessionId) === at) return state; // No-op: skip the write and the re-render.+ return { seededAt: state.seededAt, seen: new Map(state.seen).set(sessionId, at) };+}++/** Prune on Session delete; returns the input state unchanged when nothing was remembered. */+export function forgetSessionSeen(state: SessionSeenState, sessionId: string): SessionSeenState {+ if (!state.seen.has(sessionId)) return state;+ const seen = new Map(state.seen);+ seen.delete(sessionId);+ return { seededAt: state.seededAt, seen };+}++/**+ * Whether a Session has run since the user last looked at it.+ *+ * Unknown Sessions fall back to `seededAt`, so only activity after this browser first saw the+ * Project counts as unread. An unparseable timestamp reads as read (never invent an alert).+ */+export function isSessionUnread(state: SessionSeenState, sessionId: string, lastActiveAt: string) {+ const activeAt = Date.parse(lastActiveAt);+ if (Number.isNaN(activeAt)) return false;+ return activeAt > (state.seen.get(sessionId) ?? state.seededAt);+}++// —— Module-level store: storage key → markers, every subscriber re-renders on change ——++// The Map doubles as the lazy parse cache: read() seeds a missing key IN PLACE (no new+// reference, no notification — it runs inside a render via useSessionSeen's selector), while+// write() swaps in a new Map so subscribers are notified. Same shape as draft-sessions.ts.+const seenStore = createStore<{ cache: Map<string, SessionSeenState> }>(() => ({+ cache: new Map(),+}));++function read(key: string, storage?: SessionSeenStorage): SessionSeenState {+ const { cache } = seenStore.getState();+ const hit = cache.get(key);+ if (hit) return hit;+ const s = storageOf(storage);+ let state = EMPTY;+ if (s) {+ try {+ state = parseSessionSeen(s.getItem(key));+ } catch {+ state = EMPTY;+ }+ }+ cache.set(key, state);+ return state;+}++function write(key: string, state: SessionSeenState, storage?: SessionSeenStorage): void {+ const s = storageOf(storage);+ if (s) {+ try {+ s.setItem(key, serializeSessionSeen(state));+ } catch {+ // Quota / private mode: the in-memory copy still serves this tab.+ }+ }+ seenStore.setState((prev) => ({ cache: new Map(prev.cache).set(key, state) }));+}++/** Reactive read of one Project's markers (the EMPTY constant when no Project is selected). */+export function useSessionSeen(projectId: string | null): SessionSeenState {+ return useStore(seenStore, () => (projectId ? read(sessionSeenKey(projectId)) : EMPTY));+}++/**+ * Marks a Session read. Also stamps `seededAt` on a Project's first ever write, which is what+ * makes pre-existing conversations start out read rather than all-unread.+ */+export function noteSessionSeen(+ projectId: string | null,+ sessionId: string,+ lastActiveAt: string,+ storage?: SessionSeenStorage,+): void {+ if (projectId === null) return;+ const key = sessionSeenKey(projectId);+ const current = read(key, storage);+ const seeded = current.seededAt === 0 ? { seededAt: Date.now(), seen: current.seen } : current;+ const next = markSessionSeen(seeded, sessionId, lastActiveAt);+ if (next === current) return;+ write(key, next, storage);+}++/** Drops a deleted Session's marker so the id cannot linger in storage forever. */+export function forgetSession(+ projectId: string | null,+ sessionId: string,+ storage?: SessionSeenStorage,+): void {+ if (projectId === null) return;+ const key = sessionSeenKey(projectId);+ const current = read(key, storage);+ const next = forgetSessionSeen(current, sessionId);+ if (next === current) return;+ write(key, next, storage);+}++/** Test seam: drops the in-memory parse cache so a fresh storage stub is re-read. */+export function resetSessionSeenCache(): void {+ seenStore.setState({ cache: new Map() });+}diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex 05595f59..4fb2aaa5 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -1085,6 +1085,8 @@ Scenarios:} as Record<string, string>,statusRunning: "Running",statusCompacting: "Compacting",+ /** Settled Session that finished since the user last opened it (the unread dot; a Session already read shows no glyph, so it needs no label). */+ statusCompletedUnread: "Done, unread",pendingApprovals: (n: number) => `${n} pending approval${n > 1 ? "s" : ""}`,jumpToLatest: "Jump to latest",/** Top-of-stream affordance while the previous history window is being fetched (scroll-up backfill). */diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex ca7e47f1..66eb30a7 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -1048,6 +1048,8 @@ Benchmark:} as Record<string, string>,statusRunning: "运行中",statusCompacting: "压缩中",+ /** Settled Session that finished since the user last opened it (the unread dot; a Session already read shows no glyph, so it needs no label). */+ statusCompletedUnread: "运行完毕,未读",pendingApprovals: (n: number) => `${n} 个待审批`,jumpToLatest: "回到最新消息",/** Top-of-stream affordance while the previous history window is being fetched (scroll-up backfill). */diff --git a/packages/web/src/state/sessions.tsx b/packages/web/src/state/sessions.tsxindex c7a7b19a..e85d50a1 100644--- a/packages/web/src/state/sessions.tsx+++ b/packages/web/src/state/sessions.tsx@@ -26,6 +26,7 @@import { createContext, useCallback, useContext, useEffect, useMemo, useState } from "react";import type { ReactNode } from "react";import type {+ ServerEvent,SessionCategory,SessionCategoryCounts,SessionInfo,@@ -73,8 +74,12 @@ interface SessionsContextValue {isDeleted: (sessionId: string) => boolean;/** Replace the whole entry with the PATCH result. */replace: (session: SessionInfo) => void;- /** Live stream task_state → list badge. */- setStatus: (sessionId: string, status: SessionStatus) => void;+ /**+ * Live run status of one row — from the open Session's own stream (`task_state`), and from+ * the user channel (`session_state`) for every row this tab is not subscribed to. `row` is+ * the server's own fields riding the user-channel event; the Session stream has none to give.+ */+ setStatus: (sessionId: string, status: SessionStatus, row?: LiveRowFields) => void;/** session_title server event → update the title in place. */setTitle: (sessionId: string, title: string) => void;/** Whether CLI-created Sessions are listed too (persisted per user; default off = the list is served from the DB without Trace scanning). */@@ -83,6 +88,16 @@ interface SessionsContextValue {setShowCliSessions: (value: boolean) => void;}+/**+ * The row fields a `session_state` event carries alongside the status, straight from the+ * server's row. Both are needed to draw the glyph without refetching the list: `lastActiveAt`+ * decides read vs unread against the seen marker, and `hasTrace` decides settled vs never-ran.+ */+export interface LiveRowFields {+ lastActiveAt: string;+ hasTrace: boolean;+}+const SessionsContext = createContext<SessionsContextValue | null>(null);/** Page-state key of one (Agent, category) pair ("\0" never appears in Agent ids). */@@ -129,7 +144,7 @@ interface SessionsStoreState {add: (session: SessionInfo) => void;remove: (sessionId: string) => void;replace: (session: SessionInfo) => void;- setStatus: (sessionId: string, status: SessionStatus) => void;+ setStatus: (sessionId: string, status: SessionStatus, row?: LiveRowFields) => void;setTitle: (sessionId: string, title: string) => void;setShowCliSessions: (value: boolean) => void;}@@ -142,7 +157,12 @@ interface SessionsStoreState {*/const DELETED_IDS_MAX = 500;-function createSessionsStore() {+/**+ * Builds one Provider's store. Exported as a test seam: vitest runs this package in Node with+ * no DOM, so the list's own behaviour is exercised against the store directly rather than+ * through a React tree.+ */+export function createSessionsStore() {// Generation counter: invalidates any in-flight response once the Project/Agent set// changes or a reload happens.let gen = 0;@@ -372,11 +392,51 @@ function createSessionsStore() {});},- setStatus: (sessionId, status) => {+ /**+ * A status flip changes more of the row than the status, because the glyph is drawn from+ * three fields, not one (see session-activity.ts). The user-channel `session_state` event+ * carries the other two from the server's own row; the open Session's stream calls this+ * with two arguments, having none to give.+ *+ * - `lastActiveAt` is what makes a background completion legible: the read/unread split+ * compares it against the seen marker (session-seen.ts), so without the server's new+ * stamp a Session that finished while the user was elsewhere would settle into the+ * muted "already read" glyph — the exact case the user needs to notice.+ * - `hasTrace` is what keeps a FIRST run from settling into nothing at all. It separates+ * "finished" from "never ran", and a Session running its first Task still has the+ * `false` its list row was fetched with: the hourglass shows (status wins), and then+ * the moment it stops the row would go blank.+ *+ * `hasTrace` is therefore treated as monotonic, and a live status is itself proof the+ * Session has run — server-side it is a one-way cache (`has_trace = 1`, never cleared)+ * set at run start, and a running Session has by definition started a Task. That second+ * half is what keeps the two callers consistent: the Session stream carries no flag, so+ * on its own it would settle a first run into a blank row until the next list fetch.+ *+ * An id no loaded page holds is dropped rather than turned into a row: the event names a+ * Session, it does not describe one, and a row invented from a status and a timestamp+ * would have no title, Agent or Workspace to render. That same drop is what filters+ * another Project's Sessions — this store only ever holds the current Project's rows.+ */+ setStatus: (sessionId, status, row) => {const prev = get().sessions;const target = prev.find((s) => s.sessionId === sessionId);- if (!target || target.status === status) return;- set({ sessions: prev.map((s) => (s.sessionId === sessionId ? { ...s, status } : s)) });+ if (!target) return;+ const lastActiveAt = row?.lastActiveAt ?? target.lastActiveAt;+ const live = status === "running" || status === "compacting";+ const hasTrace = target.hasTrace || row?.hasTrace === true || live;+ if (+ target.status === status &&+ target.lastActiveAt === lastActiveAt &&+ target.hasTrace === hasTrace+ ) {+ return;+ }+ set({+ sessions: prev.map((s) =>+ s.sessionId === sessionId ? { ...s, status, lastActiveAt, hasTrace } : s,+ ),+ });},setTitle: (sessionId, title) => {@@ -395,6 +455,57 @@ function createSessionsStore() {});}+/** The vanilla store backing one Provider mount. */+export type SessionsStore = ReturnType<typeof createSessionsStore>;++/**+ * Routes one user-level server event (/api/events) into the list store.+ *+ * That connection is the only one that outlives every Project switch and every conversation+ * the user opens, which is why the list's cross-Session facts arrive on it rather than on a+ * Session channel. Split out from the subscription so this routing is testable without a React+ * tree or an EventSource, neither of which exists in this package's Node test environment.+ *+ * `onWebUpdated` is the escape hatch for the one event that is not a list update at all.+ */+export function applyUserEvent(+ store: SessionsStore,+ ev: ServerEvent,+ onWebUpdated: () => void,+): void {+ // The served web assets were hot-swapped (dev watch-push / platform upgrade): reload so this+ // window runs the new code.+ if (ev.type === "web_updated") {+ onWebUpdated();+ return;+ }+ // A Session changed run state. This is what keeps every row honest: a tab subscribes to the+ // ONE conversation it has open, so its `task_state` events can only ever move that row's+ // badge. Everything else — the Session the user just navigated away from, a run started from+ // another tab, a schedule, a subagent — would otherwise sit on whatever status the last list+ // fetch happened to return.+ if (ev.type === "session_state") {+ store.getState().setStatus(ev.sessionId, ev.state, {+ lastActiveAt: ev.lastActiveAt,+ hasTrace: ev.hasTrace,+ });+ return;+ }+ // The reconnect landed outside the channel's replay buffer, so an unknown number of the flips+ // above were lost — away long enough and a row sits on an hourglass that will never stop.+ // Refetch once, on the event that says so, rather than polling for it.+ if (ev.type === "resync_required") {+ void store.getState().reload();+ return;+ }+ // A scheduled task firing may have created a new Session (new-session mode); reload the list+ // so it appears immediately. schedule_queued doesn't change the list (the target Session+ // already exists), so it is ignored, as is every other Session-scoped event.+ if (ev.type !== "schedule_fired") return;+ // The event carries projectId: a trigger from another Project is unrelated to the current list.+ if (ev.projectId === store.getState().projectId) void store.getState().reload();+}+export function SessionsProvider({ children }: { children: ReactNode }) {const { currentProject, agents } = useProject();const projectId = currentProject?.projectId ?? null;@@ -442,25 +553,14 @@ export function SessionsProvider({ children }: { children: ReactNode }) {void store.getState().reload();}, [store, projectId, agentIdsKey, showCliSessions]);- // User-level event stream (/api/events): a scheduled task firing may have created a new- // Session (new-session mode); reload the list so it appears immediately. schedule_queued- // doesn't change the list (the target Session already exists), so it's ignored.- // store.getState() serves the current values: the connection stays a single one for the- // whole login session and doesn't reconnect on Project switches.+ // User-level event stream (/api/events); see applyUserEvent for what each event does. The+ // connection stays a single one for the whole login session and doesn't reconnect on Project+ // switches, so the handler reads current values through store.getState() rather than closing+ // over them.useEffect(() => {const conn = openUserEvents({onOmniMessage: () => undefined,- onServerEvent: (ev) => {- // The served web assets were hot-swapped (dev watch-push / platform- // upgrade): reload so this window runs the new code.- if (ev.type === "web_updated") {- window.location.reload();- return;- }- if (ev.type !== "schedule_fired") return;- // The event carries projectId: a trigger from another Project is unrelated to the current list.- if (ev.projectId === store.getState().projectId) void store.getState().reload();- },+ onServerEvent: (ev) => applyUserEvent(store, ev, () => window.location.reload()),});return () => conn.close();}, [store]);diff --git a/packages/web/src/styles.css b/packages/web/src/styles.cssindex ac7f3164..529cb4dd 100644--- a/packages/web/src/styles.css+++ b/packages/web/src/styles.css@@ -338,6 +338,32 @@animation: title-scroll-reveal var(--title-scroll-ms, 0ms) linear 0.3s forwards;}+/* Busy hourglass (session-activity-icon.tsx: the running and compacting glyphs). An hourglass+ does not spin — it gets turned over — so this holds the glyph still, flips it 180 degrees in+ ~360ms, holds again, and flips back. The long dwell is what makes it legible at the 12px the+ sidebar renders it at: a continuous spin at that size reads as a smudge, while two deliberate+ turns per cycle read as "still working" even out of the corner of the eye.++ `transform` is the only thing the keyframes touch and the at-rest glyph has none, so the+ global `animation: none !important` below is a free no-op here: the hourglass simply stands+ upright. Nothing needs a JS media query, and the glyph never disappears. */+@keyframes hourglass-turn {+ 0%,+ 38% {+ transform: rotate(0deg);+ }+ 50%,+ 88% {+ transform: rotate(180deg);+ }+ 100% {+ transform: rotate(360deg);+ }+}+.hourglass-turn {+ animation: hourglass-turn 3s ease-in-out infinite;+}+/* Login page circuit traces (login-circuit.tsx): pathLength=1 normalization, draw-in -> hold -> fade-outloop. Base state is fully hidden: the positive animation-delay wait keeps the first paint blank, andlines only start growing after load; once reduced-motion globally disables animation, the override below@@ -408,6 +434,8 @@entirely by the `title-scroll-reveal` keyframes above — including the inline-blockthat makes the text transformable at all — so `animation: none` leaves the titleexactly as it renders at rest, ellipsis and `title` tooltip included. */+ /* Nor does the busy hourglass (#291): its keyframes only rotate, so disabling them+ leaves the glyph upright and fully visible — still present, just not turning. */}/* ---------- Minimal typography for Markdown body content (no typography plugin) ---------- */diff --git a/packages/web/test/session-activity.test.ts b/packages/web/test/session-activity.test.tsnew file mode 100644index 00000000..a37a45b2--- /dev/null+++ b/packages/web/test/session-activity.test.ts@@ -0,0 +1,170 @@+import { describe, expect, it } from "vitest";+import { createElement } from "react";+import { renderToStaticMarkup } from "react-dom/server";+import { sessionActivity } from "../src/lib/session-activity";+import type { SessionActivity } from "../src/lib/session-activity";+import {+ ACTIVITY_GLYPH,+ SessionActivityIcon,+ sessionActivityLabel,+} from "../src/components/ui/session-activity-icon";+import { S } from "../src/lib/strings";+import { readFileSync } from "node:fs";+import { fileURLToPath } from "node:url";++type Activity = Exclude<SessionActivity, null>;++describe("sessionActivity", () => {+ it("reports a live run whatever the read state, compaction included", () => {+ expect(sessionActivity("running", true, false)).toBe("running");+ expect(sessionActivity("running", true, true)).toBe("running");+ expect(sessionActivity("compacting", true, false)).toBe("compacting");+ expect(sessionActivity("compacting", true, true)).toBe("compacting");+ });++ it("marks a settled Session only while its last reply is unread", () => {+ expect(sessionActivity("idle", true, true)).toBe("completedUnread");+ // Read: the marker is removed, not muted. Nothing left to act on, nothing shown.+ expect(sessionActivity("idle", true, false)).toBeNull();+ });++ it("shows nothing for a Session that has never run", () => {+ expect(sessionActivity("idle", false, false)).toBeNull();+ // hasTrace is still load-bearing even though read and never-ran look identical: a Session+ // created after this browser first saw the Project has no read marker of its own, so it+ // falls back to the baseline and its creation time reads as UNREAD. Without the guard every+ // brand-new conversation would wear the "go look" dot before it had ever run.+ expect(sessionActivity("idle", false, true)).toBeNull();+ });++ it("still reports a live run started before its Trace was recorded", () => {+ expect(sessionActivity("running", false, false)).toBe("running");+ expect(sessionActivity("compacting", false, false)).toBe("compacting");+ });+});++/**+ * Icon rendering contract, via react-dom/server static markup (node env, no DOM).+ *+ * Two shapes carry the two situations that differ in KIND — busy vs settled. Within each, the+ * remaining distinction is a colour, which is exactly why every glyph is also required below to+ * name its precise state in its accessible name and tooltip: the colour is never the only way+ * to find out what a row is doing.+ */+describe("SessionActivityIcon", () => {+ const ACTIVITIES: readonly Activity[] = ["running", "compacting", "completedUnread"];++ const render = (activity: Activity) =>+ renderToStaticMarkup(createElement(SessionActivityIcon, { activity }));++ it("draws one hourglass for both busy states", () => {+ expect(ACTIVITY_GLYPH.compacting).toBe(ACTIVITY_GLYPH.running);+ for (const activity of ["running", "compacting"] as const) {+ expect(render(activity)).toContain(`d="${ACTIVITY_GLYPH[activity]}"`);+ }+ });++ it("draws the unread state as a dot, not as a path glyph", () => {+ const unread = render("completedUnread");+ expect(unread).toContain("rounded-full");+ expect(unread).not.toContain("<svg");+ expect(unread).not.toContain(ACTIVITY_GLYPH.running);+ });++ it("labels each state distinctly for screen readers and hover", () => {+ expect(sessionActivityLabel("running")).toBe(S.chat.statusRunning);+ expect(sessionActivityLabel("compacting")).toBe(S.chat.statusCompacting);+ expect(sessionActivityLabel("completedUnread")).toBe(S.chat.statusCompletedUnread);+ // Three states, three different names: the compacting/running pair differs only in colour+ // on screen, so nothing may be distinguishable by colour alone to a screen reader.+ expect(new Set(ACTIVITIES.map(sessionActivityLabel)).size).toBe(ACTIVITIES.length);+ for (const activity of ACTIVITIES) {+ expect(render(activity)).toContain(`aria-label="${sessionActivityLabel(activity)}"`);+ }+ });++ it("gives the hourglass a hover tooltip through the svg title child", () => {+ for (const activity of ["running", "compacting"] as const) {+ expect(render(activity)).toContain(`<title>${sessionActivityLabel(activity)}</title>`);+ }+ // The dot is an HTML span, so its tooltip is a plain title attribute.+ expect(render("completedUnread")).toContain(+ `title="${sessionActivityLabel("completedUnread")}"`,+ );+ });++ it("announces busy states as status and the unread dot as an image", () => {+ expect(render("running")).toContain('role="status"');+ expect(render("compacting")).toContain('role="status"');+ expect(render("completedUnread")).toContain('role="img"');+ });++ it("turns the hourglass while busy and leaves the dot still", () => {+ expect(render("running")).toContain("hourglass-turn");+ expect(render("compacting")).toContain("hourglass-turn");+ expect(render("completedUnread")).not.toContain("hourglass-turn");+ });++ it("keeps the two busy states apart by ink, since shape cannot separate them", () => {+ expect(render("running")).toContain("text-gray-500");+ expect(render("running")).toContain("dark:text-gray-400");+ expect(render("compacting")).toContain("text-amber-600");+ expect(render("compacting")).toContain("dark:text-amber-400");+ });++ it("draws the dot in the Session status dot's own emerald and geometry", () => {+ // Same green and same 6px as the dot this replaces, at both surfaces: `h-1.5 w-1.5+ // rounded-full bg-emerald-500`, one tone in both themes, no per-theme override.+ const unread = render("completedUnread");+ expect(unread).toContain("bg-emerald-500");+ expect(unread).not.toMatch(/dark:bg-emerald-/);+ expect(unread).toContain("h-1.5 w-1.5");+ expect(unread).toContain("rounded-full");+ // The reservation must never inflate the mark: no larger dot sneaking back in.+ expect(unread).not.toMatch(/\bh-2 w-2\b/);+ });++ it("occupies the same box whatever the glyph, so a row never shifts", () => {+ // Every glyph renders into the same 12px box, and the sidebar reserves that same box when+ // there is no glyph at all — otherwise the title would re-flow as a run starts, finishes and+ // is read. The 6px dot is CENTRED in that box rather than sized to it: the box is the+ // reservation, the dot is the mark.+ for (const activity of ACTIVITIES) {+ const markup = render(activity);+ expect(markup).toMatch(/(width="12"|width:12px)/);+ expect(markup).toMatch(/(height="12"|height:12px)/);+ }+ // The empty state's placeholder, read from the sidebar itself so it cannot drift apart.+ const sidebar = readFileSync(+ fileURLToPath(new URL("../src/components/layout/sidebar.tsx", import.meta.url)),+ "utf8",+ );+ expect(sidebar).toMatch(/activity === null.*\n?.*className="block h-3 w-3 shrink-0"/);+ });+});++/**+ * The turning hourglass must degrade to a still, VISIBLE hourglass under reduced motion. The+ * global rule kills `animation` outright, so the guarantee is that the keyframes only ever+ * rotate — no opacity, no display, nothing whose absence would blank the glyph (the login+ * traces in the same stylesheet need an explicit override for exactly that reason).+ */+describe("hourglass-turn reduced motion", () => {+ const css = readFileSync(fileURLToPath(new URL("../src/styles.css", import.meta.url)), "utf8");++ it("is an animation, so the global reduced-motion rule disables it", () => {+ expect(css).toMatch(/\.hourglass-turn\s*\{[^}]*animation:\s*hourglass-turn/);+ expect(css).toMatch(+ /@media\s*\(prefers-reduced-motion:\s*reduce\)\s*\{[\s\S]*?animation:\s*none\s*!important/,+ );+ });++ it("only rotates, so disabling it leaves the glyph upright rather than invisible", () => {+ const block = /@keyframes hourglass-turn\s*\{([\s\S]*?)\n\}/.exec(css);+ const body = block?.[1] ?? "";+ expect(body).not.toBe("");+ const declarations = [...body.matchAll(/([a-z-]+)\s*:/g)].map((m) => m[1]);+ expect(new Set(declarations)).toEqual(new Set(["transform"]));+ expect(body).toMatch(/rotate\(180deg\)/); // A turn, not a spin.+ });+});diff --git a/packages/web/test/session-seen.test.ts b/packages/web/test/session-seen.test.tsnew file mode 100644index 00000000..64ce68f4--- /dev/null+++ b/packages/web/test/session-seen.test.ts@@ -0,0 +1,162 @@+import { beforeEach, describe, expect, it } from "vitest";+import {+ forgetSession,+ forgetSessionSeen,+ isSessionUnread,+ markSessionSeen,+ noteSessionSeen,+ parseSessionSeen,+ resetSessionSeenCache,+ serializeSessionSeen,+ sessionSeenKey,+} from "../src/lib/session-seen";+import type { SessionSeenState, SessionSeenStorage } from "../src/lib/session-seen";++const AT = (iso: string) => Date.parse(iso);+// Fixtures sit safely in the past: noteSessionSeen seeds from the real clock, so a "future"+// fixture would read as activity newer than the seed and flip these expectations.+const T0 = "2020-01-01T10:00:00.000Z";+const T1 = "2020-01-01T11:00:00.000Z";+const T2 = "2020-01-01T12:00:00.000Z";++const state = (seededAt: number, seen: Record<string, number> = {}): SessionSeenState => ({+ seededAt,+ seen: new Map(Object.entries(seen)),+});++/** In-memory localStorage stand-in (vitest runs in Node). */+function memoryStorage(initial: Record<string, string> = {}) {+ const map = new Map(Object.entries(initial));+ return {+ getItem: (k: string) => map.get(k) ?? null,+ setItem: (k: string, v: string) => void map.set(k, v),+ read: (k: string) => map.get(k) ?? null,+ } satisfies SessionSeenStorage & { read: (k: string) => string | null };+}++describe("isSessionUnread", () => {+ it("treats activity after the marker as unread and activity before it as read", () => {+ const s = state(0, { a: AT(T1) });+ expect(isSessionUnread(s, "a", T2)).toBe(true);+ expect(isSessionUnread(s, "a", T0)).toBe(false);+ // Exactly the moment it was seen: read, not unread (the user was there for it).+ expect(isSessionUnread(s, "a", T1)).toBe(false);+ });++ it("falls back to the seed so pre-existing conversations do not all start unread", () => {+ const seeded = state(AT(T1));+ expect(isSessionUnread(seeded, "never-opened", T0)).toBe(false);+ // ...but anything that runs AFTER the seed is genuinely new and does flag.+ expect(isSessionUnread(seeded, "never-opened", T2)).toBe(true);+ });++ it("flags everything as unread only when nothing has ever been seeded", () => {+ expect(isSessionUnread(state(0), "a", T0)).toBe(true);+ });++ it("never invents an alert from an unparseable timestamp", () => {+ expect(isSessionUnread(state(0), "a", "not-a-date")).toBe(false);+ });+});++describe("markSessionSeen", () => {+ it("stamps the wall clock when it is ahead of the Session's last activity", () => {+ const next = markSessionSeen(state(1), "a", T0, AT(T2));+ expect(next.seen.get("a")).toBe(AT(T2));+ });++ it("stamps lastActiveAt when the local clock lags the server, so opening always marks read", () => {+ // Browser clock an hour behind: a naive Date.now() marker would leave the row stuck unread.+ const next = markSessionSeen(state(1), "a", T2, AT(T1));+ expect(next.seen.get("a")).toBe(AT(T2));+ expect(isSessionUnread(next, "a", T2)).toBe(false);+ });++ it("returns the same state when nothing changes, so no write and no re-render happen", () => {+ const s = state(1, { a: AT(T2) });+ expect(markSessionSeen(s, "a", T0, AT(T2))).toBe(s);+ });++ it("leaves other Sessions' markers alone", () => {+ const next = markSessionSeen(state(1, { a: AT(T0) }), "b", T1, AT(T1));+ expect(next.seen.get("a")).toBe(AT(T0));+ expect(next.seen.get("b")).toBe(AT(T1));+ });+});++describe("forgetSessionSeen", () => {+ it("drops one marker and returns the input unchanged when there was none", () => {+ const s = state(1, { a: AT(T0), b: AT(T1) });+ expect([...forgetSessionSeen(s, "a").seen.keys()]).toEqual(["b"]);+ expect(forgetSessionSeen(s, "missing")).toBe(s);+ });+});++describe("storage round-trip", () => {+ it("survives a serialize/parse cycle", () => {+ const s = state(AT(T0), { a: AT(T1), b: AT(T2) });+ const back = parseSessionSeen(serializeSessionSeen(s));+ expect(back.seededAt).toBe(AT(T0));+ expect(back.seen.get("a")).toBe(AT(T1));+ expect(back.seen.get("b")).toBe(AT(T2));+ });++ it("degrades to nothing remembered on junk, rather than throwing into a render", () => {+ for (const junk of ["", "{", "null", "[]", '"nope"']) {+ const back = parseSessionSeen(junk);+ expect(back.seededAt).toBe(0);+ expect(back.seen.size).toBe(0);+ }+ });++ it("keeps well-formed markers and drops malformed ones", () => {+ const back = parseSessionSeen(+ JSON.stringify({ seededAt: "nope", seen: { a: AT(T1), b: "later", c: null } }),+ );+ expect(back.seededAt).toBe(0);+ expect([...back.seen.keys()]).toEqual(["a"]);+ });++ it("caps stored markers, evicting the least recently seen", () => {+ const seen: Record<string, number> = {};+ for (let i = 0; i < 600; i++) seen[`s${i}`] = i;+ const written = parseSessionSeen(serializeSessionSeen(state(1, seen)));+ expect(written.seen.size).toBe(500);+ expect(written.seen.has("s599")).toBe(true); // Most recent kept.+ expect(written.seen.has("s0")).toBe(false); // Oldest evicted.+ });+});++describe("noteSessionSeen", () => {+ beforeEach(resetSessionSeenCache);++ it("seeds on the first write so existing conversations start out read", () => {+ const storage = memoryStorage();+ noteSessionSeen("proj", "a", T1, storage);+ const stored = parseSessionSeen(storage.read(sessionSeenKey("proj")));+ expect(stored.seededAt).toBeGreaterThan(0);+ // A different Session that last ran before the seed reads as read.+ expect(isSessionUnread(stored, "other", T0)).toBe(false);+ expect(stored.seen.get("a")).toBeDefined();+ });++ it("scopes markers per Project", () => {+ const storage = memoryStorage();+ noteSessionSeen("one", "a", T1, storage);+ expect(storage.read(sessionSeenKey("one"))).not.toBeNull();+ expect(storage.read(sessionSeenKey("two"))).toBeNull();+ });++ it("is a no-op without a Project", () => {+ const storage = memoryStorage();+ noteSessionSeen(null, "a", T1, storage);+ expect(storage.read(sessionSeenKey("proj"))).toBeNull();+ });++ it("prunes a deleted Session's marker", () => {+ const storage = memoryStorage();+ noteSessionSeen("proj", "a", T1, storage);+ forgetSession("proj", "a", storage);+ expect(parseSessionSeen(storage.read(sessionSeenKey("proj"))).seen.has("a")).toBe(false);+ });+});diff --git a/packages/web/test/session-status-events.test.ts b/packages/web/test/session-status-events.test.tsnew file mode 100644index 00000000..f35a9479--- /dev/null+++ b/packages/web/test/session-status-events.test.ts@@ -0,0 +1,351 @@+/**+ * Live Session status over the user-level event stream (state/sessions.tsx).+ *+ * A tab subscribes to the one conversation it has open, so the Session channel's `task_state`+ * can only ever move that row's badge; every other row would sit on whatever status its last+ * list fetch returned. The user channel's `session_state` closes that gap, and these tests pin+ * both halves of it: what the store does with the event, and the glyph the row ends up drawing+ * across a whole run — which is the case the feature exists for.+ *+ * The store is exercised directly (createSessionsStore / applyUserEvent): vitest runs this+ * package in Node with no DOM, so there is no React tree to mount. `sessionRowActivity` is the+ * same function the sidebar row calls, so the glyph assertions are the real rule, not a copy.+ */+import { describe, expect, it } from "vitest";+import type { ServerEvent, SessionInfo, SessionStatus } from "@prismshadow/penguin-server/api";+import { applyUserEvent, createSessionsStore } from "../src/state/sessions";+import { isSessionUnread, markSessionSeen } from "../src/lib/session-seen";+import type { SessionSeenState } from "../src/lib/session-seen";+import { sessionRowActivity } from "../src/lib/session-activity";++const CREATED = "2026-08-19T09:00:00.000Z";+/** When the user last had the Session open — every fixture's starting `lastActiveAt`. */+const LOOKED = "2026-08-19T10:00:00.000Z";+/** The server's run-start stamp, after the user walked away. */+const STARTED = "2026-08-19T10:03:00.000Z";+/** The server's run-end stamp. */+const FINISHED = "2026-08-19T10:05:00.000Z";++function session(sessionId: string, over: Partial<SessionInfo> = {}): SessionInfo {+ return {+ sessionId,+ projectId: "proj",+ agentId: "default_agent",+ provider: "anthropic",+ modelId: "claude-sonnet-4",+ workspace: "/w",+ approvalMode: "allow-all",+ createdAt: CREATED,+ lastActiveAt: LOOKED,+ status: "idle",+ pendingApprovalCount: 0,+ pendingFollowUpCount: 0,+ hasTrace: true,+ archived: false,+ ...over,+ };+}++/** A brand-new conversation: created, never run, so its row is blank. */+const freshSession = (sessionId: string) =>+ session(sessionId, { hasTrace: false, lastActiveAt: CREATED });++/** A store holding the given rows, as a loaded first page would. */+function storeWith(...rows: SessionInfo[]) {+ const store = createSessionsStore();+ store.setState({ projectId: "proj", agentIds: ["default_agent"], sessions: rows });+ return store;+}++const stateEvent = (+ sessionId: string,+ state: SessionStatus,+ lastActiveAt: string,+ hasTrace = true,+): ServerEvent => ({ type: "session_state", sessionId, state, lastActiveAt, hasTrace });++const rowOf = (store: ReturnType<typeof storeWith>, sessionId: string) =>+ store.getState().sessions.find((s) => s.sessionId === sessionId)!;++/** The user has this Session open and has looked at it as of `at`. */+const seenAt = (sessionId: string, at: string): SessionSeenState =>+ markSessionSeen(+ { seededAt: Date.parse(CREATED), seen: new Map() },+ sessionId,+ at,+ Date.parse(at),+ );++/** No marker of its own; everything since the baseline counts as unread. */+const neverSeen: SessionSeenState = { seededAt: Date.parse(CREATED), seen: new Map() };++/** The glyph the sidebar would draw for this row. `open` is the conversation on screen. */+const glyph = (+ store: ReturnType<typeof storeWith>,+ sessionId: string,+ seen: SessionSeenState,+ open: string | null = null,+) => sessionRowActivity(rowOf(store, sessionId), seen, open);++/** applyUserEvent's web_updated escape hatch, which no status test should ever trip. */+const neverReload = () => {+ throw new Error("web_updated handler must not fire");+};++describe("session_state on the user channel", () => {+ it("moves the named row and leaves every other row alone", () => {+ const store = storeWith(session("a"), session("b"));+ applyUserEvent(store, stateEvent("b", "running", STARTED), neverReload);+ expect(rowOf(store, "b").status).toBe("running");+ expect(rowOf(store, "b").lastActiveAt).toBe(STARTED);+ // The untouched row keeps both fields AND its object identity (no needless re-render).+ expect(rowOf(store, "a").status).toBe("idle");+ expect(rowOf(store, "a").lastActiveAt).toBe(LOOKED);+ });++ it("ignores a Session no loaded page holds instead of inventing a row", () => {+ const store = storeWith(session("a"));+ const before = store.getState().sessions;+ applyUserEvent(store, stateEvent("not-loaded", "running", STARTED), neverReload);+ // Same array reference: nothing was appended and nothing re-rendered.+ expect(store.getState().sessions).toBe(before);+ expect(store.getState().sessions.map((s) => s.sessionId)).toEqual(["a"]);+ });++ it("a repeated event is a no-op (state, stamp and trace flag all already match)", () => {+ const store = storeWith(session("a", { status: "running", lastActiveAt: STARTED }));+ const before = store.getState().sessions;+ applyUserEvent(store, stateEvent("a", "running", STARTED), neverReload);+ expect(store.getState().sessions).toBe(before);+ });++ it("carries a stamp change through even when the state itself did not change", () => {+ // Run start and run end both stamp the row; a goal loop's rounds keep it "running".+ const store = storeWith(session("a", { status: "running" }));+ applyUserEvent(store, stateEvent("a", "running", FINISHED), neverReload);+ expect(rowOf(store, "a").lastActiveAt).toBe(FINISHED);+ });++ it("compaction reaches the list as its own state, not as plain running", () => {+ const store = storeWith(session("a"));+ applyUserEvent(store, stateEvent("a", "compacting", STARTED), neverReload);+ expect(rowOf(store, "a").status).toBe("compacting");+ });+});++describe("hasTrace across a status flip", () => {+ // The regression this pins: `sessionActivity` checks status first, so `running` draws the+ // hourglass whatever hasTrace says — and then falls to `if (!hasTrace) return null` once the+ // run settles. A first run on a row still carrying the `hasTrace: false` it was fetched with+ // therefore turned the hourglass into nothing, where the unread dot belongs.+ it("running -> idle on a never-run row settles into the unread dot, not a blank", () => {+ const store = storeWith(freshSession("a"));+ expect(glyph(store, "a", neverSeen)).toBeNull();++ applyUserEvent(store, stateEvent("a", "running", STARTED), neverReload);+ expect(glyph(store, "a", neverSeen)).toBe("running");++ applyUserEvent(store, stateEvent("a", "idle", FINISHED), neverReload);+ expect(rowOf(store, "a").hasTrace).toBe(true);+ expect(glyph(store, "a", neverSeen)).toBe("completedUnread");+ });++ it("the server's flag alone settles a first run seen only at its end", () => {+ // This tab connected mid-run, so the only event it gets is the settle.+ const store = storeWith(freshSession("a"));+ applyUserEvent(store, stateEvent("a", "idle", FINISHED, true), neverReload);+ expect(glyph(store, "a", neverSeen)).toBe("completedUnread");+ });++ it("a live status is proof enough on its own, for the caller that carries no flag", () => {+ // chat-page's two-argument call: the Session channel's task_state has no row fields.+ const store = storeWith(freshSession("a"));+ store.getState().setStatus("a", "running");+ expect(rowOf(store, "a").hasTrace).toBe(true);+ store.getState().setStatus("a", "idle");+ // Read, so nothing is drawn: the two-argument call moves no stamp, so nothing has happened+ // since this browser first saw the Project. hasTrace still had to flip, though — the next+ // run's settle depends on it.+ expect(glyph(store, "a", neverSeen)).toBeNull();+ expect(rowOf(store, "a").hasTrace).toBe(true);+ });++ it("never regresses to blank once the Session has run", () => {+ const store = storeWith(session("a", { hasTrace: true }));+ // A stale or conservative flag must not un-run a Session: has_trace is a one-way cache.+ applyUserEvent(store, stateEvent("a", "idle", FINISHED, false), neverReload);+ expect(rowOf(store, "a").hasTrace).toBe(true);+ });++ it("a brand-new conversation does not wear the dot before it has ever run", () => {+ // Read and never-ran both render nothing now, which makes hasTrace look redundant. It is+ // not. This Session was created AFTER this browser first saw the Project, so it has no read+ // marker of its own and falls back to the baseline — and its own timestamp is later, so the+ // unread test says TRUE. hasTrace is the only thing standing between a fresh conversation+ // and a "there is something to read here" dot it has never earned.+ const store = storeWith(+ session("new-one", { hasTrace: false, createdAt: STARTED, lastActiveAt: STARTED }),+ );+ expect(isSessionUnread(neverSeen, "new-one", STARTED)).toBe(true);+ expect(glyph(store, "new-one", neverSeen)).toBeNull();++ // The moment it actually runs, that same row earns the dot.+ applyUserEvent(store, stateEvent("new-one", "idle", FINISHED), neverReload);+ expect(glyph(store, "new-one", neverSeen)).toBe("completedUnread");+ });++ it("a Session that genuinely never ran stays blank", () => {+ const store = storeWith(freshSession("a"));+ // An idle republish for a Session with no Trace (e.g. an approval resolution on a row that+ // never started a Task) must not invent a completion.+ applyUserEvent(store, stateEvent("a", "idle", CREATED, false), neverReload);+ expect(glyph(store, "a", neverSeen)).toBeNull();+ });+});++describe("the full sequence, for a Session the user is not looking at", () => {+ it("nothing -> hourglass -> unread dot -> nothing again once opened", () => {+ const store = storeWith(freshSession("a"));+ // The user has this Project open and has looked at nothing in particular.+ let seen = neverSeen;+ expect(glyph(store, "a", seen)).toBeNull();++ applyUserEvent(store, stateEvent("a", "running", STARTED), neverReload);+ expect(glyph(store, "a", seen)).toBe("running");++ applyUserEvent(store, stateEvent("a", "idle", FINISHED), neverReload);+ expect(glyph(store, "a", seen)).toBe("completedUnread");++ // Opening it is what marks it read (sidebar's openSession -> noteSessionSeen), and a read+ // row goes back to showing nothing at all — the dot is removed, not muted.+ seen = markSessionSeen(seen, "a", rowOf(store, "a").lastActiveAt);+ expect(glyph(store, "a", seen)).toBeNull();+ });++ it("a Session the user opened earlier still goes unread when it later runs", () => {+ const store = storeWith(session("a"));+ const seen = seenAt("a", LOOKED);+ expect(glyph(store, "a", seen)).toBeNull();++ applyUserEvent(store, stateEvent("a", "running", STARTED), neverReload);+ expect(glyph(store, "a", seen)).toBe("running");+ applyUserEvent(store, stateEvent("a", "idle", FINISHED), neverReload);+ expect(glyph(store, "a", seen)).toBe("completedUnread");+ });++ it("compaction shows the hourglass too, and settles to the unread dot", () => {+ const store = storeWith(session("a"));+ const seen = seenAt("a", LOOKED);+ applyUserEvent(store, stateEvent("a", "compacting", STARTED), neverReload);+ expect(glyph(store, "a", seen)).toBe("compacting");+ applyUserEvent(store, stateEvent("a", "idle", FINISHED), neverReload);+ expect(glyph(store, "a", seen)).toBe("completedUnread");+ });++ it("the same sequence in a tab that did not start the task", () => {+ // The only difference is that nothing here ever calls setStatus with a task_state: this tab+ // has some OTHER conversation open, so every transition arrives on the user channel alone.+ const store = storeWith(freshSession("a"), session("elsewhere"));+ const open = "elsewhere";+ const seen = neverSeen;+ expect(glyph(store, "a", seen, open)).toBeNull();+ applyUserEvent(store, stateEvent("a", "running", STARTED), neverReload);+ expect(glyph(store, "a", seen, open)).toBe("running");+ applyUserEvent(store, stateEvent("a", "idle", FINISHED), neverReload);+ expect(glyph(store, "a", seen, open)).toBe("completedUnread");+ // And the conversation this tab IS looking at was never touched: read, so nothing.+ expect(glyph(store, "elsewhere", seen, open)).toBeNull();+ });+});++describe("the open Session", () => {+ it("finishes under the user's eyes as READ — nothing drawn, no unread flash", () => {+ const store = storeWith(freshSession("open"));+ // Stale marker on purpose: the seen stamp is older than the run that is about to end, so+ // only the "this is the conversation on screen" rule can keep it out of unread.+ const seen = seenAt("open", LOOKED);++ store.getState().setStatus("open", "running"); // this tab's own task_state+ expect(glyph(store, "open", seen, "open")).toBe("running");++ // The user channel settles the row first, moving lastActiveAt past the marker.+ applyUserEvent(store, stateEvent("open", "idle", FINISHED), neverReload);+ expect(glyph(store, "open", seen, "open")).toBeNull();+ // Then this tab's own stream reports the same flip: still no dot.+ store.getState().setStatus("open", "idle");+ expect(glyph(store, "open", seen, "open")).toBeNull();+ });++ it("its own stream writes the row with no stamp of its own to offer", () => {+ const store = storeWith(session("open", { lastActiveAt: FINISHED }));+ store.getState().setStatus("open", "running");+ expect(rowOf(store, "open").status).toBe("running");+ expect(rowOf(store, "open").lastActiveAt).toBe(FINISHED);+ });++ it("the two sources converge on the same row rather than overwriting each other", () => {+ const store = storeWith(session("open", { status: "running" }));+ applyUserEvent(store, stateEvent("open", "idle", FINISHED), neverReload);+ store.getState().setStatus("open", "idle");+ expect(rowOf(store, "open").status).toBe("idle");+ expect(rowOf(store, "open").lastActiveAt).toBe(FINISHED);+ });++ it("a status for the open Session before its row is loaded is dropped, not stashed", () => {+ // Deep link: the route names a Session the paged list has not fetched yet.+ const store = storeWith(session("other"));+ store.getState().setStatus("deep-linked", "running");+ expect(store.getState().sessions.map((s) => s.sessionId)).toEqual(["other"]);+ });+});++describe("other user-channel events keep their behaviour", () => {+ it("web_updated reloads the window and touches no row", () => {+ const store = storeWith(session("a"));+ let reloaded = 0;+ applyUserEvent(store, { type: "web_updated", rev: "abc" }, () => (reloaded += 1));+ expect(reloaded).toBe(1);+ expect(rowOf(store, "a").status).toBe("idle");+ });++ it("an event this list has no use for is ignored", () => {+ const store = storeWith(session("a"));+ const before = store.getState().sessions;+ applyUserEvent(store, { type: "hello" }, neverReload);+ applyUserEvent(store, { type: "session_title", sessionId: "a", title: "T" }, neverReload);+ expect(store.getState().sessions).toBe(before);+ });++ it("resync_required refetches once: the flips it missed cannot be replayed", () => {+ const store = storeWith(session("a"));+ let reloads = 0;+ store.setState({+ reload: async () => {+ reloads += 1;+ },+ });+ applyUserEvent(store, { type: "resync_required" }, neverReload);+ expect(reloads).toBe(1);+ });++ it("schedule_fired still refetches, and still only for the current Project", () => {+ const store = storeWith(session("a"));+ let reloads = 0;+ store.setState({+ reload: async () => {+ reloads += 1;+ },+ });+ const fired = (projectId: string): ServerEvent => ({+ type: "schedule_fired",+ projectId,+ agentId: "default_agent",+ name: "nightly",+ sessionId: "a",+ });+ applyUserEvent(store, fired("another-project"), neverReload);+ expect(reloads).toBe(0);+ applyUserEvent(store, fired("proj"), neverReload);+ expect(reloads).toBe(1);+ });+});