Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion apps/desktop/src/app/contrib/wiring.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ import { sessionMessagesSignature } from '@/lib/session-signatures'
import { isMessagingSource } from '@/lib/session-source'
import { latestSessionTodos } from '@/lib/todos'
import { setCronFocusJobId } from '@/store/cron'
import { $pinnedSessionIds, pinSession, restoreWorktree, unpinSession } from '@/store/layout'
import { $pinnedSessionIds, hydratePinnedSessionIds, pinSession, restoreWorktree, unpinSession } from '@/store/layout'
import { $filePreviewTarget, $previewTarget } from '@/store/preview'
import { $activeGatewayProfile, $freshSessionRequest, $profileScope, refreshActiveProfile } from '@/store/profile'
import { $startWorkSessionRequest, followActiveSessionCwd, resolveNewSessionCwd } from '@/store/projects'
Expand Down Expand Up @@ -404,6 +404,16 @@ export function ContribWiring({ children }: { children: ReactNode }) {
// global model + active-profile pill (both are nanostores — the blanket
// invalidateQueries on swap doesn't touch them).
const activeGatewayProfile = useStore($activeGatewayProfile)

// Pins span profiles and used to exist only in this renderer's localStorage.
// Only the primary window owns reconciliation: secondary windows share
// localStorage but have independent Nanostore instances.
useEffect(() => {
if (!isSecondaryWindow()) {
void hydratePinnedSessionIds()
}
}, [])

const lastGatewayProfileRef = useRef(activeGatewayProfile)

useEffect(() => {
Expand Down
12 changes: 12 additions & 0 deletions apps/desktop/src/hermes-profile-scope.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
checkHermesUpdate,
getActionStatus,
getDesktopPinnedSessions,
getStatus,
restartGateway,
saveDesktopPinnedSessions,
setApiRequestProfile,
updateHermes
} from './hermes'
Expand Down Expand Up @@ -46,4 +48,14 @@ describe('backend action helpers are profile-scoped', () => {
expect(call[0].profile).toBe('coder')
}
})

it('keeps the machine-global Desktop pin recovery record on the primary backend', () => {
setApiRequestProfile('coder')

void getDesktopPinnedSessions()
expect(lastProfile()).toBeUndefined()

void saveDesktopPinnedSessions(['root-a'])
expect(lastProfile()).toBeUndefined()
})
})
19 changes: 19 additions & 0 deletions apps/desktop/src/hermes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -477,6 +477,25 @@ export function getLogs(params: {
})
}

export interface DesktopPinnedSessionsState {
exists: boolean
pinned_session_ids: string[]
}

export function getDesktopPinnedSessions(): Promise<DesktopPinnedSessionsState> {
return window.hermesDesktop.api<DesktopPinnedSessionsState>({
path: '/api/desktop/pinned-sessions'

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This unprofiled call is routed by Electron through the primary backend; in global remote mode that backend is the remote host. Combined with the new server-side default-root record, pins become remote/backend-global rather than machine-local. Please persist this through an Electron-owned IPC store, or explicitly define and test the intended backend scope.

})
}

export function saveDesktopPinnedSessions(pinnedSessionIds: string[]): Promise<{ ok: boolean; pinned_session_ids: string[] }> {
return window.hermesDesktop.api<{ ok: boolean; pinned_session_ids: string[] }>({
path: '/api/desktop/pinned-sessions',
method: 'PUT',
body: { pinned_session_ids: pinnedSessionIds }
})
}

export function getHermesConfig(): Promise<HermesConfig> {
return window.hermesDesktop.api<HermesConfig>({
...profileScoped(),
Expand Down
86 changes: 86 additions & 0 deletions apps/desktop/src/lib/pinned-session-state.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import { describe, expect, it, vi } from 'vitest'

import { createPinnedSessionWriter, reconcilePinnedSessions } from './pinned-session-state'

describe('reconcilePinnedSessions', () => {
it('bootstraps an absent backend record from legacy local pins', () => {
expect(
reconcilePinnedSessions(
[' root-a ', 'root-a', 'root-b'],
[' root-a ', 'root-a', 'root-b'],
{ exists: false, pinned_session_ids: [] }
)
).toEqual({ pinnedSessionIds: ['root-a', 'root-b'], shouldPersist: true })
})

it('restores a durable backend record when browser storage was wiped', () => {
expect(reconcilePinnedSessions([], [], { exists: true, pinned_session_ids: ['root-a'] })).toEqual({
pinnedSessionIds: ['root-a'],
shouldPersist: false
})
})

it('treats an existing backend record as canonical, including an intentional empty list', () => {
expect(reconcilePinnedSessions(['stale-local'], ['stale-local'], { exists: true, pinned_session_ids: [] })).toEqual({
pinnedSessionIds: [],
shouldPersist: false
})
})

it('applies a pin made during recovery without discarding recovered pins', () => {
expect(reconcilePinnedSessions([], ['new-pin'], { exists: true, pinned_session_ids: ['saved-a', 'saved-b'] })).toEqual({
pinnedSessionIds: ['saved-a', 'saved-b', 'new-pin'],
shouldPersist: true
})
})

it('applies removals, additions, and reordering made during recovery', () => {
expect(
reconcilePinnedSessions(['saved-a', 'saved-b'], ['saved-b', 'new-pin'], {
exists: true,
pinned_session_ids: ['saved-a', 'saved-b']
})
).toEqual({ pinnedSessionIds: ['saved-b', 'new-pin'], shouldPersist: true })
})
})

describe('createPinnedSessionWriter', () => {
it('serializes writes so a slower old value cannot overwrite the latest value', async () => {
let releaseFirst!: () => void

const firstWrite = new Promise<void>(resolve => {
releaseFirst = resolve
})

const saved: string[][] = []

const write = createPinnedSessionWriter(async ids => {
saved.push(ids)

if (saved.length === 1) {
await firstWrite
}
})

const oldWrite = write(['old'])
const latestWrite = write(['latest'])

await new Promise(resolve => setTimeout(resolve, 0))
expect(saved).toEqual([['old']])
releaseFirst()
await Promise.all([oldWrite, latestWrite])
expect(saved).toEqual([['old'], ['latest']])
})

it('retries a transient failure even when it affects the final value', async () => {
const save = vi.fn().mockRejectedValueOnce(new Error('offline')).mockResolvedValue(undefined)
const waitForRetry = vi.fn().mockResolvedValue(undefined)
const write = createPinnedSessionWriter(save, waitForRetry)

await expect(write(['latest'])).resolves.toBeUndefined()
expect(save).toHaveBeenCalledTimes(2)
expect(save).toHaveBeenNthCalledWith(1, ['latest'])
expect(save).toHaveBeenNthCalledWith(2, ['latest'])
expect(waitForRetry).toHaveBeenCalledTimes(1)
})
})
114 changes: 114 additions & 0 deletions apps/desktop/src/lib/pinned-session-state.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
export interface DurablePinnedSessions {
exists: boolean
pinned_session_ids: string[]
}

export interface PinnedSessionReconciliation {
pinnedSessionIds: string[]
shouldPersist: boolean
}

type SavePinnedSessions = (pinnedSessionIds: string[]) => Promise<unknown>
type WaitForRetry = (attempt: number) => Promise<void>

function normalize(ids: unknown): string[] {
if (!Array.isArray(ids)) {
return []
}

const seen = new Set<string>()
const normalized: string[] = []

for (const id of ids) {
if (typeof id !== 'string') {
continue
}

const value = id.trim()

if (!value || seen.has(value)) {
continue
}

seen.add(value)
normalized.push(value)
}

return normalized
}

/**
* Resolve the one-time startup handoff from legacy localStorage to the
* machine-owned backend record. Once the backend record exists it is canonical,
* including an intentionally empty list after a user unpinned every chat.
*/
export function reconcilePinnedSessions(
localPinsAtRequest: unknown,
localPinsNow: unknown,
durable: DurablePinnedSessions
): PinnedSessionReconciliation {
const baseline = normalize(localPinsAtRequest)
const current = normalize(localPinsNow)
const remote = normalize(durable.pinned_session_ids)

if (!durable.exists) {
return { pinnedSessionIds: current, shouldPersist: true }
}

const changedDuringRequest =
baseline.length !== current.length || baseline.some((id, index) => id !== current[index])

if (!changedDuringRequest) {
return { pinnedSessionIds: remote, shouldPersist: false }
}

// Apply the local user's in-flight delta to the recovered durable list. This
// preserves remote-only pins after a localStorage wipe while still honoring
// removals, additions, and reorderings made before the GET completed.
const baselineSet = new Set(baseline)
const currentSet = new Set(current)
const removed = new Set(baseline.filter(id => !currentSet.has(id)))
const remoteSurvivors = remote.filter(id => !removed.has(id))
const remoteSurvivorSet = new Set(remoteSurvivors)
const reorderedKnown = current.filter(id => baselineSet.has(id) && remoteSurvivorSet.has(id))
const remoteOnly = remoteSurvivors.filter(id => !baselineSet.has(id))
const localOnly = current.filter(id => !baselineSet.has(id) && !remoteSurvivorSet.has(id))

return { pinnedSessionIds: normalize([...reorderedKnown, ...remoteOnly, ...localOnly]), shouldPersist: true }
}

const defaultWaitForRetry: WaitForRetry = attempt =>
new Promise(resolve => window.setTimeout(resolve, 250 * 2 ** (attempt - 1)))

/** Serialize writes and retry transient failures without reordering snapshots. */
export function createPinnedSessionWriter(
save: SavePinnedSessions,
waitForRetry: WaitForRetry = defaultWaitForRetry,
maxAttempts = 3
): (pinnedSessionIds: readonly string[]) => Promise<void> {
let queue = Promise.resolve()

return pinnedSessionIds => {
const snapshot = normalize(pinnedSessionIds)

queue = queue
.catch(() => undefined)
.then(async () => {
for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
try {
await save(snapshot)

return
} catch (error) {
if (attempt === maxAttempts) {
throw error
}

await waitForRetry(attempt)
}
}
})

return queue
}
}
Loading