Skip to content

AI-native design editor. Open-source Figma alternative.

fix(storage): preserve durable sync work

Danila Poyarkov49b2d49e403f
diff --git a/packages/vue/src/i18n/locales/de/dialogs.json b/packages/vue/src/i18n/locales/de/dialogs.json
index dc0a8107c..564378440 100644
--- a/packages/vue/src/i18n/locales/de/dialogs.json
+++ b/packages/vue/src/i18n/locales/de/dialogs.json
@@ -105,6 +105,7 @@
"emptyStorageWorkspace": "Noch keine gespeicherten Dokumente.",
"loadingDocuments": "Dokumente werden geladen…",
"storageNotConfigured": "Konfiguriere den Speicher, bevor du diesen Arbeitsbereich verwendest.",
+ "copyStorageCors": "CORS-JSON kopieren",
"storageEndpoint": "Endpunkt",
"storageBucket": "Bucket",
"storageRegion": "Region",
diff --git a/packages/vue/src/i18n/locales/es/dialogs.json b/packages/vue/src/i18n/locales/es/dialogs.json
index a5c88b29c..25c9e5f69 100644
--- a/packages/vue/src/i18n/locales/es/dialogs.json
+++ b/packages/vue/src/i18n/locales/es/dialogs.json
@@ -105,6 +105,7 @@
"emptyStorageWorkspace": "Aún no hay documentos guardados.",
"loadingDocuments": "Cargando documentos…",
"storageNotConfigured": "Configura el almacenamiento antes de usar este espacio.",
+ "copyStorageCors": "Copiar JSON de CORS",
"storageEndpoint": "Punto de conexión",
"storageBucket": "Bucket",
"storageRegion": "Región",
diff --git a/packages/vue/src/i18n/locales/fr/dialogs.json b/packages/vue/src/i18n/locales/fr/dialogs.json
index 0ddc77c64..2091bb83e 100644
--- a/packages/vue/src/i18n/locales/fr/dialogs.json
+++ b/packages/vue/src/i18n/locales/fr/dialogs.json
@@ -105,6 +105,7 @@
"emptyStorageWorkspace": "Aucun document stocké pour le moment.",
"loadingDocuments": "Chargement des documents…",
"storageNotConfigured": "Configurez le stockage avant d’utiliser cet espace.",
+ "copyStorageCors": "Copier le JSON CORS",
"storageEndpoint": "Point de terminaison",
"storageBucket": "Bucket",
"storageRegion": "Région",
diff --git a/packages/vue/src/i18n/locales/it/dialogs.json b/packages/vue/src/i18n/locales/it/dialogs.json
index b4916194a..b9a7218eb 100644
--- a/packages/vue/src/i18n/locales/it/dialogs.json
+++ b/packages/vue/src/i18n/locales/it/dialogs.json
@@ -105,6 +105,7 @@
"emptyStorageWorkspace": "Nessun documento archiviato.",
"loadingDocuments": "Caricamento documenti…",
"storageNotConfigured": "Configura l’archiviazione prima di usare quest’area.",
+ "copyStorageCors": "Copia JSON CORS",
"storageEndpoint": "Endpoint",
"storageBucket": "Bucket",
"storageRegion": "Regione",
diff --git a/packages/vue/src/i18n/locales/ja/dialogs.json b/packages/vue/src/i18n/locales/ja/dialogs.json
index 8f71feb97..ff2922486 100644
--- a/packages/vue/src/i18n/locales/ja/dialogs.json
+++ b/packages/vue/src/i18n/locales/ja/dialogs.json
@@ -105,6 +105,7 @@
"emptyStorageWorkspace": "保存されたドキュメントはまだありません。",
"loadingDocuments": "ドキュメントを読み込み中…",
"storageNotConfigured": "このワークスペースを使用する前にストレージを設定してください。",
+ "copyStorageCors": "CORS JSONをコピー",
"storageEndpoint": "エンドポイント",
"storageBucket": "バケット",
"storageRegion": "リージョン",
diff --git a/packages/vue/src/i18n/locales/pl/dialogs.json b/packages/vue/src/i18n/locales/pl/dialogs.json
index 62bcef9f2..b386afd57 100644
--- a/packages/vue/src/i18n/locales/pl/dialogs.json
+++ b/packages/vue/src/i18n/locales/pl/dialogs.json
@@ -105,6 +105,7 @@
"emptyStorageWorkspace": "Brak zapisanych dokumentów.",
"loadingDocuments": "Ładowanie dokumentów…",
"storageNotConfigured": "Skonfiguruj przechowywanie przed użyciem tego obszaru.",
+ "copyStorageCors": "Kopiuj JSON CORS",
"storageEndpoint": "Punkt końcowy",
"storageBucket": "Zasobnik",
"storageRegion": "Region",
diff --git a/packages/vue/src/i18n/locales/ru/dialogs.json b/packages/vue/src/i18n/locales/ru/dialogs.json
index 4a75ced1d..f264c58be 100644
--- a/packages/vue/src/i18n/locales/ru/dialogs.json
+++ b/packages/vue/src/i18n/locales/ru/dialogs.json
@@ -105,6 +105,7 @@
"emptyStorageWorkspace": "Сохранённых документов пока нет.",
"loadingDocuments": "Загрузка документов…",
"storageNotConfigured": "Настройте хранилище перед использованием этой области.",
+ "copyStorageCors": "Скопировать JSON CORS",
"storageEndpoint": "Конечная точка",
"storageBucket": "Бакет",
"storageRegion": "Регион",
diff --git a/packages/vue/src/i18n/locales/zh-cn/dialogs.json b/packages/vue/src/i18n/locales/zh-cn/dialogs.json
index 606095eb0..a9f6e9e60 100644
--- a/packages/vue/src/i18n/locales/zh-cn/dialogs.json
+++ b/packages/vue/src/i18n/locales/zh-cn/dialogs.json
@@ -105,6 +105,7 @@
"emptyStorageWorkspace": "暂无已存储的文档。",
"loadingDocuments": "正在加载文档…",
"storageNotConfigured": "请先配置存储,再使用此工作区。",
+ "copyStorageCors": "复制 CORS JSON",
"storageEndpoint": "端点",
"storageBucket": "存储桶",
"storageRegion": "区域",
diff --git a/packages/vue/src/i18n/messages/dialogs.ts b/packages/vue/src/i18n/messages/dialogs.ts
index 31f885c68..5c22f6564 100644
--- a/packages/vue/src/i18n/messages/dialogs.ts
+++ b/packages/vue/src/i18n/messages/dialogs.ts
@@ -154,6 +154,7 @@ export const dialogMessageDefaults = {
emptyStorageWorkspace: 'No stored documents yet.',
loadingDocuments: 'Loading documents…',
storageNotConfigured: 'Configure storage before using this workspace.',
+ copyStorageCors: 'Copy CORS JSON',
storageEndpoint: 'Endpoint',
storageBucket: 'Bucket',
storageRegion: 'Region',
diff --git a/src/App.vue b/src/App.vue
index 0cc9bc9d8..3848eefac 100644
--- a/src/App.vue
+++ b/src/App.vue
@@ -10,6 +10,7 @@ import { useEditorStore } from '@/app/editor/active-store'
import { toast } from '@/app/shell/ui'
import { useAppTheme } from '@/app/shell/theme'
import { scheduleStartupUpdateCheck } from '@/app/shell/updater'
+import { kickSyncEngine } from '@/app/storage/sync'
useHead({ titleTemplate: (title) => (title ? `${title} — OpenPencil` : 'OpenPencil') })
@@ -21,6 +22,7 @@ useAppTheme()
onMounted(() => {
toast.setupGlobalErrorHandler()
scheduleStartupUpdateCheck(dialogs)
+ void kickSyncEngine()
})
</script>
diff --git a/src/app/ai/models/store.ts b/src/app/ai/models/store.ts
index b34269d59..532f892c9 100644
--- a/src/app/ai/models/store.ts
+++ b/src/app/ai/models/store.ts
@@ -34,7 +34,10 @@ function isRecord(value: unknown): value is Record<string, unknown> {
}
function isProviderID(value: unknown): value is AIProviderID {
- return typeof value === 'string' && AI_PROVIDERS.some((provider) => provider.id === value)
+ return (
+ typeof value === 'string' &&
+ (value.startsWith('acp:') || AI_PROVIDERS.some((provider) => provider.id === value))
+ )
}
function isAPIType(value: unknown): value is 'completions' | 'responses' {
@@ -49,8 +52,10 @@ function stringValue(value: unknown, fallback = ''): string {
return typeof value === 'string' ? value : fallback
}
-function numberValue(value: unknown, fallback: number): number {
- return typeof value === 'number' && Number.isFinite(value) ? value : fallback
+function normalizedMaxOutputTokens(value: unknown): number {
+ return typeof value === 'number' && Number.isFinite(value)
+ ? Math.min(128_000, Math.max(1024, Math.round(value)))
+ : DEFAULT_MAX_OUTPUT_TOKENS
}
function parseConnection(value: unknown): AIModelConnection | null {
@@ -81,7 +86,7 @@ function parseProfile(value: unknown, connectionIds: Set<string>): AIModelProfil
connectionId,
modelID: stringValue(value.modelID),
customModelID: stringValue(value.customModelID),
- maxOutputTokens: numberValue(value.maxOutputTokens, DEFAULT_MAX_OUTPUT_TOKENS),
+ maxOutputTokens: normalizedMaxOutputTokens(value.maxOutputTokens),
capabilities: [...new Set(capabilities)]
}
}
@@ -107,17 +112,24 @@ function parseSettings(value: unknown): AIModelSettings | null {
const rawAssignments = isRecord(value.assignments) ? value.assignments : {}
const rawDesign = stringValue(rawAssignments.design)
const design = rawDesign.startsWith('model-') ? (rawDesign as AIModelProfileId) : models[0].id
- return {
- version: 1,
- connections,
- models,
- assignments: {
- design: modelIds.has(design) ? design : models[0].id,
- review: optionalAssignment(rawAssignments.review, modelIds),
- fast: optionalAssignment(rawAssignments.fast, modelIds),
- vision: optionalAssignment(rawAssignments.vision, modelIds)
- }
+ const resolvedDesign = modelIds.has(design) ? design : models[0].id
+ const assignments: AIModelSettings['assignments'] = {
+ design: resolvedDesign,
+ review: optionalAssignment(rawAssignments.review, modelIds),
+ fast: optionalAssignment(rawAssignments.fast, modelIds),
+ vision: optionalAssignment(rawAssignments.vision, modelIds)
+ }
+ for (const role of ['review', 'fast', 'vision'] as const) {
+ const assignment = assignments[role]
+ if (assignment === null) continue
+ const profileId = assignment === 'design' ? resolvedDesign : assignment
+ const profile = models.find((candidate) => candidate.id === profileId)
+ const connection = connections.find((candidate) => candidate.id === profile?.connectionId)
+ const invalidACP = connection?.providerID.startsWith('acp:')
+ const invalidVision = role === 'vision' && !profile?.capabilities.includes('vision')
+ if (invalidACP || invalidVision) assignments[role] = null
}
+ return { version: 1, connections, models, assignments }
}
function legacySettings(): AIModelSettings {
@@ -191,6 +203,10 @@ export function modelConnection(connectionId: string): AIModelConnection | null
)
}
+export function isACPModelProfile(profile: AIModelProfile | null): boolean {
+ return Boolean(profile && modelConnection(profile.connectionId)?.providerID.startsWith('acp:'))
+}
+
export function resolveAIModelRole(role: AIModelRole): ResolvedAIModelRole | null {
const assignment = aiModelSettings.value.assignments[role]
if (assignment === null) return null
@@ -302,7 +318,7 @@ export function saveModelProfileDraft(draft: AIModelProfileDraft): AIModelProfil
connectionId: connection.id,
modelID: draft.modelID.trim() || provider?.defaultModel || '',
customModelID: draft.customModelID.trim(),
- maxOutputTokens: Math.max(1024, Math.round(draft.maxOutputTokens)),
+ maxOutputTokens: normalizedMaxOutputTokens(draft.maxOutputTokens),
capabilities: [...new Set(draft.capabilities)]
}
const index = aiModelSettings.value.models.findIndex((model) => model.id === profile.id)
@@ -366,12 +382,13 @@ export function setModelRoleAssignment(role: AIModelRole, assignment: AIModelRol
return
}
if (assignment !== null && assignment !== 'design' && !modelProfile(assignment)) return
- if (role === 'vision' && assignment !== null) {
+ if (assignment !== null) {
const profile =
assignment === 'design'
? modelProfile(aiModelSettings.value.assignments.design)
: modelProfile(assignment)
- if (!profile?.capabilities.includes('vision')) return
+ if (isACPModelProfile(profile)) return
+ if (role === 'vision' && !profile?.capabilities.includes('vision')) return
}
aiModelSettings.value.assignments[role] = assignment
}
diff --git a/src/app/integrations/storage/s3/adapter.ts b/src/app/integrations/storage/s3/adapter.ts
index 4ac33d09b..a01ae0364 100644
--- a/src/app/integrations/storage/s3/adapter.ts
+++ b/src/app/integrations/storage/s3/adapter.ts
@@ -17,12 +17,7 @@ import type {
StorageProviderRuntime
} from '../types'
import { S3HttpError, deleteObject, getObject, headObject, listObjects, putObject } from './client'
-import {
- CloudCorsError,
- ensureWebCorsOnBucket,
- formatBrowserCorsHelpMessage,
- isLikelyCorsOrNetworkError
-} from './cors'
+import { CloudCorsError, formatBrowserCorsHelpMessage, isLikelyCorsOrNetworkError } from './cors'
import type { S3CompatibleConfig, S3ConnectionResult } from './types'
const ENDPOINT_FIELD = 'endpoint'
@@ -101,9 +96,6 @@ export function createS3StorageAdapter(runtime: StorageProviderRuntime): S3Stora
return {
async testConnection() {
const config = await resolveConfig(runtime)
- let cors = await ensureWebCorsOnBucket(config)
- if (!cors.applied) console.warn('[Storage] Automatic PutBucketCors failed:', cors.error)
-
try {
await ensureNamespace(config)
await listObjects(config, STORAGE_DOCUMENTS_PREFIX)
@@ -113,19 +105,16 @@ export function createS3StorageAdapter(runtime: StorageProviderRuntime): S3Stora
return {
ok: false,
message: connectionErrorMessage(error, isCors),
- corsApplied: cors.applied,
+ corsApplied: false,
isCorsFailure: isCors,
- corsError: cors.error
+ corsError: null
}
}
- if (!cors.applied) cors = await ensureWebCorsOnBucket(config)
return {
ok: true,
- message: cors.applied
- ? 'Connected. Bucket CORS was applied automatically for the web app.'
- : 'Connected. Storage namespace is ready.',
- corsApplied: cors.applied,
+ message: 'Connected. Storage namespace is ready.',
+ corsApplied: false,
isCorsFailure: false,
corsError: null
}
@@ -141,26 +130,33 @@ export function createS3StorageAdapter(runtime: StorageProviderRuntime): S3Stora
})
.filter((entry): entry is { id: string; lastModified: string | null } => entry !== null)
- const documents = await Promise.all(
- entries.map(async ({ id, lastModified }) => {
- const fallback = {
- name: id,
- updatedAt: lastModified ?? new Date(0).toISOString()
- }
- const metadataBytes = await getObject(config, documentMetaKey(id)).catch(
- (error: unknown) => {
- console.warn('[Storage] Document metadata fetch failed:', id, error)
- return null
- }
- )
- const { metadata, authoritative } = parseMetadata(metadataBytes, fallback)
- return {
- id,
- ...metadata,
- metadataAuthoritative: authoritative
- } satisfies StorageDocument
- })
- )
+ const documents: StorageDocument[] = []
+ // Bound sidecar reads so large buckets do not open hundreds of requests at once.
+ for (let offset = 0; offset < entries.length; offset += 12) {
+ const batch = entries.slice(offset, offset + 12)
+ documents.push(
+ ...(await Promise.all(
+ batch.map(async ({ id, lastModified }) => {
+ const fallback = {
+ name: id,
+ updatedAt: lastModified ?? new Date(0).toISOString()
+ }
+ const metadataBytes = await getObject(config, documentMetaKey(id)).catch(
+ (error: unknown) => {
+ console.warn('[Storage] Document metadata fetch failed:', id, error)
+ return null
+ }
+ )
+ const { metadata, authoritative } = parseMetadata(metadataBytes, fallback)
+ return {
+ id,
+ ...metadata,
+ metadataAuthoritative: authoritative
+ } satisfies StorageDocument
+ })
+ ))
+ )
+ }
return documents.sort((first, second) => second.updatedAt.localeCompare(first.updatedAt))
},
diff --git a/src/app/integrations/storage/s3/client.ts b/src/app/integrations/storage/s3/client.ts
index 69c7faaef..a56633ba6 100644
--- a/src/app/integrations/storage/s3/client.ts
+++ b/src/app/integrations/storage/s3/client.ts
@@ -29,9 +29,6 @@ export function normalizeEndpoint(endpoint: string): string {
return `https://${trimmed}`
}
-/** Alias for CORS module import clarity. */
-export const normalizeEndpointForCors = normalizeEndpoint
-
/** Path-style object URL: {endpoint}/{bucket}/{key} — works with B2, MinIO, R2, AWS. */
export function objectUrl(config: S3CompatibleConfig, key: string): string {
const base = normalizeEndpoint(config.endpoint)
@@ -317,6 +314,9 @@ export async function listObjects(
const parsed = parseListObjectsV2Page(xml)
all.push(...parsed.objects)
if (!parsed.isTruncated || !parsed.nextContinuationToken) break
+ if (page === 49) {
+ throw new Error('S3 listing exceeded the 50,000-object safety limit')
+ }
continuationToken = parsed.nextContinuationToken
}
diff --git a/src/app/integrations/storage/s3/cors.ts b/src/app/integrations/storage/s3/cors.ts
index 1de21f735..445f08540 100644
--- a/src/app/integrations/storage/s3/cors.ts
+++ b/src/app/integrations/storage/s3/cors.ts
@@ -1,11 +1,3 @@
-import {
- createAwsClient,
- normalizeEndpointForCors,
- S3HttpError
-} from '@/app/integrations/storage/s3/client'
-import { storageFetch } from '@/app/integrations/storage/s3/fetch'
-import type { S3CompatibleConfig } from '@/app/integrations/storage/s3/types'
-import { isTauri } from '@/app/tauri/env'
import { IS_BROWSER, WEB_APP_ORIGIN } from '@/constants'
/** Origins OpenPencil may run from when calling S3 from the browser. */
@@ -113,86 +105,6 @@ export function isLikelyCorsOrNetworkError(error: unknown): boolean {
export function formatBrowserCorsHelpMessage(): string {
return (
'CORS issue: the browser blocked access to your bucket. ' +
- 'OpenPencil tried to set CORS automatically but could not from the web app ' +
- '(the bucket must already allow this site, or use the desktop app once). ' +
- 'Click “Copy CORS JSON”, paste it into your bucket CORS settings, wait ~1 minute, then try again.'
+ 'Click “Copy CORS JSON”, paste it into your bucket CORS settings, wait about a minute, then try again.'
)
}
-
-/**
- * Apply recommended CORS via S3 PutBucketCors — same operation as AWS CLI put-bucket-cors.
- * - Desktop: always works (no browser CORS on the request itself).
- * - Web: only works if the bucket already allows this origin for PUT, or CORS was set externally.
- */
-export async function putBucketCors(
- config: S3CompatibleConfig,
- origins: string[] = collectCloudCorsOrigins()
-): Promise<void> {
- const base = normalizeEndpointForCors(config.endpoint)
- const url = `${base}/${encodeURIComponent(config.bucket)}?cors`
- const body = buildCorsConfigurationXml(origins)
- const client = createAwsClient(config)
- let signed: Request
- try {
- signed = await client.sign(url, {
- method: 'PUT',
- headers: {
- 'Content-Type': 'application/xml'
- },
- body,
- credentials: 'omit'
- })
- } catch (error) {
- throw error instanceof Error ? error : new Error(String(error))
- }
-
- let res: Response
- try {
- res = await storageFetch(signed)
- } catch (error) {
- if (isLikelyCorsOrNetworkError(error)) {
- throw new CloudCorsError(
- isTauri()
- ? 'Network error while applying bucket CORS.'
- : 'Could not apply CORS from the browser (preflight blocked). Use Copy CORS JSON or the desktop app.'
- )
- }
- throw error instanceof Error ? error : new Error(String(error))
- }
-
- if (!res.ok) {
- const text = await res.text().catch(() => '')
- if (res.status === 403 || res.status === 401) {
- throw new S3HttpError(
- res.status,
- 'Access key cannot update bucket CORS. Grant bucket write / PutBucketCors permission.'
- )
- }
- throw new S3HttpError(
- res.status,
- text.trim().slice(0, 200) || `PutBucketCors failed with status ${res.status}`
- )
- }
-}
-
-export type EnsureCorsResult = {
- applied: boolean
- error: string | null
-}
-
-/**
- * Always attempt PutBucketCors (automatic CORS setup for the web app origins).
- * Returns whether it worked; never throws.
- */
-export async function ensureWebCorsOnBucket(config: S3CompatibleConfig): Promise<EnsureCorsResult> {
- const origins = collectCloudCorsOrigins()
- try {
- await putBucketCors(config, origins)
- return { applied: true, error: null }
- } catch (error) {
- return {
- applied: false,
- error: error instanceof Error ? error.message : String(error)
- }
- }
-}
diff --git a/src/app/storage/local-store/idb.ts b/src/app/storage/local-store/idb.ts
index 322157bc6..782723f88 100644
--- a/src/app/storage/local-store/idb.ts
+++ b/src/app/storage/local-store/idb.ts
@@ -37,6 +37,10 @@ function bytesToBuffer(bytes: Uint8Array) {
return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength)
}
+async function readMetaRow(store: IDBObjectStore, id: string): Promise<LocalCanvasMeta | null> {
+ return ((await reqToPromise(store.get(id))) as LocalCanvasMeta | undefined) ?? null
+}
+
/** IndexedDB-backed local canvas store (meta + fig/thumb blobs). */
export function createIdbLocalCanvasStore(): LocalCanvasStore {
let dbPromise: Promise<IDBDatabase> | null = null
@@ -83,14 +87,13 @@ export function createIdbLocalCanvasStore(): LocalCanvasStore {
async writeCanvas(input: LocalCanvasWriteInput) {
const database = await db()
- const existing = await this.getMeta(input.id)
-
- let hasThumb = existing?.hasThumb ?? false
const tx = database.transaction([STORE_META, STORE_FIG, STORE_THUMB], 'readwrite')
const figStore = tx.objectStore(STORE_FIG)
const thumbStore = tx.objectStore(STORE_THUMB)
const metaStore = tx.objectStore(STORE_META)
+ const existing = await readMetaRow(metaStore, input.id)
+ let hasThumb = existing?.hasThumb ?? false
figStore.put(bytesToBuffer(input.figBytes), input.id)
if (input.thumbBytes != null) {
@@ -110,20 +113,25 @@ export function createIdbLocalCanvasStore(): LocalCanvasStore {
},
async upsertIndexMeta(input) {
- const existing = await this.getMeta(input.id)
- const meta = buildIndexMeta(input, existing)
const database = await db()
const tx = database.transaction(STORE_META, 'readwrite')
- tx.objectStore(STORE_META).put(meta)
+ const store = tx.objectStore(STORE_META)
+ const existing = await readMetaRow(store, input.id)
+ const meta = buildIndexMeta(input, existing)
+ store.put(meta)
await txDone(tx)
return meta
},
async writeThumb(id: string, thumbBytes: Uint8Array) {
- const existing = await this.getMeta(id)
- if (!existing) return null
const database = await db()
const tx = database.transaction([STORE_META, STORE_THUMB], 'readwrite')
+ const metaStore = tx.objectStore(STORE_META)
+ const existing = await readMetaRow(metaStore, id)
+ if (!existing) {
+ await txDone(tx)
+ return null
+ }
tx.objectStore(STORE_THUMB).put(bytesToBuffer(thumbBytes), id)
// Thumb freshness is tracked by its own outbox job — never demote the
// document's syncStatus here (it orphaned rows as 'pending' forever).
@@ -131,18 +139,25 @@ export function createIdbLocalCanvasStore(): LocalCanvasStore {
...existing,
hasThumb: true
}
- tx.objectStore(STORE_META).put(meta)
+ metaStore.put(meta)
await txDone(tx)
return meta
},
- async updateMeta(id: string, patch: Partial<LocalCanvasMeta>) {
- const existing = await this.getMeta(id)
- if (!existing) return null
- const next = { ...existing, ...patch, id: existing.id }
+ async updateMeta(id: string, patch: Partial<LocalCanvasMeta>, options) {
const database = await db()
const tx = database.transaction(STORE_META, 'readwrite')
- tx.objectStore(STORE_META).put(next)
+ const store = tx.objectStore(STORE_META)
+ const existing = await readMetaRow(store, id)
+ if (
+ !existing ||
+ (options?.expectedRevision != null && existing.revision !== options.expectedRevision)
+ ) {
+ await txDone(tx)
+ return null
+ }
+ const next = { ...existing, ...patch, id: existing.id }
+ store.put(next)
await txDone(tx)
return next
},
@@ -156,13 +171,17 @@ export function createIdbLocalCanvasStore(): LocalCanvasStore {
},
async clearFig(id: string) {
- const existing = await this.getMeta(id)
- if (!existing) return null
const database = await db()
const tx = database.transaction([STORE_META, STORE_FIG], 'readwrite')
+ const metaStore = tx.objectStore(STORE_META)
+ const existing = await readMetaRow(metaStore, id)
+ if (!existing) {
+ await txDone(tx)
+ return null
+ }
tx.objectStore(STORE_FIG).delete(id)
const meta: LocalCanvasMeta = { ...existing, hasFig: false, figSize: 0 }
- tx.objectStore(STORE_META).put(meta)
+ metaStore.put(meta)
await txDone(tx)
return meta
},
diff --git a/src/app/storage/local-store/memory.ts b/src/app/storage/local-store/memory.ts
index 4065c2ffb..c2d22c7ee 100644
--- a/src/app/storage/local-store/memory.ts
+++ b/src/app/storage/local-store/memory.ts
@@ -67,9 +67,14 @@ export function createMemoryLocalCanvasStore(): LocalCanvasStore {
return meta
},
- async updateMeta(id: string, patch: Partial<LocalCanvasMeta>) {
+ async updateMeta(id: string, patch: Partial<LocalCanvasMeta>, options) {
const existing = metas.get(id)
- if (!existing) return null
+ if (
+ !existing ||
+ (options?.expectedRevision != null && existing.revision !== options.expectedRevision)
+ ) {
+ return null
+ }
const next = { ...existing, ...patch, id: existing.id }
metas.set(id, next)
return next
diff --git a/src/app/storage/local-store/store.ts b/src/app/storage/local-store/store.ts
index 16ab138b4..8b3d74740 100644
--- a/src/app/storage/local-store/store.ts
+++ b/src/app/storage/local-store/store.ts
@@ -6,6 +6,11 @@ import type {
LocalCanvasWriteInput
} from '@/app/storage/local-store/types'
+export type UpdateLocalCanvasMetaOptions = {
+ /** Apply only if the row still has this revision. */
+ expectedRevision?: number
+}
+
export type LocalCanvasStore = {
listMetas(includeTombstones?: boolean): Promise<LocalCanvasMeta[]>
getMeta(id: string): Promise<LocalCanvasMeta | null>
@@ -15,7 +20,11 @@ export type LocalCanvasStore = {
/** Index-only row for remote canvases not yet downloaded (no fig body). */
upsertIndexMeta(meta: LocalCanvasIndexInput): Promise<LocalCanvasMeta>
writeThumb(id: string, thumbBytes: Uint8Array): Promise<LocalCanvasMeta | null>
- updateMeta(id: string, patch: Partial<LocalCanvasMeta>): Promise<LocalCanvasMeta | null>
+ updateMeta(
+ id: string,
+ patch: Partial<LocalCanvasMeta>,
+ options?: UpdateLocalCanvasMetaOptions
+ ): Promise<LocalCanvasMeta | null>
tombstone(id: string): Promise<LocalCanvasMeta | null>
/** Drop only the cached fig blob (eviction) — meta and thumb stay. */
clearFig(id: string): Promise<LocalCanvasMeta | null>
diff --git a/src/app/storage/reconcile.ts b/src/app/storage/reconcile.ts
new file mode 100644
index 000000000..7bd57bbe5
--- /dev/null
+++ b/src/app/storage/reconcile.ts
@@ -0,0 +1,46 @@
+import type { StorageDocument } from '@/app/integrations/storage'
+import type { LocalCanvasMeta } from '@/app/storage/local-store'
+
+export type StorageReconciliation = {
+ documents: StorageDocument[]
+ remoteDocumentsToSeed: StorageDocument[]
+ localIdsToPurge: string[]
+}
+
+/** Merge a successful remote listing with pending local work without reviving tombstones. */
+export function reconcileStorageDocuments(
+ local: LocalCanvasMeta[],
+ remote: StorageDocument[]
+): StorageReconciliation {
+ const localById = new Map(local.map((metadata) => [metadata.id, metadata]))
+ const tombstonedIds = new Set(
+ local.filter((metadata) => metadata.tombstoned).map((metadata) => metadata.id)
+ )
+ const remoteIds = new Set(remote.map((document) => document.id))
+ const merged = new Map(
+ remote
+ .filter((document) => !tombstonedIds.has(document.id))
+ .map((document) => [document.id, document])
+ )
+
+ for (const metadata of local) {
+ if (metadata.tombstoned) continue
+ if (metadata.syncStatus === 'synced' && merged.has(metadata.id)) continue
+ merged.set(metadata.id, {
+ id: metadata.id,
+ name: metadata.name,
+ updatedAt: metadata.updatedAt,
+ metadataAuthoritative: true
+ })
+ }
+
+ return {
+ documents: [...merged.values()].sort((first, second) =>
+ second.updatedAt.localeCompare(first.updatedAt)
+ ),
+ remoteDocumentsToSeed: remote.filter((document) => !localById.has(document.id)),
+ localIdsToPurge: local
+ .filter((metadata) => metadata.tombstoned && !remoteIds.has(metadata.id))
+ .map((metadata) => metadata.id)
+ }
+}
diff --git a/src/app/storage/sync/engine.ts b/src/app/storage/sync/engine.ts
index 37df9da96..24ecd2b26 100644
--- a/src/app/storage/sync/engine.ts
+++ b/src/app/storage/sync/engine.ts
@@ -3,8 +3,11 @@ import { IS_BROWSER } from '@open-pencil/core/constants'
import {
activeStorageProviderID,
createActiveStorageAdapter,
- storagePreferencesComplete
+ storageCredentialStatuses,
+ storagePreferencesComplete,
+ storageProviderRegistry
} from '@/app/integrations/storage'
+import { evictLocalFigCache } from '@/app/storage/cache-eviction'
import { getLocalCanvasStore } from '@/app/storage/local-store'
import { getOutbox } from '@/app/storage/sync/outbox'
import { setUploadProgress } from '@/app/storage/sync/progress'
@@ -15,6 +18,13 @@ const MAX_ATTEMPTS = 8
const BASE_BACKOFF_MS = 1500
const MAX_BACKOFF_MS = 60_000
+class StorageSyncBlockedError extends Error {
+ constructor(message: string) {
+ super(message)
+ this.name = 'StorageSyncBlockedError'
+ }
+}
+
let pumping = false
let wakeTimer: ReturnType<typeof setTimeout> | null = null
let onlineBound = false
@@ -30,6 +40,12 @@ function backoffMs(attempts: number): number {
return exp + jitter
}
+export function nextSyncWakeDelay(jobs: OutboxJob[], now = Date.now()): number | null {
+ if (jobs.length === 0) return null
+ const nextAt = Math.min(...jobs.map((job) => job.nextAttemptAt))
+ return nextAt === Number.MAX_SAFE_INTEGER ? null : Math.max(250, nextAt - now)
+}
+
function isPermanentError(error: unknown): boolean {
if (!(error instanceof Error)) return false
const msg = error.message.toLowerCase()
@@ -43,12 +59,21 @@ function isPermanentError(error: unknown): boolean {
}
async function runJob(job: OutboxJob): Promise<void> {
- if (!storagePreferencesComplete(activeStorageProviderID.value)) {
- throw new Error('Storage is not configured')
- }
- const adapter = createActiveStorageAdapter()
const store = getLocalCanvasStore()
const meta = await store.getMeta(job.canvasId)
+ const providerID = meta?.providerId ?? activeStorageProviderID.value
+ if (!storagePreferencesComplete(providerID)) {
+ throw new StorageSyncBlockedError('Storage is not configured')
+ }
+ const provider = storageProviderRegistry.get(providerID)
+ const statuses = await storageCredentialStatuses(providerID)
+ const missingCredential = provider.credentialFields.some(
+ (field) => field.required && statuses[field.id] !== 'configured'
+ )
+ if (missingCredential) {
+ throw new StorageSyncBlockedError('Storage credentials are unavailable')
+ }
+ const adapter = createActiveStorageAdapter(providerID)
if (job.type === 'deleteCanvas') {
await adapter.deleteDocument(job.canvasId)
@@ -89,11 +114,16 @@ async function runJob(job: OutboxJob): Promise<void> {
// Only mark synced if still on this revision and no other pending work for newer rev
const latest = await store.getMeta(job.canvasId)
if (latest && latest.revision === job.revision && !latest.tombstoned) {
- await store.updateMeta(job.canvasId, {
- syncStatus: 'synced',
- lastSyncedAt: new Date().toISOString(),
- lastSyncError: null
- })
+ await store.updateMeta(
+ job.canvasId,
+ {
+ syncStatus: 'synced',
+ lastSyncedAt: new Date().toISOString(),
+ lastSyncError: null
+ },
+ { expectedRevision: job.revision }
+ )
+ await evictLocalFigCache(new Set([job.canvasId]))
}
return
}
@@ -126,8 +156,8 @@ async function pumpOnce(): Promise<void> {
// Single-flight globally for simplicity (large figs)
const job = jobs.find((j) => j.nextAttemptAt <= now)
if (!job) {
- const nextAt = Math.min(...jobs.map((j) => j.nextAttemptAt))
- scheduleWake(Math.max(250, nextAt - now))
+ const delay = nextSyncWakeDelay(jobs, now)
+ if (delay != null) scheduleWake(delay)
return
}
@@ -139,9 +169,18 @@ async function pumpOnce(): Promise<void> {
if (remaining.length === 0) setSyncUi('idle')
else scheduleWake(50)
} catch (error) {
+ const message = error instanceof Error ? error.message : String(error)
+ if (error instanceof StorageSyncBlockedError) {
+ await outbox.update({
+ ...job,
+ nextAttemptAt: Number.MAX_SAFE_INTEGER
+ })
+ setSyncUi('error', message)
+ return
+ }
+
const attempts = job.attempts + 1
const permanent = isPermanentError(error) || attempts >= MAX_ATTEMPTS
- const message = error instanceof Error ? error.message : String(error)
console.warn('[Storage sync] job failed:', job.type, job.canvasId, message)
if (permanent) {
@@ -158,11 +197,21 @@ async function pumpOnce(): Promise<void> {
// thumbnail is at least diagnosable.
await getLocalCanvasStore().updateMeta(job.canvasId, { lastSyncError: message })
}
- await outbox.remove(job.id)
- const remaining = await outbox.list()
- setPendingSyncCount(remaining.length)
- if (remaining.length > 0) scheduleWake(1000)
- else if (job.type === 'putThumb') setSyncUi('idle')
+ if (job.type === 'putThumb') {
+ await outbox.remove(job.id)
+ const remaining = await outbox.list()
+ setPendingSyncCount(remaining.length)
+ if (remaining.length > 0) scheduleWake(1000)
+ else setSyncUi('idle')
+ } else {
+ // Never discard a document mutation. Keep it durable until the user
+ // repairs credentials/permissions and explicitly wakes synchronization.
+ await outbox.update({
+ ...job,
+ attempts,
+ nextAttemptAt: Number.MAX_SAFE_INTEGER
+ })
+ }
return
}
@@ -252,6 +301,16 @@ export async function enqueueDeleteCanvas(canvasId: string): Promise<void> {
void kickSyncEngine()
}
+/** Retry durable work immediately after storage settings or credentials change. */
+export async function resumeStorageSync(): Promise<void> {
+ const outbox = getOutbox()
+ const jobs = await outbox.list()
+ const now = Date.now()
+ await Promise.all(jobs.map((job) => outbox.update({ ...job, nextAttemptAt: now })))
+ if (jobs.length > 0) setSyncUi('syncing')
+ void kickSyncEngine()
+}
+
/** After credentials cleared — drop local mirror + outbox (optional safety). */
export async function clearStorageLocalMirror(): Promise<void> {
await getLocalCanvasStore().clearAll()
diff --git a/src/app/storage/sync/index.ts b/src/app/storage/sync/index.ts
index 4bf9f5533..dc919be23 100644
--- a/src/app/storage/sync/index.ts
+++ b/src/app/storage/sync/index.ts
@@ -3,7 +3,8 @@ export {
enqueueDeleteCanvas,
enqueuePutCanvas,
enqueuePutThumb,
- kickSyncEngine
+ kickSyncEngine,
+ resumeStorageSync
} from './engine'
export { createMemoryOutbox, getOutbox, resetOutboxForTests } from './outbox'
export {
diff --git a/src/app/storage/sync/persist.ts b/src/app/storage/sync/persist.ts
index 507658da8..d9c454828 100644
--- a/src/app/storage/sync/persist.ts
+++ b/src/app/storage/sync/persist.ts
@@ -1,4 +1,5 @@
import type { StorageProviderID } from '@/app/integrations/storage/types'
+import { evictLocalFigCache } from '@/app/storage/cache-eviction'
import { getLocalCanvasStore } from '@/app/storage/local-store'
import type { LocalCanvasStore } from '@/app/storage/local-store/store'
import { enqueuePutCanvas } from '@/app/storage/sync/engine'
@@ -63,4 +64,5 @@ export async function seedStorageCanvasFromRemote(
syncStatus: 'synced',
lastSyncError: null
})
+ await evictLocalFigCache(new Set([options.canvasId]))
}
diff --git a/src/app/storage/validate-import.ts b/src/app/storage/validate-import.ts
deleted file mode 100644
index a567e6728..000000000
--- a/src/app/storage/validate-import.ts
+++ /dev/null
@@ -1,137 +0,0 @@
-import { unzipSync } from 'fflate'
-
-export type DesignImportValidation = { ok: true } | { ok: false; message: string }
-
-const FIG_KIWI_MAGIC = 'fig-kiwi'
-/** ZIP local-file / empty / spanned signatures (PK..) */
-const ZIP_LOCAL_SIG = [0x50, 0x4b] as const
-
-function isZipBytes(bytes: Uint8Array): boolean {
- return bytes.byteLength >= 4 && bytes[0] === ZIP_LOCAL_SIG[0] && bytes[1] === ZIP_LOCAL_SIG[1]
-}
-
-function hasFigKiwiMagic(bytes: Uint8Array): boolean {
- if (bytes.byteLength < 8) return false
- return new TextDecoder().decode(bytes.subarray(0, 8)) === FIG_KIWI_MAGIC
-}
-
-/** Pull canvas payload from a Figma ZIP the same way the core parser prefers. */
-function extractFigCanvasBytes(zipBytes: Uint8Array): Uint8Array | null {
- let zip: Record<string, Uint8Array>
- try {
- zip = unzipSync(zipBytes, {
- filter: (file) =>
- file.name === 'canvas.fig' ||
- file.name === 'canvas' ||
- (file.name.startsWith('images/') && file.name !== 'images/')
- })
- } catch {
- return null
- }
-
- const entries = Object.keys(zip)
- for (const name of entries) {
- if (name === 'canvas.fig' || name === 'canvas') return zip[name] ?? null
- }
-
- let best: Uint8Array | null = null
- let maxSize = 0
- for (const name of entries) {
- const lower = name.toLowerCase()
- if (lower.endsWith('.png') || lower.endsWith('.jpg') || lower.endsWith('.json')) continue
- const entry = zip[name]
- if (entry.byteLength > maxSize) {
- maxSize = entry.byteLength
- best = entry
- }
- }
- return best
-}
-
-/**
- * Cheap structural check before cloud upload.
- * Real .fig files are a ZIP with a `fig-kiwi` canvas payload (or raw fig-kiwi).
- */
-export function validateFigBytes(bytes: Uint8Array): DesignImportValidation {
- if (bytes.byteLength < 8) {
- return { ok: false, message: 'This is not a valid .fig file (file is too small).' }
- }
-
- if (isZipBytes(bytes)) {
- const canvas = extractFigCanvasBytes(bytes)
- if (!canvas) {
- return {
- ok: false,
- message: 'This is not a valid .fig file (missing canvas data).'
- }
- }
- if (!hasFigKiwiMagic(canvas)) {
- return {
- ok: false,
- message: 'This is not a valid .fig file (canvas is not fig-kiwi).'
- }
- }
- return { ok: true }
- }
-
- if (hasFigKiwiMagic(bytes)) return { ok: true }
-
- return {
- ok: false,
- message: 'This is not a valid .fig file (expected a Figma document).'
- }
-}
-
-/**
- * Cheap structural check: UTF-8 JSON object with a `children` array (Pencil .pen shape).
- */
-export function validatePenBytes(bytes: Uint8Array): DesignImportValidation {
- if (bytes.byteLength === 0) {
- return { ok: false, message: 'This is not a valid .pen file (file is empty).' }
- }
-
- let text: string
- try {
- text = new TextDecoder('utf-8', { fatal: true }).decode(bytes)
- } catch {
- return {
- ok: false,
- message: 'This is not a valid .pen file (not valid UTF-8 text).'
- }
- }
-
- let parsed: unknown
- try {
- parsed = JSON.parse(text)
- } catch {
- return { ok: false, message: 'This is not a valid .pen file (invalid JSON).' }
- }
-
- if (parsed == null || typeof parsed !== 'object' || Array.isArray(parsed)) {
- return {
- ok: false,
- message: 'This is not a valid .pen file (expected a JSON object).'
- }
- }
-
- const children = (parsed as { children?: unknown }).children
- if (!Array.isArray(children)) {
- return {
- ok: false,
- message: 'This is not a valid .pen file (missing a children array).'
- }
- }
-
- return { ok: true }
-}
-
-/** Validate import bytes by file extension (.fig / .pen). */
-export function validateDesignImportBytes(
- fileName: string,
- bytes: Uint8Array
-): DesignImportValidation {
- const lower = fileName.toLowerCase()
- if (lower.endsWith('.fig')) return validateFigBytes(bytes)
- if (lower.endsWith('.pen')) return validatePenBytes(bytes)
- return { ok: false, message: 'Only .fig and .pen files can be imported.' }
-}
diff --git a/src/components/settings/models/ModelsPanel.vue b/src/components/settings/models/ModelsPanel.vue
index f16f5a182..105c989ae 100644
--- a/src/components/settings/models/ModelsPanel.vue
+++ b/src/components/settings/models/ModelsPanel.vue
@@ -2,7 +2,7 @@
import { computed, ref, watch } from 'vue'
import { useI18n } from '@open-pencil/vue'
-import { AI_PROVIDERS } from '@open-pencil/core/constants'
+import { ACP_AGENTS, AI_PROVIDERS } from '@open-pencil/core/constants'
import { aiModelSettings, modelConnection, modelConnectionCredentialStatus } from '@/app/ai/models'
import type { CredentialStatus } from '@/app/settings/credentials/types'
@@ -13,6 +13,14 @@ const { dialogs } = useI18n()
const editing = ref(false)
const editingProfileId = ref<string>()
const statusByConnection = ref<Record<string, CredentialStatus>>({})
+function providerName(providerID: string): string {
+ if (providerID.startsWith('acp:')) {
+ const agentID = providerID.slice('acp:'.length)
+ return ACP_AGENTS.find((agent) => agent.id === agentID)?.name ?? providerID
+ }
+ return AI_PROVIDERS.find((provider) => provider.id === providerID)?.name ?? providerID
+}
+
const profiles = computed(() =>
aiModelSettings.value.models.map((profile) => {
const connection = modelConnection(profile.connectionId)
@@ -22,7 +30,7 @@ const profiles = computed(() =>
return {
...profile,
providerID: connection?.providerID ?? '',
- providerName: provider?.name ?? connection?.providerID ?? '',
+ providerName: providerName(connection?.providerID ?? ''),
modelName
}
})
diff --git a/src/components/settings/models/ProfileEditor.vue b/src/components/settings/models/ProfileEditor.vue
index 64faf8f7c..1c3739f84 100644
--- a/src/components/settings/models/ProfileEditor.vue
+++ b/src/components/settings/models/ProfileEditor.vue
@@ -8,7 +8,7 @@ import {
} from 'reka-ui'
import { useI18n } from '@open-pencil/vue'
-import { AI_PROVIDERS, type AIProviderID } from '@open-pencil/core/constants'
+import { ACP_AGENTS, AI_PROVIDERS, type AIProviderID } from '@open-pencil/core/constants'
import { refreshAIProviderStatus } from '@/app/ai/chat/storage'
import {
@@ -53,6 +53,11 @@ const providerDef = computed(
() => AI_PROVIDERS.find((provider) => provider.id === draft.providerID) ?? AI_PROVIDERS[0]
)
const isACP = computed(() => draft.providerID.startsWith('acp:'))
+const providerDisplayName = computed(() => {
+ if (!isACP.value) return providerDef.value.name
+ const agentID = draft.providerID.slice('acp:'.length)
+ return ACP_AGENTS.find((agent) => agent.id === agentID)?.name ?? draft.providerID
+})
const modelOptions = computed(() =>
providerDef.value.models.map((model) => ({ value: model.id, label: model.name }))
)
@@ -108,7 +113,7 @@ function updateProvider(providerID: AIProviderID): void {
draft.customAPIType = 'completions'
if (providerID.startsWith('acp:')) {
draft.capabilities = ['tools']
- if (!draft.name.trim()) draft.name = provider?.name ?? ''
+ if (!draft.name.trim()) draft.name = providerDisplayName.value
}
keyInput.value = ''
resetConnectionTest()
@@ -124,7 +129,7 @@ function updateModel(modelID: string): void {
async function save(): Promise<void> {
saveError.value = null
try {
- if (!draft.name.trim()) draft.name = modelDisplayName.value || providerDef.value.name
+ if (!draft.name.trim()) draft.name = modelDisplayName.value || providerDisplayName.value
const profile = saveModelProfileDraft(draft)
if (keyInput.value.trim()) {
await setModelConnectionAPIKey(profile.connectionId, keyInput.value)
diff --git a/src/components/settings/models/RoleAssignments.vue b/src/components/settings/models/RoleAssignments.vue
index d60c9058e..d8c5daa13 100644
--- a/src/components/settings/models/RoleAssignments.vue
+++ b/src/components/settings/models/RoleAssignments.vue
@@ -4,6 +4,7 @@ import { useI18n } from '@open-pencil/vue'
import {
aiModelSettings,
+ isACPModelProfile,
modelProfile,
setModelRoleAssignment,
type AIModelRole,
@@ -48,6 +49,7 @@ function optionsForRole(role: AIModelRole) {
const profiles = aiModelSettings.value.models
.filter((profile) => {
if (role === 'design') return profile.capabilities.includes('tools')
+ if (isACPModelProfile(profile)) return false
if (role === 'vision') return profile.capabilities.includes('vision')
return true
})
@@ -55,7 +57,8 @@ function optionsForRole(role: AIModelRole) {
if (role === 'design') return profiles
const design = modelProfile(aiModelSettings.value.assignments.design)
- const canInherit = role !== 'vision' || design?.capabilities.includes('vision')
+ const canInherit =
+ !isACPModelProfile(design) && (role !== 'vision' || design?.capabilities.includes('vision'))
return [
...(canInherit ? [{ value: SAME_AS_DESIGN, label: dialogs.value.modelRoleUseDesign }] : []),
{ value: NO_MODEL, label: dialogs.value.noModel },
diff --git a/src/components/settings/storage/StorageSettingsPanel.vue b/src/components/settings/storage/StorageSettingsPanel.vue
index a3655dac0..6a343613a 100644
--- a/src/components/settings/storage/StorageSettingsPanel.vue
+++ b/src/components/settings/storage/StorageSettingsPanel.vue
@@ -1,5 +1,6 @@
<script setup lang="ts">
-import { computed, onMounted, ref } from 'vue'
+import { computed, onMounted, ref, watch } from 'vue'
+import { useClipboard } from '@vueuse/core'
import { useRouter } from 'vue-router'
import { useI18n } from '@open-pencil/vue'
@@ -12,24 +13,32 @@ import {
storageProviderRegistry,
writeStoragePreference
} from '@/app/integrations/storage'
+import {
+ buildCorsConfigurationJson,
+ collectCloudCorsOrigins
+} from '@/app/integrations/storage/s3/cors'
import { appCredentialServices } from '@/app/settings/credentials/app'
import { settingsDialogOpen } from '@/app/settings/dialog'
import { credentialRef } from '@/app/settings/credentials/reference'
import type { CredentialStatus } from '@/app/settings/credentials/types'
+import { resumeStorageSync } from '@/app/storage/sync'
import AppInput from '@/components/ui/AppInput.vue'
const { dialogs } = useI18n()
const router = useRouter()
-const provider = storageProviderRegistry.get(activeStorageProviderID.value)
-const preferenceDrafts = ref<Record<string, string>>({ ...readStoragePreferences(provider.id) })
+const { copy, copied } = useClipboard()
+const provider = computed(() => storageProviderRegistry.get(activeStorageProviderID.value))
+const preferenceDrafts = ref<Record<string, string>>({
+ ...readStoragePreferences(provider.value.id)
+})
const credentialDrafts = ref<Record<string, string>>({})
const credentialStatuses = ref<Record<string, CredentialStatus>>({})
const busy = ref(false)
const result = ref<{ ok: boolean; message: string } | null>(null)
const configured = computed(
() =>
- storagePreferencesComplete(provider.id) &&
- provider.credentialFields.every(
+ storagePreferencesComplete(provider.value.id) &&
+ provider.value.credentialFields.every(
(field) => !field.required || credentialStatuses.value[field.id] === 'configured'
)
)
@@ -48,25 +57,27 @@ function credentialLabel(field: string): string {
}
async function refreshStatuses(): Promise<void> {
- credentialStatuses.value = await storageCredentialStatuses(provider.id)
+ credentialStatuses.value = await storageCredentialStatuses(provider.value.id)
}
function savePreferences(): void {
- for (const field of provider.preferenceFields) {
- writeStoragePreference(provider.id, field.id, preferenceDrafts.value[field.id] ?? '')
+ for (const field of provider.value.preferenceFields) {
+ writeStoragePreference(provider.value.id, field.id, preferenceDrafts.value[field.id] ?? '')
}
+ void resumeStorageSync()
}
async function saveCredential(field: string): Promise<void> {
const value = credentialDrafts.value[field]?.trim()
if (!value) return
- await appCredentialServices.manager.set(credentialRef(provider.id, field), value)
+ await appCredentialServices.manager.set(credentialRef(provider.value.id, field), value)
credentialDrafts.value[field] = ''
await refreshStatuses()
+ await resumeStorageSync()
}
async function clearCredential(field: string): Promise<void> {
- await appCredentialServices.manager.clear(credentialRef(provider.id, field))
+ await appCredentialServices.manager.clear(credentialRef(provider.value.id, field))
credentialDrafts.value[field] = ''
await refreshStatuses()
}
@@ -76,15 +87,20 @@ async function openWorkspace(): Promise<void> {
await router.push('/storage')
}
+function copyCorsConfiguration(): void {
+ void copy(buildCorsConfigurationJson(collectCloudCorsOrigins()))
+}
+
async function testConnection(): Promise<void> {
busy.value = true
result.value = null
try {
savePreferences()
- for (const field of provider.credentialFields) {
+ for (const field of provider.value.credentialFields) {
await saveCredential(field.id)
}
- result.value = await createActiveStorageAdapter(provider.id).testConnection()
+ await resumeStorageSync()
+ result.value = await createActiveStorageAdapter(provider.value.id).testConnection()
} catch (error) {
result.value = {
ok: false,
@@ -95,6 +111,13 @@ async function testConnection(): Promise<void> {
}
}
+watch(activeStorageProviderID, (providerID) => {
+ preferenceDrafts.value = { ...readStoragePreferences(providerID) }
+ credentialDrafts.value = {}
+ result.value = null
+ void refreshStatuses()
+})
+
onMounted(() => void refreshStatuses())
</script>
@@ -174,6 +197,15 @@ onMounted(() => void refreshStatuses())
{{ dialogs.testConnection }}
</button>
+ <button
+ v-if="provider.id === 's3-compatible'"
+ type="button"
+ class="rounded px-3 py-1.5 text-[11px] text-muted hover:bg-hover hover:text-surface"
+ @click="copyCorsConfiguration"
+ >
+ {{ copied ? dialogs.copied : dialogs.copyStorageCors }}
+ </button>
+
<button
type="button"
class="rounded border border-border px-3 py-1.5 text-[11px] font-medium text-surface hover:bg-hover disabled:text-muted disabled:opacity-50"
diff --git a/src/views/StorageView.vue b/src/views/StorageView.vue
index b106572f8..039e7b6a6 100644
--- a/src/views/StorageView.vue
+++ b/src/views/StorageView.vue
@@ -14,19 +14,20 @@ import {
import { openSettingsDialog, settingsDialogOpen } from '@/app/settings/dialog'
import type { CredentialStatus } from '@/app/settings/credentials/types'
import { createCanvasId } from '@/app/storage/id'
+import { reconcileStorageDocuments } from '@/app/storage/reconcile'
import AppPlaceholder from '@/components/ui/AppPlaceholder.vue'
import { getLocalCanvasStore } from '@/app/storage/local-store'
import { activeTab, createTab, openStorageDocumentInNewTab } from '@/app/tabs'
const { dialogs } = useI18n()
const router = useRouter()
-const provider = storageProviderRegistry.get(activeStorageProviderID.value)
+const provider = computed(() => storageProviderRegistry.get(activeStorageProviderID.value))
const documents = ref<StorageDocument[]>([])
const credentialStatuses = ref<Record<string, CredentialStatus>>({})
const configured = computed(
() =>
- storagePreferencesComplete(provider.id) &&
- provider.credentialFields.every(
+ storagePreferencesComplete(provider.value.id) &&
+ provider.value.credentialFields.every(
(field) => !field.required || credentialStatuses.value[field.id] === 'configured'
)
)
@@ -34,7 +35,9 @@ const loading = ref(false)
const error = ref<string | null>(null)
async function paintLocalDocuments(): Promise<void> {
- const local = await getLocalCanvasStore().listMetas()
+ const local = (await getLocalCanvasStore().listMetas()).filter(
+ (metadata) => metadata.providerId === activeStorageProviderID.value
+ )
documents.value = local.map((metadata) => ({
id: metadata.id,
name: metadata.name,
@@ -48,31 +51,22 @@ async function refresh(): Promise<void> {
error.value = null
await paintLocalDocuments()
try {
- credentialStatuses.value = await storageCredentialStatuses(provider.id)
+ credentialStatuses.value = await storageCredentialStatuses(provider.value.id)
if (!configured.value) {
error.value = dialogs.value.storageNotConfigured
return
}
const remote = await createActiveStorageAdapter().listDocuments()
- const local = await getLocalCanvasStore().listMetas()
- const localById = new Map(local.map((metadata) => [metadata.id, metadata]))
- const merged = new Map(remote.map((document) => [document.id, document]))
- for (const metadata of local) {
- if (metadata.syncStatus === 'synced' && merged.has(metadata.id)) continue
- merged.set(metadata.id, {
- id: metadata.id,
- name: metadata.name,
- updatedAt: metadata.updatedAt,
- metadataAuthoritative: true
- })
- }
- documents.value = [...merged.values()].sort((first, second) =>
- second.updatedAt.localeCompare(first.updatedAt)
+ const localStore = getLocalCanvasStore()
+ const local = (await localStore.listMetas(true)).filter(
+ (metadata) => metadata.providerId === activeStorageProviderID.value
)
+ const reconciliation = reconcileStorageDocuments(local, remote)
+ documents.value = reconciliation.documents
- for (const document of remote) {
- if (localById.has(document.id)) continue
- await getLocalCanvasStore().upsertIndexMeta({
+ for (const id of reconciliation.localIdsToPurge) await localStore.remove(id)
+ for (const document of reconciliation.remoteDocumentsToSeed) {
+ await localStore.upsertIndexMeta({
id: document.id,
providerId: activeStorageProviderID.value,
name: document.name,
@@ -112,6 +106,8 @@ async function createDocument(): Promise<void> {
await store.saveFigFile()
}
+watch(activeStorageProviderID, () => void refresh())
+
watch(settingsDialogOpen, (open, wasOpen) => {
if (wasOpen && !open) void refresh()
})
diff --git a/tests/engine/app/ai/model-roles.test.ts b/tests/engine/app/ai/model-roles.test.ts
index 9b8cf255e..1adae8eb8 100644
--- a/tests/engine/app/ai/model-roles.test.ts
+++ b/tests/engine/app/ai/model-roles.test.ts
@@ -111,6 +111,43 @@ describe('AI model profiles and role assignments', () => {
expect(modelSettingsSnapshot().connections).toHaveLength(2)
})
+ test('keeps ACP agents exclusive to the Design role', () => {
+ const settings = modelSettingsSnapshot()
+ settings.connections.push({
+ id: 'connection-acp',
+ providerID: 'acp:claude-code',
+ customBaseURL: '',
+ customAPIType: 'completions',
+ credentialProfileId: 'connection-acp'
+ })
+ settings.models.push({
+ id: 'model-acp',
+ name: 'Claude Code',
+ connectionId: 'connection-acp',
+ modelID: '',
+ customModelID: '',
+ maxOutputTokens: 16_384,
+ capabilities: ['tools']
+ })
+ replaceAIModelSettings(settings)
+
+ setModelRoleAssignment('review', null)
+ setModelRoleAssignment('review', 'model-acp')
+ expect(resolveAIModelRole('review')).toBeNull()
+
+ setModelRoleAssignment('design', 'model-acp')
+ expect(resolveAIModelRole('design')?.profile.id).toBe('model-acp')
+ setModelRoleAssignment('fast', null)
+ setModelRoleAssignment('fast', 'design')
+ expect(resolveAIModelRole('fast')).toBeNull()
+ })
+
+ test('normalizes invalid output limits before persistence', () => {
+ const draft = createModelProfileDraft('model-fast')
+ draft.maxOutputTokens = Number.NaN
+ expect(saveModelProfileDraft(draft).maxOutputTokens).toBe(16_384)
+ })
+
test('repairs assignments when removing a model', () => {
removeModelProfile('model-design')
const settings = modelSettingsSnapshot()
diff --git a/tests/engine/app/storage/local-store.test.ts b/tests/engine/app/storage/local-store.test.ts
index 87122c90c..de72ce3a9 100644
--- a/tests/engine/app/storage/local-store.test.ts
+++ b/tests/engine/app/storage/local-store.test.ts
@@ -1,9 +1,11 @@
+import 'fake-indexeddb/auto'
import { describe, expect, test } from 'bun:test'
import {
createMemoryLocalCanvasStore,
resetLocalCanvasStoreForTests
} from '@/app/storage/local-store'
+import { createIdbLocalCanvasStore } from '@/app/storage/local-store/idb'
import { expectDefined } from '#tests/helpers/assert'
@@ -49,6 +51,21 @@ describe('local canvas store (memory)', () => {
expect((await store.listMetas(true)).length).toBe(1)
})
+ test('rejects stale revision-conditional metadata updates', async () => {
+ const store = createMemoryLocalCanvasStore()
+ await store.writeCanvas({
+ id: 'conditional',
+ providerId: 's3-compatible',
+ name: 'Draft',
+ figBytes: new Uint8Array([1])
+ })
+
+ expect(
+ await store.updateMeta('conditional', { syncStatus: 'synced' }, { expectedRevision: 0 })
+ ).toBeNull()
+ expect((await store.getMeta('conditional'))?.syncStatus).toBe('pending')
+ })
+
test('upsertIndexMeta does not require fig body', async () => {
const store = createMemoryLocalCanvasStore()
const meta = await store.upsertIndexMeta({
@@ -65,3 +82,27 @@ describe('local canvas store (memory)', () => {
expect(await store.readFig('remote-1')).toBeNull()
})
})
+
+describe('local canvas store (IndexedDB)', () => {
+ test('serializes concurrent writes into distinct revisions', async () => {
+ const store = createIdbLocalCanvasStore()
+ const id = `concurrent-${crypto.randomUUID()}`
+ const writes = await Promise.all([
+ store.writeCanvas({
+ id,
+ providerId: 's3-compatible',
+ name: 'First',
+ figBytes: new Uint8Array([1])
+ }),
+ store.writeCanvas({
+ id,
+ providerId: 's3-compatible',
+ name: 'Second',
+ figBytes: new Uint8Array([2])
+ })
+ ])
+
+ expect(writes.map((meta) => meta.revision).sort()).toEqual([1, 2])
+ expect((await store.getMeta(id))?.revision).toBe(2)
+ })
+})
diff --git a/tests/engine/app/storage/reconcile.test.ts b/tests/engine/app/storage/reconcile.test.ts
new file mode 100644
index 000000000..7363899f1
--- /dev/null
+++ b/tests/engine/app/storage/reconcile.test.ts
@@ -0,0 +1,63 @@
+import { describe, expect, test } from 'bun:test'
+
+import type { StorageDocument } from '@/app/integrations/storage'
+import type { LocalCanvasMeta } from '@/app/storage/local-store'
+import { reconcileStorageDocuments } from '@/app/storage/reconcile'
+
+function localMeta(
+ id: string,
+ syncStatus: LocalCanvasMeta['syncStatus'],
+ tombstoned = false
+): LocalCanvasMeta {
+ return {
+ id,
+ providerId: 's3-compatible',
+ name: `Local ${id}`,
+ updatedAt: '2026-01-02T00:00:00.000Z',
+ revision: 1,
+ syncStatus,
+ lastSyncedAt: null,
+ lastSyncError: null,
+ tombstoned,
+ hasFig: true,
+ hasThumb: false,
+ figSize: 1
+ }
+}
+
+function remoteDocument(id: string): StorageDocument {
+ return {
+ id,
+ name: `Remote ${id}`,
+ updatedAt: '2026-01-01T00:00:00.000Z',
+ metadataAuthoritative: true
+ }
+}
+
+describe('storage workspace reconciliation', () => {
+ test('keeps pending local metadata ahead of the remote listing', () => {
+ const result = reconcileStorageDocuments(
+ [localMeta('pending', 'pending')],
+ [remoteDocument('pending'), remoteDocument('remote')]
+ )
+
+ expect(result.documents.map((document) => document.name)).toEqual([
+ 'Local pending',
+ 'Remote remote'
+ ])
+ expect(result.remoteDocumentsToSeed.map((document) => document.id)).toEqual(['remote'])
+ })
+
+ test('hides tombstones until deletion is confirmed and then purges them', () => {
+ const waiting = reconcileStorageDocuments(
+ [localMeta('deleted', 'synced', true)],
+ [remoteDocument('deleted')]
+ )
+ expect(waiting.documents).toEqual([])
+ expect(waiting.localIdsToPurge).toEqual([])
+ expect(waiting.remoteDocumentsToSeed).toEqual([])
+
+ const confirmed = reconcileStorageDocuments([localMeta('deleted', 'synced', true)], [])
+ expect(confirmed.localIdsToPurge).toEqual(['deleted'])
+ })
+})
diff --git a/tests/engine/app/storage/sync-outbox.test.ts b/tests/engine/app/storage/sync-outbox.test.ts
index f452e4dd4..9738ead8a 100644
--- a/tests/engine/app/storage/sync-outbox.test.ts
+++ b/tests/engine/app/storage/sync-outbox.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, test } from 'bun:test'
+import { nextSyncWakeDelay } from '@/app/storage/sync/engine'
import { createMemoryOutbox } from '@/app/storage/sync/outbox'
import { supersedePutCanvasJobs, type OutboxJob } from '@/app/storage/sync/types'
@@ -39,6 +40,22 @@ describe('supersedePutCanvasJobs', () => {
})
})
+describe('sync wake scheduling', () => {
+ test('does not poll jobs parked for repaired configuration', () => {
+ const parked: OutboxJob = {
+ id: 'parked',
+ canvasId: 'c1',
+ type: 'putCanvas',
+ revision: 1,
+ createdAt: 1,
+ attempts: 0,
+ nextAttemptAt: Number.MAX_SAFE_INTEGER
+ }
+ expect(nextSyncWakeDelay([parked], 100)).toBeNull()
+ expect(nextSyncWakeDelay([{ ...parked, nextAttemptAt: 500 }], 100)).toBe(400)
+ })
+})
+
describe('memory outbox', () => {
test('enqueues and supersedes putCanvas', async () => {
const outbox = createMemoryOutbox()
diff --git a/tests/engine/app/storage/validate-import.test.ts b/tests/engine/app/storage/validate-import.test.ts
deleted file mode 100644
index 0990ee08d..000000000
--- a/tests/engine/app/storage/validate-import.test.ts
+++ /dev/null
@@ -1,70 +0,0 @@
-import { describe, expect, test } from 'bun:test'
-import { readFileSync } from 'node:fs'
-import { join } from 'node:path'
-
-import {
- validateDesignImportBytes,
- validateFigBytes,
- validatePenBytes
-} from '@/app/storage/validate-import'
-
-const fixtureFig = join(import.meta.dir, '../../../fixtures/gold-preview.fig')
-
-describe('validateFigBytes', () => {
- test('accepts a real Figma ZIP fixture', () => {
- const bytes = new Uint8Array(readFileSync(fixtureFig))
- expect(validateFigBytes(bytes)).toEqual({ ok: true })
- })
-
- test('accepts raw fig-kiwi payload', () => {
- const raw = new TextEncoder().encode('fig-kiwi' + '\0'.repeat(8))
- expect(validateFigBytes(raw).ok).toBe(true)
- })
-
- test('rejects empty / random / plain text', () => {
- expect(validateFigBytes(new Uint8Array()).ok).toBe(false)
- expect(validateFigBytes(new TextEncoder().encode('hello world')).ok).toBe(false)
- expect(validateFigBytes(new TextEncoder().encode('{"foo":1}')).ok).toBe(false)
- })
-
- test('rejects a ZIP that is not a Figma document', () => {
- // Minimal empty ZIP (end of central directory only) — not a fig container.
- const emptyZip = Uint8Array.from([
- 0x50, 0x4b, 0x05, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
- ])
- expect(validateFigBytes(emptyZip).ok).toBe(false)
- })
-})
-
-describe('validatePenBytes', () => {
- test('accepts a minimal pen document shape', () => {
- const bytes = new TextEncoder().encode(
- JSON.stringify({
- version: '2.6',
- children: [{ type: 'frame', id: '1', name: 'Page 1' }]
- })
- )
- expect(validatePenBytes(bytes)).toEqual({ ok: true })
- })
-
- test('rejects invalid JSON and wrong shapes', () => {
- expect(validatePenBytes(new TextEncoder().encode('not json')).ok).toBe(false)
- expect(validatePenBytes(new TextEncoder().encode('[]')).ok).toBe(false)
- expect(validatePenBytes(new TextEncoder().encode('{"name":"x"}')).ok).toBe(false)
- expect(validatePenBytes(new TextEncoder().encode('{"children":{}}')).ok).toBe(false)
- expect(validatePenBytes(new Uint8Array()).ok).toBe(false)
- })
-})
-
-describe('validateDesignImportBytes', () => {
- test('routes by extension', () => {
- const fig = new Uint8Array(readFileSync(fixtureFig))
- expect(validateDesignImportBytes('a.fig', fig).ok).toBe(true)
- expect(
- validateDesignImportBytes('a.pen', new TextEncoder().encode(JSON.stringify({ children: [] })))
- .ok
- ).toBe(true)
- expect(validateDesignImportBytes('a.txt', fig).ok).toBe(false)
- })
-})