Skip to content

Open source file-system and knowledge based agent template. Build AI agents that stay up to date with your knowledge base

feat: improve syncing flow

Hugo Richarde49c3d92877c
diff --git a/apps/chat/app/app.vue b/apps/chat/app/app.vue
index 5dfc3bb..832afe0 100644
--- a/apps/chat/app/app.vue
+++ b/apps/chat/app/app.vue
@@ -3,6 +3,8 @@ const colorMode = useColorMode()
const color = computed(() => colorMode.value === 'dark' ? '#1b1718' : 'white')
+useSnapshotSync()
+
useHead({
meta: [
{ charset: 'utf-8' },
diff --git a/apps/chat/app/composables/useSnapshotSync.ts b/apps/chat/app/composables/useSnapshotSync.ts
new file mode 100644
index 0000000..2f7347b
--- /dev/null
+++ b/apps/chat/app/composables/useSnapshotSync.ts
@@ -0,0 +1,106 @@
+import type { SnapshotSyncStatus } from '~~/shared/types/snapshot'
+
+const POLL_INTERVAL_MS = 5 * 60 * 1000
+
+const status = ref<SnapshotSyncStatus | null>(null)
+const isSyncing = ref(false)
+const isLoading = ref(false)
+const error = ref<string | null>(null)
+const isInitialized = ref(false)
+
+let pollInterval: ReturnType<typeof setInterval> | null = null
+
+export function useSnapshotSync() {
+ const { isAdmin } = useAdmin()
+ const toast = useToast()
+
+ const needsSync = computed(() => status.value?.needsSync ?? false)
+
+ async function syncNow() {
+ if (!isAdmin.value || isSyncing.value) return
+
+ isSyncing.value = true
+ error.value = null
+
+ try {
+ await $fetch('/api/snapshot/sync', { method: 'POST' })
+
+ toast.add({
+ title: 'Snapshot synced',
+ description: 'The application is now using the latest snapshot.',
+ icon: 'i-lucide-check-circle',
+ color: 'success',
+ })
+
+ await checkStatus(false)
+ } catch (e) {
+ const message = (e as Error).message || 'Failed to sync snapshot'
+ error.value = message
+ toast.add({
+ title: 'Sync failed',
+ description: message,
+ icon: 'i-lucide-alert-circle',
+ color: 'error',
+ })
+ } finally {
+ isSyncing.value = false
+ }
+ }
+
+ async function checkStatus(autoSync = true) {
+ if (!isAdmin.value) return
+
+ isLoading.value = true
+ error.value = null
+
+ try {
+ const newStatus = await $fetch<SnapshotSyncStatus>('/api/snapshot/status')
+ status.value = newStatus
+
+ if (autoSync && newStatus.needsSync && !isSyncing.value) {
+ await syncNow()
+ }
+ } catch (e) {
+ error.value = (e as Error).message || 'Failed to check snapshot status'
+ } finally {
+ isLoading.value = false
+ }
+ }
+
+ function startPolling() {
+ if (pollInterval) return
+ pollInterval = setInterval(() => checkStatus(true), POLL_INTERVAL_MS)
+ }
+
+ function stopPolling() {
+ if (pollInterval) {
+ clearInterval(pollInterval)
+ pollInterval = null
+ }
+ }
+
+ onMounted(() => {
+ if (isInitialized.value) return
+ isInitialized.value = true
+
+ watch(isAdmin, (admin) => {
+ if (admin) {
+ checkStatus(true)
+ startPolling()
+ } else {
+ stopPolling()
+ status.value = null
+ }
+ }, { immediate: true })
+ })
+
+ return {
+ status,
+ needsSync,
+ isSyncing,
+ isLoading,
+ error,
+ checkStatus,
+ syncNow,
+ }
+}
diff --git a/apps/chat/app/layouts/admin.vue b/apps/chat/app/layouts/admin.vue
index 04e3830..f0fc9d8 100644
--- a/apps/chat/app/layouts/admin.vue
+++ b/apps/chat/app/layouts/admin.vue
@@ -4,6 +4,12 @@ const navigation = [
label: 'Sources',
icon: 'i-lucide-database',
to: '/admin',
+ exact: true,
+ },
+ {
+ label: 'Sandbox',
+ icon: 'i-lucide-box',
+ to: '/admin/sandbox',
},
]
</script>
diff --git a/apps/chat/app/pages/admin/index.vue b/apps/chat/app/pages/admin/index.vue
index c3f9836..4260593 100644
--- a/apps/chat/app/pages/admin/index.vue
+++ b/apps/chat/app/pages/admin/index.vue
@@ -1,6 +1,11 @@
<script setup lang="ts">
+import { formatDistanceToNow } from 'date-fns'
import { LazyModalConfirm } from '#components'
+const SYNC_REMINDER_DAYS = 7
+const SYNC_REMINDER_MS = SYNC_REMINDER_DAYS * 24 * 60 * 60 * 1000
+const ITEMS_PER_PAGE = 5
+
interface SerializedSource {
id: string
type: 'github' | 'youtube'
@@ -25,10 +30,56 @@ const { data: sources, refresh } = await useFetch('/api/sources')
const editingSource = ref<SerializedSource | null>(null)
const isSyncingAll = ref(false)
+const searchQuery = ref('')
+const githubPage = ref(1)
+const youtubePage = ref(1)
+
const deleteModal = overlay.create(LazyModalConfirm, {
destroyOnClose: true,
})
+const needsSync = computed(() => {
+ if (!sources.value?.lastSyncAt) return true
+ return Date.now() - sources.value.lastSyncAt > SYNC_REMINDER_MS
+})
+
+const lastSyncAgo = computed(() => {
+ if (!sources.value?.lastSyncAt) return null
+ return formatDistanceToNow(sources.value.lastSyncAt, { addSuffix: true })
+})
+
+function filterSources(sourceList: SerializedSource[] | undefined) {
+ if (!sourceList) return []
+ if (!searchQuery.value.trim()) return sourceList
+
+ const query = searchQuery.value.toLowerCase().trim()
+ return sourceList.filter((source) => {
+ const label = source.label.toLowerCase()
+ const repo = source.repo?.toLowerCase() || ''
+ const handle = source.handle?.toLowerCase() || ''
+ const channelId = source.channelId?.toLowerCase() || ''
+ return label.includes(query) || repo.includes(query) || handle.includes(query) || channelId.includes(query)
+ })
+}
+
+const filteredGithubSources = computed(() => filterSources(sources.value?.github?.sources as SerializedSource[] | undefined))
+const filteredYoutubeSources = computed(() => filterSources(sources.value?.youtube?.sources as SerializedSource[] | undefined))
+
+const paginatedGithubSources = computed(() => {
+ const start = (githubPage.value - 1) * ITEMS_PER_PAGE
+ return filteredGithubSources.value.slice(start, start + ITEMS_PER_PAGE)
+})
+
+const paginatedYoutubeSources = computed(() => {
+ const start = (youtubePage.value - 1) * ITEMS_PER_PAGE
+ return filteredYoutubeSources.value.slice(start, start + ITEMS_PER_PAGE)
+})
+
+watch(searchQuery, () => {
+ githubPage.value = 1
+ youtubePage.value = 1
+})
+
async function deleteSource(source: SerializedSource) {
const confirmed = await deleteModal.open({
title: 'Delete Source',
@@ -66,6 +117,7 @@ async function triggerSync(sourceId?: string) {
description: 'The sync workflow has been triggered.',
icon: 'i-lucide-check',
})
+ refresh()
} catch (error: unknown) {
toast.add({
title: 'Error',
@@ -97,27 +149,73 @@ const hasSources = computed(() => (sources.value?.github?.count || 0) + (sources
</p>
</header>
+ <div
+ v-if="hasSources && needsSync"
+ class="mb-6 rounded-lg border border-warning/20 bg-warning/10 p-4"
+ >
+ <div class="flex items-center justify-between gap-4">
+ <div class="flex items-center gap-3">
+ <UIcon name="i-lucide-alert-triangle" class="size-5 text-warning" />
+ <div>
+ <p class="text-sm font-medium text-highlighted">
+ Sources need syncing
+ </p>
+ <p class="text-xs text-muted">
+ <template v-if="lastSyncAgo">
+ Last synced {{ lastSyncAgo }}
+ </template>
+ <template v-else>
+ Never synced
+ </template>
+ </p>
+ </div>
+ </div>
+ <UButton
+ size="xs"
+ color="warning"
+ :loading="isSyncingAll"
+ @click="triggerSync()"
+ >
+ Sync now
+ </UButton>
+ </div>
+ </div>
+
<div
v-if="hasSources"
- class="flex items-center gap-2 mb-6"
+ class="flex flex-col gap-4 mb-6"
>
- <UButton
- icon="i-lucide-refresh-cw"
- color="neutral"
- variant="ghost"
- size="xs"
- :loading="isSyncingAll"
- @click="triggerSync()"
- >
- Sync All
- </UButton>
- <UButton
- icon="i-lucide-plus"
- size="xs"
- to="/admin/new"
- >
- Add Source
- </UButton>
+ <div class="flex items-center gap-2">
+ <UButton
+ icon="i-lucide-refresh-cw"
+ color="neutral"
+ variant="ghost"
+ size="xs"
+ :loading="isSyncingAll"
+ @click="triggerSync()"
+ >
+ Sync All
+ </UButton>
+ <UButton
+ icon="i-lucide-plus"
+ size="xs"
+ to="/admin/new"
+ >
+ Add Source
+ </UButton>
+ <span v-if="lastSyncAgo && !needsSync" class="text-xs text-muted ml-2">
+ Last synced {{ lastSyncAgo }}
+ </span>
+ </div>
+
+ <UInput
+ v-model="searchQuery"
+ icon="i-lucide-search"
+ placeholder="Filter sources..."
+ size="sm"
+ class="max-w-xs"
+ :ui="{ root: 'w-full' }"
+ />
</div>
<div
@@ -144,23 +242,44 @@ const hasSources = computed(() => (sources.value?.github?.count || 0) + (sources
<div v-else class="space-y-8">
<section>
- <p class="text-xs text-muted mb-3">
- GitHub Repositories
- </p>
+ <div class="flex items-center justify-between mb-3">
+ <p class="text-xs text-muted">
+ GitHub Repositories
+ </p>
+ <p v-if="filteredGithubSources.length" class="text-xs text-muted">
+ {{ filteredGithubSources.length }} {{ filteredGithubSources.length === 1 ? 'repository' : 'repositories' }}
+ </p>
+ </div>
- <div
- v-if="sources?.github?.count"
- class="rounded-lg border border-default divide-y divide-default overflow-hidden"
- >
- <div v-for="source in sources.github.sources" :key="source.id" class="px-4 hover:bg-elevated/50 transition-colors">
- <SourceCard
- :source
- @edit="editingSource = source"
- @delete="deleteSource(source)"
- @sync="triggerSync(source.id)"
+ <template v-if="filteredGithubSources.length">
+ <div class="rounded-lg border border-default divide-y divide-default overflow-hidden">
+ <div v-for="source in paginatedGithubSources" :key="source.id" class="px-4 hover:bg-elevated/50 transition-colors">
+ <SourceCard
+ :source
+ @edit="editingSource = source"
+ @delete="deleteSource(source)"
+ @sync="triggerSync(source.id)"
+ />
+ </div>
+ </div>
+ <div v-if="filteredGithubSources.length > ITEMS_PER_PAGE" class="flex justify-center mt-4">
+ <UPagination
+ v-model:page="githubPage"
+ :items-per-page="ITEMS_PER_PAGE"
+ :total="filteredGithubSources.length"
+ :sibling-count="1"
+ show-edges
+ size="sm"
/>
</div>
- </div>
+ </template>
+ <template v-else-if="sources?.github?.count && searchQuery">
+ <div class="py-8 text-center border border-dashed border-default rounded-lg">
+ <p class="text-sm text-muted">
+ No GitHub repositories match your search
+ </p>
+ </div>
+ </template>
<UButton
v-else
color="neutral"
@@ -174,23 +293,44 @@ const hasSources = computed(() => (sources.value?.github?.count || 0) + (sources
</section>
<section>
- <p class="text-xs text-muted mb-3">
- YouTube Channels
- </p>
+ <div class="flex items-center justify-between mb-3">
+ <p class="text-xs text-muted">
+ YouTube Channels
+ </p>
+ <p v-if="filteredYoutubeSources.length" class="text-xs text-muted">
+ {{ filteredYoutubeSources.length }} {{ filteredYoutubeSources.length === 1 ? 'channel' : 'channels' }}
+ </p>
+ </div>
- <div
- v-if="sources?.youtube?.count"
- class="rounded-lg border border-default divide-y divide-default overflow-hidden"
- >
- <div v-for="source in sources.youtube.sources" :key="source.id" class="px-4 hover:bg-elevated/50 transition-colors">
- <SourceCard
- :source
- @edit="editingSource = source"
- @delete="deleteSource(source)"
- @sync="triggerSync(source.id)"
+ <template v-if="filteredYoutubeSources.length">
+ <div class="rounded-lg border border-default divide-y divide-default overflow-hidden">
+ <div v-for="source in paginatedYoutubeSources" :key="source.id" class="px-4 hover:bg-elevated/50 transition-colors">
+ <SourceCard
+ :source
+ @edit="editingSource = source"
+ @delete="deleteSource(source)"
+ @sync="triggerSync(source.id)"
+ />
+ </div>
+ </div>
+ <div v-if="filteredYoutubeSources.length > ITEMS_PER_PAGE" class="flex justify-center mt-4">
+ <UPagination
+ v-model:page="youtubePage"
+ :items-per-page="ITEMS_PER_PAGE"
+ :total="filteredYoutubeSources.length"
+ :sibling-count="1"
+ show-edges
+ size="sm"
/>
</div>
- </div>
+ </template>
+ <template v-else-if="sources?.youtube?.count && searchQuery">
+ <div class="py-8 text-center border border-dashed border-default rounded-lg">
+ <p class="text-sm text-muted">
+ No YouTube channels match your search
+ </p>
+ </div>
+ </template>
<UButton
v-else
color="neutral"
diff --git a/apps/chat/app/pages/admin/sandbox.vue b/apps/chat/app/pages/admin/sandbox.vue
new file mode 100644
index 0000000..2689037
--- /dev/null
+++ b/apps/chat/app/pages/admin/sandbox.vue
@@ -0,0 +1,131 @@
+<script setup lang="ts">
+import { formatDistanceToNow } from 'date-fns'
+
+const {
+ status,
+ needsSync,
+ isSyncing,
+ isLoading,
+ checkStatus,
+ syncNow,
+} = useSnapshotSync()
+
+const createdAgo = computed(() => {
+ if (!status.value?.latestCreatedAt) return null
+ return formatDistanceToNow(status.value.latestCreatedAt, { addSuffix: true })
+})
+
+const isInitialLoading = computed(() => status.value === null)
+</script>
+
+<template>
+ <div class="px-6 lg:px-10 py-8 max-w-3xl">
+ <header class="mb-8">
+ <h1 class="text-lg font-medium text-highlighted mb-1">
+ Sandbox
+ </h1>
+ <p class="text-sm text-muted max-w-lg">
+ Manage sandbox snapshots. Snapshots are pre-configured environments used by the AI to read documentation.
+ </p>
+ </header>
+
+ <section class="mb-8">
+ <p class="text-xs text-muted mb-3">
+ Current Snapshot
+ </p>
+ <div class="rounded-lg border border-default p-4">
+ <div v-if="isInitialLoading" class="space-y-2">
+ <div class="flex items-center gap-2">
+ <USkeleton class="size-2 rounded-full" />
+ <USkeleton class="h-4 w-16" />
+ </div>
+ <USkeleton class="h-3 w-64" />
+ </div>
+ <div v-else-if="status?.currentSnapshotId" class="space-y-2">
+ <div class="flex items-center gap-2">
+ <span class="size-2 rounded-full bg-success" />
+ <span class="text-sm font-medium text-highlighted">Active</span>
+ </div>
+ <p class="text-xs text-muted font-mono">
+ {{ status.currentSnapshotId }}
+ </p>
+ </div>
+ <div v-else class="text-sm text-muted">
+ No snapshot configured. Sync to the latest snapshot to get started.
+ </div>
+ </div>
+ </section>
+
+ <section class="mb-8">
+ <p class="text-xs text-muted mb-3">
+ Latest Available
+ </p>
+ <div class="rounded-lg border border-default p-4">
+ <div class="flex items-center justify-between gap-4">
+ <div class="flex-1 min-w-0">
+ <div v-if="isInitialLoading" class="space-y-2">
+ <div class="flex items-center gap-2">
+ <USkeleton class="size-2 rounded-full" />
+ <USkeleton class="h-4 w-24" />
+ </div>
+ <USkeleton class="h-3 w-64" />
+ <USkeleton class="h-3 w-32" />
+ </div>
+ <div v-else-if="status?.latestSnapshotId" class="space-y-2">
+ <div class="flex items-center gap-2">
+ <span
+ class="size-2 rounded-full"
+ :class="needsSync ? 'bg-warning' : 'bg-success'"
+ />
+ <span class="text-sm font-medium text-highlighted">
+ {{ needsSync ? 'Update available' : 'Up to date' }}
+ </span>
+ </div>
+ <p class="text-xs text-muted font-mono">
+ {{ status.latestSnapshotId }}
+ </p>
+ <p v-if="createdAgo" class="text-xs text-muted">
+ Created {{ createdAgo }}
+ </p>
+ </div>
+ <div v-else class="text-sm text-muted">
+ No snapshots available from Vercel.
+ </div>
+ </div>
+ <div v-if="!isInitialLoading" class="flex items-center gap-2">
+ <UButton
+ icon="i-lucide-refresh-cw"
+ color="neutral"
+ variant="ghost"
+ size="xs"
+ :loading="isLoading"
+ @click="checkStatus"
+ >
+ Refresh
+ </UButton>
+ <UButton
+ v-if="needsSync"
+ size="xs"
+ :loading="isSyncing"
+ @click="syncNow"
+ >
+ Sync now
+ </UButton>
+ </div>
+ </div>
+ </div>
+ </section>
+
+ <section>
+ <div class="rounded-lg bg-elevated/50 p-4 text-xs text-muted space-y-2">
+ <p>
+ <strong class="text-highlighted">How it works:</strong>
+ Snapshots are pre-built sandbox environments created from your documentation repositories.
+ </p>
+ <p>
+ When a new snapshot is created on Vercel, it will be synced automatically.
+ </p>
+ </div>
+ </section>
+ </div>
+</template>
diff --git a/apps/chat/server/api/snapshot/status.get.ts b/apps/chat/server/api/snapshot/status.get.ts
new file mode 100644
index 0000000..de00206
--- /dev/null
+++ b/apps/chat/server/api/snapshot/status.get.ts
@@ -0,0 +1,14 @@
+import { getSnapshotSyncStatus } from '../../utils/sandbox/snapshot-sync'
+import { requireAdmin } from '../../utils/admin'
+
+/**
+ * GET /api/snapshot/status
+ * Returns current snapshot sync status (admin only)
+ *
+ * Response: { currentSnapshotId, latestSnapshotId, needsSync, latestCreatedAt }
+ */
+export default defineEventHandler(async (event) => {
+ await requireAdmin(event)
+
+ return await getSnapshotSyncStatus()
+})
diff --git a/apps/chat/server/api/snapshot/sync.post.ts b/apps/chat/server/api/snapshot/sync.post.ts
new file mode 100644
index 0000000..72b170e
--- /dev/null
+++ b/apps/chat/server/api/snapshot/sync.post.ts
@@ -0,0 +1,19 @@
+import { syncToSnapshot } from '../../utils/sandbox/snapshot-sync'
+import { requireAdmin } from '../../utils/admin'
+
+/**
+ * POST /api/snapshot/sync
+ * Updates KV to use the latest snapshot (admin only)
+ *
+ * Response: { success: true, snapshotId }
+ */
+export default defineEventHandler(async (event) => {
+ await requireAdmin(event)
+
+ const metadata = await syncToSnapshot()
+
+ return {
+ success: true,
+ snapshotId: metadata.snapshotId,
+ }
+})
diff --git a/apps/chat/server/api/sources/index.get.ts b/apps/chat/server/api/sources/index.get.ts
index 57e27d8..8f8930f 100644
--- a/apps/chat/server/api/sources/index.get.ts
+++ b/apps/chat/server/api/sources/index.get.ts
@@ -1,5 +1,7 @@
+import { kv } from '@nuxthub/kv'
import { db, schema } from '@nuxthub/db'
import { asc } from 'drizzle-orm'
+import { KV_KEYS } from '../../utils/sandbox/types'
/**
* GET /api/sources
@@ -8,13 +10,17 @@ import { asc } from 'drizzle-orm'
* Response format matches SourcesResponse from @savoir/sdk
*/
export default defineEventHandler(async () => {
- const allSources = await db.select().from(schema.sources).orderBy(asc(schema.sources.label))
+ const [allSources, lastSyncAt] = await Promise.all([
+ db.select().from(schema.sources).orderBy(asc(schema.sources.label)),
+ kv.get<number>(KV_KEYS.LAST_SOURCE_SYNC),
+ ])
const github = allSources.filter(s => s.type === 'github')
const youtube = allSources.filter(s => s.type === 'youtube')
return {
total: allSources.length,
+ lastSyncAt,
github: {
count: github.length,
sources: github,
diff --git a/apps/chat/server/api/sync/index.post.ts b/apps/chat/server/api/sync/index.post.ts
index 8c481ce..79d6a22 100644
--- a/apps/chat/server/api/sync/index.post.ts
+++ b/apps/chat/server/api/sync/index.post.ts
@@ -1,7 +1,9 @@
+import { kv } from '@nuxthub/kv'
import { start } from 'workflow/api'
import { z } from 'zod'
import { syncDocumentation } from '../../workflows/sync-docs'
import type { GitHubSource } from '../../workflows/sync-docs'
+import { KV_KEYS } from '../../utils/sandbox/types'
const bodySchema = z
.object({
@@ -65,6 +67,9 @@ export default defineEventHandler(async (event) => {
await start(syncDocumentation, [syncConfig, sources])
+ // Track last sync time
+ await kv.set(KV_KEYS.LAST_SOURCE_SYNC, Date.now())
+
return {
status: 'started',
message: `Sync workflow started for ${sources.length} source(s).`,
diff --git a/apps/chat/server/utils/sandbox/snapshot-sync.ts b/apps/chat/server/utils/sandbox/snapshot-sync.ts
new file mode 100644
index 0000000..709f515
--- /dev/null
+++ b/apps/chat/server/utils/sandbox/snapshot-sync.ts
@@ -0,0 +1,102 @@
+import { kv } from '@nuxthub/kv'
+import { Snapshot } from '@vercel/sandbox'
+import type { SnapshotMetadata, SnapshotSyncStatus } from './types'
+import { KV_KEYS } from './types'
+import { getCurrentSnapshot, setCurrentSnapshot } from './snapshot'
+
+const CACHE_TTL_MS = 60 * 1000
+
+interface CachedSnapshotStatus {
+ latestSnapshotId: string | null
+ latestCreatedAt: number | null
+ cachedAt: number
+}
+
+interface VercelSnapshot {
+ id: string
+ region: string
+ status: 'failed' | 'created' | 'deleted'
+ createdAt: number
+ updatedAt: number
+ sourceSandboxId: string
+ sizeBytes: number
+ expiresAt: number
+}
+
+export async function listSnapshots(): Promise<VercelSnapshot[]> {
+ const result = await Snapshot.list()
+ return result.json.snapshots
+}
+
+export async function getLatestSnapshot(): Promise<VercelSnapshot | null> {
+ const snapshots = await listSnapshots()
+
+ const validSnapshots = snapshots
+ .filter((s: VercelSnapshot) => s.status === 'created')
+ .sort((a: VercelSnapshot, b: VercelSnapshot) => b.createdAt - a.createdAt)
+
+ return validSnapshots[0] ?? null
+}
+
+async function getCachedLatestSnapshot(): Promise<CachedSnapshotStatus> {
+ const cached = await kv.get<CachedSnapshotStatus>(KV_KEYS.SNAPSHOT_STATUS_CACHE)
+
+ if (cached && Date.now() - cached.cachedAt < CACHE_TTL_MS) {
+ return cached
+ }
+
+ const latest = await getLatestSnapshot()
+ const freshCache: CachedSnapshotStatus = {
+ latestSnapshotId: latest?.id ?? null,
+ latestCreatedAt: latest?.createdAt ?? null,
+ cachedAt: Date.now(),
+ }
+
+ await kv.set(KV_KEYS.SNAPSHOT_STATUS_CACHE, freshCache)
+
+ return freshCache
+}
+
+export async function getSnapshotSyncStatus(): Promise<SnapshotSyncStatus> {
+ const [current, cached] = await Promise.all([
+ getCurrentSnapshot(),
+ getCachedLatestSnapshot(),
+ ])
+
+ const currentSnapshotId = current?.snapshotId ?? null
+ const { latestSnapshotId, latestCreatedAt } = cached
+ const needsSync = latestSnapshotId !== null && latestSnapshotId !== currentSnapshotId
+
+ return {
+ currentSnapshotId,
+ latestSnapshotId,
+ needsSync,
+ latestCreatedAt,
+ }
+}
+
+export async function syncToSnapshot(snapshotId?: string): Promise<SnapshotMetadata> {
+ let targetSnapshotId = snapshotId
+
+ if (!targetSnapshotId) {
+ const latest = await getLatestSnapshot()
+ if (!latest) {
+ throw new Error('No snapshots available to sync to')
+ }
+ targetSnapshotId = latest.id
+ }
+
+ const snapshot = await Snapshot.get({ snapshotId: targetSnapshotId })
+ const config = useRuntimeConfig()
+
+ const metadata: SnapshotMetadata = {
+ snapshotId: snapshot.snapshotId,
+ createdAt: Date.now(),
+ sourceRepo: config.github.snapshotRepo || '',
+ }
+
+ await setCurrentSnapshot(metadata)
+ await kv.del(KV_KEYS.SNAPSHOT_STATUS_CACHE)
+
+ return metadata
+}
diff --git a/apps/chat/server/utils/sandbox/types.ts b/apps/chat/server/utils/sandbox/types.ts
index d4e5805..9da3a42 100644
--- a/apps/chat/server/utils/sandbox/types.ts
+++ b/apps/chat/server/utils/sandbox/types.ts
@@ -73,5 +73,7 @@ export interface ActiveSandbox {
*/
export const KV_KEYS = {
CURRENT_SNAPSHOT: 'snapshot:current',
+ SNAPSHOT_STATUS_CACHE: 'snapshot:status-cache',
+ LAST_SOURCE_SYNC: 'sources:last-sync',
session: (sessionId: string) => `session:${sessionId}`,
} as const
diff --git a/apps/chat/shared/types/snapshot.ts b/apps/chat/shared/types/snapshot.ts
new file mode 100644
index 0000000..373ec50
--- /dev/null
+++ b/apps/chat/shared/types/snapshot.ts
@@ -0,0 +1,6 @@
+export interface SnapshotSyncStatus {
+ currentSnapshotId: string | null
+ latestSnapshotId: string | null
+ needsSync: boolean
+ latestCreatedAt: number | null
+}
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 506c0b0..f1143e1 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -99,6 +99,9 @@ savoir/
│ │ └── plugins/ # Nitro plugins
│ │ └── logger.ts
│ └── nuxt.config.ts
+├── shared/
+│ └── types/
+│ └── snapshot.ts # SnapshotSyncStatus type
├── packages/
│ ├── sdk/ # @savoir/sdk
│ │ └── src/
@@ -329,6 +332,34 @@ Sync a specific source.
}
```
+### Snapshot Endpoints
+
+#### GET /api/snapshot/status
+
+Get current vs latest snapshot status. Returns whether the sandbox needs to sync to a newer snapshot. Admin only.
+
+**Response:**
+```json
+{
+ "currentSnapshotId": "snap_abc123",
+ "latestSnapshotId": "snap_def456",
+ "needsSync": true,
+ "latestCreatedAt": 1706400000000
+}
+```
+
+#### POST /api/snapshot/sync
+
+Sync sandbox to the latest Vercel snapshot. Admin only.
+
+**Response:**
+```json
+{
+ "status": "synced",
+ "snapshotId": "snap_def456"
+}
+```
+
### Sources Endpoints
#### GET /api/sources
@@ -366,6 +397,12 @@ Used for caching and session management:
// Active sandbox sessions
`session:${sessionId}` -> { sandboxId: string, snapshotId: string, ... }
+
+// Snapshot status cache (1 min TTL)
+`snapshot:status-cache` -> { latestSnapshotId: string, latestCreatedAt: number, cachedAt: number }
+
+// Last source sync timestamp
+`sources:last-sync` -> number (timestamp)
```
### Snapshot Repository
diff --git a/docs/LOGGING.md b/docs/LOGGING.md
deleted file mode 100644
index d2def20..0000000
--- a/docs/LOGGING.md
+++ /dev/null
@@ -1,73 +0,0 @@
-# Logging
-
-Use `@savoir/logger` for all logging.
-
-## Simple Logs
-
-For workflow progress and general logging:
-
-```typescript
-import { getLogger } from '@savoir/logger'
-
-const logger = getLogger()
-
-logger.log('sandbox', `Created: ${sandboxId}`)
-logger.log('sync', `${sourceId}: synced ${fileCount} files`)
-```
-
-## Wide Events
-
-For request logging (one event per request):
-
-```typescript
-import { getLogger } from '@savoir/logger'
-
-const logger = getLogger()
-
-export default defineEventHandler(async (event) => {
- const log = logger.request({
- method: event.method,
- path: event.path,
- })
-
- try {
- const user = await getUser(event)
- log.set({ userId: user.id, plan: user.plan })
-
- const result = await doWork()
- log.set({ itemCount: result.items.length })
-
- return result
- } catch (error) {
- log.error(error)
- throw error
- } finally {
- log.emit()
- }
-})
-```
-
-## Structured Errors
-
-```typescript
-import { createError } from '@savoir/logger'
-
-throw createError({
- message: 'Failed to sync repository',
- why: 'GitHub API rate limit exceeded',
- fix: 'Wait 1 hour or use a different token',
- link: 'https://docs.github.com/en/rest/rate-limit',
- cause: originalError,
-})
-```
-
-## What to Log
-
-**Good logs include:**
-- Unique identifiers (`sandboxId`, `sessionId`, `userId`)
-- Quantifiable metrics (`count`, `fileCount`)
-- Final summaries with statistics
-
-**Avoid:**
-- Obvious steps: `logger.log('sync', 'Taking snapshot...')`
-- Messages without data: `logger.log('sync', 'No changes')`
diff --git a/docs/SOURCES.md b/docs/SOURCES.md
index ca80abd..91efcdb 100644
--- a/docs/SOURCES.md
+++ b/docs/SOURCES.md
@@ -147,6 +147,16 @@ curl -X POST http://localhost:3000/api/sync/nuxt \
-H "Authorization: Bearer $SAVOIR_SECRET_KEY"
```
+### Sync Tracking
+
+The system tracks when sources were last synced:
+
+- `lastSyncAt` timestamp is stored in KV after each successful sync
+- `GET /api/sources` returns the `lastSyncAt` value
+- Admin UI (`/admin`) shows a reminder if the last sync was more than 7 days ago
+
+This helps ensure documentation stays up-to-date by providing visibility into sync freshness.
+
## Content Normalization
All content is normalized to Markdown: