feat(web): persist session-dot acknowledgements across reloads

`flags.done`/`flags.error` are unread markers: the plugin keeps raising them
until nvim's own TabEnter, while `markSeen` only cleared them in the in-memory
store. The next snapshot — a reload, or a reconnect's resync — replayed the
flag, so a notification the user had already consumed blinked again and the
dot looked stuck on unread.

The acknowledgement is now durable in `localStorage` (`pi2-seen-sessions`, per
browser), recorded under the occurrence it was given for: the id of the
transcript's newest entry. A replayed snapshot ends on the same entry, so
ingress clears the flag; the next completed turn appends entries first, so its
token differs and that new notification blinks again. A row with no entries
cannot be scoped and keeps the in-memory-only behaviour. `removeSession`
forgets the ledger row and the `tmp-N` → real-id migration moves it. This stays
a client-side view concern — the wire, the reducer and `fixtures/` are
untouched.
This commit is contained in:
yuez committed 2026-10-30 16:19:40 +08:00
1 parent 2f2f1bb518
commit 00c81a56f4
4 files changed
+261 -6

No files matched your search

+11
View File
@@ -122,6 +122,17 @@ so the session you open stops being green or red — which is why a viewed child
failure is solid while an unviewed one blinks. The canonical reducer (`src/protocol/reducer.ts`) failure is solid while an unviewed one blinks. The canonical reducer (`src/protocol/reducer.ts`)
and `fixtures/` are deliberately untouched: this is a client-side view concern. and `fixtures/` are deliberately untouched: this is a client-side view concern.
The acknowledgement is **durable**, because the plugin keeps raising the flag until nvim's own
`TabEnter`: an in-memory-only `markSeen` meant the next snapshot (a page reload, or a reconnect's
resync) replayed `done: true` and the green blink returned for a notification the user had
already seen. `web/src/features/chat/acknowledged.ts` persists it in `localStorage`
(`pi2-seen-sessions`, per browser) under the **occurrence** it was given for — the id of the
transcript's newest entry. A replayed snapshot is the same occurrence (same trailing entry id),
so the store clears the flag on ingress; the next completed turn appends entries first, so its
token differs and that new notification blinks again. A notification for a state with no entries
cannot be scoped and is never suppressed. `removeSession` forgets the row and the `tmp-N` →
real-id migration moves it.
## One clock for every dot ## One clock for every dot
No dot animates itself. `web/src/lib/blink.ts` owns a single ref-counted 500ms interval that No dot animates itself. `web/src/lib/blink.ts` owns a single ref-counted 500ms interval that
+130
View File
@@ -0,0 +1,130 @@
import type { SessionState } from "@/lib/protocol";
/**
* Durable acknowledgements for the session-list notification dot.
*
* `flags.done` / `flags.error` are **unread markers**: the plugin raises them for
* a session the user is not looking at and clears them on nvim's TabEnter. The
* browser's TabEnter is `useSessionsStore.markSeen`, which used to clear the
* flags in the in-memory store only — so the next snapshot (a page reload, or a
* reconnect's resync) replayed `done: true` and the green blink came back for a
* notification the user had already seen. A fresh page load has no memory, but
* the plugin's flag still stands, so the dot looked stuck on "unread".
*
* The acknowledgement is therefore persisted (localStorage, per browser) under
* the *occurrence* it was given for: the id of the transcript's newest entry.
* The notification is the same one while the transcript still ends on that
* entry; the next completed turn appends entries, so the token changes and the
* new notification blinks again. This stays a client-side view concern — the
* wire, the reducer and `fixtures/` are untouched.
*/
export const SEEN_STORAGE_KEY = "pi2-seen-sessions";
/** Bound the ledger; a browser sees a few dozen sessions, not thousands. */
const SEEN_LIMIT = 200;
type Ledger = Record<string, string>;
/**
* Identity of the notification occurrence: the newest transcript entry.
*
* `undefined` when the state carries no entries (a REST list row before any
* snapshot). Such a session cannot be acknowledged durably — recording an empty
* token would swallow every future notification — so the caller keeps the
* in-memory-only behaviour.
*/
export function occurrenceToken(session: Pick<SessionState, "entries">): string | undefined {
const last = session.entries[session.entries.length - 1];
return last === undefined || last.id === "" ? undefined : last.id;
}
function storage(): Storage | undefined {
try {
return typeof localStorage === "undefined" ? undefined : localStorage;
} catch {
// Accessing `localStorage` can throw (Safari private mode, blocked cookies).
return undefined;
}
}
function read(): Ledger {
const store = storage();
if (store === undefined) return {};
try {
const raw = store.getItem(SEEN_STORAGE_KEY);
const parsed: unknown = raw === null ? null : JSON.parse(raw);
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return {};
const ledger: Ledger = {};
for (const [sessionId, token] of Object.entries(parsed as Record<string, unknown>)) {
if (typeof token === "string" && token !== "") ledger[sessionId] = token;
}
return ledger;
} catch {
return {};
}
}
function write(ledger: Ledger): void {
const store = storage();
if (store === undefined) return;
try {
// Insertion order is the LRU: drop the oldest keys past the cap.
const ids = Object.keys(ledger);
if (ids.length > SEEN_LIMIT) {
const trimmed: Ledger = {};
for (const id of ids.slice(ids.length - SEEN_LIMIT)) {
const token = ledger[id];
if (token !== undefined) trimmed[id] = token;
}
store.setItem(SEEN_STORAGE_KEY, JSON.stringify(trimmed));
return;
}
store.setItem(SEEN_STORAGE_KEY, JSON.stringify(ledger));
} catch {
// Quota or private mode: the in-memory store still clears the flag.
}
}
/** Record that the user has seen this session's notification. */
export function acknowledge(session: Pick<SessionState, "sessionId" | "entries">): void {
const token = occurrenceToken(session);
if (token === undefined) return;
const ledger = read();
// Re-insert so the entry moves to the LRU tail.
delete ledger[session.sessionId];
ledger[session.sessionId] = token;
write(ledger);
}
/** The session is gone: its ledger row is dead weight. */
export function forget(sessionId: string): void {
const ledger = read();
if (!(sessionId in ledger)) return;
delete ledger[sessionId];
write(ledger);
}
/** `tmp-N` → real id migration: the acknowledgement follows the session. */
export function move(from: string, to: string): void {
if (from === to) return;
const ledger = read();
const token = ledger[from];
if (token === undefined) return;
delete ledger[from];
ledger[to] = token;
write(ledger);
}
/**
* Clear a notification the user has already acknowledged for this occurrence.
* A replay of the same `done`/`error` (snapshot, reconnect, reload) therefore
* cannot resurrect the blink; a new completion appends an entry first, so its
* token differs and it is left alone.
*/
export function suppressAcknowledged(session: SessionState): SessionState {
if (!session.flags.done && !session.flags.error) return session;
const token = occurrenceToken(session);
if (token === undefined) return session;
if (read()[session.sessionId] !== token) return session;
return { ...session, flags: { ...session.flags, done: false, error: false } };
}
+21 -5
View File
@@ -1,5 +1,6 @@
import { create } from "zustand"; import { create } from "zustand";
import { acknowledge, forget, move, suppressAcknowledged } from "@/features/chat/acknowledged";
import type { SessionState } from "@/lib/protocol"; import type { SessionState } from "@/lib/protocol";
export interface SessionsStore { export interface SessionsStore {
@@ -41,7 +42,7 @@ export const useSessionsStore = create<SessionsStore>((set, get) => ({
setSessions: (workspaceId, sessions) => setSessions: (workspaceId, sessions) =>
set((state) => ({ set((state) => ({
byWorkspace: { ...state.byWorkspace, [workspaceId]: sessions }, byWorkspace: { ...state.byWorkspace, [workspaceId]: sessions.map(suppressAcknowledged) },
status: "idle", status: "idle",
error: null, error: null,
})), })),
@@ -51,7 +52,12 @@ export const useSessionsStore = create<SessionsStore>((set, get) => ({
const list = state.byWorkspace[session.workspaceId] ?? []; const list = state.byWorkspace[session.workspaceId] ?? [];
const index = list.findIndex((s) => s.sessionId === session.sessionId); const index = list.findIndex((s) => s.sessionId === session.sessionId);
if (index === -1) { if (index === -1) {
return { byWorkspace: { ...state.byWorkspace, [session.workspaceId]: [...list, session] } }; return {
byWorkspace: {
...state.byWorkspace,
[session.workspaceId]: [...list, suppressAcknowledged(session)],
},
};
} }
// Tree metadata is list metadata: a live update (`pi2:session`, // Tree metadata is list metadata: a live update (`pi2:session`,
// reducer events, a rename) carries no `parentId`/`visible`/`task`/ // reducer events, a rename) carries no `parentId`/`visible`/`task`/
@@ -69,7 +75,7 @@ export const useSessionsStore = create<SessionsStore>((set, get) => ({
createdAt: session.createdAt !== undefined ? session.createdAt : previous.createdAt, createdAt: session.createdAt !== undefined ? session.createdAt : previous.createdAt,
lastActiveAt: session.lastActiveAt !== undefined ? session.lastActiveAt : previous.lastActiveAt, lastActiveAt: session.lastActiveAt !== undefined ? session.lastActiveAt : previous.lastActiveAt,
}; };
const next = list.map((s, i) => (i === index ? merged : s)); const next = list.map((s, i) => (i === index ? suppressAcknowledged(merged) : s));
return { byWorkspace: { ...state.byWorkspace, [session.workspaceId]: next } }; return { byWorkspace: { ...state.byWorkspace, [session.workspaceId]: next } };
}), }),
@@ -108,6 +114,9 @@ export const useSessionsStore = create<SessionsStore>((set, get) => ({
byWorkspace[workspaceId] = next; byWorkspace[workspaceId] = next;
} }
if (!moved) return state; if (!moved) return state;
// An acknowledgement given on a `tmp-N` row belongs to the real id
// once the plugin reports it; keep it across the migration.
move(from, to);
return { return {
byWorkspace, byWorkspace,
selectedSessionId: state.selectedSessionId === from ? to : state.selectedSessionId, selectedSessionId: state.selectedSessionId === from ? to : state.selectedSessionId,
@@ -116,6 +125,7 @@ export const useSessionsStore = create<SessionsStore>((set, get) => ({
removeSession: (sessionId) => removeSession: (sessionId) =>
set((state) => { set((state) => {
forget(sessionId);
const byWorkspace: Record<string, SessionState[]> = {}; const byWorkspace: Record<string, SessionState[]> = {};
for (const [workspaceId, list] of Object.entries(state.byWorkspace)) { for (const [workspaceId, list] of Object.entries(state.byWorkspace)) {
byWorkspace[workspaceId] = list byWorkspace[workspaceId] = list
@@ -129,7 +139,12 @@ export const useSessionsStore = create<SessionsStore>((set, get) => ({
selectSession: (selectedSessionId) => set({ selectedSessionId }), selectSession: (selectedSessionId) => set({ selectedSessionId }),
markSeen: (sessionId) => markSeen: (sessionId) => {
// Remember *which* notification this is before clearing it: the plugin
// keeps raising `done`/`error` until nvim's TabEnter, so a later snapshot
// (reload / reconnect) must not revive a blink the user already consumed.
const current = get().getSession(sessionId);
if (current) acknowledge(current);
set((state) => { set((state) => {
let changed = false; let changed = false;
const byWorkspace: Record<string, SessionState[]> = {}; const byWorkspace: Record<string, SessionState[]> = {};
@@ -147,7 +162,8 @@ export const useSessionsStore = create<SessionsStore>((set, get) => ({
} }
// Nothing to consume: keep the state object so zustand skips the render. // Nothing to consume: keep the state object so zustand skips the render.
return changed ? { byWorkspace } : state; return changed ? { byWorkspace } : state;
}), });
},
listFor: (workspaceId) => get().byWorkspace[workspaceId] ?? [], listFor: (workspaceId) => get().byWorkspace[workspaceId] ?? [],
+99 -1
View File
@@ -1,8 +1,9 @@
import { beforeEach, describe, expect, it, vi } from "vitest"; import { beforeEach, describe, expect, it, vi } from "vitest";
import { SEEN_STORAGE_KEY } from "@/features/chat/acknowledged";
import { emptySessionState, normalizeSnapshotState } from "@/features/chat/session-state"; import { emptySessionState, normalizeSnapshotState } from "@/features/chat/session-state";
import { useSessionsStore } from "@/stores/sessions"; import { useSessionsStore } from "@/stores/sessions";
import { sessionFixture } from "./chat-fixtures"; import { entryFixture, sessionFixture } from "./chat-fixtures";
function state() { function state() {
return useSessionsStore.getState(); return useSessionsStore.getState();
@@ -308,3 +309,100 @@ describe("sessions store — markSeen", () => {
unsub(); unsub();
}); });
}); });
describe("sessions store — an acknowledged notification never replays", () => {
const entries = (...ids: string[]) => ids.map((id) => entryFixture({ id }));
it("keeps done cleared when a reload's snapshot replays the same notification", () => {
const transcript = entries("e1", "e2");
state().setSessions("w1", [
fixture({ sessionId: "s1", workspaceId: "w1", flags: { done: true }, entries: transcript }),
]);
state().markSeen("s1");
expect(state().getSession("s1")?.flags.done).toBe(false);
// The occurrence the browser acknowledged is the transcript tail.
expect(JSON.parse(localStorage.getItem(SEEN_STORAGE_KEY) ?? "{}")).toEqual({ s1: "e2" });
// Page reload: the store is empty, but the plugin still raises `done`
// until nvim's TabEnter, so the snapshot carries it again.
state().reset();
state().upsertSession(
normalizeSnapshotState("s1", "w1", {
state: { status: "idle", flags: { attention: false, done: true, error: false }, entries: transcript },
}),
);
expect(state().getSession("s1")?.flags.done).toBe(false);
// A reconnect replays it too, through the cached-row merge.
state().upsertSession({
...emptySessionState({ sessionId: "s1", workspaceId: "w1" }),
flags: { attention: false, done: true, error: false },
entries: transcript,
});
expect(state().getSession("s1")?.flags.done).toBe(false);
});
it("blinks again once the next turn appends an entry", () => {
state().setSessions("w1", [
fixture({ sessionId: "s1", workspaceId: "w1", flags: { done: true }, entries: entries("e1") }),
]);
state().markSeen("s1");
state().upsertSession({
...emptySessionState({ sessionId: "s1", workspaceId: "w1" }),
status: "idle",
flags: { attention: false, done: true, error: false },
entries: entries("e1", "e2"),
});
expect(state().getSession("s1")?.flags.done).toBe(true);
});
it("re-arms an acknowledged error the same way", () => {
state().setSessions("w1", [
fixture({ sessionId: "s1", workspaceId: "w1", flags: { error: true }, entries: entries("e1") }),
]);
state().markSeen("s1");
state().reset();
state().upsertSession({
...emptySessionState({ sessionId: "s1", workspaceId: "w1" }),
status: "idle",
flags: { attention: false, done: false, error: true },
entries: entries("e1"),
});
expect(state().getSession("s1")?.flags.error).toBe(false);
state().upsertSession({
...emptySessionState({ sessionId: "s1", workspaceId: "w1" }),
status: "idle",
flags: { attention: false, done: false, error: true },
entries: entries("e1", "e2"),
});
expect(state().getSession("s1")?.flags.error).toBe(true);
});
it("carries the acknowledgement across the tmp-N → real-id migration", () => {
state().setSessions("w1", [
fixture({ sessionId: "tmp-1", workspaceId: "w1", flags: { done: true }, entries: entries("e1") }),
]);
state().markSeen("tmp-1");
state().renameSessionId("tmp-1", "real-1");
state().reset();
state().upsertSession(
normalizeSnapshotState("real-1", "w1", {
state: { status: "idle", flags: { attention: false, done: true, error: false }, entries: entries("e1") },
}),
);
expect(state().getSession("real-1")?.flags.done).toBe(false);
});
it("forgets the acknowledgement when the session is removed", () => {
state().setSessions("w1", [
fixture({ sessionId: "s1", workspaceId: "w1", flags: { done: true }, entries: entries("e1") }),
]);
state().markSeen("s1");
state().removeSession("s1");
expect(JSON.parse(localStorage.getItem(SEEN_STORAGE_KEY) ?? "{}")).not.toHaveProperty("s1");
});
});