feat: live-sync-client im frontend

- WebSocket-Verbindung nach dem Login, Wiederverbindung mit Backoff (1-30 s)
- nach jeder Wiederverbindung wird die Liste neu geladen
- sofortige Wiederverbindung bei Rückkehr in den Vordergrund (iOS) und online-Event
- Watchdog erkennt tote Verbindungen nach 75 s ohne Nachricht
- Clip-Store übernimmt nur neuere Versionen; Logout leert die lokalen Daten
- Statuspunkt im Header: live / verbinde / offline

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
dbildhauerandClaude Opus 5.5 committed 2026-10-25 11:17:00 +01:00
1 parent 0d89399090
commit e20af699dc
5 files changed
+230 -3

No files matched your search

+19 -2
View File
@@ -24,19 +24,33 @@ export const useClipsStore = defineStore('clips', () => {
const total = ref(0)
const loading = ref(false)
const error = ref<string | null>(null)
const loaded = ref(false)
/** Insert or replace a clip locally (also the entry point for live sync later). */
/**
* Insert or replace a clip locally. Used for API responses and live-sync events;
* an older version never overwrites a newer one, whatever arrives first.
*/
function upsert(clip: Clip): void {
const index = items.value.findIndex((c) => c.id === clip.id)
if (index === -1) {
items.value.push(clip)
total.value += 1
} else {
} else if (items.value[index]!.version <= clip.version) {
items.value[index] = clip
} else {
return
}
items.value.sort(compareClips)
}
/** Forget everything, e.g. on logout so the next user on this device sees nothing. */
function reset(): void {
items.value = []
total.value = 0
error.value = null
loaded.value = false
}
function removeLocal(id: number): void {
const before = items.value.length
items.value = items.value.filter((c) => c.id !== id)
@@ -50,6 +64,7 @@ export const useClipsStore = defineStore('clips', () => {
const page = await api.get<ClipList>(`/clips?limit=${PAGE_SIZE}&offset=0`)
items.value = page.items
total.value = page.total
loaded.value = true
} catch (e) {
error.value = e instanceof Error ? e.message : String(e)
} finally {
@@ -101,8 +116,10 @@ export const useClipsStore = defineStore('clips', () => {
total,
loading,
error,
loaded,
upsert,
removeLocal,
reset,
load,
loadMore,
fetchOne,
+144
View File
@@ -0,0 +1,144 @@
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { notifyUnauthorized } from '@/api/client'
import type { Clip } from '@/api/types'
import { useClipsStore } from '@/stores/clips'
export type SyncStatus = 'offline' | 'connecting' | 'live'
type ServerMessage =
| { type: 'hello' }
| { type: 'ping' }
| { type: 'clip.created' | 'clip.updated'; data: Clip }
| { type: 'clip.deleted'; data: { id: number } }
const MIN_RETRY_MS = 1_000
const MAX_RETRY_MS = 30_000
// Server pings every 30 s; silence beyond this means the connection is dead
const WATCHDOG_MS = 75_000
const CLOSE_UNAUTHORIZED = 4401
/**
* Live sync: receives change events over a WebSocket and applies them to the clip store.
* Writes always go through the REST API; the socket is read-only.
*/
export const useSyncStore = defineStore('sync', () => {
const status = ref<SyncStatus>('offline')
let socket: WebSocket | null = null
let wanted = false
let retryDelay = MIN_RETRY_MS
let retryTimer: ReturnType<typeof setTimeout> | undefined
let watchdogTimer: ReturnType<typeof setTimeout> | undefined
let listenersAdded = false
function handle(message: ServerMessage): void {
const clips = useClipsStore()
switch (message.type) {
case 'hello':
status.value = 'live'
retryDelay = MIN_RETRY_MS
// Events may have been missed while disconnected
if (clips.loaded) void clips.load()
break
case 'clip.created':
case 'clip.updated':
clips.upsert(message.data)
break
case 'clip.deleted':
clips.removeLocal(message.data.id)
break
case 'ping':
break
}
}
function resetWatchdog(ws: WebSocket): void {
clearTimeout(watchdogTimer)
watchdogTimer = setTimeout(() => drop(ws), WATCHDOG_MS)
}
/** Abandon a (possibly half-dead) socket and reconnect. */
function drop(ws: WebSocket): void {
if (socket !== ws) return
ws.onclose = ws.onmessage = ws.onerror = null
ws.close()
socket = null
scheduleReconnect()
}
function connect(): void {
if (!wanted || socket) return
clearTimeout(retryTimer)
status.value = 'connecting'
const scheme = location.protocol === 'https:' ? 'wss' : 'ws'
const ws = new WebSocket(`${scheme}://${location.host}/api/ws`)
socket = ws
resetWatchdog(ws)
ws.onmessage = (event: MessageEvent<string>) => {
resetWatchdog(ws)
try {
handle(JSON.parse(event.data) as ServerMessage)
} catch (e) {
console.warn('Ignoring invalid sync message', e)
}
}
ws.onclose = (event: CloseEvent) => {
if (socket !== ws) return
socket = null
clearTimeout(watchdogTimer)
if (event.code === CLOSE_UNAUTHORIZED) {
stop()
notifyUnauthorized()
return
}
scheduleReconnect()
}
}
function scheduleReconnect(): void {
clearTimeout(watchdogTimer)
status.value = wanted ? 'connecting' : 'offline'
if (!wanted) return
const jitter = 0.5 + Math.random()
retryTimer = setTimeout(connect, retryDelay * jitter)
retryDelay = Math.min(retryDelay * 2, MAX_RETRY_MS)
}
/** Reconnect right away, e.g. when an iPhone brings the app back to the foreground. */
function reconnectNow(): void {
if (!wanted || document.visibilityState !== 'visible') return
if (socket && socket.readyState === WebSocket.OPEN) return
if (socket) drop(socket)
clearTimeout(retryTimer)
retryDelay = MIN_RETRY_MS
connect()
}
function start(): void {
wanted = true
if (!listenersAdded) {
document.addEventListener('visibilitychange', reconnectNow)
window.addEventListener('online', reconnectNow)
listenersAdded = true
}
connect()
}
function stop(): void {
wanted = false
clearTimeout(retryTimer)
clearTimeout(watchdogTimer)
if (socket) {
socket.onclose = socket.onmessage = socket.onerror = null
socket.close(1000)
socket = null
}
status.value = 'offline'
}
return { status, start, stop }
})