Skip to content
Open
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
112 changes: 112 additions & 0 deletions ui/composables/useCardsMode.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
import { describe, expect, it, vi } from 'vitest'
import type { CardsPileState, CardsSharedState } from '../../src/devframe/rpc/types'
import type { ListItem } from '../types/list-item'
import { DEFAULT_PILE_OPTIONS, useCardsMode } from './useCardsMode'

type Listener = (next: CardsSharedState) => void

const shared = vi.hoisted(() => {
const listeners = new Set<Listener>()
const handle = {
current: { pile: null } as CardsSharedState,
value(): CardsSharedState {
return this.current
},
on(_event: 'updated', fn: Listener): () => void {
listeners.add(fn)
return () => {
listeners.delete(fn)
}
},
mutate(recipe: (draft: CardsSharedState) => void): void {
recipe(this.current)
for (const fn of listeners)
fn(this.current)
},
emit(next: CardsSharedState): void {
this.current = next
for (const fn of listeners)
fn(next)
},
}
let resolveGet: (state: typeof handle) => void = () => {}
const pendingGet = new Promise<typeof handle>((resolve) => {
resolveGet = resolve
})
return { handle, pendingGet, resolveGet }
})

vi.mock('#imports', () => ({
useRouter: () => ({
currentRoute: { value: { path: '/' } },
push: async () => {},
}),
useRoute: () => ({ path: '/' }),
}))

vi.mock('./useRpc', () => ({
useRpcClient: async () => ({
sharedState: {
get: () => shared.pendingGet,
},
}),
}))

vi.mock('./useSeenHistory', () => ({
useSeenHistory: () => ({ getSeenEntry: () => undefined }),
}))

vi.mock('./useUiState', () => ({
useUiState: () => ({
isTodo: () => false,
isIgnored: () => false,
}),
}))

vi.mock('./useProjectPayload', () => ({
useProjectPayload: () => ({ ensureLoaded: async () => {} }),
}))

function item(number: number): ListItem {
return {
key: `p-issue-${number}`,
projectId: 'p',
repo: 'o/r',
kind: 'issue',
number,
title: `Issue ${number}`,
state: 'open',
author: 'octocat',
updatedAt: `2026-01-0${number}T00:00:00.000Z`,
}
}

const emptyPile: CardsPileState = {
pile: [],
index: 0,
processedOps: [],
source: { label: 'Cards' },
options: { ...DEFAULT_PILE_OPTIONS },
}

describe('useCardsMode start', () => {
it('keeps a pile built locally when the server then echoes an empty one', async () => {
const cards = useCardsMode()
const started = cards.start(
[item(1), item(2)],
{ label: 'Cards' },
{ ...DEFAULT_PILE_OPTIONS, excludeSeen: false, size: 10 },
null,
)

await Promise.resolve()
shared.resolveGet(shared.handle)
await Promise.resolve()
shared.handle.emit({ pile: emptyPile })

await started

expect(cards.pile.value.map(card => card.number)).toEqual([2, 1])
expect(shared.handle.current.pile?.pile.map(card => card.number)).toEqual([2, 1])
})
})
46 changes: 30 additions & 16 deletions ui/composables/useCardsMode.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { computed, ref } from 'vue'
import { computed, ref, toRaw } from 'vue'
import { useRoute, useRouter } from '#imports'
import type {
CardRef,
Expand Down Expand Up @@ -79,18 +79,18 @@ let saveFn: (() => void) | null = null
* reply to the initial `get`). Falls back to a timeout so a server that
* has nothing saved still releases the hydrate spinner.
*/
function waitForFirstUpdate<T>(state: SharedState<T>, timeoutMs = 1500): Promise<void> {
return new Promise<void>((resolve) => {
function waitForFirstUpdate<T>(state: SharedState<T>, timeoutMs = 1500): Promise<boolean> {
return new Promise<boolean>((resolve) => {
let settled = false
const finish = () => {
const finish = (updated: boolean) => {
if (settled)
return
settled = true
off()
resolve()
resolve(updated)
}
const off = state.on('updated', finish)
setTimeout(finish, timeoutMs)
const off = state.on('updated', () => finish(true))
setTimeout(() => finish(false), timeoutMs)
})
}

Expand All @@ -104,12 +104,17 @@ async function ensureShared(): Promise<SharedState<CardsSharedState>> {
const state = await client.sharedState.get('ghfs:cards-pile', {
initialValue: { pile: null },
})
// The client returns the local initialValue immediately; the server
// reply arrives asynchronously and fires `updated`. Block hydrate
// on it so the page doesn't flash empty → loaded for a saved pile.
await waitForFirstUpdate(state)
applyServerState(state.value().pile ?? null)
// Subscribe before the first read. `sharedState.get` applies the server
// reply through a second `mutate`, which fires `updated` again, and that
// reply can land after `start()` has already written a fresh pile.
// Missing it lets the empty initial value overwrite the pile the user
// just created.
state.on('updated', (next) => applyServerState(next.pile ?? null))
// Only read back when the server actually replied. On timeout the value
// is still the empty initialValue, and applying it would wipe a pile
// `start()` wrote while this promise was in flight.
if (await waitForFirstUpdate(state))
applyServerState(state.value().pile ?? null)
sharedHandle = state
return state
})()
Expand Down Expand Up @@ -291,16 +296,25 @@ function pickFromCandidates(
}

function snapshot(): CardsPileState {
// `source` and `options` live in reactive() proxies. immer freezes the
// draft and then reads these back; a Vue proxy refuses that read, so hand
// immer plain objects.
return {
pile: pile.value,
pile: pile.value.map(card => ({ ...card })),
index: index.value,
processedOps: processedOps.value,
source: source.value,
options: options.value,
processedOps: processedOps.value.map(op => ({ ...op })),
source: { ...toRaw(source.value) },
options: { ...toRaw(options.value) },
}
}

function applyServerState(next: CardsPileState | null): void {
// A server echo can arrive after `start()` has already built a pile locally
// but before that pile is persisted. Applying the stale empty value here
// wipes it, and the following persist then saves the empty pile.
const incoming = next?.pile.length ?? 0
if (incoming === 0 && pile.value.length > 0)
return
if (!next) {
pile.value = []
index.value = 0
Expand Down
10 changes: 10 additions & 0 deletions vitest.config.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,16 @@
import { fileURLToPath } from 'node:url'
import { defineConfig } from 'vitest/config'

const fromRoot = (path: string) => fileURLToPath(new URL(path, import.meta.url))

export default defineConfig({
resolve: {
alias: {
// The root package does not depend on vue, but the UI does. Point
// tests at the copy pnpm already installed for it.
vue: fromRoot('./node_modules/.pnpm/node_modules/vue'),
},
},
test: {
exclude: [
'**/node_modules/**',
Expand Down