Skip to content

The agent that grows with you

fix(desktop): keep sidebar pin toggles from reverting after the write guard

Barclay McFadden6891c657023a
diff --git a/apps/desktop/src/store/session-pin-sync.test.ts b/apps/desktop/src/store/session-pin-sync.test.ts
index 28314f1308b..f3c3aabef5c 100644
--- a/apps/desktop/src/store/session-pin-sync.test.ts
+++ b/apps/desktop/src/store/session-pin-sync.test.ts
@@ -337,6 +337,87 @@ describe('watchSessionPins remote pull', () => {
}
})
+ it('does not resurrect an unpin from a stale row that outlives the guard', async () => {
+ // A just-unpinned chat drops out of the backend's pinned back-fill, but it
+ // stays in $sessions as a SURVIVOR (open tile / selected / recently
+ // settled) — the same object that said pinned=true before the unpin. No
+ // page ever replaces it, so once the write guard's cooldown expires the
+ // next unrelated refresh must not read that frozen flag as a remote pin.
+ vi.useFakeTimers()
+
+ try {
+ const sticky = row('survivor', { pinned: true })
+ $sessions.set([sticky])
+ await flush()
+ expect($pinnedSessionIds.get()).toEqual(['survivor'])
+
+ $pinnedSessionIds.set([])
+ await flush()
+ expect(patch).toHaveBeenCalledWith('survivor', false, undefined)
+
+ vi.advanceTimersByTime(11_000)
+
+ // An unrelated refresh: the survivor row object is carried forward.
+ $sessions.set([...$sessions.get(), row('other')])
+ await flush()
+
+ expect($pinnedSessionIds.get()).not.toContain('survivor')
+ } finally {
+ vi.useRealTimers()
+ }
+ })
+
+ it('does not re-pin an unpinned row when the next shift-click lands after the guard', async () => {
+ // The reported workflow: shift-click A to unpin, keep working through the
+ // list, shift-click B more than 10 s later. A PATCH emits no list refresh,
+ // so $sessions still holds A's pre-unpin row; B's toggle fires reconcile,
+ // the guard has lapsed, and that frozen pinned=true used to re-adopt A.
+ vi.useFakeTimers()
+
+ try {
+ $sessions.set([row('A', { pinned: true }), row('B', { pinned: false })])
+ await flush()
+ expect($pinnedSessionIds.get()).toEqual(['A'])
+
+ $pinnedSessionIds.set([])
+ await flush()
+
+ vi.advanceTimersByTime(11_000)
+
+ $pinnedSessionIds.set(['B'])
+ await flush()
+
+ expect($pinnedSessionIds.get()).toEqual(['B'])
+ expect($unconfirmedPinWrites.get().has('A')).toBe(false)
+ } finally {
+ vi.useRealTimers()
+ }
+ })
+
+ it('does not resurrect a batch of shift-click unpins after the guard', async () => {
+ vi.useFakeTimers()
+
+ try {
+ $sessions.set([row('s1', { pinned: true }), row('s2', { pinned: true }), row('s3', { pinned: true })])
+ await flush()
+ expect($pinnedSessionIds.get()).toEqual(['s1', 's2', 's3'])
+
+ // Rapid, one-at-a-time unpins (shift+click each row).
+ $pinnedSessionIds.set(['s2', 's3'])
+ $pinnedSessionIds.set(['s3'])
+ $pinnedSessionIds.set([])
+ await flush()
+
+ vi.advanceTimersByTime(11_000)
+ $sessions.set([...$sessions.get()])
+ await flush()
+
+ expect($pinnedSessionIds.get()).toEqual([])
+ } finally {
+ vi.useRealTimers()
+ }
+ })
+
it('keeps the pin and retries when the write itself fails', async () => {
patch.mockImplementationOnce(() => Promise.reject(new Error('offline')))
diff --git a/apps/desktop/src/store/session-pin-sync.ts b/apps/desktop/src/store/session-pin-sync.ts
index b0920b57ca0..6d674d55519 100644
--- a/apps/desktop/src/store/session-pin-sync.ts
+++ b/apps/desktop/src/store/session-pin-sync.ts
@@ -27,7 +27,16 @@ import { setSessionPinnedRemote } from '@/hermes'
import { onConnectionScopeChange } from '@/lib/connection-scoped'
import { $pinnedSessionIds, pinSession, unpinSession } from '@/store/layout'
import { $activeGatewayProfile, normalizeProfileKey } from '@/store/profile'
-import { $cronSessions, $messagingSessions, $sessions, sessionMatchesStoredId, sessionPinId } from '@/store/session'
+import {
+ $cronSessions,
+ $messagingSessions,
+ $sessions,
+ sessionMatchesStoredId,
+ sessionPinId,
+ setCronSessions,
+ setMessagingSessions,
+ setSessions
+} from '@/store/session'
import type { SessionInfo } from '@/types/hermes'
// pin ids we've successfully PATCHed pinned=true this session.
@@ -40,6 +49,10 @@ const pending = new Set<string>()
// write. Hold the guard until a page actually CONFIRMS the written value,
// with a cooldown so a row that never comes back can't fence itself forever.
const unconfirmed = new Map<string, { at: number; value: boolean }>()
+// Rows this module rewrote to match a local toggle. They carry OUR intent, not
+// the server's, so they may never confirm (release) a write guard — only a row
+// a real list page delivered can do that.
+const optimisticRows = new WeakSet<SessionInfo>()
/**
* The ids `unconfirmed` currently fences, for readers outside this module.
@@ -124,9 +137,54 @@ function rowsByPinId(rows: readonly SessionInfo[]): Map<string, SessionInfo> {
return byId
}
+/**
+ * Paint the local intent onto every loaded row for `pinId`, in every slice.
+ *
+ * Without this the cached row keeps the pre-toggle flag until a page replaces
+ * it — and a row kept alive as a survivor (open tile, selection, recently
+ * settled, or simply no refresh yet) never is. Once the write guard's cooldown
+ * lapsed, the next unrelated slice change read that frozen `pinned: true` as a
+ * remote pin and re-listed the chat the user had just unpinned (and the mirror
+ * image for a fresh pin). Rows without the flag (backend predating it) are left
+ * alone so the pull still has no opinion on them.
+ */
+function applyRowPinned(pinId: string, pinned: boolean, profile?: null | string): void {
+ // Session ids are only unique per profile; when the write names its owner,
+ // leave a same-id twin in another profile carrying its own server flag.
+ const owner = profile == null ? null : normalizeProfileKey(profile)
+
+ const patchRows = (rows: SessionInfo[]): SessionInfo[] => {
+ let changed = false
+
+ const next = rows.map(row => {
+ if (
+ typeof row.pinned !== 'boolean' ||
+ row.pinned === pinned ||
+ !sessionMatchesStoredId(row, pinId) ||
+ (owner != null && normalizeProfileKey(row.profile) !== owner)
+ ) {
+ return row
+ }
+
+ changed = true
+ const updated = { ...row, pinned }
+ optimisticRows.add(updated)
+
+ return updated
+ })
+
+ return changed ? next : rows
+ }
+
+ setSessions(patchRows)
+ setCronSessions(patchRows)
+ setMessagingSessions(patchRows)
+}
+
/** PATCH the flag, guarding reads against pages that predate the write. */
function writePin(id: string, pinned: boolean, profile?: null | string): Promise<void> {
unconfirmed.set(id, { at: Date.now(), value: pinned })
+ applyRowPinned(id, pinned, profile)
return setSessionPinnedRemote(id, pinned, profile).then(
() => {
@@ -138,6 +196,9 @@ function writePin(id: string, pinned: boolean, profile?: null | string): Promise
(err: unknown) => {
// A failed write leaves the server on the old value, so the guard would
// be fencing out the truth. Drop it and let the page win.
+ // The painted rows are left as-is: a failed pin is retried by the caller
+ // (repainting here would fire a reconcile before that retry is booked
+ // and drop the pin), and the next real page replaces them anyway.
unconfirmed.delete(id)
publishUnconfirmed()
throw err
@@ -177,7 +238,14 @@ function pullRemotePins(): void {
const guard = guardKey ? unconfirmed.get(guardKey) : undefined
if (guard && guardKey) {
- if (guard.value === row.pinned) {
+ if (optimisticRows.has(row)) {
+ // Our own painted row agrees by construction, so it is not a
+ // confirmation. Let the cooldown retire the guard as usual; the row
+ // then matches the local set and the checks below are a no-op.
+ if (Date.now() - guard.at >= WRITE_GUARD_MS) {
+ unconfirmed.delete(guardKey)
+ }
+ } else if (guard.value === row.pinned) {
unconfirmed.delete(guardKey)
} else if (Date.now() - guard.at < WRITE_GUARD_MS) {
continue