Skip to content

The agent that grows with you

fix(desktop): don't re-list a just-unpinned session under Pinned

Brooklyn Nicholson524b062289e9
diff --git a/apps/desktop/src/app/chat/sidebar/index.tsx b/apps/desktop/src/app/chat/sidebar/index.tsx
index 868b1167083..fe11212e457 100644
--- a/apps/desktop/src/app/chat/sidebar/index.tsx
+++ b/apps/desktop/src/app/chat/sidebar/index.tsx
@@ -126,6 +126,7 @@ import {
setCurrentCwd
} from '@/store/session'
import { $sessionDotStateById, sessionStatusBucket } from '@/store/session-dot-state'
+import { $unconfirmedPinWrites } from '@/store/session-pin-sync'
import { $focusedStoredSessionId, $workingSessionIds, type SplitDir } from '@/store/session-states'
import { ackAllSessionsRead } from '@/store/session-unread'
import { markSessionUnread } from '@/store/session-unread-remote'
@@ -370,6 +371,7 @@ export function ChatSidebar({
const sortOrderIds = useStore($sidebarSessionRankIds)
const agentsGrouped = grouping === 'project'
const pinnedSessionIds = useStore($pinnedSessionIds)
+ const unconfirmedPinWrites = useStore($unconfirmedPinWrites)
const pinsOpen = useStore($sidebarPinsOpen)
const agentsOpen = useStore($sidebarRecentsOpen)
const cronOpen = useStore($sidebarCronOpen)
@@ -561,15 +563,17 @@ export function ChatSidebar({
// Local pin ids first (hand-picked order), then server-flagged pins the
// local set doesn't know about — a backend `pinned=1` row must never be
- // invisible just because localStorage is cold or was clobbered (#85969).
+ // invisible just because localStorage is cold or was clobbered (#85969) —
+ // minus the rows whose flag our own in-flight pin write already contradicts.
const pinnedSessions = useMemo(
() =>
- resolvePinnedSessions(pinnedSessionIds, sessionByAnyId, [
- ...visibleSessions,
- ...cronSessions,
- ...messagingSessions
- ]),
- [pinnedSessionIds, sessionByAnyId, visibleSessions, cronSessions, messagingSessions]
+ resolvePinnedSessions(
+ pinnedSessionIds,
+ sessionByAnyId,
+ [...visibleSessions, ...cronSessions, ...messagingSessions],
+ unconfirmedPinWrites
+ ),
+ [pinnedSessionIds, sessionByAnyId, visibleSessions, cronSessions, messagingSessions, unconfirmedPinWrites]
)
// Every id a pin is reachable under: the raw stored ids, plus BOTH identities
diff --git a/apps/desktop/src/app/chat/sidebar/session-index.test.ts b/apps/desktop/src/app/chat/sidebar/session-index.test.ts
index a63b484b577..b714a0fa126 100644
--- a/apps/desktop/src/app/chat/sidebar/session-index.test.ts
+++ b/apps/desktop/src/app/chat/sidebar/session-index.test.ts
@@ -7,6 +7,9 @@ import { buildSessionByAnyId, resolvePinnedSessions } from './session-index'
const row = (id: string, extra: Partial<SessionInfo> = {}): SessionInfo =>
({ id, message_count: 1, source: 'cli', started_at: 0, title: id, ...extra }) as SessionInfo
+// No pin write in flight — the server flag is trustworthy.
+const settled: ReadonlySet<string> = new Set()
+
describe('buildSessionByAnyId', () => {
it('resolves a pin from every slice the sidebar fetches', () => {
// The contract that matters: a pin is looked up in this map no matter
@@ -52,7 +55,7 @@ describe('resolvePinnedSessions', () => {
const sessions = [row('a'), row('b'), row('c')]
const index = buildSessionByAnyId(sessions, [], [])
- expect(resolvePinnedSessions(['c', 'a'], index, sessions).map(s => s.id)).toEqual(['c', 'a'])
+ expect(resolvePinnedSessions(['c', 'a'], index, sessions, settled).map(s => s.id)).toEqual(['c', 'a'])
})
it('falls back to the server pinned flag when localStorage is cold (#85969)', () => {
@@ -63,28 +66,57 @@ describe('resolvePinnedSessions', () => {
const sessions = [row('a', { pinned: true }), row('b', { pinned: false })]
const index = buildSessionByAnyId(sessions, [], [])
- expect(resolvePinnedSessions([], index, sessions).map(s => s.id)).toEqual(['a'])
+ expect(resolvePinnedSessions([], index, sessions, settled).map(s => s.id)).toEqual(['a'])
})
it('does not duplicate a session held both locally and server-side', () => {
const sessions = [row('a', { pinned: true })]
const index = buildSessionByAnyId(sessions, [], [])
- expect(resolvePinnedSessions(['a'], index, sessions).map(s => s.id)).toEqual(['a'])
+ expect(resolvePinnedSessions(['a'], index, sessions, settled).map(s => s.id)).toEqual(['a'])
})
it('does not duplicate a server-pinned row whose pin is stored on the lineage root', () => {
const sessions = [row('tip', { _lineage_root_id: 'root', pinned: true })]
const index = buildSessionByAnyId(sessions, [], [])
- expect(resolvePinnedSessions(['root'], index, sessions).map(s => s.id)).toEqual(['tip'])
+ expect(resolvePinnedSessions(['root'], index, sessions, settled).map(s => s.id)).toEqual(['tip'])
})
it('keeps locally pinned rows ahead of server-only fallback pins', () => {
const sessions = [row('server-pin', { pinned: true }), row('local-pin')]
const index = buildSessionByAnyId(sessions, [], [])
- expect(resolvePinnedSessions(['local-pin'], index, sessions).map(s => s.id)).toEqual(['local-pin', 'server-pin'])
+ expect(resolvePinnedSessions(['local-pin'], index, sessions, settled).map(s => s.id)).toEqual([
+ 'local-pin',
+ 'server-pin'
+ ])
+ })
+
+ it('does not resurrect a session the user just unpinned', () => {
+ // The unpin left the local set immediately, but the loaded row still says
+ // pinned=true until a page issued after the PATCH lands. Reading that as a
+ // foreign pin parked the session at the bottom of Pinned for a whole
+ // refresh cycle before it moved to Sessions.
+ const sessions = [row('just-unpinned', { pinned: true })]
+ const index = buildSessionByAnyId(sessions, [], [])
+
+ expect(resolvePinnedSessions([], index, sessions, new Set(['just-unpinned']))).toEqual([])
+ })
+
+ it('fences a stale row under the lineage root the pin was written on', () => {
+ const sessions = [row('tip', { _lineage_root_id: 'root', pinned: true })]
+ const index = buildSessionByAnyId(sessions, [], [])
+
+ expect(resolvePinnedSessions([], index, sessions, new Set(['root']))).toEqual([])
+ })
+
+ it('still adopts a foreign pin while an unrelated write is in flight', () => {
+ // The fence is per id, not a blanket "trust nothing" switch.
+ const sessions = [row('foreign', { pinned: true })]
+ const index = buildSessionByAnyId(sessions, [], [])
+
+ expect(resolvePinnedSessions([], index, sessions, new Set(['other'])).map(s => s.id)).toEqual(['foreign'])
})
it('ignores rows from a backend that predates the pinned flag', () => {
@@ -92,6 +124,6 @@ describe('resolvePinnedSessions', () => {
const sessions = [row('a')]
const index = buildSessionByAnyId(sessions, [], [])
- expect(resolvePinnedSessions([], index, sessions)).toEqual([])
+ expect(resolvePinnedSessions([], index, sessions, settled)).toEqual([])
})
})
diff --git a/apps/desktop/src/app/chat/sidebar/session-index.ts b/apps/desktop/src/app/chat/sidebar/session-index.ts
index be353fe6537..3f28d7f836b 100644
--- a/apps/desktop/src/app/chat/sidebar/session-index.ts
+++ b/apps/desktop/src/app/chat/sidebar/session-index.ts
@@ -47,11 +47,19 @@ export function buildSessionByAnyId(
* a session the backend says is pinned is always reachable from the Pinned
* section, whatever the local cache holds. session-pin-sync then adopts the
* pin into the local set on its next reconcile, restoring ordering control.
+ *
+ * `unconfirmedPinWrites` is that same module's fence, and the fallback has to
+ * respect it. Unpinning drops the id from the local set immediately, but the
+ * loaded row keeps saying `pinned: true` until a page issued after the PATCH
+ * lands — so an unfenced fallback reads the user's own unpin as a foreign pin
+ * and parks the session at the bottom of Pinned for a refresh cycle before it
+ * finally moves to Sessions.
*/
export function resolvePinnedSessions(
pinnedSessionIds: readonly string[],
sessionByAnyId: Map<string, SessionInfo>,
- allSessions: readonly SessionInfo[]
+ allSessions: readonly SessionInfo[],
+ unconfirmedPinWrites: ReadonlySet<string>
): SessionInfo[] {
const seen = new Set<string>()
const out: SessionInfo[] = []
@@ -66,10 +74,21 @@ export function resolvePinnedSessions(
}
for (const session of allSessions) {
- if (session.pinned === true && !seen.has(session.id)) {
- seen.add(session.id)
- out.push(session)
+ if (session.pinned !== true || seen.has(session.id)) {
+ continue
}
+
+ // A pin write of ours the row predates — under either identity, since the
+ // fence is keyed on the durable id and the row may surface as its tip.
+ if (
+ unconfirmedPinWrites.has(session.id) ||
+ (session._lineage_root_id != null && unconfirmedPinWrites.has(session._lineage_root_id))
+ ) {
+ continue
+ }
+
+ seen.add(session.id)
+ out.push(session)
}
return out
diff --git a/apps/desktop/src/store/session-pin-sync.test.ts b/apps/desktop/src/store/session-pin-sync.test.ts
index d77d9d68d5b..f9c39e76b3b 100644
--- a/apps/desktop/src/store/session-pin-sync.test.ts
+++ b/apps/desktop/src/store/session-pin-sync.test.ts
@@ -17,7 +17,7 @@ import { $pinnedSessionIds } from '@/store/layout'
import { $activeGatewayProfile } from '@/store/profile'
import { $sessions } from '@/store/session'
-import { resetSessionPinMirror, watchSessionPins } from './session-pin-sync'
+import { $unconfirmedPinWrites, resetSessionPinMirror, watchSessionPins } from './session-pin-sync'
const row = (id: string, extra: Partial<SessionInfo> = {}): SessionInfo =>
({ id, message_count: 1, source: 'cli', started_at: 0, title: id, ...extra }) as SessionInfo
@@ -308,6 +308,39 @@ describe('watchSessionPins remote pull', () => {
expect($pinnedSessionIds.get()).toEqual(['shared'])
})
+ it('publishes the fence so the sidebar can ignore the rows it covers', async () => {
+ // The Pinned section falls back to the server flag for pins the local set
+ // doesn't hold. Without the fence it reads a just-unpinned row's stale
+ // pinned=true as a foreign pin and re-lists the session.
+ $sessions.set([row('exposed', { pinned: true })])
+ await flush()
+ expect($pinnedSessionIds.get()).toContain('exposed')
+
+ $pinnedSessionIds.set([])
+ await flush()
+
+ expect($unconfirmedPinWrites.get().has('exposed')).toBe(true)
+
+ // Server catches up; nothing left to fence.
+ $sessions.set([row('exposed', { pinned: false })])
+ await flush()
+
+ expect($unconfirmedPinWrites.get().has('exposed')).toBe(false)
+ })
+
+ it('keeps the published fence reference stable across an unrelated refresh', async () => {
+ // The sidebar memoizes the Pinned section on this set; a fresh Set every
+ // session refresh would rebuild the list for nothing.
+ $sessions.set([row('quiet')])
+ await flush()
+
+ const before = $unconfirmedPinWrites.get()
+ $sessions.set([row('quiet'), row('another')])
+ await flush()
+
+ expect($unconfirmedPinWrites.get()).toBe(before)
+ })
+
it('prefers the active gateway profile when duplicate ids disagree', async () => {
$activeGatewayProfile.set('hcoder')
$sessions.set([
diff --git a/apps/desktop/src/store/session-pin-sync.ts b/apps/desktop/src/store/session-pin-sync.ts
index e299b72cb2d..8d162a7e831 100644
--- a/apps/desktop/src/store/session-pin-sync.ts
+++ b/apps/desktop/src/store/session-pin-sync.ts
@@ -21,6 +21,8 @@
* fenced out until a later page confirms the value we wrote.
*/
+import { atom } from 'nanostores'
+
import { setSessionPinnedRemote } from '@/hermes'
import { onConnectionScopeChange } from '@/lib/connection-scoped'
import { $pinnedSessionIds, pinSession, unpinSession } from '@/store/layout'
@@ -39,11 +41,35 @@ const pending = new Set<string>()
// with a cooldown so a row that never comes back can't fence itself forever.
const unconfirmed = new Map<string, { at: number; value: boolean }>()
+/**
+ * The ids `unconfirmed` currently fences, for readers outside this module.
+ *
+ * The sidebar's Pinned section falls back to the server `pinned` flag for rows
+ * the local set doesn't know about, and that fallback needs the same fence the
+ * pull pass uses: a row whose flag our own in-flight write contradicts is not
+ * news, it's the past. Without it an unpin re-lists the session under Pinned
+ * until the next page lands.
+ *
+ * Re-published only when the key set actually changes, so a sidebar memo keyed
+ * on it survives an ordinary session refresh.
+ */
+export const $unconfirmedPinWrites = atom<ReadonlySet<string>>(new Set())
+
// How long an unconfirmed write outranks a page that contradicts it. Long
// enough to cover a list request issued just before the PATCH (those are the
// slow ones), short enough that a genuine server-side change still wins.
const WRITE_GUARD_MS = 10_000
+function publishUnconfirmed(): void {
+ const published = $unconfirmedPinWrites.get()
+
+ if (published.size === unconfirmed.size && [...unconfirmed.keys()].every(id => published.has(id))) {
+ return
+ }
+
+ $unconfirmedPinWrites.set(new Set(unconfirmed.keys()))
+}
+
function profileFor(pinId: string): null | string | undefined {
return $sessions.get().find(row => sessionMatchesStoredId(row, pinId))?.profile
}
@@ -96,6 +122,7 @@ function writePin(id: string, pinned: boolean, profile?: null | string): Promise
// 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.
unconfirmed.delete(id)
+ publishUnconfirmed()
throw err
}
)
@@ -184,6 +211,9 @@ function reconcile(): void {
reconcileInner()
} finally {
reconciling = false
+ // One publish per top-level pass: writePin adds guards and pullRemotePins
+ // retires them, and re-entrant calls above returned without touching either.
+ publishUnconfirmed()
}
}
@@ -263,4 +293,5 @@ export function resetSessionPinMirror(): void {
mirrored.clear()
pending.clear()
unconfirmed.clear()
+ publishUnconfirmed()
}