From 6c49f849b7f9a7251ed3129886b926fe26709262 Mon Sep 17 00:00:00 2001 From: Qijun Date: Fri, 2 Oct 2026 22:31:16 -0700 Subject: [PATCH] feat: keep a project in step with a deployment's remote source A deployment can name a remote source with GAMMA_SOURCE_NAME and GAMMA_SOURCE_URL, served at /api/source. The reader then opens one project for that source and checks it when the library opens and when the reader returns to it. When the source has changed it says so, and Sync brings in added and changed files and removes the ones that left. A file edited in the library since the last sync is kept rather than replaced, and counts as synced, so its next version arrives once the edit reaches the source. The source is any address serving a listing of paths and opaque versions and each file under its path; the reader knows nothing about where it comes from or who may read it. --- ui-packages/web/src/core/projects.ts | 8 ++ ui-packages/web/src/data/project-store.ts | 20 ++- .../web/src/data/workspace-database.ts | 1 + .../src/features/resources/resource-panel.tsx | 2 + .../features/resources/use-file-library.ts | 1 + .../web/src/features/source/load-source.ts | 15 ++ .../web/src/features/source/plan.test.ts | 61 ++++++++ ui-packages/web/src/features/source/plan.ts | 63 +++++++++ .../web/src/features/source/protocol.ts | 36 +++++ .../web/src/features/source/sync-status.tsx | 50 +++++++ .../src/features/source/use-source-sync.ts | 131 ++++++++++++++++++ ui-packages/web/src/shell/project-root.tsx | 9 ++ .../src/shell/projects.integration.test.tsx | 72 +++++++++- ui-packages/web/src/styles.css | 22 +++ ui-packages/web/src/test/setup.ts | 1 + web-packages/server/src/app.test.ts | 12 ++ web-packages/server/src/app.ts | 5 + web-packages/server/src/main.ts | 4 +- web-packages/server/src/source-config.ts | 11 ++ 19 files changed, 520 insertions(+), 4 deletions(-) create mode 100644 ui-packages/web/src/features/source/load-source.ts create mode 100644 ui-packages/web/src/features/source/plan.test.ts create mode 100644 ui-packages/web/src/features/source/plan.ts create mode 100644 ui-packages/web/src/features/source/protocol.ts create mode 100644 ui-packages/web/src/features/source/sync-status.tsx create mode 100644 ui-packages/web/src/features/source/use-source-sync.ts create mode 100644 web-packages/server/src/source-config.ts diff --git a/ui-packages/web/src/core/projects.ts b/ui-packages/web/src/core/projects.ts index 29957ef..b467789 100644 --- a/ui-packages/web/src/core/projects.ts +++ b/ui-packages/web/src/core/projects.ts @@ -1,9 +1,13 @@ +// A remote source the project's library is kept in step with, named by the deployment. +export type ProjectSource = { name: string; url: string } + export type Project = { id: string name: string databaseName: string createdAt: number lastActiveAt: number + source?: ProjectSource } // The library that existed before projects keeps its name, so upgrading moves no data. @@ -12,6 +16,10 @@ export const defaultProjectName = 'My reading' export const projectPath = (projectId: string) => `/p/${projectId}` +// One project per source, found again by its name on every visit. +export const sourceProjectId = (source: ProjectSource) => + `source-${encodeURIComponent(source.name.toLowerCase())}` + export const projectDeletionPath = (projectId: string) => `/?delete=${encodeURIComponent(projectId)}` diff --git a/ui-packages/web/src/data/project-store.ts b/ui-packages/web/src/data/project-store.ts index db310d2..c7f8c79 100644 --- a/ui-packages/web/src/data/project-store.ts +++ b/ui-packages/web/src/data/project-store.ts @@ -5,6 +5,8 @@ import { legacyDatabaseName, normalizeProjectName, type Project, + type ProjectSource, + sourceProjectId, } from '../core/projects' import { deleteIndexedDatabase, @@ -19,8 +21,7 @@ type ProjectDatabase = DBSchema & { const registryName = 'gamma-reader-projects' let registryPromise: Promise> | undefined -const newProject = (name: string, databaseName?: string): Project => { - const id = nanoid(10) +const newProject = (name: string, databaseName?: string, id = nanoid(10)): Project => { const now = Date.now() return { id, @@ -66,6 +67,21 @@ export const createProject = async (name: string) => { return project } +// The deployment's source decides the project, so a visit always lands in the same library, and +// the address it records follows the deployment if that changes. +export const openSourceProject = async (source: ProjectSource) => { + const database = await openRegistry() + const id = sourceProjectId(source) + const existing = await database.get('projects', id) + const project = { + ...(existing ?? newProject(source.name, undefined, id)), + source, + lastActiveAt: Date.now(), + } + await database.put('projects', project) + return project +} + export const renameProject = async (id: string, name: string) => { const database = await openRegistry() const project = await database.get('projects', id) diff --git a/ui-packages/web/src/data/workspace-database.ts b/ui-packages/web/src/data/workspace-database.ts index 23ca36e..e1dc04e 100644 --- a/ui-packages/web/src/data/workspace-database.ts +++ b/ui-packages/web/src/data/workspace-database.ts @@ -43,6 +43,7 @@ export const setWorkspaceDatabaseName = (name: string) => { export const workspaceStorageBases = { workspace: 'gamma-reader.workspace', activeConversation: 'gamma-reader.active-conversation', + sourceSync: 'gamma-reader.source-sync', } as const // Settings saved before projects existed belong to the legacy library and keep their keys. diff --git a/ui-packages/web/src/features/resources/resource-panel.tsx b/ui-packages/web/src/features/resources/resource-panel.tsx index 07ffdbc..a7b18af 100644 --- a/ui-packages/web/src/features/resources/resource-panel.tsx +++ b/ui-packages/web/src/features/resources/resource-panel.tsx @@ -5,6 +5,7 @@ import type { Project } from '../../core/projects' import { useSourceDrafts } from '../../shell/workspace-context' import { sourceDirty } from '../../shell/workspace-store' import { ProjectSwitcher } from '../projects/project-switcher' +import { SourceSyncStatus } from '../source/sync-status' import { AddFromUrlDialog } from './add-from-url-dialog' import { AddMenu } from './add-menu' import { DuplicateFilesDialog, RemoveFileDialog, RemoveFolderDialog } from './file-dialogs' @@ -163,6 +164,7 @@ export const ResourcePanel = ({ }} /> + {project.source && } {library.progress && (

{library.progress} diff --git a/ui-packages/web/src/features/resources/use-file-library.ts b/ui-packages/web/src/features/resources/use-file-library.ts index 402612a..22cf5c9 100644 --- a/ui-packages/web/src/features/resources/use-file-library.ts +++ b/ui-packages/web/src/features/resources/use-file-library.ts @@ -316,6 +316,7 @@ export const useFileLibrary = (prepareFile: (file: File) => File = keepFile) => updateTextFile, resolveDuplicates, removeFiles, + reload, retry: () => { setLoading(true) void reload() diff --git a/ui-packages/web/src/features/source/load-source.ts b/ui-packages/web/src/features/source/load-source.ts new file mode 100644 index 0000000..43c68af --- /dev/null +++ b/ui-packages/web/src/features/source/load-source.ts @@ -0,0 +1,15 @@ +import type { ProjectSource } from '../../core/projects' +import { isProjectSource } from './protocol' + +// Most deployments have no source and answer 404; one that cannot be asked opens as they do. +export const loadProjectSource = async (): Promise => { + try { + const response = await fetch('/api/source', { cache: 'no-store' }) + if (!response.ok) return null + const body: unknown = await response.json() + return isProjectSource(body) ? body : null + } catch (cause) { + console.error('Unable to read the source configuration', cause) + return null + } +} diff --git a/ui-packages/web/src/features/source/plan.test.ts b/ui-packages/web/src/features/source/plan.test.ts new file mode 100644 index 0000000..cdccd19 --- /dev/null +++ b/ui-packages/web/src/features/source/plan.test.ts @@ -0,0 +1,61 @@ +import { describe, expect, it } from 'vitest' +import { planSync, type SyncSnapshot, snapshotAfter } from './plan' + +const listing = (files: Record) => ({ + version: Object.values(files).join('-'), + files: Object.entries(files).map(([path, version]) => ({ path, version, size: 1 })), +}) + +const previous: SyncSnapshot = { + version: 'old', + files: { + 'notes/same.md': { version: 'a', revision: 1 }, + 'notes/changed.md': { version: 'b', revision: 1 }, + 'notes/edited.md': { version: 'c', revision: 1 }, + 'notes/gone.md': { version: 'd', revision: 1 }, + 'notes/gone-edited.md': { version: 'e', revision: 1 }, + }, +} +const local = [ + { id: 'same', path: 'notes/same.md', revision: 1 }, + { id: 'changed', path: 'notes/changed.md', revision: 1 }, + { id: 'edited', path: 'notes/edited.md', revision: 2 }, + { id: 'gone', path: 'notes/gone.md', revision: 1 }, + { id: 'gone-edited', path: 'notes/gone-edited.md', revision: 3 }, + { id: 'mine', path: 'notes/mine.md', revision: 1 }, +] + +describe('source sync plan', () => { + it('brings in changes, removes what left the source and keeps edits made here', () => { + const next = listing({ + 'notes/same.md': 'a', + 'notes/changed.md': 'b2', + 'notes/edited.md': 'c2', + 'notes/new.md': 'f', + }) + + const plan = planSync(previous, next, local) + + expect(plan.download.map(file => file.path)).toEqual(['notes/changed.md', 'notes/new.md']) + expect(plan.remove).toEqual(['gone']) + expect(plan.kept).toEqual(['notes/edited.md', 'notes/gone-edited.md']) + }) + + it('adds everything to an empty library and keeps a file it already holds', () => { + const plan = planSync(null, listing({ 'a.md': '1', 'notes/mine.md': '2' }), local) + + expect(plan.download.map(file => file.path)).toEqual(['a.md']) + expect(plan.kept).toEqual(['notes/mine.md']) + }) + + it('records kept edits as synced so the next version of them arrives', () => { + const next = listing({ 'notes/edited.md': 'c2' }) + const snapshot = snapshotAfter(next, local) + + expect(snapshot).toEqual({ + version: next.version, + files: { 'notes/edited.md': { version: 'c2', revision: 2 } }, + }) + expect(planSync(snapshot, listing({ 'notes/edited.md': 'c3' }), local).download).toHaveLength(1) + }) +}) diff --git a/ui-packages/web/src/features/source/plan.ts b/ui-packages/web/src/features/source/plan.ts new file mode 100644 index 0000000..b285703 --- /dev/null +++ b/ui-packages/web/src/features/source/plan.ts @@ -0,0 +1,63 @@ +import type { SourceFile, SourceListing } from './protocol' + +// What the library held after the last sync: each source file's version, and the revision the +// library gave it, so a later edit in the library can be told apart from the copy that arrived. +export type SyncSnapshot = { + version: string + files: Record +} + +type LocalFile = { id: string; path: string; revision: number } + +export type SyncPlan = { + download: SourceFile[] + remove: string[] + // Edited here since the last sync, so the library keeps its own copy. + kept: string[] +} + +// Paths in the library are matched without regard to case, as the store matches them. +const byPath = (files: readonly LocalFile[]) => + new Map(files.map(file => [file.path.toLowerCase(), file])) + +export const planSync = ( + previous: SyncSnapshot | null, + listing: SourceListing, + local: readonly LocalFile[], +): SyncPlan => { + const here = byPath(local) + const edited = (path: string) => { + const file = here.get(path.toLowerCase()) + const synced = previous?.files[path] + return file !== undefined && file.revision !== synced?.revision + } + const changed = listing.files.filter(file => previous?.files[file.path]?.version !== file.version) + const listed = new Set(listing.files.map(file => file.path)) + const gone = Object.keys(previous?.files ?? {}).filter(path => !listed.has(path)) + return { + download: changed.filter(file => !edited(file.path)), + remove: gone.flatMap(path => { + const file = here.get(path.toLowerCase()) + return file && !edited(path) ? [file.id] : [] + }), + kept: [...changed, ...gone.map(path => ({ path }))].map(file => file.path).filter(edited), + } +} + +// Every listed file the library now holds counts as synced at its current revision, including a +// kept edit: once that edit is pushed to the source, its next version arrives as usual. +export const snapshotAfter = ( + listing: SourceListing, + local: readonly LocalFile[], +): SyncSnapshot => { + const here = byPath(local) + return { + version: listing.version, + files: Object.fromEntries( + listing.files.flatMap(file => { + const held = here.get(file.path.toLowerCase()) + return held ? [[file.path, { version: file.version, revision: held.revision }]] : [] + }), + ), + } +} diff --git a/ui-packages/web/src/features/source/protocol.ts b/ui-packages/web/src/features/source/protocol.ts new file mode 100644 index 0000000..9483dc3 --- /dev/null +++ b/ui-packages/web/src/features/source/protocol.ts @@ -0,0 +1,36 @@ +import type { ProjectSource } from '../../core/projects' + +// What a remote source serves: one listing, and each file under its path. Versions are opaque; +// they only have to change when the content does. +export type SourceFile = { path: string; version: string; size: number } +export type SourceListing = { version: string; files: SourceFile[] } + +const isSourceFile = (value: unknown): value is SourceFile => + typeof value === 'object' && + value !== null && + 'path' in value && + typeof value.path === 'string' && + 'version' in value && + typeof value.version === 'string' && + 'size' in value && + typeof value.size === 'number' + +export const isSourceListing = (value: unknown): value is SourceListing => + typeof value === 'object' && + value !== null && + 'version' in value && + typeof value.version === 'string' && + 'files' in value && + Array.isArray(value.files) && + value.files.every(isSourceFile) + +export const isProjectSource = (value: unknown): value is ProjectSource => + typeof value === 'object' && + value !== null && + 'name' in value && + typeof value.name === 'string' && + 'url' in value && + typeof value.url === 'string' + +export const sourceFileUrl = (source: ProjectSource, path: string) => + `${source.url.replace(/\/$/, '')}/files/${path.split('/').map(encodeURIComponent).join('/')}` diff --git a/ui-packages/web/src/features/source/sync-status.tsx b/ui-packages/web/src/features/source/sync-status.tsx new file mode 100644 index 0000000..3472337 --- /dev/null +++ b/ui-packages/web/src/features/source/sync-status.tsx @@ -0,0 +1,50 @@ +import { RefreshCw } from 'lucide-react' +import type { ProjectSource } from '../../core/projects' +import { useSourceSync } from './use-source-sync' + +const fileCount = (count: number) => `${count.toLocaleString()} ${count === 1 ? 'file' : 'files'}` + +// One line under the toolbar: whether the source has changed, and the action that brings it in. +export const SourceSyncStatus = ({ + source, + reload, +}: { + source: ProjectSource + reload: () => Promise +}) => { + const { state, sync } = useSourceSync(source, reload) + const message = + state.kind === 'checking' + ? `Checking ${source.name}…` + : state.kind === 'current' + ? `${source.name} is up to date.` + : state.kind === 'available' + ? `${source.name} has changes.` + : state.kind === 'syncing' + ? `Syncing ${source.name}… ${state.done.toLocaleString()} of ${fileCount(state.total)}` + : state.kind === 'synced' + ? [ + `${source.name} is up to date.`, + state.kept.length + ? `Kept your edits to ${fileCount(state.kept.length)}: ${state.kept.join(', ')}.` + : '', + state.refused + ? `${fileCount(state.refused)} did not fit the library limits.` + : '', + ] + .filter(Boolean) + .join(' ') + : state.message + const actionable = state.kind === 'available' || state.kind === 'failed' + return ( +

+ {message} + {actionable && ( + + )} +
+ ) +} diff --git a/ui-packages/web/src/features/source/use-source-sync.ts b/ui-packages/web/src/features/source/use-source-sync.ts new file mode 100644 index 0000000..1ea77c0 --- /dev/null +++ b/ui-packages/web/src/features/source/use-source-sync.ts @@ -0,0 +1,131 @@ +import { useCallback, useEffect, useRef, useState } from 'react' +import { baseName } from '../../core/files' +import type { ProjectSource } from '../../core/projects' +import { importStoredFiles, listStoredFiles, removeStoredFiles } from '../../data/file-store' +import { workspaceStorageBases, workspaceStorageKey } from '../../data/workspace-database' +import { planSync, type SyncSnapshot, snapshotAfter } from './plan' +import { isSourceListing, type SourceFile, sourceFileUrl } from './protocol' + +export type SourceSyncState = + | { kind: 'checking' } + | { kind: 'current' } + | { kind: 'available' } + | { kind: 'syncing'; done: number; total: number } + | { kind: 'synced'; kept: string[]; refused: number } + | { kind: 'failed'; message: string } + +// The source is checked when the library opens and whenever the reader comes back to it, but +// not more than once a minute. +const checkInterval = 60_000 +const downloadsAtOnce = 6 + +class SourceError extends Error {} + +const snapshotKey = () => workspaceStorageKey(workspaceStorageBases.sourceSync) + +const readSnapshot = (): SyncSnapshot | null => { + const raw = localStorage.getItem(snapshotKey()) + return raw ? (JSON.parse(raw) as SyncSnapshot) : null +} + +const fetchOk = async (url: string) => { + const response = await fetch(url, { cache: 'no-store' }) + if (!response.ok) throw new SourceError(`The source returned HTTP ${response.status}.`) + return response +} + +const fetchListing = async (source: ProjectSource) => { + const listing: unknown = await (await fetchOk(source.url)).json() + if (!isSourceListing(listing)) + throw new SourceError('The source sent a listing it could not read.') + return listing +} + +const libraryFiles = async () => + (await listStoredFiles()).filter(file => (file.collection ?? 'files') === 'files') + +const downloadAll = async ( + source: ProjectSource, + files: readonly SourceFile[], + onDone: (done: number) => void, +) => { + const sources: { path: string; file: File }[] = [] + let next = 0 + let done = 0 + const work = async () => { + for (let index = next++; index < files.length; index = next++) { + const { path } = files[index] as SourceFile + const response = await fetchOk(sourceFileUrl(source, path)) + const type = response.headers.get('content-type')?.split(';')[0]?.trim() ?? '' + sources[index] = { path, file: new File([await response.blob()], baseName(path), { type }) } + done += 1 + onDone(done) + } + } + await Promise.all(Array.from({ length: Math.min(downloadsAtOnce, files.length) }, work)) + return sources +} + +const failure = (cause: unknown) => { + console.error('Unable to sync the source', cause) + return { + kind: 'failed', + message: + cause instanceof SourceError ? cause.message : 'The source could not be reached. Try again.', + } as const +} + +export const useSourceSync = (source: ProjectSource, reload: () => Promise) => { + const [state, setState] = useState({ kind: 'checking' }) + const busy = useRef(false) + const checkedAt = useRef(0) + + const check = useCallback(async () => { + if (busy.current || Date.now() - checkedAt.current < checkInterval) return + checkedAt.current = Date.now() + try { + const listing = await fetchListing(source) + if (!busy.current) + setState({ kind: readSnapshot()?.version === listing.version ? 'current' : 'available' }) + } catch (cause) { + if (!busy.current) setState(failure(cause)) + } + }, [source]) + + useEffect(() => { + void check() + const onVisible = () => { + if (document.visibilityState === 'visible') void check() + } + document.addEventListener('visibilitychange', onVisible) + return () => document.removeEventListener('visibilitychange', onVisible) + }, [check]) + + const sync = async () => { + if (busy.current) return + busy.current = true + try { + const listing = await fetchListing(source) + const plan = planSync(readSnapshot(), listing, await libraryFiles()) + setState({ kind: 'syncing', done: 0, total: plan.download.length }) + const downloaded = await downloadAll(source, plan.download, done => + setState({ kind: 'syncing', done, total: plan.download.length }), + ) + const result = await importStoredFiles(downloaded, 'replace') + if (plan.remove.length) await removeStoredFiles(plan.remove) + localStorage.setItem( + snapshotKey(), + JSON.stringify(snapshotAfter(listing, await libraryFiles())), + ) + await reload() + checkedAt.current = Date.now() + setState({ kind: 'synced', kept: plan.kept, refused: result.rejected.length }) + } catch (cause) { + setState(failure(cause)) + } finally { + busy.current = false + } + } + + return { state, sync } +} diff --git a/ui-packages/web/src/shell/project-root.tsx b/ui-packages/web/src/shell/project-root.tsx index 4222a11..24181bb 100644 --- a/ui-packages/web/src/shell/project-root.tsx +++ b/ui-packages/web/src/shell/project-root.tsx @@ -13,9 +13,11 @@ import { getProject, isPendingDeletion, listProjects, + openSourceProject, touchProject, } from '../data/project-store' import { openWorkspaceDatabase, setWorkspaceDatabaseName } from '../data/workspace-database' +import { loadProjectSource } from '../features/source/load-source' import { EmptyWorkbench } from './empty-workbench' import { Workbench } from './workbench' @@ -42,6 +44,13 @@ const resolveProject = async (): Promise => { const project = await touchProject(decodeURIComponent(requested)) if (project) return project } + // A deployment bound to a source opens its project unless another one was asked for. + const source = await loadProjectSource() + if (source) { + const project = await openSourceProject(source) + window.history.replaceState(null, '', `${projectPath(project.id)}${search}${hash}`) + return project + } const projects = await listProjects() // Links from before projects existed all point into the library that became the first one. const legacy = !requested && isLegacyPath(pathname) diff --git a/ui-packages/web/src/shell/projects.integration.test.tsx b/ui-packages/web/src/shell/projects.integration.test.tsx index 82a9d4e..30c52dd 100644 --- a/ui-packages/web/src/shell/projects.integration.test.tsx +++ b/ui-packages/web/src/shell/projects.integration.test.tsx @@ -4,7 +4,12 @@ import { openDB } from 'idb' import { beforeEach, describe, expect, it, vi } from 'vitest' import { rootSources } from '../core/files' import { legacyDatabaseName, projectDeletionPath, projectWindowName } from '../core/projects' -import { importStoredFiles, listStoredFiles } from '../data/file-store' +import { + getStoredFileContent, + importStoredFiles, + listStoredFiles, + writeStoredTextFile, +} from '../data/file-store' import { createProject, getProject, @@ -26,6 +31,71 @@ const visit = (path: string) => { const fileNames = async () => (await listStoredFiles()).map(file => file.path) describe('projects', () => { + it('opens a deployment source as its project and brings in its changes on request', async () => { + const user = userEvent.setup({ delay: null }) + const contents: Record = { + 'knowledge/agents.md': '# Agents', + 'knowledge/old.md': '# Old', + 'journal/today.md': '# Today', + } + let version = 'v1' + vi.spyOn(globalThis, 'fetch').mockImplementation(async input => { + const url = String(input) + if (url === '/api/agent/config') return Response.json({ enabled: false }) + if (url === '/api/source') return Response.json({ name: 'brain2', url: '/source/brain2' }) + if (url === '/source/brain2') + return Response.json({ + version, + files: Object.entries(contents).map(([path, text]) => ({ + path, + version: `${version}:${text}`, + size: text.length, + })), + }) + const path = decodeURIComponent(url.replace('/source/brain2/files/', '')) + return new Response(contents[path] ?? '', { headers: { 'Content-Type': 'text/markdown' } }) + }) + const text = async (path: string) => { + const file = (await listStoredFiles()).find(candidate => candidate.path === path) + return file ? (await getStoredFileContent(file.id))?.text() : undefined + } + + visit('/') + expect(await screen.findByText('brain2 has changes.')).toBeVisible() + expect(window.location.pathname).toMatch(/^\/p\/source-brain2(\/|$)/) + expect(await fileNames()).toEqual([]) + await user.click(screen.getByRole('button', { name: 'Sync' })) + expect(await screen.findByText('brain2 is up to date.')).toBeVisible() + expect((await fileNames()).sort()).toEqual([ + 'journal/today.md', + 'knowledge/agents.md', + 'knowledge/old.md', + ]) + + await writeStoredTextFile('journal/today.md', '# Today, edited here') + contents['journal/today.md'] = '# Today, from the source' + contents['knowledge/agents.md'] = '# Agents, revised' + delete contents['knowledge/old.md'] + version = 'v2' + cleanup() + visit('/') + await user.click(await screen.findByRole('button', { name: 'Sync' })) + + expect( + await screen.findByText('brain2 is up to date. Kept your edits to 1 file: journal/today.md.'), + ).toBeVisible() + expect(await text('knowledge/agents.md')).toBe('# Agents, revised') + expect(await text('journal/today.md')).toBe('# Today, edited here') + expect(await fileNames()).not.toContain('knowledge/old.md') + }) + + it('opens as before when the deployment has no source', async () => { + visit('/') + + expect(await screen.findByRole('button', { name: 'My reading' })).toBeInTheDocument() + expect(screen.queryByText(/has changes|is up to date/)).not.toBeInTheDocument() + }) + it('opens the library kept before projects as the first project', async () => { await importStoredFiles( rootSources([new File(['# Notes'], 'Notes.md', { type: 'text/markdown' })]), diff --git a/ui-packages/web/src/styles.css b/ui-packages/web/src/styles.css index dd8b2b4..9667adb 100644 --- a/ui-packages/web/src/styles.css +++ b/ui-packages/web/src/styles.css @@ -742,6 +742,28 @@ svg { .resource-row:focus-within .resource-actions { opacity: 1; } +.source-sync { + display: flex; + align-items: center; + gap: 8px; + margin: 0 10px 6px; + color: var(--muted); + font-size: 11px; + line-height: 1.5; +} +.source-sync span { + flex: 1; + min-width: 0; + overflow-wrap: anywhere; +} +.source-sync button { + display: inline-flex; + flex-shrink: 0; + align-items: center; + gap: 4px; + padding: 0; + font-size: 11px; +} .file-progress { margin: 0 10px 6px; color: var(--muted); diff --git a/ui-packages/web/src/test/setup.ts b/ui-packages/web/src/test/setup.ts index f5337d5..9a98282 100644 --- a/ui-packages/web/src/test/setup.ts +++ b/ui-packages/web/src/test/setup.ts @@ -82,6 +82,7 @@ afterEach(async () => { beforeEach(() => { vi.spyOn(globalThis, 'fetch').mockImplementation(async input => { if (String(input) === '/api/agent/config') return Response.json({ enabled: false }) + if (String(input) === '/api/source') return Response.json({}, { status: 404 }) throw new Error(`Unexpected network request in test: ${String(input)}`) }) }) diff --git a/web-packages/server/src/app.test.ts b/web-packages/server/src/app.test.ts index 652c04a..b19b376 100644 --- a/web-packages/server/src/app.test.ts +++ b/web-packages/server/src/app.test.ts @@ -5,6 +5,7 @@ import { afterAll, beforeAll, describe, expect, it } from 'vitest' import { createApp } from './app.js' import { createQuotaGuard } from './quota/guard.js' import { openQuotaStore } from './quota/store.js' +import { readSourceConfig } from './source-config.js' const guard = createQuotaGuard( openQuotaStore(':memory:'), @@ -94,4 +95,15 @@ describe('application HTTP boundaries', () => { expect(response.status).toBe(404) expect(await response.text()).not.toBe(page) }) + + it('names the source a deployment syncs from, and has none by default', async () => { + expect((await build().request('/api/source')).status).toBe(404) + const source = readSourceConfig({ + GAMMA_SOURCE_NAME: 'brain2', + GAMMA_SOURCE_URL: '/source/brain2', + }) + const response = await createApp(guard, undefined, undefined, source).request('/api/source') + expect(await response.json()).toEqual({ name: 'brain2', url: '/source/brain2' }) + expect(() => readSourceConfig({ GAMMA_SOURCE_NAME: 'brain2' })).toThrow() + }) }) diff --git a/web-packages/server/src/app.ts b/web-packages/server/src/app.ts index f5718e9..43faa48 100644 --- a/web-packages/server/src/app.ts +++ b/web-packages/server/src/app.ts @@ -3,16 +3,21 @@ import { Hono } from 'hono' import type { ModelProxyConfig } from './model-proxy/config.js' import { createModelProxyRoutes } from './model-proxy/routes.js' import type { QuotaGuard } from './quota/guard.js' +import type { SourceConfig } from './source-config.js' export const createApp = ( guard: QuotaGuard, webRoot?: string, modelConfig: ModelProxyConfig = { providers: {}, publicConfig: { enabled: false } }, + source: SourceConfig | null = null, ) => { const app = new Hono() app.get('/api/health', c => c.json({ status: 'ok', service: 'gamma-reader' })) app.route('/api/agent', createModelProxyRoutes(modelConfig, guard)) + app.get('/api/source', c => + source ? c.json(source) : c.json({ error: 'No source is configured' }, 404), + ) app.all('/api', c => c.json({ error: 'Not found' }, 404)) app.all('/api/*', c => c.json({ error: 'Not found' }, 404)) diff --git a/web-packages/server/src/main.ts b/web-packages/server/src/main.ts index 4e71bcd..f26f321 100644 --- a/web-packages/server/src/main.ts +++ b/web-packages/server/src/main.ts @@ -7,6 +7,7 @@ import providers from './model-proxy/providers.json' with { type: 'json' } import { readQuotaConfig } from './quota/config.js' import { createQuotaGuard } from './quota/guard.js' import { openQuotaStore } from './quota/store.js' +import { readSourceConfig } from './source-config.js' const port = Number(process.env.PORT ?? 3302) if (!Number.isInteger(port) || port < 1 || port > 65535) { @@ -33,7 +34,8 @@ const config = resolveModelProxyConfig(providers, process.env) const quota = readQuotaConfig(process.env) const store = openQuotaStore(quota.databaseFile) const guard = createQuotaGuard(store, quota) +const source = readSourceConfig(process.env) -serve({ fetch: createApp(guard, webRoot, config).fetch, port, hostname }, info => { +serve({ fetch: createApp(guard, webRoot, config, source).fetch, port, hostname }, info => { console.info(`Gamma Reader: http://${hostname}:${info.port}`) }) diff --git a/web-packages/server/src/source-config.ts b/web-packages/server/src/source-config.ts new file mode 100644 index 0000000..974ab1d --- /dev/null +++ b/web-packages/server/src/source-config.ts @@ -0,0 +1,11 @@ +// A deployment can bind its library to a remote source, which the reader keeps in sync. The source +// is any address serving the listing the reader asks for; this server only says where it is. +export type SourceConfig = { name: string; url: string } + +export const readSourceConfig = (env: Record): SourceConfig | null => { + const url = env.GAMMA_SOURCE_URL?.trim() + const name = env.GAMMA_SOURCE_NAME?.trim() + if (!url && !name) return null + if (!url || !name) throw new Error('GAMMA_SOURCE_URL and GAMMA_SOURCE_NAME must be set together') + return { name, url } +}