` per QA rule, kind `qa-rule`, no permissions — labels/descriptions from `QA_RULE_LABELS`) and `FORMAT_EXTENSION_MANIFESTS` (`format.xliff`/`format.docx`/`format.tmx`/`format.tbx`/`format.csv`, kinds `import-format`/`export-format`, `filesystem` permission); `BUILTIN_MANIFESTS` = MT + QA + formats, all registered by `registerBuiltinExtensions()`. `core/qa/registryRules.ts` — `isQaRuleEnabled(code)` (registry, **defaults on when the manifest isn't registered** so `runQA` stays pure and its tests are untouched) + `effectiveQaRules(toggles)` which ANDs the per-project rule toggles with the registry; `QAPanel` runs `runQA` with `effectiveQaRules(settings.qaRules)` and re-derives via `useSyncExternalStore(extensionRegistry.subscribe)` so toggling a QA addon changes QA output live. `features/addons/AddonsPage.tsx` — the `/addons` catalogue: sections per kind (Machine translation, Quality assurance, Import & export formats), each row showing the name, description, **permission chips**, and a Built-in badge; MT + QA rows get a working enable/disable toggle (enforced — MT panel + QA output react), formats are shown **Always on** (their round-trip logic stays in `core/*`; format-level gating is a follow-up, kept out to avoid touching every import/export path). New `/addons` route (lazy `AddonsPage`) + a Puzzle nav item. Deviations (noted): built on the designated session branch, not `claude/revamp-phase-6-2`; format addons are catalogue/display-only in v1 (no toggle) — only the DoD's QA + the 6.1 MT toggles are enforced. No migration. Tests: `qa.registryRules` (falls back all-on when unregistered; disabling `qa.double_space` forces it off + **removes the finding from `runQA` output** — the DoD; others unaffected), `AddonsPage` (lists MT + QA + format sections/rows; toggling a QA addon flips registry enablement; formats have no toggle). Verified: flag-OFF `dist` Supabase-free (AddonsPage its own lazy chunk); full e2e green after the nav/route addition. Green: 688 unit (+6) / 29 e2e / build. No new e2e (ROADMAP §6.2 asks none).
+- 2026-07-21 — Phase 6.2 merged in PR #64. Phase 6.3 built: the Google Drive storage-connector addon (start of the connector half of **Milestone 6**). **Pure client OAuth** via Google Identity Services (GIS) — **independent of Supabase**, so the connector works for 100%-local users too (ROADMAP §6.3). New generic `src/extensions/connectors/types.ts` — a provider-agnostic `StorageConnector` (`isConfigured`/`listFiles`/`downloadFile`/`uploadFile`) + `ConnectorFile`/`ConnectorUpload` + a coarse `ConnectorError` (mirrors `MTError`), written once so 6.4's OneDrive reuses it. `src/extensions/connectors/gdrive/`: `config.ts` (lightweight gate — `googleClientId()` from `VITE_GOOGLE_CLIENT_ID`, `isGdriveConfigured()`, `isGdriveAvailable()` = configured AND registry-enabled; no GIS/REST imports so UI can decide whether to *offer* Drive without pulling the heavy code); `driveApi.ts` (the pure, unit-testable REST layer — `listDriveFiles`/`downloadDriveFile`/`uploadDriveFile`, each taking an OAuth token + an injectable `fetchImpl` like `core/mt/*`, using the narrow **`drive.file` scope** to dodge Google's restricted-scope verification, multipart upload, status→code error mapping); `gis.ts` (thin DOM boundary — injects the GSI script on first use, requests a `drive.file` token via popup, token held **in memory only**, never Dexie/localStorage); `index.ts` (`createGdriveConnector({getToken, fetchImpl})` factory pairing GIS+REST, tested with a fake token getter + fetch, plus the real `gdriveConnector` singleton). Generic `ConnectorFilePicker.tsx` lists a connector's files, filters by an `accept` predicate, and returns the downloaded `File`. `core/extensions/builtins.ts` registers `CONNECTOR_EXTENSION_MANIFESTS` (`connector.gdrive`, kind `storage-connector`, permissions `network`/`credentials`/`filesystem`); `BUILTIN_MANIFESTS` = MT + QA + formats + connectors. Wiring: `ImportDialog` gains a **From Google Drive** button (gated on `isGdriveAvailable()`; dynamically imports the connector on click → picker → sets the import file, then the existing import flow runs unchanged); `ExportDocxButton` gains **Save to Drive** (builds the same clean `.docx`, uploads via the connector); `AddonsPage` gains a **Storage connectors** section with a working enable/disable toggle (disabling hides both affordances). `deploy.yml` + `.env.example` carry `VITE_GOOGLE_CLIENT_ID` (public by design — a Web OAuth client id gated by the console's authorised-origins allow-list). Deviations (noted): built on the designated session branch, not `claude/revamp-phase-6-3`; the connector is intentionally **not** hidden behind the Supabase flag (it is pure client OAuth, so it ships in the entry like the collab leases — the heavy Drive REST is still code-split into a lazy chunk, and no connector code executes until the user clicks, via the dynamic `import()` + the `isGdriveAvailable()` gate). `docs/cloud.md` §13 (Google Cloud console setup + manual verification). Tests: `connectors.driveApi` (list builds the right query/Bearer + maps files; download `alt=media`; multipart upload asserts metadata+media in the body; 401→auth / 429→rate_limit / network-throw mapping), `connectors.gdrive` (config gating on the env var; manifest registration; `isGdriveAvailable` ANDs config with registry enablement; the factory lists/downloads-into-a-named-`File`/uploads through injected token+fetch), `ConnectorFilePicker` (lists accepted files, hides rejected, pick→download→onPick+close, error surfaced), `AddonsPage` extended (storage-connector section + `connector.gdrive` row + toggle). Verified: flag-OFF `dist` still **zero** `GoTrueClient`; the Drive REST is a separate lazy chunk. Green: 705 unit (+17) / build. No new e2e (ROADMAP §6.3 asks none; the real Drive round-trip is the `docs/cloud.md` §13 manual matrix — vitest never hits GIS or the network).
diff --git a/src/core/extensions/builtins.ts b/src/core/extensions/builtins.ts
index aa3786e..b1562d3 100644
--- a/src/core/extensions/builtins.ts
+++ b/src/core/extensions/builtins.ts
@@ -112,11 +112,27 @@ export const FORMAT_EXTENSION_MANIFESTS: ExtensionManifest[] = [
},
]
-/** Every built-in manifest, in catalogue order (MT, then QA, then formats). */
+/** Storage connectors as addons (ROADMAP §6.3/§6.4). Pure client OAuth, so they
+ * work for local-only users too; disabling one hides its import/export
+ * affordances. `credentials` = it holds an OAuth token in memory. */
+export const CONNECTOR_EXTENSION_MANIFESTS: ExtensionManifest[] = [
+ {
+ id: 'connector.gdrive',
+ name: 'Google Drive',
+ version: '1.0.0',
+ kinds: ['storage-connector'],
+ permissions: ['network', 'credentials', 'filesystem'],
+ builtIn: true,
+ description: 'Import files from and save exports to Google Drive.',
+ },
+]
+
+/** Every built-in manifest, in catalogue order (MT, QA, formats, connectors). */
export const BUILTIN_MANIFESTS: ExtensionManifest[] = [
...MT_EXTENSION_MANIFESTS,
...QA_EXTENSION_MANIFESTS,
...FORMAT_EXTENSION_MANIFESTS,
+ ...CONNECTOR_EXTENSION_MANIFESTS,
]
let registered = false
diff --git a/src/extensions/connectors/ConnectorFilePicker.tsx b/src/extensions/connectors/ConnectorFilePicker.tsx
new file mode 100644
index 0000000..8f3e9e4
--- /dev/null
+++ b/src/extensions/connectors/ConnectorFilePicker.tsx
@@ -0,0 +1,176 @@
+import { useEffect, useState } from 'react'
+import { FileText, RefreshCw } from 'lucide-react'
+import {
+ Dialog,
+ DialogContent,
+ DialogHeader,
+ DialogTitle,
+ DialogDescription,
+ DialogFooter,
+} from '@/components/ui/dialog'
+import { Button } from '@/components/ui/button'
+import { Input } from '@/components/ui/input'
+import type { ConnectorFile, StorageConnector } from './types'
+
+/**
+ * Generic cloud-file picker (Phase 6.3). Provider-agnostic — it lists files
+ * from any `StorageConnector`, filters to the acceptable ones, and calls
+ * `onPick` with the downloaded `File`. Reused by every connector (Google Drive
+ * now, OneDrive in 6.4) so import/export wiring is written once.
+ */
+
+interface ConnectorFilePickerProps {
+ connector: StorageConnector
+ open: boolean
+ onOpenChange: (open: boolean) => void
+ /** Predicate limiting which listed files are selectable (e.g. by extension). */
+ accept?: (file: ConnectorFile) => boolean
+ /** Called with the downloaded file once the user picks one. */
+ onPick: (file: File) => void
+}
+
+function messageFor(err: unknown): string {
+ const msg = err instanceof Error ? err.message : String(err)
+ return msg || 'Could not reach the cloud drive.'
+}
+
+export function ConnectorFilePicker({
+ connector,
+ open,
+ onOpenChange,
+ accept,
+ onPick,
+}: ConnectorFilePickerProps) {
+ const [files, setFiles] = useState(null)
+ const [error, setError] = useState(null)
+ const [loading, setLoading] = useState(false)
+ const [downloadingId, setDownloadingId] = useState(null)
+ const [query, setQuery] = useState('')
+
+ async function load(q?: string) {
+ setLoading(true)
+ setError(null)
+ try {
+ const listed = await connector.listFiles(q ? { query: q } : undefined)
+ setFiles(accept ? listed.filter(accept) : listed)
+ } catch (err) {
+ setError(messageFor(err))
+ setFiles(null)
+ } finally {
+ setLoading(false)
+ }
+ }
+
+ useEffect(() => {
+ if (open) {
+ setQuery('')
+ void load()
+ } else {
+ setFiles(null)
+ setError(null)
+ setDownloadingId(null)
+ }
+ // Load once per open; `connector` is stable.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [open])
+
+ async function pick(file: ConnectorFile) {
+ if (downloadingId) return
+ setDownloadingId(file.id)
+ setError(null)
+ try {
+ const downloaded = await connector.downloadFile(file)
+ onPick(downloaded)
+ onOpenChange(false)
+ } catch (err) {
+ setError(messageFor(err))
+ } finally {
+ setDownloadingId(null)
+ }
+ }
+
+ return (
+
+ )
+}
diff --git a/src/extensions/connectors/gdrive/config.ts b/src/extensions/connectors/gdrive/config.ts
new file mode 100644
index 0000000..a601ac6
--- /dev/null
+++ b/src/extensions/connectors/gdrive/config.ts
@@ -0,0 +1,35 @@
+import { extensionRegistry } from '@/core/extensions/registry'
+
+/**
+ * Lightweight Google Drive connector config + availability gate (Phase 6.3).
+ *
+ * Kept free of GIS / REST imports so UI can decide whether to *offer* the Drive
+ * affordances without pulling the connector's heavy code into the initial graph
+ * — the connector module (`./index`) is dynamically imported only when the user
+ * actually clicks "From cloud" / "Save to Drive".
+ */
+
+/** Manifest id for the Google Drive storage-connector addon. */
+export const CONNECTOR_GDRIVE_ID = 'connector.gdrive'
+
+/** The Google OAuth client id, if configured at build time. */
+export function googleClientId(): string | undefined {
+ const id = import.meta.env.VITE_GOOGLE_CLIENT_ID
+ return id && id.trim() ? id.trim() : undefined
+}
+
+/** True when the connector has the client id it needs to run. */
+export function isGdriveConfigured(): boolean {
+ return googleClientId() !== undefined
+}
+
+/**
+ * True when Drive is both configured *and* enabled in the Add-ons registry.
+ * The import/export affordances gate on this; disabling the addon hides them.
+ * Unregistered ⇒ treated as enabled (registry default), so config alone gates
+ * before the built-ins are registered.
+ */
+export function isGdriveAvailable(): boolean {
+ if (!isGdriveConfigured()) return false
+ return !extensionRegistry.has(CONNECTOR_GDRIVE_ID) || extensionRegistry.isEnabled(CONNECTOR_GDRIVE_ID)
+}
diff --git a/src/extensions/connectors/gdrive/driveApi.ts b/src/extensions/connectors/gdrive/driveApi.ts
new file mode 100644
index 0000000..a16131f
--- /dev/null
+++ b/src/extensions/connectors/gdrive/driveApi.ts
@@ -0,0 +1,137 @@
+import { ConnectorError, type ConnectorFile, type ListFilesOptions } from '../types'
+import { CONNECTOR_GDRIVE_ID } from './config'
+
+/**
+ * Pure Google Drive REST layer (Phase 6.3). No GIS / no DOM — every call takes
+ * an OAuth access token and an injectable `fetchImpl`, mirroring the `fetchImpl`
+ * seam in `src/core/mt/*` so vitest never hits the network. The `drive.file`
+ * scope only exposes files the app created or the user explicitly opened, which
+ * avoids Google's restricted-scope verification burden (ROADMAP §6.3).
+ */
+
+const FILES_URL = 'https://www.googleapis.com/drive/v3/files'
+const UPLOAD_URL = 'https://www.googleapis.com/upload/drive/v3/files'
+const FILE_FIELDS = 'id,name,mimeType,modifiedTime,size'
+
+interface DriveFileResource {
+ id: string
+ name: string
+ mimeType?: string
+ modifiedTime?: string
+ size?: string
+}
+
+function codeForStatus(status: number): 'auth' | 'rate_limit' | 'invalid' | 'network' {
+ if (status === 401 || status === 403) return 'auth'
+ if (status === 429) return 'rate_limit'
+ if (status === 400 || status === 404) return 'invalid'
+ return 'network'
+}
+
+function authHeaders(token: string): HeadersInit {
+ return { Authorization: `Bearer ${token}` }
+}
+
+async function driveError(resp: Response): Promise {
+ let detail = `Drive request failed (${resp.status})`
+ try {
+ const body = (await resp.json()) as { error?: { message?: string } }
+ if (body?.error?.message) detail = body.error.message
+ } catch {
+ // non-JSON error body; keep the status-based message
+ }
+ return new ConnectorError(CONNECTOR_GDRIVE_ID, codeForStatus(resp.status), detail)
+}
+
+function mapFile(f: DriveFileResource): ConnectorFile {
+ return {
+ id: f.id,
+ name: f.name,
+ ...(f.mimeType ? { mimeType: f.mimeType } : {}),
+ ...(f.modifiedTime ? { modifiedTime: f.modifiedTime } : {}),
+ ...(f.size ? { sizeBytes: Number(f.size) } : {}),
+ }
+}
+
+/** List non-trashed Drive files, newest first. `options.query` narrows by name. */
+export async function listDriveFiles(
+ token: string,
+ options: ListFilesOptions = {},
+ fetchImpl: typeof fetch = fetch,
+): Promise {
+ const q = ["trashed = false", "mimeType != 'application/vnd.google-apps.folder'"]
+ if (options.query?.trim()) {
+ q.push(`name contains '${options.query.trim().replace(/'/g, "\\'")}'`)
+ }
+ const params = new URLSearchParams({
+ q: q.join(' and '),
+ fields: `files(${FILE_FIELDS})`,
+ orderBy: 'modifiedTime desc',
+ pageSize: String(options.limit ?? 50),
+ spaces: 'drive',
+ })
+ let resp: Response
+ try {
+ resp = await fetchImpl(`${FILES_URL}?${params.toString()}`, { headers: authHeaders(token) })
+ } catch (err) {
+ throw new ConnectorError(CONNECTOR_GDRIVE_ID, 'network', err instanceof Error ? err.message : 'fetch failed')
+ }
+ if (!resp.ok) throw await driveError(resp)
+ const body = (await resp.json()) as { files?: DriveFileResource[] }
+ return (body.files ?? []).map(mapFile)
+}
+
+/** Download a file's raw bytes (`alt=media`). */
+export async function downloadDriveFile(
+ token: string,
+ fileId: string,
+ fetchImpl: typeof fetch = fetch,
+): Promise {
+ const params = new URLSearchParams({ alt: 'media' })
+ let resp: Response
+ try {
+ resp = await fetchImpl(`${FILES_URL}/${encodeURIComponent(fileId)}?${params.toString()}`, {
+ headers: authHeaders(token),
+ })
+ } catch (err) {
+ throw new ConnectorError(CONNECTOR_GDRIVE_ID, 'network', err instanceof Error ? err.message : 'fetch failed')
+ }
+ if (!resp.ok) throw await driveError(resp)
+ return resp.arrayBuffer()
+}
+
+/** Upload bytes as a new Drive file via a multipart/related request. */
+export async function uploadDriveFile(
+ token: string,
+ input: { name: string; mimeType: string; bytes: ArrayBuffer | Uint8Array },
+ fetchImpl: typeof fetch = fetch,
+): Promise {
+ const boundary = `verbalis-${Math.random().toString(36).slice(2)}`
+ const metadata = JSON.stringify({ name: input.name, mimeType: input.mimeType })
+ // Blob's typings insist on an ArrayBuffer-backed view; a plain Blob wrapper of
+ // the bytes sidesteps the SharedArrayBuffer generic without copying semantics.
+ const media = new Blob([input.bytes as BlobPart])
+ const body = new Blob([
+ `--${boundary}\r\nContent-Type: application/json; charset=UTF-8\r\n\r\n`,
+ metadata,
+ `\r\n--${boundary}\r\nContent-Type: ${input.mimeType}\r\n\r\n`,
+ media,
+ `\r\n--${boundary}--`,
+ ])
+ const params = new URLSearchParams({ uploadType: 'multipart', fields: FILE_FIELDS })
+ let resp: Response
+ try {
+ resp = await fetchImpl(`${UPLOAD_URL}?${params.toString()}`, {
+ method: 'POST',
+ headers: {
+ Authorization: `Bearer ${token}`,
+ 'Content-Type': `multipart/related; boundary=${boundary}`,
+ },
+ body,
+ })
+ } catch (err) {
+ throw new ConnectorError(CONNECTOR_GDRIVE_ID, 'network', err instanceof Error ? err.message : 'fetch failed')
+ }
+ if (!resp.ok) throw await driveError(resp)
+ return mapFile((await resp.json()) as DriveFileResource)
+}
diff --git a/src/extensions/connectors/gdrive/gis.ts b/src/extensions/connectors/gdrive/gis.ts
new file mode 100644
index 0000000..f5747ff
--- /dev/null
+++ b/src/extensions/connectors/gdrive/gis.ts
@@ -0,0 +1,115 @@
+import { ConnectorError } from '../types'
+import { CONNECTOR_GDRIVE_ID, googleClientId } from './config'
+
+/**
+ * Google Identity Services (GIS) OAuth token client (Phase 6.3).
+ *
+ * Pure client-side OAuth: the GSI script is injected on first use, an access
+ * token for the `drive.file` scope is requested via a popup, and the token lives
+ * **only in memory** (never Dexie, never localStorage) — it evaporates on
+ * reload, matching the connector's session-only contract. No Supabase, so this
+ * works for 100%-local users. This DOM boundary is intentionally thin; the
+ * testable logic lives in the pure `driveApi` layer.
+ */
+
+const GSI_SRC = 'https://accounts.google.com/gsi/client'
+const DRIVE_SCOPE = 'https://www.googleapis.com/auth/drive.file'
+// Refresh a little before the real expiry to avoid a mid-request 401.
+const EXPIRY_SKEW_MS = 60_000
+
+interface TokenResponse {
+ access_token?: string
+ expires_in?: number
+ error?: string
+ error_description?: string
+}
+interface TokenClient {
+ requestAccessToken(overrides?: { prompt?: string }): void
+ callback: (resp: TokenResponse) => void
+}
+interface GoogleOAuth2 {
+ initTokenClient(config: {
+ client_id: string
+ scope: string
+ prompt?: string
+ callback: (resp: TokenResponse) => void
+ error_callback?: (err: { type?: string; message?: string }) => void
+ }): TokenClient
+}
+interface GoogleGlobal {
+ accounts?: { oauth2?: GoogleOAuth2 }
+}
+
+declare global {
+ interface Window {
+ google?: GoogleGlobal
+ }
+}
+
+let scriptPromise: Promise | null = null
+let cachedToken: { value: string; expiresAt: number } | null = null
+
+function loadGis(): Promise {
+ if (window.google?.accounts?.oauth2) return Promise.resolve(window.google.accounts.oauth2)
+ if (scriptPromise) return scriptPromise
+ scriptPromise = new Promise((resolve, reject) => {
+ const existing = document.querySelector(`script[src="${GSI_SRC}"]`)
+ const onReady = () => {
+ const oauth2 = window.google?.accounts?.oauth2
+ if (oauth2) resolve(oauth2)
+ else reject(new ConnectorError(CONNECTOR_GDRIVE_ID, 'network', 'Google Identity Services failed to initialise'))
+ }
+ if (existing) {
+ existing.addEventListener('load', onReady, { once: true })
+ existing.addEventListener('error', () => reject(new ConnectorError(CONNECTOR_GDRIVE_ID, 'network', 'Failed to load Google Identity Services')), { once: true })
+ return
+ }
+ const script = document.createElement('script')
+ script.src = GSI_SRC
+ script.async = true
+ script.defer = true
+ script.onload = onReady
+ script.onerror = () => reject(new ConnectorError(CONNECTOR_GDRIVE_ID, 'network', 'Failed to load Google Identity Services'))
+ document.head.appendChild(script)
+ })
+ return scriptPromise
+}
+
+/**
+ * Return a valid Drive access token, prompting the user for consent the first
+ * time (or when the cached token has expired). `forceConsent` re-prompts.
+ */
+export async function requestDriveToken(forceConsent = false): Promise {
+ const clientId = googleClientId()
+ if (!clientId) throw new ConnectorError(CONNECTOR_GDRIVE_ID, 'auth', 'Google client id not configured')
+ if (!forceConsent && cachedToken && cachedToken.expiresAt - EXPIRY_SKEW_MS > Date.now()) {
+ return cachedToken.value
+ }
+ const oauth2 = await loadGis()
+ return new Promise((resolve, reject) => {
+ const client = oauth2.initTokenClient({
+ client_id: clientId,
+ scope: DRIVE_SCOPE,
+ callback: (resp) => {
+ if (resp.error || !resp.access_token) {
+ reject(new ConnectorError(CONNECTOR_GDRIVE_ID, 'auth', resp.error_description || resp.error || 'Authorisation failed'))
+ return
+ }
+ cachedToken = {
+ value: resp.access_token,
+ expiresAt: Date.now() + (resp.expires_in ?? 3600) * 1000,
+ }
+ resolve(resp.access_token)
+ },
+ error_callback: (err) => {
+ reject(new ConnectorError(CONNECTOR_GDRIVE_ID, 'auth', err.message || 'Authorisation cancelled'))
+ },
+ })
+ client.requestAccessToken({ prompt: forceConsent ? 'consent' : '' })
+ })
+}
+
+/** Drop the in-memory token (e.g. on an auth failure) so the next call re-prompts. */
+export function resetDriveToken(): void {
+ cachedToken = null
+}
diff --git a/src/extensions/connectors/gdrive/index.ts b/src/extensions/connectors/gdrive/index.ts
new file mode 100644
index 0000000..b837a15
--- /dev/null
+++ b/src/extensions/connectors/gdrive/index.ts
@@ -0,0 +1,54 @@
+import type {
+ ConnectorFile,
+ ConnectorUpload,
+ ListFilesOptions,
+ StorageConnector,
+} from '../types'
+import { CONNECTOR_GDRIVE_ID, isGdriveConfigured } from './config'
+import { downloadDriveFile, listDriveFiles, uploadDriveFile } from './driveApi'
+import { requestDriveToken } from './gis'
+
+export { CONNECTOR_GDRIVE_ID, isGdriveConfigured, isGdriveAvailable, googleClientId } from './config'
+
+/**
+ * The Google Drive storage connector (Phase 6.3) — pairs the GIS token client
+ * with the pure `driveApi` REST layer. Built through a factory so tests can
+ * inject a fake token getter + `fetchImpl` (no GIS, no network); the exported
+ * `gdriveConnector` singleton uses the real GIS popup + `fetch`.
+ */
+
+export interface GdriveDeps {
+ /** Acquire a Drive access token (real GIS by default). */
+ getToken: (forceConsent?: boolean) => Promise
+ fetchImpl: typeof fetch
+}
+
+export function createGdriveConnector(deps: GdriveDeps): StorageConnector {
+ const { getToken, fetchImpl } = deps
+ return {
+ id: CONNECTOR_GDRIVE_ID,
+ name: 'Google Drive',
+ isConfigured: isGdriveConfigured,
+ async listFiles(options?: ListFilesOptions): Promise {
+ const token = await getToken()
+ return listDriveFiles(token, options, fetchImpl)
+ },
+ async downloadFile(file: ConnectorFile): Promise {
+ const token = await getToken()
+ const bytes = await downloadDriveFile(token, file.id, fetchImpl)
+ return new File([bytes], file.name, {
+ type: file.mimeType || 'application/octet-stream',
+ })
+ },
+ async uploadFile(input: ConnectorUpload): Promise {
+ const token = await getToken()
+ return uploadDriveFile(token, input, fetchImpl)
+ },
+ }
+}
+
+/** The process-wide Google Drive connector (real GIS token + `fetch`). */
+export const gdriveConnector: StorageConnector = createGdriveConnector({
+ getToken: requestDriveToken,
+ fetchImpl: (...args) => fetch(...args),
+})
diff --git a/src/extensions/connectors/types.ts b/src/extensions/connectors/types.ts
new file mode 100644
index 0000000..7b6220a
--- /dev/null
+++ b/src/extensions/connectors/types.ts
@@ -0,0 +1,77 @@
+/**
+ * Generic storage-connector contract (ROADMAP §6.3/§6.4, D9).
+ *
+ * A storage connector lets Verbalis read files from and write files to a cloud
+ * drive (Google Drive first, OneDrive in 6.4) as a built-in addon. The contract
+ * is deliberately provider-agnostic so the `ConnectorFilePicker` and the
+ * import/export wiring are written once and reused by every connector. Auth is
+ * the connector's own concern (pure client OAuth — no Supabase dependency), and
+ * access tokens live only in memory/session, never in Dexie.
+ */
+
+/** A file as listed by a connector (the fields the picker needs). */
+export interface ConnectorFile {
+ /** Provider-native file id. */
+ id: string
+ /** Display name including extension. */
+ name: string
+ /** MIME type, when the provider reports it. */
+ mimeType?: string
+ /** ISO timestamp of the last modification, when available. */
+ modifiedTime?: string
+ /** Size in bytes, when available. */
+ sizeBytes?: number
+}
+
+/** Bytes to upload to a connector, with the target file name and type. */
+export interface ConnectorUpload {
+ name: string
+ mimeType: string
+ bytes: ArrayBuffer | Uint8Array
+}
+
+export interface ListFilesOptions {
+ /** Free-text query the connector may use to narrow the listing. */
+ query?: string
+ /** Maximum number of files to return. */
+ limit?: number
+}
+
+/**
+ * A pluggable cloud-drive connector. Implementations pair this with an
+ * `ExtensionManifest` (kind `storage-connector`) so the Add-ons page can list
+ * and toggle them.
+ */
+export interface StorageConnector {
+ /** The manifest id this connector is paired to, e.g. `connector.gdrive`. */
+ id: string
+ /** Human-facing name shown in the picker and buttons. */
+ name: string
+ /** True when the connector has the build-time config it needs (e.g. a client id). */
+ isConfigured(): boolean
+ /** List files, acquiring/refreshing an access token as needed. */
+ listFiles(options?: ListFilesOptions): Promise
+ /** Download a file's bytes, returned as a `File` ready for the import flow. */
+ downloadFile(file: ConnectorFile): Promise
+ /** Upload bytes, returning the created file's metadata. */
+ uploadFile(input: ConnectorUpload): Promise
+}
+
+/** A recoverable connector failure with a coarse cause (mirrors `MTError`). */
+export type ConnectorErrorCode =
+ | 'auth' // token missing / rejected / consent denied
+ | 'rate_limit'
+ | 'invalid'
+ | 'network'
+ | 'aborted'
+
+export class ConnectorError extends Error {
+ code: ConnectorErrorCode
+ connectorId: string
+ constructor(connectorId: string, code: ConnectorErrorCode, message: string) {
+ super(message)
+ this.code = code
+ this.connectorId = connectorId
+ this.name = 'ConnectorError'
+ }
+}
diff --git a/src/features/addons/AddonsPage.tsx b/src/features/addons/AddonsPage.tsx
index 54325d3..ca15f4a 100644
--- a/src/features/addons/AddonsPage.tsx
+++ b/src/features/addons/AddonsPage.tsx
@@ -33,10 +33,15 @@ const SECTIONS: { title: string; kinds: ExtensionKind[]; hint: string }[] = [
kinds: ['import-format', 'export-format'],
hint: 'File formats Verbalis can read and write.',
},
+ {
+ title: 'Storage connectors',
+ kinds: ['storage-connector'],
+ hint: 'Cloud drives to import from and save to. Disabling one hides its buttons.',
+ },
]
/** Kinds the user can turn on/off here (their enablement is enforced elsewhere). */
-const TOGGLEABLE_KINDS = new Set(['mt-provider', 'qa-rule'])
+const TOGGLEABLE_KINDS = new Set(['mt-provider', 'qa-rule', 'storage-connector'])
const PERMISSION_LABEL: Record = {
network: 'Network',
diff --git a/src/features/editor/tools/ExportDocxButton.tsx b/src/features/editor/tools/ExportDocxButton.tsx
index 0656eab..0a0b46b 100644
--- a/src/features/editor/tools/ExportDocxButton.tsx
+++ b/src/features/editor/tools/ExportDocxButton.tsx
@@ -1,38 +1,52 @@
import { useLiveQuery } from 'dexie-react-hooks'
import { useState } from 'react'
-import { FileDown, AlertTriangle } from 'lucide-react'
+import { FileDown, AlertTriangle, HardDriveDownload, Check } from 'lucide-react'
import { documentRepo, blockRepo, assetRepo } from '@/storage/repositories/documentRepo'
import { segmentRepo } from '@/storage/repositories/segmentRepo'
import { exportProjectDocx, hasPendingForExport } from '@/core/documents/toDocx'
+import { isGdriveAvailable } from '@/extensions/connectors/gdrive/config'
+
+const DOCX_MIME = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
/**
* Export the translated document as a clean .docx (Phase 2.4). Only shown for
* projects that have a document tree (monolingual). Pending tracked changes are
* exported as their accepted preview (D2); a warning marker appears when any
- * remain unresolved.
+ * remain unresolved. When the Google Drive connector is available (Phase 6.3),
+ * a "Save to Drive" action uploads the same .docx back to the user's Drive.
*/
export function ExportDocxButton({ projectId, name }: { projectId: string; name: string }) {
const [busy, setBusy] = useState(false)
+ const [saving, setSaving] = useState(false)
+ const [saved, setSaved] = useState(false)
+ const [saveError, setSaveError] = useState(null)
const doc = useLiveQuery(() => documentRepo.getByProject(projectId), [projectId])
const segments = useLiveQuery(() => segmentRepo.byProject(projectId), [projectId])
const pending = segments ? hasPendingForExport(segments) : false
+ const gdrive = isGdriveAvailable()
if (!doc) return null
+ const filename = `${name.trim() || 'document'}.docx`
+
+ const buildBlob = async (): Promise => {
+ const [blocks, segs, assets] = await Promise.all([
+ blockRepo.byDocument(doc.id),
+ segmentRepo.byProject(projectId),
+ assetRepo.byDocument(doc.id),
+ ])
+ return exportProjectDocx(blocks, segs, assets)
+ }
+
const onExport = async () => {
if (busy) return
setBusy(true)
try {
- const [blocks, segs, assets] = await Promise.all([
- blockRepo.byDocument(doc.id),
- segmentRepo.byProject(projectId),
- assetRepo.byDocument(doc.id),
- ])
- const blob = await exportProjectDocx(blocks, segs, assets)
+ const blob = await buildBlob()
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
- a.download = `${name.trim() || 'document'}.docx`
+ a.download = filename
document.body.appendChild(a)
a.click()
a.remove()
@@ -42,21 +56,60 @@ export function ExportDocxButton({ projectId, name }: { projectId: string; name:
}
}
+ const onSaveToDrive = async () => {
+ if (saving) return
+ setSaving(true)
+ setSaved(false)
+ setSaveError(null)
+ try {
+ const blob = await buildBlob()
+ const bytes = await blob.arrayBuffer()
+ const { gdriveConnector } = await import('@/extensions/connectors/gdrive')
+ await gdriveConnector.uploadFile({ name: filename, mimeType: DOCX_MIME, bytes })
+ setSaved(true)
+ setTimeout(() => setSaved(false), 3000)
+ } catch (err) {
+ setSaveError(err instanceof Error ? err.message : 'Could not save to Drive.')
+ } finally {
+ setSaving(false)
+ }
+ }
+
return (
-