A local-first multi-agent app development platform, built on PenguinHarness
fix(web): the session row's scheduled-task mark stops flickering and recedes (#677)
Yaowei Zheng7dca5c5aa510
diff --git a/changelog/unreleased/2026-09-10-session-row-schedule-mark.md b/changelog/unreleased/2026-09-10-session-row-schedule-mark.mdnew file mode 100644index 00000000..0ffcbc1f--- /dev/null+++ b/changelog/unreleased/2026-09-10-session-row-schedule-mark.md@@ -0,0 +1,32 @@+# The session row's scheduled-task mark stops flickering and recedes++- **Date:** 2026-09-10+- **Type:** fix+- **Scope:** `web`+- **PR:** [#677](https://github.com/Prism-Shadow/penguin-harness/pull/677)++[中文版](2026-09-10-session-row-schedule-mark.zh.md)++The alarm clock a session row wears while a scheduled task is bound to it blinked in and out+while switching between conversations, and it was drawn in the same amber as the running+hourglass and the pending-approval badge. The schedules store now caches one list per Agent+instead of pointing a single slot at one, and the mark takes the muted ink of the marks it+belongs with.++## Details++- The store keys its list, its error and its in-flight request by project and agent. Moving to+ another Agent no longer throws away the list the previous one had, and a read asked for while+ another Agent's is still out is issued for the Agent that was asked for instead of being+ answered by the older request.+- `refreshSchedules` takes the scope it refreshes. The dock's scheduled-tasks panel names the+ open conversation's Agent on its poll and after every create, edit, toggle and delete; a+ regained focus and the `schedule_fired` / `schedule_queued` events refresh only the scopes a+ mounted reader is showing.+- The session list holds the marks already on screen while an Agent's list has never been read,+ rather than reading "not loaded yet" as "no Session is scheduled".+- The mark moved next to the pin and the messaging-relay glyph, ahead of the live-status glyph,+ and all three take `muted` from the shared tone tokens.+- The background-tasks mark took `muted` as well, both on a session row and on the tool row of a+ call made with `run_in_background`. The chat header's own background-tasks count is drawn+ separately and kept the tone it had.diff --git a/changelog/unreleased/2026-09-10-session-row-schedule-mark.zh.md b/changelog/unreleased/2026-09-10-session-row-schedule-mark.zh.mdnew file mode 100644index 00000000..d61cfc11--- /dev/null+++ b/changelog/unreleased/2026-09-10-session-row-schedule-mark.zh.md@@ -0,0 +1,26 @@+# 会话行的定时任务标记不再闪烁,并退回次要位置++- **Date:** 2026-09-10+- **Type:** fix+- **Scope:** `web`+- **PR:** [#677](https://github.com/Prism-Shadow/penguin-harness/pull/677)++[English](2026-09-10-session-row-schedule-mark.md)++会话行在绑定了定时任务时会佩戴一个闹钟标记,此前在多个对话之间切换时它会时隐时现,且用的是与运行中沙漏、+待审批徽章相同的琥珀色。定时任务 store 改为按 Agent 分别缓存列表,不再让唯一的槽位指向某一个 Agent;标记+本身也改用与它同类的次要墨色。++## 细节++- store 按 project 与 agent 为键保存列表、错误与进行中的请求。切换到另一个 Agent 不再丢弃前一个 Agent 已+ 有的列表;在另一个 Agent 的请求尚未返回时发起的读取,会为真正被请求的那个 Agent 发出请求,而不是被那个+ 更早的请求代答。+- `refreshSchedules` 改为接收要刷新的 scope。Dock 的定时任务面板在轮询以及每次新建、编辑、启停、删除之后+ 都会指明当前对话的 Agent;窗口重新获得焦点与 `schedule_fired` / `schedule_queued` 事件只刷新有已挂载读者+ 正在展示的 scope。+- 某个 Agent 的列表尚未被读取过时,会话列表保留已经显示在屏幕上的标记,而不再把「尚未加载」当成「没有+ Session 有定时任务」。+- 该标记移到了置顶图标与消息中继图标旁边、实时状态图标之前,三者统一从共享的 tone token 取 `muted`。+- 后台任务标记也改用 `muted`:会话行上,以及标记 `run_in_background` 调用的工具行上。对话页头部自绘的+ 后台任务计数不在其列,仍是原来的墨色。diff --git a/packages/web/src/components/layout/sidebar.tsx b/packages/web/src/components/layout/sidebar.tsxindex dc98b125..00590107 100644--- a/packages/web/src/components/layout/sidebar.tsx+++ b/packages/web/src/components/layout/sidebar.tsx@@ -170,6 +170,7 @@ import { navNoteFor, useUpdateBadges } from "../../lib/use-update-badges";import { pendingScheduleSessions } from "../../features/schedules/schedule-panel-state";import { useAgentSchedules } from "../../features/schedules/schedule-store";import { ICON_SIZE } from "../../lib/icon-scale";+import { toneInk } from "../../lib/tone";/** New-chat pencil (the pinned "New chat" button and the collapsed rail share it). */export const NEW_CHAT_ICON = "M12 20h9M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z";@@ -296,6 +297,9 @@ 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";+/** Standing "no Session is scheduled", so the first render has something to hold before any answer. */+const NO_SCHEDULED_SESSIONS: ReadonlySet<string> = new Set();+/*** 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@@ -353,12 +357,13 @@ export function Sidebar({/** This Project's read markers; re-renders the rows whenever one is stamped. */const sessionSeen = useSessionSeen(currentProjectId);// The current Agent's scheduled tasks, shared with the dock's schedules panel through one- // store. The scope is the current Agent because that is the one the store can hold: the chat- // page keeps the current Agent in step with the open conversation, so the panel and these rows- // ask for the same list. In workspace or time grouping the list can also show OTHER Agents'- // Sessions, and those rows simply wear no mark — a row saying nothing is honest, a row- // answered from another Agent's list would not be. Re-read on every navigation: opening a- // conversation is the moment a task may just have been created or switched off.+ // store, which caches a list per Agent so that neither surface's scope discards the other's.+ // The scope is the current Agent: the chat page keeps it in step with the open conversation,+ // so the panel and these rows ask for the same list. In workspace or time grouping the list+ // can also show OTHER Agents' Sessions, and those rows simply wear no mark — a row saying+ // nothing is honest, a row answered from another Agent's list would not be. Re-read on every+ // navigation: opening a conversation is the moment a task may just have been created or+ // switched off.const { items: agentSchedules } = useAgentSchedules(currentProjectId,currentAgent?.agentId ?? null,@@ -368,7 +373,19 @@ export function Sidebar({// enough. The store re-renders these rows on every refresh (a navigation, a schedule event, a// turn ending, the panel's poll), and the server recomputes `nextFireAt` on each listing, so a// task that fired for the last time loses its mark at the next refresh.- const scheduledSessions = pendingScheduleSessions(agentSchedules ?? []);+ const pendingScheduled = useMemo(+ () => (agentSchedules === null ? null : pendingScheduleSessions(agentSchedules)),+ [agentSchedules],+ );+ // A null list means "this Agent has not been read yet", never "this Agent has no tasks":+ // reading it as the second blanks every alarm in the list for as long as a request takes. The+ // marks on screen stand until a real answer replaces them, which is the standing the pin and+ // the relay glyph get for free by being fields of the row itself.+ const lastScheduledRef = useRef<ReadonlySet<string>>(NO_SCHEDULED_SESSIONS);+ useEffect(() => {+ if (pendingScheduled !== null) lastScheduledRef.current = pendingScheduled;+ }, [pendingScheduled]);+ const scheduledSessions = pendingScheduled ?? lastScheduledRef.current;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). */@@ -2651,43 +2668,46 @@ function SessionRow({: "text-gray-700 dark:text-gray-300"}`}/>- {/* Pinned indicator: a dim pin after the title (tooltip + sr text; unpin lives in the row menu). */}+ {/* Four marks for the row's STANDING arrangements, all in one dim cluster and all in+ the `muted` ink: how the row is filed (pinned), where it can be reached from+ (messaging relay), whether it runs on its own (a scheduled task) and whether it+ owns work that outlives the turn (background tasks). None of them is live work, so+ none competes with the status glyph that follows; each names itself in a tooltip+ and in sr text, which is what lets them recede this far. */}+ {/* Pinned indicator: a dim pin after the title (unpin lives in the row menu). */}{pinned && canPin && (- <span- title={S.chat.pinnedSession}- className="shrink-0 text-gray-400 dark:text-gray-500"- >+ <span title={S.chat.pinnedSession} className={`shrink-0 ${toneInk.muted}`}><Icon d={PIN_ICON} size={ICON_SIZE.rowMark} /><span className="sr-only">{S.chat.pinnedSession}</span></span>)}{/* Enabled-messaging indicator: one glyph for every channel, the channel named in- the tooltip and sr text. Same dim treatment as the pin (saved-but-disabled- configs stay off the row; the binding dialog lives in the row menu). */}+ the tooltip and sr text (saved-but-disabled configs stay off the row; the binding+ dialog lives in the row menu). */}{s.messagingChannel !== undefined && (<spantitle={S.messaging.enabledIndicator[s.messagingChannel]}- className="shrink-0 text-gray-400 dark:text-gray-500"+ className={`shrink-0 ${toneInk.muted}`}><Icon d={MESSAGING_RELAY_ICON} size={ICON_SIZE.rowMark} /><span className="sr-only">{S.messaging.enabledIndicator[s.messagingChannel]}</span></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. */}- <StatusGlyph activity={activity} />- {/* Beside the glyph, not instead of it: an idle row can still own background work,- and the mark leaves with the last task (live via session_background). */}+ {/* Scheduled-task indicator: the row says this conversation will run on its own, and+ the schedules panel says how often and what. A paused task, or one past its end+ time, draws nothing — nothing more will fire from it, and a mark would be noise. */}+ {scheduled && <ScheduleMark size={ICON_SIZE.rowMark} />}+ {/* Background work the conversation owns while sitting idle: parked, not running,+ so it reads as an arrangement rather than as a turn in progress. The mark leaves+ with the last task (live via session_background). */}{background > 0 && (<BackgroundTasksMarklabel={S.chat.backgroundTasks(background)}size={ICON_SIZE.rowMark}/>)}- {/* Standing arrangement rather than live work: the row says this conversation will run- on its own, and the schedules panel says how often and what. A paused task, or one- past its end time, draws nothing — nothing more will fire from it, and a mark- would be noise. */}- {scheduled && <ScheduleMark size={ICON_SIZE.rowMark} />}+ {/* 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. */}+ <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.tsxindex 9ca81af5..9bac848c 100644--- a/packages/web/src/components/ui/session-activity-icon.tsx+++ b/packages/web/src/components/ui/session-activity-icon.tsx@@ -29,10 +29,12 @@ type Activity = Exclude<SessionActivity, null>;* because it renders nothing, which is correct — there is no state to report.** Background work is a separate mark, not a fourth state (BackgroundTasksMark below): an- * activity trace in the `busy` tone, drawn beside whichever glyph the row wears — an idle, read- * Session can still own a dev server or a background subagent, and the row says both. A standing- * scheduled task is a third such mark (ScheduleMark below), for the same reason: it says what- * the conversation will do without anyone opening it, not what it is doing now.+ * activity trace drawn beside whichever glyph the row wears — an idle, read Session can still+ * own a dev server or a background subagent, and the row says both. A standing scheduled task is+ * a mark of another kind again (ScheduleMark below): it says what the conversation will do+ * without anyone opening it, not what it is doing now, and sits with the row's settled marks+ * ahead of the live states. Each of the two names its own tone where it is defined, so a tone is+ * spelled in one place and cannot go stale in another.** Ink comes from the shared tone tokens (lib/tone.ts), which carry the measured contrast ratios* against the two surfaces these glyphs sit on: the sidebar (gray-50 / gray-900) and the chat@@ -68,7 +70,10 @@ export function sessionActivityLabel(activity: Activity): string {* The background-task mark: "work is going on behind this" wherever the app says so — a* session row and the chat header, where it stands for the conversation's whole set of* background command processes and subagents, and a tool row, where it marks the one call- * that was made with `run_in_background`. `busy` ink, because that is what it means.+ * that was made with `run_in_background`. `muted` ink: background work is parked, not a turn in+ * progress, so it joins the row's dim cluster of standing arrangements rather than reading as+ * the conversation being busy. `muted` may only mark a state already spelled out in text, which+ * the required label below is.** Both props are the caller's to decide, because the two placements genuinely differ: the* label names a count in one place and a single call in the other, and the size is the rung@@ -83,7 +88,7 @@ export function BackgroundTasksMark({ label, size }: { label: string; size: numbrole="img"aria-label={label}title={label}- className={`flex shrink-0 items-center ${toneInk.busy}`}+ className={`flex shrink-0 items-center ${toneInk.muted}`}><GlyphIcon d={BACKGROUND_TASKS_ICON} size={size} /></span>@@ -94,9 +99,11 @@ export function BackgroundTasksMark({ label, size }: { label: string; size: numb* The scheduled-task mark: a session row wears an alarm clock while at least one bound task still* has a next fire time (features/schedules' `pendingScheduleSessions`). A task switched off, past* its end time, or a one-off that has already run has none and draws nothing — the panel is where- * it stays visible. `attention` ink, the tone for work waiting on time, which is what- * a scheduled task is; the hourglass beside it shares the tone and differs in shape and motion,- * as two marks in one row must.+ * it stays visible. `muted` ink, the tone for a mark that should recede: a standing arrangement is+ * settled, not live work, so it joins the row's dim cluster (the pin and the messaging-relay glyph)+ * rather than competing with the hourglass and the pending-approval badge for the eye. `muted` may+ * only mark a state that is already spelled out in text, which the `aria-label` and tooltip below+ * are.** Icon only, no count: the row's job is to say that this conversation runs on its own, and how* many tasks do it is the panel's business. The label is the only carrier of that meaning, so it@@ -110,7 +117,7 @@ export function ScheduleMark({ size }: { size: number }) {role="img"aria-label={label}title={label}- className={`flex shrink-0 items-center ${toneInk.attention}`}+ className={`flex shrink-0 items-center ${toneInk.muted}`}><GlyphIcon d={SCHEDULE_ICON} size={size} /></span>diff --git a/packages/web/src/features/schedules/schedule-panel.tsx b/packages/web/src/features/schedules/schedule-panel.tsxindex c9da3714..238a4cb5 100644--- a/packages/web/src/features/schedules/schedule-panel.tsx+++ b/packages/web/src/features/schedules/schedule-panel.tsx@@ -164,18 +164,20 @@ export function SchedulePanel({ session, active, onPrefillComposer }: SchedulePa// On coming to the front, and on a timer while it stays there. Focus and visibility are the// store's own business (it refreshes for the toolbar mark too); a hidden tab adds no poll.+ // Every refresh names this conversation's agent: the store holds a list per agent, and the+ // sidebar is reading another one whenever the current Agent has moved ahead of this panel.useEffect(() => {if (!active) return;- void refreshSchedules();+ void refreshSchedules(projectId, session.agentId);const timer = window.setInterval(() => {- if (document.visibilityState === "visible") void refreshSchedules();+ if (document.visibilityState === "visible") void refreshSchedules(projectId, session.agentId);}, REFRESH_MS);return () => window.clearInterval(timer);- }, [active]);+ }, [active, projectId, session.agentId]);/** After a create or delete: the list, and the agent card's schedule count. */const changed = () => {- void refreshSchedules();+ void refreshSchedules(projectId, session.agentId);void reloadAgents();};@@ -191,7 +193,7 @@ export function SchedulePanel({ session, active, onPrefillComposer }: SchedulePatoggleBody(item, !item.enabled),);toastSuccess(item.enabled ? S.schedule.toastDisabled : S.schedule.toastEnabled);- await refreshSchedules();+ await refreshSchedules(projectId, session.agentId);} catch (e) {toastError(apiErrorText(e));} finally {diff --git a/packages/web/src/features/schedules/schedule-store.ts b/packages/web/src/features/schedules/schedule-store.tsindex 7e0ae5d5..fc5356a6 100644--- a/packages/web/src/features/schedules/schedule-store.ts+++ b/packages/web/src/features/schedules/schedule-store.ts@@ -1,21 +1,23 @@/**- * One agent's scheduled tasks, as a tiny module-level store shared by the two surfaces that- * read them: the sidebar's alarm-clock mark (which of the listed Sessions have an enabled task- * bound to them) and the dock's scheduled-tasks panel (the conversation's own tasks, listed).- * They must never disagree about whether a conversation has tasks, so they read one list rather- * than fetching one each.+ * Scheduled tasks per agent, as a tiny module-level store shared by the two surfaces that read+ * them: the sidebar's alarm-clock mark (which of the listed Sessions have an enabled task bound+ * to them) and the dock's scheduled-tasks panel (the conversation's own tasks, listed). They must+ * never disagree about whether a conversation has tasks, so they read one cache rather than+ * fetching one each.** The server has no per-Session schedule field and no push channel for the schedule* directory — an agent may write a task file at any moment — so the store decides *when* to- * look: on the Session or agent changing, whenever the window regains focus while anyone is- * subscribed, on the `schedule_fired` / `schedule_queued` events (wired in state/sessions.tsx),- * on the panel's slow poll while it is on screen, and after every mutation the panel makes.+ * look: on the Session or agent changing, whenever the window regains focus while a reader is+ * mounted, on the `schedule_fired` / `schedule_queued` events (wired in state/sessions.tsx), on+ * the panel's slow poll while it is on screen, and after every mutation the panel makes.*- * The scope is set, not stacked: the sidebar names the current Agent and the panel names the- * open conversation's, which the chat page keeps in step, so a different agent replaces the- * cached list instead of keeping both. Readers ask for the scope they want and get nothing until- * the store is actually pointed at it, which is what keeps the previous agent's marks off screen- * for the frame after a navigation.+ * Everything here is keyed by scope — one project and one agent — rather than held in a single+ * slot the store points at. The two readers genuinely disagree for as long as a navigation takes+ * to settle: the sidebar names the current Agent, which flips the moment a row is clicked, while+ * the panel names the open conversation's. With one slot every such moment threw the list away+ * and bought it back with a round trip, so the row marks blinked; with one entry per scope, a+ * reader whose scope has already answered keeps answering from it, and a request asked for on+ * behalf of agent B is issued for B even while A's is still out.*/import { useEffect, useSyncExternalStore } from "react";import type { ScheduleItem } from "@prismshadow/penguin-server/api";@@ -27,13 +29,54 @@ interface Scope {agentId: string;}-let scope: Scope | null = null;-/** Null until the current scope has answered once; a refetch keeps the list it has. */-let items: ScheduleItem[] | null = null;-/** Only the first load's failure is reported; later failures leave the last known list alone. */-let error: string | null = null;+interface Entry {+ scope: Scope;+ /** Null until this scope has answered once; a refetch keeps the list it already has. */+ items: ScheduleItem[] | null;+ /** Last failure text, cleared by the next success. The panel shows it only while `items` is null. */+ error: string | null;+ /** This scope's request: concurrent readers of one scope share it, another scope gets its own. */+ inflight: Promise<void> | null;+ /** Mounted readers of this scope (retainSchedules); zero means nothing on screen shows this list. */+ readers: number;+}++/**+ * One entry per scope, kept for the lifetime of the tab. Growth is bounded in practice by how+ * many Agents one sitting opens — a project holds a handful, and an entry is a list already+ * loaded once — so nothing is evicted: dropping an entry would trade a few kilobytes back for+ * exactly the blank-then-refetch this cache exists to remove.+ */+const entries = new Map<string, Entry>();++/** Cache key. "\0" separates the pair, as it does elsewhere for keys built from ids, so no+ * spelling of either id can make two pairs collide. */+function keyOf(projectId: string, agentId: string): string {+ return `${projectId}\0${agentId}`;+}++function entryFor(projectId: string, agentId: string): Entry {+ const key = keyOf(projectId, agentId);+ const existing = entries.get(key);+ if (existing) return existing;+ const created: Entry = {+ scope: { projectId, agentId },+ items: null,+ error: null,+ inflight: null,+ readers: 0,+ };+ entries.set(key, created);+ return created;+}++/** Lookup that creates nothing: a render must not add an entry for a scope nobody is loading. */+function peek(projectId: string | null, agentId: string | null): Entry | undefined {+ if (projectId === null || agentId === null) return undefined;+ return entries.get(keyOf(projectId, agentId));+}+let version = 0;-let inflight: Promise<void> | null = null;const listeners = new Set<() => void>();function notify(): void {@@ -46,68 +89,79 @@ export function schedulesVersion(): number {return version;}-/** Whether the store currently holds this agent's list (a reader asking for another scope must wait). */-export function schedulesScopedTo(projectId: string | null, agentId: string | null): boolean {- return scope !== null && scope.projectId === projectId && scope.agentId === agentId;-}--/** The loaded list, or null while the current scope has not answered yet. */-export function scheduleItems(): ScheduleItem[] | null {- return items;+/** This agent's loaded list, or null while this scope has never answered. */+export function scheduleItems(+ projectId: string | null,+ agentId: string | null,+): ScheduleItem[] | null {+ return peek(projectId, agentId)?.items ?? null;}-/** The first load's failure text, or null. */-export function scheduleError(): string | null {- return error;+/** This agent's last failure text, or null. */+export function scheduleError(projectId: string | null, agentId: string | null): string | null {+ return peek(projectId, agentId)?.error ?? null;}/**- * Points the store at an agent. A different agent drops the list at once — an alarm clock- * standing for the previous agent's tasks is worse than no mark at all.+ * Re-reads one agent's list. The scope is an argument rather than whatever the store last pointed+ * at, which is what makes the request always the one the caller asked for: concurrent calls for a+ * scope share its request, and a call for another scope issues its own instead of waiting on a+ * promise that will answer about somebody else.*/-export function scopeSchedules(projectId: string | null, agentId: string | null): void {- if (schedulesScopedTo(projectId, agentId)) return;- scope = projectId !== null && agentId !== null ? { projectId, agentId } : null;- items = null;- error = null;- notify();-}--/** Re-reads the scoped agent's list; concurrent calls share one request. */-export function refreshSchedules(): Promise<void> {- const target = scope;- if (target === null) return Promise.resolve();- if (inflight) return inflight;- inflight = (async () => {+export function refreshSchedules(projectId: string | null, agentId: string | null): Promise<void> {+ if (projectId === null || agentId === null) return Promise.resolve();+ const entry = entryFor(projectId, agentId);+ if (entry.inflight) return entry.inflight;+ const request = (async () => {try {- const res = await api.listSchedules(target.projectId, target.agentId);- // The scope may have moved while the request was out; that answer belongs to nobody.- if (scope !== target) return;- items = res.schedules;- error = null;- notify();+ const res = await api.listSchedules(projectId, agentId);+ entry.items = res.schedules;+ entry.error = null;} catch (e) {- if (scope !== target) return;- error = apiErrorText(e);- notify();+ // The list it already has stays: a refetch failing is not news that the tasks are gone.+ entry.error = apiErrorText(e);} finally {- inflight = null;+ entry.inflight = null;}+ notify();})();- return inflight;+ // Assigned after the body starts, which is safe because the body suspends at its first+ // `await`: any second caller for this scope runs after that point and finds the promise here.+ entry.inflight = request;+ return request;}/**- * A schedule event landed for some agent (state/sessions.tsx): refresh only when it is the one- * on screen, so a task firing in another Project or another Agent costs no request.+ * Counts one mounted reader of a scope; the returned function releases it. The count decides+ * which scopes an event or a regained focus re-reads — refreshing a list nothing is showing+ * spends a request on an answer that would be re-read anyway when it next comes on screen.+ * Releasing keeps the cached list, which is precisely what the reader shows again on return.+ */+export function retainSchedules(projectId: string | null, agentId: string | null): () => void {+ if (projectId === null || agentId === null) return () => {};+ const entry = entryFor(projectId, agentId);+ entry.readers += 1;+ return () => {+ entry.readers -= 1;+ };+}++/**+ * A schedule event landed for some agent (state/sessions.tsx, chat-page.tsx): refresh only when+ * that agent is on screen, so a task firing in another Project or another Agent costs no request.*/export function noteScheduleEvent(projectId: string, agentId: string): void {- if (!schedulesScopedTo(projectId, agentId)) return;- void refreshSchedules();+ const entry = peek(projectId, agentId);+ if (entry === undefined || entry.readers === 0) return;+ void refreshSchedules(projectId, agentId);}+/** Regaining focus re-reads every scope a mounted reader is showing, and no other. */const onFocus = (): void => {- if (document.visibilityState === "visible") void refreshSchedules();+ if (document.visibilityState !== "visible") return;+ for (const entry of [...entries.values()]) {+ if (entry.readers > 0) void refreshSchedules(entry.scope.projectId, entry.scope.agentId);+ }};export function subscribeSchedules(listener: () => void): () => void {@@ -126,10 +180,14 @@ export function subscribeSchedules(listener: () => void): () => void {}/**- * Subscribes to the store and points it at one agent, refetching whenever `refreshKey` changes- * — the Session on screen, so two conversations of the same agent each get a fresh read. The- * result is this agent's whole list; callers narrow it to a Session themselves+ * Subscribes to the store and keeps one agent's list loaded, refetching whenever `refreshKey`+ * changes — the Session on screen, so two conversations of the same agent each get a fresh read.+ * The result is this agent's whole list; callers narrow it to a Session themselves* (`sessionSchedules` / `pendingScheduleSessions`).+ *+ * `items` is null only for a scope that has never been answered. An agent already loaded answers+ * from its own entry on the first render after a navigation, while the refetch is still out,+ * which is what keeps the session rows' marks from blinking as the current Agent changes.*/export function useAgentSchedules(projectId: string | null,@@ -137,12 +195,14 @@ export function useAgentSchedules(refreshKey: string,): { items: ScheduleItem[] | null; error: string | null } {useSyncExternalStore(subscribeSchedules, schedulesVersion, schedulesVersion);+ // Held for as long as this reader is mounted, and deliberately not keyed on `refreshKey`:+ // moving between two conversations of one agent must not release the scope and take it again.+ useEffect(() => retainSchedules(projectId, agentId), [projectId, agentId]);useEffect(() => {- scopeSchedules(projectId, agentId);- void refreshSchedules();+ void refreshSchedules(projectId, agentId);}, [projectId, agentId, refreshKey]);- // Read through the scope check rather than the raw fields: the effect above runs after this- // render, so on the first render after a navigation the store still holds the old agent.- const mine = schedulesScopedTo(projectId, agentId);- return { items: mine ? items : null, error: mine ? error : null };+ return {+ items: scheduleItems(projectId, agentId),+ error: scheduleError(projectId, agentId),+ };}diff --git a/packages/web/test/schedule-store.test.ts b/packages/web/test/schedule-store.test.tsnew file mode 100644index 00000000..d88fd90c--- /dev/null+++ b/packages/web/test/schedule-store.test.ts@@ -0,0 +1,184 @@+/**+ * The scheduled-tasks store (src/features/schedules/schedule-store.ts), which is shared by two+ * readers whose scopes disagree while a navigation settles: the sidebar names the current Agent,+ * which flips the instant a session row is clicked, and the dock's panel names the open+ * conversation's. What is asserted here is that neither reader can take the other's answer away+ * — one entry and one request per scope — because a single shared slot is what made the session+ * rows' alarm-clock marks blink in and out on every switch.+ *+ * No React and no DOM: the hook is a thin wrapper over these functions, and the scope behaviour+ * is the part that was wrong. Each test uses its own project id, so the module-level cache needs+ * no reset between them.+ */+import { beforeEach, describe, expect, it, vi } from "vitest";+import type { ScheduleItem, SchedulesResponse } from "@prismshadow/penguin-server/api";++vi.mock("../src/api/endpoints", () => ({ listSchedules: vi.fn() }));++import * as api from "../src/api/endpoints";+import {+ noteScheduleEvent,+ refreshSchedules,+ retainSchedules,+ scheduleError,+ scheduleItems,+} from "../src/features/schedules/schedule-store";++const listSchedules = vi.mocked(api.listSchedules);++function response(...names: string[]): SchedulesResponse {+ const schedules: ScheduleItem[] = names.map((name) => ({+ name,+ prompt: "Summarize yesterday",+ enabled: true,+ startAt: "2026-09-01T00:00:00.000Z",+ status: "active",+ queued: false,+ }));+ return { schedules, invalidFiles: [] };+}++const names = (projectId: string, agentId: string) =>+ scheduleItems(projectId, agentId)?.map((i) => i.name) ?? null;++/** A promise plus its resolve handle, so a request can be held open across assertions. */+function deferred<T>(): { promise: Promise<T>; resolve: (v: T) => void } {+ let resolve!: (v: T) => void;+ const promise = new Promise<T>((res) => {+ resolve = res;+ });+ return { promise, resolve };+}++beforeEach(() => {+ listSchedules.mockReset();+});++describe("refreshSchedules", () => {+ it("keeps a list per agent, so moving to another scope never blanks the one already answered", async () => {+ listSchedules.mockImplementation(async (_projectId, agentId) => response(agentId));++ await refreshSchedules("p1", "a1");+ await refreshSchedules("p1", "a2");++ expect(names("p1", "a1")).toEqual(["a1"]);+ expect(names("p1", "a2")).toEqual(["a2"]);+ // Null means "never answered" and nothing else — the one honest reason for a row to wear+ // no mark before the first read lands.+ expect(scheduleItems("p1", "a3")).toBeNull();+ });++ it("issues a request for the scope it was asked for, mid-flight, and lands each answer in its own entry", async () => {+ const first = deferred<SchedulesResponse>();+ const second = deferred<SchedulesResponse>();+ listSchedules.mockReturnValueOnce(first.promise).mockReturnValueOnce(second.promise);++ const a1 = refreshSchedules("p2", "a1");+ const a2 = refreshSchedules("p2", "a2");++ // The switch happened while a1's read was still out: a2 must have been fetched too, rather+ // than handed a1's promise and left forever unread.+ expect(listSchedules.mock.calls.map((c) => c[1])).toEqual(["a1", "a2"]);++ second.resolve(response("nightly"));+ await a2;+ expect(names("p2", "a2")).toEqual(["nightly"]);+ expect(scheduleItems("p2", "a1")).toBeNull();++ // The older request answers about its own agent, not about whoever asked last.+ first.resolve(response("hourly"));+ await a1;+ expect(names("p2", "a1")).toEqual(["hourly"]);+ expect(names("p2", "a2")).toEqual(["nightly"]);+ });++ it("shares one request per scope while it is out, and refetches once it has settled", async () => {+ const pending = deferred<SchedulesResponse>();+ listSchedules.mockReturnValueOnce(pending.promise);++ const a = refreshSchedules("p3", "a1");+ const b = refreshSchedules("p3", "a1");+ expect(b).toBe(a);+ expect(listSchedules).toHaveBeenCalledTimes(1);++ pending.resolve(response("nightly"));+ await a;++ listSchedules.mockResolvedValueOnce(response("nightly", "weekly"));+ await refreshSchedules("p3", "a1");+ expect(listSchedules).toHaveBeenCalledTimes(2);+ expect(names("p3", "a1")).toEqual(["nightly", "weekly"]);+ });++ it("confines a failure to the scope that failed", async () => {+ listSchedules.mockResolvedValueOnce(response("nightly"));+ await refreshSchedules("p4", "a1");+ listSchedules.mockRejectedValueOnce(new Error("offline"));+ await refreshSchedules("p4", "a2");++ expect(scheduleError("p4", "a2")).not.toBeNull();+ expect(scheduleItems("p4", "a2")).toBeNull();+ // The healthy agent keeps both its list and its clean slate: one global error field used to+ // mean a failure anywhere put an error message under every reader.+ expect(scheduleError("p4", "a1")).toBeNull();+ expect(names("p4", "a1")).toEqual(["nightly"]);+ });+});++/**+ * The reader count is what decides whether a `schedule_fired` / `schedule_queued` event costs a+ * request: with a list per scope, the store can no longer tell "on screen" from "cached" by+ * asking which scope it points at. Refreshing a scope nothing is showing would spend a request+ * on an answer the next mount re-reads anyway, and skipping one a reader IS showing would leave+ * a fired task's row stale until the next poll — so both directions are asserted here.+ */+describe("retainSchedules and noteScheduleEvent", () => {+ it("re-reads a scope a reader is mounted on, and leaves a cached one nobody shows alone", async () => {+ listSchedules.mockImplementation(async (_projectId, agentId) => response(agentId));++ await refreshSchedules("p5", "a1");+ // Loaded, but nothing on screen is reading it: the event costs nothing.+ noteScheduleEvent("p5", "a1");+ expect(listSchedules).toHaveBeenCalledTimes(1);++ const release = retainSchedules("p5", "a1");+ noteScheduleEvent("p5", "a1");+ expect(listSchedules).toHaveBeenCalledTimes(2);+ // Joins the request the event started rather than issuing a third.+ await refreshSchedules("p5", "a1");+ expect(listSchedules).toHaveBeenCalledTimes(2);++ // Releasing the last reader keeps the list — that is exactly what the reader draws again on+ // return — and stops the events nothing would display.+ release();+ noteScheduleEvent("p5", "a1");+ expect(listSchedules).toHaveBeenCalledTimes(2);+ expect(names("p5", "a1")).toEqual(["a1"]);+ });++ it("counts readers, so the panel unmounting does not silence the sidebar's refreshes", async () => {+ listSchedules.mockImplementation(async (_projectId, agentId) => response(agentId));+ // Both surfaces on one agent, which is the resting state: the sidebar's current Agent is+ // the open conversation's. A flag rather than a count would let either release silence both.+ const sidebar = retainSchedules("p6", "a1");+ const panel = retainSchedules("p6", "a1");++ panel();+ noteScheduleEvent("p6", "a1");+ // Read before settling: the request goes out synchronously, so a count of 0 here is the+ // event having been dropped, not a request that has yet to be made.+ expect(listSchedules).toHaveBeenCalledTimes(1);+ // Joins the request the event started rather than issuing one of its own.+ await refreshSchedules("p6", "a1");+ expect(listSchedules).toHaveBeenCalledTimes(1);++ sidebar();+ noteScheduleEvent("p6", "a1");+ expect(listSchedules).toHaveBeenCalledTimes(1);+ });++ it("ignores an event for a scope no reader has ever asked about", () => {+ noteScheduleEvent("p7", "a1");+ expect(listSchedules).not.toHaveBeenCalled();+ });+});diff --git a/packages/web/test/session-activity.test.ts b/packages/web/test/session-activity.test.tsindex df0e56f5..42c020bc 100644--- a/packages/web/test/session-activity.test.ts+++ b/packages/web/test/session-activity.test.ts@@ -6,10 +6,11 @@ import type { SessionActivity } from "../src/lib/session-activity";import {ACTIVITY_GLYPH,BackgroundTasksMark,+ ScheduleMark,SessionActivityIcon,sessionActivityLabel,} from "../src/components/ui/session-activity-icon";-import { BACKGROUND_TASKS_ICON } from "../src/components/ui/icons";+import { BACKGROUND_TASKS_ICON, SCHEDULE_ICON } from "../src/components/ui/icons";import { ICON_SIZE } from "../src/lib/icon-scale";import { S } from "../src/lib/strings";import { toneInk } from "../src/lib/tone";@@ -64,7 +65,7 @@ describe("sessionBackgroundTasks", () => {});/**- * The background-task mark: one glyph in the `busy` tone for both of its placements — a+ * The background-task mark: one glyph in the `muted` tone for both of its placements — a* session row / the chat header, where it stands for a count, and a tool row, where it marks* the single call made with `run_in_background`. Rendered only when there is background work* to report (the caller's decision), and always naming what it means in the accessible name@@ -91,19 +92,39 @@ describe("BackgroundTasksMark", () => {expect(S.chat.backgroundCall).not.toMatch(/\d/);});- it("draws the activity trace in the busy tone, at the rung its caller passes", () => {+ it("draws the activity trace in the muted tone, at the rung its caller passes", () => {expect(render(S.chat.backgroundCall, ICON_SIZE.rowMark)).toMatch(/width="12"/);expect(render(S.chat.backgroundCall, ICON_SIZE.inlineGlyph)).toMatch(/width="13"/);const markup = render(S.chat.backgroundTasks(1), ICON_SIZE.rowMark);expect(markup).toContain(`d="${BACKGROUND_TASKS_ICON}"`);- expect(markup).toContain(toneInk.busy);- // Not one of the activity glyphs, and no motion: it is a fact about the Session, not a- // live-progress indicator.+ // Parked work is a fact about the Session, not a turn in progress: the mark recedes with+ // the pin and the relay glyph instead of borrowing the tone the running hourglass wears.+ expect(markup).toContain(toneInk.muted);+ expect(markup).not.toContain(toneInk.busy);+ // Not one of the activity glyphs, and no motion, for the same reason.expect(markup).not.toContain(ACTIVITY_GLYPH.running);expect(markup).not.toContain("hourglass-turn");});});+describe("ScheduleMark", () => {+ const markup = () =>+ renderToStaticMarkup(createElement(ScheduleMark, { size: ICON_SIZE.rowMark }));++ it("recedes with the row's other standing marks instead of reading as live work", () => {+ // A scheduled task is an arrangement, not something happening now: it takes the `muted` ink+ // the pin and the messaging-relay glyph wear, and neither the busy nor the attention tone+ // that the hourglass and the pending-approval badge own.+ expect(markup()).toContain(toneInk.muted);+ expect(markup()).not.toContain(toneInk.attention);+ expect(markup()).not.toContain(toneInk.busy);+ // Muted is the one tone allowed under 3:1, and only where the meaning is already in text.+ expect(markup()).toContain(`aria-label="${S.chat.sessionScheduled}"`);+ expect(markup()).toContain(`title="${S.chat.sessionScheduled}"`);+ expect(markup()).toContain(`d="${SCHEDULE_ICON}"`);+ });+});+/*** Icon rendering contract, via react-dom/server static markup (node env, no DOM).*