Skip to content
Merged
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
34 changes: 34 additions & 0 deletions ui-packages/web/src/data/storage-summary.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { describe, expect, it } from 'vitest'
import { emptyConversationDraft } from '../core/conversations'
import { rootSources } from '../core/files'
import { saveStoredConversationDraft } from './conversation-store'
import { importStoredFiles, listStoredFiles } from './file-store'
import { readStorageSummary } from './storage-summary'

describe('storage summary', () => {
it('counts every table of the open project and sums the stored file bytes', async () => {
await importStoredFiles(
rootSources([new File(['# Notes'], 'Notes.md', { type: 'text/markdown' })]),
'keep',
)
await saveStoredConversationDraft({
id: 'conversation',
title: null,
draft: emptyConversationDraft(),
createdAt: 1,
lastActiveAt: 1,
})
const files = await listStoredFiles()

const summary = await readStorageSummary()

expect(Object.fromEntries(summary.stores.map(store => [store.name, store.records]))).toEqual({
contents: files.length,
conversations: 1,
files: files.length,
folderExports: 0,
messages: 0,
})
expect(summary.fileBytes).toBe(files.reduce((total, file) => total + file.size, 0))
})
})
49 changes: 49 additions & 0 deletions ui-packages/web/src/data/storage-summary.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { listStoredFiles } from './file-store'
import { openWorkspaceDatabase } from './workspace-database'

export type StoreSummary = { name: string; records: number }

export type BrowserStorage = { usage: number; quota: number; persisted: boolean }

export type StorageSummary = {
databaseName: string
stores: readonly StoreSummary[]
/** The same sum the library limit checks: every stored file, attachments included. */
fileBytes: number
browser: BrowserStorage | null
}

// Origin-wide, so it covers every project in this browser, not just the open one.
const readBrowserStorage = async (): Promise<BrowserStorage | null> => {
if (!navigator.storage?.estimate || !navigator.storage.persisted) return null
try {
const [{ usage = 0, quota = 0 }, persisted] = await Promise.all([
navigator.storage.estimate(),
navigator.storage.persisted(),
])
return { usage, quota, persisted }
} catch (error) {
console.error('Unable to read browser storage usage', error)
return null
}
}

export const readStorageSummary = async (): Promise<StorageSummary> => {
const database = await openWorkspaceDatabase()
const [stores, files, browser] = await Promise.all([
Promise.all(
Array.from(database.objectStoreNames, async name => ({
name,
records: await database.count(name),
})),
),
listStoredFiles(),
readBrowserStorage(),
])
return {
databaseName: database.name,
stores,
fileBytes: files.reduce((total, file) => total + file.size, 0),
browser,
}
}
90 changes: 90 additions & 0 deletions ui-packages/web/src/features/projects/project-storage-dialog.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import { useEffect, useState } from 'react'
import { ConfirmationDialog as Modal } from '../../components/confirmation-dialog'
import { formatBytes, maximumLibraryBytes } from '../../core/files'
import type { Project } from '../../core/projects'
import {
type BrowserStorage,
readStorageSummary,
type StorageSummary,
} from '../../data/storage-summary'
import styles from './style.module.scss'

const percent = new Intl.NumberFormat('en-US', { style: 'percent', maximumFractionDigits: 1 })
// A fresh library is a sliver of the quota; rounding it to 0% would read as nothing stored.
const share = (ratio: number) => (ratio < 0.001 ? 'under 0.1%' : percent.format(ratio))

const BrowserStorageNote = ({ usage, quota, persisted }: BrowserStorage) => (
<p>
This browser, all projects: {formatBytes(usage)} used
{quota > 0 && `, ${share(usage / quota)} of what it allows`}.{' '}
{persisted
? 'Storage is persistent.'
: 'Storage is not persistent; the browser may clear it under disk pressure.'}
</p>
)

export const ProjectStorageDialog = ({
project,
onClose,
}: {
project: Project
onClose: () => void
}) => {
const [summary, setSummary] = useState<StorageSummary | null>(null)
const [failed, setFailed] = useState(false)
useEffect(() => {
let current = true
readStorageSummary().then(
result => {
if (current) setSummary(result)
},
cause => {
console.error('Unable to read project storage', cause)
if (current) setFailed(true)
},
)
return () => {
current = false
}
}, [])
return (
<Modal label={`${project.name} storage`} onCancel={onClose}>
<h2>{project.name} storage</h2>
{failed && <p role="alert">Unable to read this project's storage.</p>}
{summary && (
<>
<dl className={styles.storage}>
<dt>Database</dt>
<dd>{summary.databaseName}</dd>
<dt>Library</dt>
<dd>
{formatBytes(summary.fileBytes)} of {maximumLibraryBytes / 1024 ** 3} GiB
</dd>
</dl>
<table className={styles.stores}>
<thead>
<tr>
<th scope="col">Table</th>
<th scope="col">Records</th>
</tr>
</thead>
<tbody>
{summary.stores.map(store => (
<tr key={store.name}>
<td>{store.name}</td>
<td>{store.records.toLocaleString('en-US')}</td>
</tr>
))}
</tbody>
</table>
{summary.browser && <BrowserStorageNote {...summary.browser} />}
</>
)}
<div className="dialog-actions">
<button type="button" className="secondary-button" onClick={onClose}>
Close
</button>
</div>
</Modal>
)
}
18 changes: 17 additions & 1 deletion ui-packages/web/src/features/projects/project-switcher.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import type { FileExportController } from '../resources/use-file-export'
import { DeleteProjectDialog } from './delete-project-dialog'
import { NewProjectForm } from './new-project-form'
import { ProjectLink } from './project-link'
import { ProjectStorageDialog } from './project-storage-dialog'
import styles from './style.module.scss'

type Mode = 'list' | 'create' | 'rename'
Expand Down Expand Up @@ -72,6 +73,7 @@ export const ProjectSwitcher = (props: ProjectSwitcherProps) => {
const [projects, setProjects] = useState<Project[] | null>(null)
const [listError, setListError] = useState<string | null>(null)
const [deleting, setDeleting] = useState(false)
const [showingStorage, setShowingStorage] = useState(false)
const others = (projects ?? []).filter(project => project.id !== current?.id)

const loadProjects = () => {
Expand Down Expand Up @@ -165,9 +167,20 @@ export const ProjectSwitcher = (props: ProjectSwitcherProps) => {
</button>
{current && (
<>
<div className={styles.separator} />
<button type="button" onClick={() => setMode('rename')}>
Rename…
Rename project…
</button>
<button
type="button"
onClick={() => {
setOpen(false)
setShowingStorage(true)
}}
>
View storage
</button>
<div className={styles.separator} />
<button
type="button"
onClick={() => {
Expand All @@ -183,6 +196,9 @@ export const ProjectSwitcher = (props: ProjectSwitcherProps) => {
)}
</Popover.Content>
</Popover.Root>
{showingStorage && current && (
<ProjectStorageDialog project={current} onClose={() => setShowingStorage(false)} />
)}
{deleting && props.project && current && (
<DeleteProjectDialog
project={current}
Expand Down
35 changes: 35 additions & 0 deletions ui-packages/web/src/features/projects/style.module.scss
Original file line number Diff line number Diff line change
Expand Up @@ -130,3 +130,38 @@ a.project,
padding: 0;
}
}
.storage {
display: grid;
grid-template-columns: auto 1fr;
gap: 4px 16px;
margin: 0 0 14px;
font-size: 13px;
dt {
color: var(--muted);
}
dd {
margin: 0;
overflow-wrap: anywhere;
}
}
.stores {
width: 100%;
margin-bottom: 14px;
border-collapse: collapse;
font-size: 13px;
th,
td {
padding: 4px 0;
border-bottom: 1px solid var(--line);
text-align: left;
}
th {
color: var(--muted);
font-weight: 500;
}
th:last-child,
td:last-child {
text-align: right;
font-variant-numeric: tabular-nums;
}
}