diff --git a/.env.example b/.env.example index 482617b..6d9c3d9 100644 --- a/.env.example +++ b/.env.example @@ -16,3 +16,10 @@ VITE_SUPABASE_ANON_KEY=sb_publishable_c8YdrT2-abKdW1Kl7FDKyA_v5OwqLdY # google, azure (Microsoft), apple. Defaults to `google` when unset. Only list # providers you have configured in the Supabase dashboard, or the button 400s. VITE_AUTH_PROVIDERS=google + +# Google OAuth client id for the Drive storage connector (Phase 6.3). Pure +# client OAuth via Google Identity Services (independent of Supabase — the +# connector works in 100%-local mode too). When unset, the Drive "From cloud" / +# "Save to Drive" buttons stay hidden. Uses the drive.file scope only. See +# docs/cloud.md §13 for the Google Cloud console setup. +# VITE_GOOGLE_CLIENT_ID=xxxxxxxx.apps.googleusercontent.com diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 4ad01c1..6c649ee 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -54,6 +54,11 @@ jobs: VITE_SUPABASE_URL: ${{ vars.VITE_SUPABASE_URL || secrets.VITE_SUPABASE_URL || secrets.SUPABASE_URL }} VITE_SUPABASE_ANON_KEY: ${{ vars.VITE_SUPABASE_ANON_KEY || secrets.VITE_SUPABASE_ANON_KEY }} VITE_AUTH_PROVIDERS: ${{ vars.VITE_AUTH_PROVIDERS || secrets.VITE_AUTH_PROVIDERS }} + # Google Drive connector (Phase 6.3) — pure client OAuth, independent of + # Supabase. Public by design (a Web OAuth client id is not a secret; it is + # gated by the console's authorised-origins allow-list). Unset -> the + # Drive buttons stay hidden. + VITE_GOOGLE_CLIENT_ID: ${{ vars.VITE_GOOGLE_CLIENT_ID || secrets.VITE_GOOGLE_CLIENT_ID }} - uses: actions/upload-pages-artifact@v3 with: path: dist diff --git a/docs/cloud.md b/docs/cloud.md index 2a66b0b..51f5baa 100644 --- a/docs/cloud.md +++ b/docs/cloud.md @@ -319,3 +319,47 @@ first. With a project_manager, a translator, and a revisor on one cloud project: - [ ] **Local-only unchanged**: a project with no cloud link behaves as "PM-of-self" — direct editing, suggesting, and accept/reject all available, exactly as before roles existed. + +## 13. Google Drive connector (Phase 6.3) + +The Drive connector is **pure client OAuth** via Google Identity Services (GIS) +— it does **not** use Supabase, so it works for 100%-local users too. It uses +the narrow `drive.file` scope (only files the app creates or the user explicitly +opens through the Google picker/consent), which avoids Google's restricted-scope +verification burden. The access token lives in memory only (gone on reload). + +### One-time setup (Google Cloud console) + +1. Create (or reuse) a project at . +2. **APIs & Services → Library** → enable the **Google Drive API**. +3. **APIs & Services → OAuth consent screen** → configure (External is fine for + testing; add yourself as a test user). Add the scope + `https://www.googleapis.com/auth/drive.file`. +4. **APIs & Services → Credentials → Create credentials → OAuth client ID → + Web application**. Under *Authorised JavaScript origins* add the exact + origins the app runs on, e.g. `http://localhost:5173` and + `https://verbalis.britx.me`. (No redirect URI is needed — GIS uses the token + flow, not a redirect.) +5. Copy the client id into `VITE_GOOGLE_CLIENT_ID` (build-time env; see §1). In + `deploy.yml` add it as a repo **Variable** the same way as the Supabase vars. + +Leaving `VITE_GOOGLE_CLIENT_ID` unset keeps the Drive buttons hidden — no GIS +script is loaded and the connector code stays out of the initial bundle. + +### Manual verification + +With `VITE_GOOGLE_CLIENT_ID` set: + +- [ ] **Addon listed**: the Add-ons page shows **Google Drive** under *Storage + connectors* with Network / API key / Files permission chips and a working + on/off toggle. +- [ ] **Import from Drive**: in the Import dialog, **From Google Drive** opens the + Google consent popup, then a file list; picking a `.docx`/`.txt`/`.md`/XLIFF + imports it as a new project exactly as a local file would. +- [ ] **Save to Drive**: on a monolingual project, **Save to Drive** uploads the + exported `.docx` to your Drive (visible in ) and + shows a "Saved to Drive" confirmation. +- [ ] **Disable hides it**: turning the addon off on the Add-ons page hides both + the "From Google Drive" and "Save to Drive" buttons. +- [ ] **Unset ⇒ absent**: with `VITE_GOOGLE_CLIENT_ID` unset the buttons never + appear and `dist` contains no `gsi/client` reference in the entry chunk. diff --git a/docs/revamp/STATUS.md b/docs/revamp/STATUS.md index 8036ae6..951d018 100644 --- a/docs/revamp/STATUS.md +++ b/docs/revamp/STATUS.md @@ -37,8 +37,8 @@ Rules for autonomous sessions: | 5.2 | Role-gated editing workflow | M | 5.1, 1.6 | done (PR #61) | | 5.3 | Approval workflow + attribution in versioning | S | 5.2 | done (PR #62) | | 6.1 | Extension registry + MT providers as built-in addons | M | 0.1 | done (PR #63) | -| 6.2 | QA rules + formats as addons + Add-ons page | M | 6.1 | in-review (PR #64) | -| 6.3 | Google Drive connector | M | 6.1, 2.4 | pending | +| 6.2 | QA rules + formats as addons + Add-ons page | M | 6.1 | done (PR #64) | +| 6.3 | Google Drive connector | M | 6.1, 2.4 | in-review (PR #65) | | 6.4 | OneDrive connector | S | 6.3 | pending | ## Log @@ -80,3 +80,4 @@ Rules for autonomous sessions: - 2026-07-21 — Phase 5.2 merged in PR #61. Phase 5.3 built: approval workflow + unified attribution in versioning (**Milestone 5 complete → web v2 launch candidate**). `ProjectVersion` gains `authorId?` (the stable `profile.identity` author id — the *same* identity tracked-change marks, comments, and presence use, so attribution is unified across the app, D8) and `approval?: { authorId, authorName, at }`. `versionRepo.capture` now stamps `authorId` on **every** version (via `ensureLocalAuthor()`), and a new `versionRepo.signOff(projectId, liveDoc?)` records a `named` version labeled `Approved by {name}` with the `approval` metadata set (its presence marks an approval milestone). Wiring: `useWorkflowStore` gains a `useCanReview()` selector (revisor/PM; local-only → PM-of-self → true); `VersionHistoryPanel` shows a **Sign off** button beside Save version only when `canReview`, and renders approval versions with an accent `BadgeCheck` + their `Approved by …` label. No migration + no schema bump (versions are local Dexie; `authorId`/`approval` are additive unindexed fields; pre-5.3 rows simply lack them). Deviations (noted): built on the designated session branch, not `claude/revamp-phase-5-3`; sign-off gating is client-enforced via the workflow rules at the call site (D8) — the append-only authored update log remains the tamper-evident audit trail. Tests: `versionRepo` extended (every capture stamps a stable authorId consistent across captures; `signOff` records a labeled approval version whose `approval.authorId`/`at` match the version's `authorId`/`createdAt`, while a plain `saveNamed` has no `approval`). Verified: flag-OFF `dist` has **zero** `GoTrueClient`; the version-history e2e still green. Green: 673 unit (+2) / 1 version e2e / build. No new e2e (ROADMAP §5.3 asks none). **Milestone 5 (roles & workflow) complete — the web v2 launch candidate.** - 2026-07-21 — Phase 5.3 merged in PR #62. Phase 6.1 built: the typed extension registry + the four MT providers re-registered as built-in addons (start of **Milestone 6**, extensions & connectors; D9 — in-process registry now, sandboxed hosting later, but the manifest contract is **final**). `src/core/extensions/types.ts` — `ExtensionManifest {id, name, version, kinds, permissions, builtIn, description?}`; `ExtensionKind = mt-provider|qa-rule|panel|import-format|export-format|storage-connector`; `ExtensionPermission = network|credentials|storage|clipboard|filesystem`. `src/core/extensions/registry.ts` — a dependency-free (no storage/React imports) singleton `extensionRegistry`: `register`/`unregister`/`get`/`has`/`list(kind?)` (id-sorted), enablement as a **disabled set** so a registered extension is enabled by default and an unknown id is treated as enabled (behaviour unchanged until something is explicitly turned off), `isEnabled`/`setEnabled`/`getDisabledIds`/`setDisabledIds`, and `subscribe`. `src/core/extensions/builtins.ts` — the four MT manifests (`mt.mymemory`/`mt.libretranslate`/`mt.ollama`/`mt.claude`; permissions `network` + `credentials` for the keyed ones) + idempotent `registerBuiltinExtensions()`. `src/extensions/mt/index.ts` — thin **wrappers** pairing each manifest to its existing `core/mt` provider (**no provider logic moved** — the existing MT unit tests are untouched and keep proving behaviour) + `registryEnabledMtProviderIds()`. `core/mt/index.ts` gains `MT_EXTENSION_ID` + `isProviderExtensionEnabled(id)` (defaults enabled when the manifest isn't registered), and `enabledProviders` now ANDs the user setting with the registry — so **disabling the addon removes the provider**; `useMTSettings.enabledIds` does the same and re-derives via `useSyncExternalStore(extensionRegistry.subscribe)` so the MT panel updates live. Wiring: `features/addons/registryPersistence.ts` (`registerExtensions()` sync + `startExtensionRegistry()` hydrating the disabled set from the new device-local `extensions.disabled` settings key and persisting subsequent changes), started from `main.tsx` before render. Deviations (noted): built on the designated session branch, not `claude/revamp-phase-6-1`; no Add-ons **page** yet (that's 6.2) — 6.1 ships the registry + reactive resolution and proves the disable→panel path via unit tests. `docs/cloud.md` unchanged (no migration). Tests: `extensions.registry` (register/list-by-kind/default-enabled/toggle/unknown-id/hydrate+notify/unregister), `extensions.mt` (the four register as `mt-provider`; wrappers point at the real `MT_PROVIDERS`; **disabling `mt.claude` removes it from `enabledProviders` even with the user setting on** — the DoD — and re-enabling restores it). Verified: flag-OFF `dist` Supabase-free; the untouched MT unit tests + `mt-flow` e2e stay green. Green: 682 unit (+9) / 3 mt-flow e2e / build. No new e2e (ROADMAP §6.1 asks none). - 2026-07-21 — Phase 6.1 merged in PR #63. Phase 6.2 built: QA rules + formats as addons + the Add-ons page. `core/extensions/builtins.ts` now also registers `QA_EXTENSION_MANIFESTS` (one `qa.` 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 ( + + + + {connector.name} + Choose a file to import from {connector.name}. + + +
{ + e.preventDefault() + void load(query) + }} + > + setQuery(e.target.value)} + placeholder="Search by name…" + aria-label="Search files" + data-testid="connector-search" + /> + +
+ +
+ {loading && ( +

+ Loading… +

+ )} + {!loading && error && ( +

+ {error} +

+ )} + {!loading && !error && files && files.length === 0 && ( +

+ No matching files found. +

+ )} + {!loading && !error && files && files.length > 0 && ( +
    + {files.map((f) => ( +
  • + +
  • + ))} +
+ )} +
+ + + + +
+
+ ) +} 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 ( - + + {gdrive && ( + )} - + ) } diff --git a/src/features/import/ImportDialog.tsx b/src/features/import/ImportDialog.tsx index 3c86017..35716da 100644 --- a/src/features/import/ImportDialog.tsx +++ b/src/features/import/ImportDialog.tsx @@ -12,6 +12,10 @@ import { Input } from '@/components/ui/input' import { Label } from '@/components/ui/label' import { Select } from '@/components/ui/select' import { LANGUAGE_OPTIONS } from '@/core/i18n/languages' +import { HardDriveUpload } from 'lucide-react' +import { ConnectorFilePicker } from '@/extensions/connectors/ConnectorFilePicker' +import type { ConnectorFile, StorageConnector } from '@/extensions/connectors/types' +import { isGdriveAvailable } from '@/extensions/connectors/gdrive/config' import { useImportProject } from './useImportProject' interface ImportDialogProps { @@ -19,11 +23,19 @@ interface ImportDialogProps { onOpenChange: (open: boolean) => void } +const IMPORTABLE_EXTENSIONS = ['.txt', '.md', '.markdown', '.docx', '.xlf', '.xliff', '.mqxliff'] + function stripExtension(filename: string): string { const i = filename.lastIndexOf('.') return i > 0 ? filename.slice(0, i) : filename } +/** True when a cloud file is one of the formats the import flow understands. */ +function isImportable(file: ConnectorFile): boolean { + const n = file.name.toLowerCase() + return IMPORTABLE_EXTENSIONS.some((ext) => n.endsWith(ext)) +} + function isBilingual(file: File | null): boolean { if (!file) return false const n = file.name.toLowerCase() @@ -36,12 +48,29 @@ export function ImportDialog({ open, onOpenChange }: ImportDialogProps) { const [sourceLang, setSourceLang] = useState('en') const [targetLang, setTargetLang] = useState('es') const [file, setFile] = useState(null) + const [connector, setConnector] = useState(null) + const [pickerOpen, setPickerOpen] = useState(false) + const gdrive = isGdriveAvailable() function reset() { setName('') setSourceLang('en') setTargetLang('es') setFile(null) + setPickerOpen(false) + } + + function acceptPickedFile(f: File) { + setFile(f) + if (!name) setName(stripExtension(f.name)) + } + + async function openDrivePicker() { + // The Drive connector (GIS + REST) is loaded only on demand, so it never + // weighs on the initial bundle. + const { gdriveConnector } = await import('@/extensions/connectors/gdrive') + setConnector(gdriveConnector) + setPickerOpen(true) } function handleFileChange(e: React.ChangeEvent) { @@ -72,6 +101,7 @@ export function ImportDialog({ open, onOpenChange }: ImportDialogProps) { !isImporting return ( + <> { @@ -98,8 +128,25 @@ export function ImportDialog({ open, onOpenChange }: ImportDialogProps) { type="file" accept=".txt,.md,.docx,.xlf,.xliff,.mqxliff,text/plain,text/markdown,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/xml,text/xml" onChange={handleFileChange} - required + required={!file} /> + {gdrive && ( + + )} + {file && ( +

+ Selected: {file.name} +

+ )}
@@ -180,5 +227,16 @@ export function ImportDialog({ open, onOpenChange }: ImportDialogProps) {
+ + {connector && ( + + )} + ) } diff --git a/src/vite-env.d.ts b/src/vite-env.d.ts index 5278e3e..957c44c 100644 --- a/src/vite-env.d.ts +++ b/src/vite-env.d.ts @@ -12,6 +12,13 @@ interface ImportMetaEnv { readonly VITE_SUPABASE_ANON_KEY?: string /** Comma-separated OAuth providers to offer, e.g. "google,azure,apple". */ readonly VITE_AUTH_PROVIDERS?: string + /** + * Google OAuth client id for the Drive storage connector (Phase 6.3). When + * unset, the Drive "From cloud" / "Save to cloud" affordances stay hidden. + * Pure client OAuth (Google Identity Services) — independent of Supabase, so + * the connector works for 100%-local users too. + */ + readonly VITE_GOOGLE_CLIENT_ID?: string } interface ImportMeta { readonly env: ImportMetaEnv diff --git a/tests/unit/AddonsPage.test.tsx b/tests/unit/AddonsPage.test.tsx index a582844..72a1f07 100644 --- a/tests/unit/AddonsPage.test.tsx +++ b/tests/unit/AddonsPage.test.tsx @@ -11,16 +11,26 @@ describe('AddonsPage (§6.2)', () => { registerBuiltinExtensions() }) - it('lists everything pluggable: MT providers, QA rules, and formats', () => { + it('lists everything pluggable: MT providers, QA rules, formats, connectors', () => { render() // A section per kind. expect(screen.getByTestId('addons-section-mt-provider')).toBeInTheDocument() expect(screen.getByTestId('addons-section-qa-rule')).toBeInTheDocument() expect(screen.getByTestId('addons-section-import-format')).toBeInTheDocument() + expect(screen.getByTestId('addons-section-storage-connector')).toBeInTheDocument() // Representative entries of each kind. expect(screen.getByTestId('addon-mt.claude')).toBeInTheDocument() expect(screen.getByTestId('addon-qa.double_space')).toBeInTheDocument() expect(screen.getByTestId('addon-format.xliff')).toBeInTheDocument() + expect(screen.getByTestId('addon-connector.gdrive')).toBeInTheDocument() + }) + + it('the Google Drive connector is toggleable', () => { + render() + const toggle = screen.getByTestId('addon-toggle-connector.gdrive') as HTMLInputElement + expect(toggle.checked).toBe(true) + fireEvent.click(toggle) + expect(extensionRegistry.isEnabled('connector.gdrive')).toBe(false) }) it('toggling a QA addon flips its registry enablement', () => { diff --git a/tests/unit/ConnectorFilePicker.test.tsx b/tests/unit/ConnectorFilePicker.test.tsx new file mode 100644 index 0000000..64708b2 --- /dev/null +++ b/tests/unit/ConnectorFilePicker.test.tsx @@ -0,0 +1,67 @@ +import { describe, expect, it, vi } from 'vitest' +import { render, screen, fireEvent, waitFor } from '@testing-library/react' +import { ConnectorFilePicker } from '@/extensions/connectors/ConnectorFilePicker' +import type { ConnectorFile, StorageConnector } from '@/extensions/connectors/types' + +function fakeConnector(files: ConnectorFile[]): StorageConnector { + return { + id: 'connector.gdrive', + name: 'Google Drive', + isConfigured: () => true, + listFiles: vi.fn().mockResolvedValue(files), + downloadFile: vi.fn().mockImplementation(async (f: ConnectorFile) => new File(['data'], f.name)), + uploadFile: vi.fn(), + } +} + +const FILES: ConnectorFile[] = [ + { id: '1', name: 'report.docx' }, + { id: '2', name: 'image.png' }, +] + +describe('ConnectorFilePicker (§6.3)', () => { + it('lists accepted files and hides rejected ones', async () => { + const connector = fakeConnector(FILES) + render( + {}} + accept={(f) => f.name.endsWith('.docx')} + onPick={() => {}} + />, + ) + expect(await screen.findByTestId('connector-file-1')).toBeInTheDocument() + expect(screen.queryByTestId('connector-file-2')).toBeNull() + expect(connector.listFiles).toHaveBeenCalled() + }) + + it('downloads the picked file and calls onPick + closes', async () => { + const connector = fakeConnector(FILES) + const onPick = vi.fn() + const onOpenChange = vi.fn() + render( + , + ) + fireEvent.click(await screen.findByTestId('connector-file-1')) + + await waitFor(() => expect(onPick).toHaveBeenCalled()) + expect(connector.downloadFile).toHaveBeenCalledWith(FILES[0]) + const picked = onPick.mock.calls[0][0] as File + expect(picked).toBeInstanceOf(File) + expect(picked.name).toBe('report.docx') + expect(onOpenChange).toHaveBeenCalledWith(false) + }) + + it('surfaces a listing error', async () => { + const connector = fakeConnector(FILES) + ;(connector.listFiles as ReturnType).mockRejectedValueOnce(new Error('Authorisation cancelled')) + render( {}} onPick={() => {}} />) + expect(await screen.findByTestId('connector-error')).toHaveTextContent('Authorisation cancelled') + }) +}) diff --git a/tests/unit/connectors.driveApi.test.ts b/tests/unit/connectors.driveApi.test.ts new file mode 100644 index 0000000..49a944b --- /dev/null +++ b/tests/unit/connectors.driveApi.test.ts @@ -0,0 +1,119 @@ +import { describe, expect, it, vi } from 'vitest' +import { + listDriveFiles, + downloadDriveFile, + uploadDriveFile, +} from '@/extensions/connectors/gdrive/driveApi' +import { ConnectorError } from '@/extensions/connectors/types' + +function jsonOk(body: unknown) { + return { ok: true, status: 200, json: async () => body } +} + +describe('driveApi.listDriveFiles', () => { + it('sends a Bearer token, excludes folders/trashed, and maps files', async () => { + const fetchImpl = vi.fn().mockResolvedValueOnce( + jsonOk({ + files: [ + { id: 'a', name: 'doc.docx', mimeType: 'application/vnd...', modifiedTime: '2026-07-20T00:00:00Z', size: '1234' }, + { id: 'b', name: 'notes.txt' }, + ], + }), + ) + const files = await listDriveFiles('tok-123', {}, fetchImpl as unknown as typeof fetch) + + const [url, init] = fetchImpl.mock.calls[0] + expect(url).toContain('https://www.googleapis.com/drive/v3/files?') + expect(url).toContain('trashed+%3D+false') + expect(url).toContain('mimeType+%21%3D') + expect((init.headers as Record).Authorization).toBe('Bearer tok-123') + + expect(files).toEqual([ + { id: 'a', name: 'doc.docx', mimeType: 'application/vnd...', modifiedTime: '2026-07-20T00:00:00Z', sizeBytes: 1234 }, + { id: 'b', name: 'notes.txt' }, + ]) + }) + + it('adds a name-contains clause when a query is given', async () => { + const fetchImpl = vi.fn().mockResolvedValueOnce(jsonOk({ files: [] })) + await listDriveFiles('t', { query: 'report' }, fetchImpl as unknown as typeof fetch) + expect(fetchImpl.mock.calls[0][0]).toContain('name+contains') + }) + + it('maps a 401 to an auth ConnectorError', async () => { + const fetchImpl = vi.fn().mockResolvedValueOnce({ + ok: false, + status: 401, + json: async () => ({ error: { message: 'Invalid Credentials' } }), + }) + await expect(listDriveFiles('bad', {}, fetchImpl as unknown as typeof fetch)).rejects.toMatchObject({ + name: 'ConnectorError', + code: 'auth', + message: 'Invalid Credentials', + }) + }) + + it('maps a 429 to rate_limit', async () => { + const fetchImpl = vi.fn().mockResolvedValueOnce({ ok: false, status: 429, json: async () => ({}) }) + await expect(listDriveFiles('t', {}, fetchImpl as unknown as typeof fetch)).rejects.toMatchObject({ + code: 'rate_limit', + }) + }) +}) + +describe('driveApi.downloadDriveFile', () => { + it('requests alt=media with the token and returns the bytes', async () => { + const bytes = new TextEncoder().encode('hello').buffer + const fetchImpl = vi.fn().mockResolvedValueOnce({ + ok: true, + status: 200, + arrayBuffer: async () => bytes, + }) + const out = await downloadDriveFile('tok', 'file 1', fetchImpl as unknown as typeof fetch) + + const [url, init] = fetchImpl.mock.calls[0] + expect(url).toBe('https://www.googleapis.com/drive/v3/files/file%201?alt=media') + expect((init.headers as Record).Authorization).toBe('Bearer tok') + expect(new TextDecoder().decode(out)).toBe('hello') + }) +}) + +describe('driveApi.uploadDriveFile', () => { + it('POSTs a multipart/related body with metadata + media and returns the file', async () => { + const fetchImpl = vi.fn().mockResolvedValueOnce( + jsonOk({ id: 'new1', name: 'out.docx', mimeType: 'application/x-docx' }), + ) + const bytes = new TextEncoder().encode('DOCXBYTES') + const created = await uploadDriveFile( + 'tok', + { name: 'out.docx', mimeType: 'application/x-docx', bytes }, + fetchImpl as unknown as typeof fetch, + ) + + const [url, init] = fetchImpl.mock.calls[0] + expect(url).toContain('https://www.googleapis.com/upload/drive/v3/files?') + expect(url).toContain('uploadType=multipart') + expect(init.method).toBe('POST') + const headers = init.headers as Record + expect(headers.Authorization).toBe('Bearer tok') + expect(headers['Content-Type']).toMatch(/^multipart\/related; boundary=verbalis-/) + + const bodyText = await (init.body as Blob).text() + expect(bodyText).toContain('"name":"out.docx"') + expect(bodyText).toContain('"mimeType":"application/x-docx"') + expect(bodyText).toContain('DOCXBYTES') + + expect(created).toEqual({ id: 'new1', name: 'out.docx', mimeType: 'application/x-docx' }) + }) + + it('wraps a network throw as a ConnectorError', async () => { + const fetchImpl = vi.fn().mockRejectedValueOnce(new Error('offline')) + const err = await uploadDriveFile( + 'tok', + { name: 'x', mimeType: 'text/plain', bytes: new Uint8Array() }, + fetchImpl as unknown as typeof fetch, + ).catch((e) => e) + expect(err).toBeInstanceOf(ConnectorError) + expect((err as ConnectorError).code).toBe('network') + }) +}) diff --git a/tests/unit/connectors.gdrive.test.ts b/tests/unit/connectors.gdrive.test.ts new file mode 100644 index 0000000..67cd78e --- /dev/null +++ b/tests/unit/connectors.gdrive.test.ts @@ -0,0 +1,90 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { createGdriveConnector } from '@/extensions/connectors/gdrive' +import { + CONNECTOR_GDRIVE_ID, + isGdriveConfigured, + isGdriveAvailable, +} from '@/extensions/connectors/gdrive/config' +import { extensionRegistry } from '@/core/extensions/registry' +import { registerBuiltinExtensions, __resetBuiltinsForTest } from '@/core/extensions/builtins' + +function jsonOk(body: unknown) { + return { ok: true, status: 200, json: async () => body } +} + +describe('gdrive config gating', () => { + afterEach(() => vi.unstubAllEnvs()) + + it('isGdriveConfigured follows VITE_GOOGLE_CLIENT_ID', () => { + vi.stubEnv('VITE_GOOGLE_CLIENT_ID', '') + expect(isGdriveConfigured()).toBe(false) + vi.stubEnv('VITE_GOOGLE_CLIENT_ID', 'abc.apps.googleusercontent.com') + expect(isGdriveConfigured()).toBe(true) + }) + + it('registers as a storage-connector manifest', () => { + extensionRegistry.__resetForTest() + __resetBuiltinsForTest() + registerBuiltinExtensions() + const ids = extensionRegistry.list('storage-connector').map((m) => m.id) + expect(ids).toContain(CONNECTOR_GDRIVE_ID) + expect(extensionRegistry.get(CONNECTOR_GDRIVE_ID)?.permissions).toContain('credentials') + }) + + it('isGdriveAvailable ANDs config with the registry enablement', () => { + extensionRegistry.__resetForTest() + __resetBuiltinsForTest() + registerBuiltinExtensions() + + vi.stubEnv('VITE_GOOGLE_CLIENT_ID', '') + expect(isGdriveAvailable()).toBe(false) // unconfigured + + vi.stubEnv('VITE_GOOGLE_CLIENT_ID', 'id.apps.googleusercontent.com') + expect(isGdriveAvailable()).toBe(true) // configured + enabled by default + + extensionRegistry.setEnabled(CONNECTOR_GDRIVE_ID, false) + expect(isGdriveAvailable()).toBe(false) // configured but disabled + }) +}) + +describe('createGdriveConnector', () => { + beforeEach(() => { + extensionRegistry.__resetForTest() + __resetBuiltinsForTest() + registerBuiltinExtensions() + }) + + it('lists files through an injected token + fetch', async () => { + const getToken = vi.fn().mockResolvedValue('tok-x') + const fetchImpl = vi.fn().mockResolvedValueOnce(jsonOk({ files: [{ id: '1', name: 'a.txt' }] })) + const c = createGdriveConnector({ getToken, fetchImpl: fetchImpl as unknown as typeof fetch }) + + const files = await c.listFiles() + expect(getToken).toHaveBeenCalled() + expect(files).toEqual([{ id: '1', name: 'a.txt' }]) + expect((fetchImpl.mock.calls[0][1].headers as Record).Authorization).toBe('Bearer tok-x') + }) + + it('downloads a file into a named File with its mime type', async () => { + const getToken = vi.fn().mockResolvedValue('tok') + const bytes = new TextEncoder().encode('body').buffer + const fetchImpl = vi.fn().mockResolvedValueOnce({ ok: true, status: 200, arrayBuffer: async () => bytes }) + const c = createGdriveConnector({ getToken, fetchImpl: fetchImpl as unknown as typeof fetch }) + + const file = await c.downloadFile({ id: '9', name: 'report.docx', mimeType: 'application/x-docx' }) + expect(file).toBeInstanceOf(File) + expect(file.name).toBe('report.docx') + expect(file.type).toBe('application/x-docx') + expect(await file.text()).toBe('body') + }) + + it('uploads bytes and returns the created file', async () => { + const getToken = vi.fn().mockResolvedValue('tok') + const fetchImpl = vi.fn().mockResolvedValueOnce(jsonOk({ id: 'up1', name: 'x.docx' })) + const c = createGdriveConnector({ getToken, fetchImpl: fetchImpl as unknown as typeof fetch }) + + const created = await c.uploadFile({ name: 'x.docx', mimeType: 'application/x-docx', bytes: new Uint8Array([1, 2]) }) + expect(created).toEqual({ id: 'up1', name: 'x.docx' }) + expect(fetchImpl.mock.calls[0][1].method).toBe('POST') + }) +})