From 73a7eef760d160b4e1ebe49ba55c2b751da709b7 Mon Sep 17 00:00:00 2001 From: DevBehindYou Date: Thu, 12 Nov 2026 23:01:18 +0530 Subject: [PATCH 1/2] feat: enforce rolling guest file quota --- .github/workflows/checks.yml | 1 + docs/quota/00_AUDIT.md | 43 +++ docs/quota/FUTURE_AUTH_RESEND.md | 17 + docs/quota/IMPLEMENTATION_STATUS.md | 13 + docs/quota/MASTER_PROMPT.md | 19 + docs/quota/ROLLOUT.md | 22 ++ extension/PRIVACY.md | 6 +- extension/popup.html | 1 + extension/src/bridge.js | 2 +- extension/src/ui/controller.js | 28 +- extension/src/uploads.js | 26 +- extension/test/uploads.test.mjs | 4 +- frontend/app/ConverterClient.js | 2 + frontend/app/api/convert/route.js | 8 + frontend/app/api/jobs/tick/route.js | 1 + frontend/app/api/quota/route.js | 29 ++ frontend/app/api/uploads/create/route.js | 9 +- frontend/app/api/uploads/reserve/route.js | 22 ++ .../components/converter/QuotaIndicator.js | 23 ++ frontend/lib/i18n/messages/de.json | 34 +- frontend/lib/i18n/messages/en-US.json | 34 +- frontend/lib/i18n/messages/es.json | 34 +- frontend/lib/i18n/messages/ja.json | 34 +- frontend/lib/i18n/messages/ru.json | 34 +- frontend/lib/i18n/messages/zh-CN.json | 34 +- frontend/lib/legal/policies.js | 1 + frontend/lib/models/conversionService.js | 52 +-- frontend/lib/models/quotaClient.js | 40 +++ frontend/lib/server/quotaService.js | 105 ++++++ frontend/test/publicRoutes.test.mjs | 9 +- frontend/test/quotaClient.test.mjs | 18 + frontend/test/quotaService.test.mjs | 23 ++ frontend/test/sql/quota.test.mjs | 110 ++++++ frontend/viewmodels/useConverterViewModel.js | 51 ++- supabase/MDIFY_SETUP.sql | 330 +++++++++++++++++- .../20261111000000_llmiser_guest_quota.sql | 325 +++++++++++++++++ tests/integration/postgres_quota.mjs | 42 +++ 37 files changed, 1477 insertions(+), 109 deletions(-) create mode 100644 docs/quota/00_AUDIT.md create mode 100644 docs/quota/FUTURE_AUTH_RESEND.md create mode 100644 docs/quota/IMPLEMENTATION_STATUS.md create mode 100644 docs/quota/MASTER_PROMPT.md create mode 100644 docs/quota/ROLLOUT.md create mode 100644 frontend/app/api/quota/route.js create mode 100644 frontend/app/api/uploads/reserve/route.js create mode 100644 frontend/components/converter/QuotaIndicator.js create mode 100644 frontend/lib/models/quotaClient.js create mode 100644 frontend/lib/server/quotaService.js create mode 100644 frontend/test/quotaClient.test.mjs create mode 100644 frontend/test/quotaService.test.mjs create mode 100644 frontend/test/sql/quota.test.mjs create mode 100644 supabase/migrations/20261111000000_llmiser_guest_quota.sql create mode 100644 tests/integration/postgres_quota.mjs diff --git a/.github/workflows/checks.yml b/.github/workflows/checks.yml index 44244ac..cc71586 100644 --- a/.github/workflows/checks.yml +++ b/.github/workflows/checks.yml @@ -99,6 +99,7 @@ jobs: - run: npm ci --no-audit --no-fund working-directory: frontend - run: node --disable-warning=MODULE_TYPELESS_PACKAGE_JSON tests/integration/postgres_recovery.mjs + - run: node --disable-warning=MODULE_TYPELESS_PACKAGE_JSON tests/integration/postgres_quota.mjs edge: runs-on: ubuntu-latest timeout-minutes: 5 diff --git a/docs/quota/00_AUDIT.md b/docs/quota/00_AUDIT.md new file mode 100644 index 0000000..56efc0b --- /dev/null +++ b/docs/quota/00_AUDIT.md @@ -0,0 +1,43 @@ +# Guest quota audit + +11 November 2026. Local baseline: `fb38df3`. Source inspection only: production schema, dashboards and deployment are not verified. The original Downloads prompt is no longer present; MASTER_PROMPT.md records the corrected implementation contract from the reviewed text. + +## Acceptance graph + +```mermaid +flowchart TD + W[Web batch / extension batch] --> I[Server-issued guest cookie] + I --> R[Atomic batch quota + storage + job reservation] + R --> S[Per-file signed upload issuance] + S --> U[Private Storage upload] + U --> J[start_uploaded_job / enqueue root] + J --> C[claim_work_items] + C --> Q[Database quota start fence] + Q --> B[N / O / Z backend] + B --> F[Existing finalization and output signing] + F --> D[Result access independent of remaining quota] +``` + +Existing entry points: `frontend/app/api/uploads/create/route.js`, `api/convert`, `api/jobs/[id]/start`, `advance`, `download`, authenticated tick and admin routes. `jobService.js` calls `create_reserved_upload_job`; that transaction already enforces storage forecasts and the 32-active-root ceiling. `publicAdmission.js` adds global and keyed-IP request budgets, not a daily file quota. `supabaseRest.js` uses service-role PostgREST, not a direct SQL connection. Workers require the shared backend secret. Anonymous REST/RPC privileges remain revoked. + +The extension already uploads files; its transport previously omitted credentials. Web and extension must bootstrap the same host cookie, send credentials only to the canonical app, and reserve full selections before upload. An extension update and native browser acceptance are required before enabling enforcement. Old clients receive a structured update-required error, never a bypass. + +## Decisions + +- DB policy is the enforcement switch, default disabled. All server entry points consult it; unknown policy fails closed. Schema must be applied before frontend deployment. +- Guest 20, rolling 24 hours from admission. A reserved file occupies a slot immediately. First durable worker claim commits `started`; completed/failed processing never refunds. Pending slots expire after three hours; expired slots cannot claim workers. No worker page/ZIP child charges. +- Entire batch reserves atomically, including existing storage/active-job checks. Insufficient quota rejects all files. User removes files and resubmits; no partial implicit conversion. +- Manifest-bound UUID idempotency key returns original jobs. Different manifest with same key is a conflict. Storage signing/HTTP uncertainty retains reservations for safe replay. +- Upload signing is restricted to 45 minutes after admission, preserving the existing three-hour storage guard for two-hour signed URLs. Replays can resume an existing upload without issuing another upload URL. +- Protected ledger has no cascading job FK: deleting results must not refund charged usage. Existing UUID-capability result retrieval is preserved. Quota identity does not silently become document ownership or account membership. +- A separate server secret signs guest cookies and hashes tokens. Cookie clearing creates a new identity; global abuse controls remain. No person-level guarantee. +- Same-subject locking serializes reservations, releases and first worker charge. Read database clock after the lock. No raw cookies, file contents or signed URLs in logs. +- Direct multipart processing is disabled with a structured use-storage response while quota enforcement is enabled. Requests already carrying body bytes cannot be retroactively stopped at the network edge. +- Shared policy activation must not grandfather newly created unmetered jobs. Only jobs predating initial activation retain legacy processing access. +- Account promotion, passwords and SMTP remain design-only. Future usage merge must preserve distinct events and cannot grant result access on a shared browser. + +## Risks and evidence gates + +Use real PostgreSQL multi-connection concurrency tests in addition to PGlite. Test fresh-cookie multi-tab bootstrap, extension cookie behavior, blocked cookies, signed-URL replay after reservation expiry, processing/cleanup races, lost HTTP responses, differing-manifest replay, existing result retrieval and all six UI languages. Keep feature disabled until native extension and production migration checks pass. No production load tests or account/email activation are authorized by this rollout. + +48-hour default document retention and KEEP/EXTEND remain intact. Existing storage admission keeps the three-hour guard independently of quota release. Ledger expiry is not permission to delete Storage objects or alter retained results. diff --git a/docs/quota/FUTURE_AUTH_RESEND.md b/docs/quota/FUTURE_AUTH_RESEND.md new file mode 100644 index 0000000..976ce6c --- /dev/null +++ b/docs/quota/FUTURE_AUTH_RESEND.md @@ -0,0 +1,17 @@ +# Verified accounts and transactional email + +Design only, 12 November 2026. The guest release uses a secure browser cookie. The account milestone adds Supabase Auth email/password and confirmed email, with Resend custom SMTP for transactional mail. + +## Account quota + +- Validate the Supabase session server-side and use the verified user UUID. Unverified sessions retain the guest limit. Keep credentials and service keys server-only. +- The verified limit is 50 total top-level uploads over the same rolling 24 hours. Account activity is shared across devices. +- During sign-in or verification, lock the guest and account quota subjects in deterministic order. Associate that guest once and preserve unique event IDs, timestamps, in-flight reservations and prior account usage. Treat repeated association as idempotent. If the combined usage exceeds 50, reject new reservations until the required slots return. +- Decide how logout, browser sharing, account deletion and expired sessions affect guest association before implementation. Avoid granting result access as a side effect of reconciling quota usage. Keep upload/result access governed by their own authorization. + +## Email setup + +- Use the [Supabase email/password flow](https://supabase.com/docs/guides/auth/passwords) with confirmation and recovery. Allow only intended HTTPS redirects. Test expired, reused and invalid links and use neutral responses to reduce account enumeration. +- Verify a sending subdomain the operator controls, such as `auth.llmiser.devbehindyou.com` if selected. Add the records shown for that domain by [Resend domain verification](https://resend.com/docs/dashboard/domains/introduction). Review sender identity, authentication and DMARC before sending. +- Use the supported [Resend SMTP integration](https://resend.com/docs/send-with-supabase-smtp). Store the API key in the provider configuration. Verify current SMTP settings, [Resend pricing and allowances](https://resend.com/pricing) and [Supabase sending limits](https://supabase.com/docs/guides/auth/auth-smtp) at rollout. Keep file quota and email rate limits independent. +- Test verification, resend, reset, delivery failures and throttling with test addresses. Review abuse controls, accessibility, all supported app languages, shared-browser access, data retention and account deletion before exposing signup. diff --git a/docs/quota/IMPLEMENTATION_STATUS.md b/docs/quota/IMPLEMENTATION_STATUS.md new file mode 100644 index 0000000..2468908 --- /dev/null +++ b/docs/quota/IMPLEMENTATION_STATUS.md @@ -0,0 +1,13 @@ +# Guest quota implementation status + +12 November 2026. The branch contains the additive migration, atomic whole-batch admission, signed-upload and claim checks, quota UI and updated Chrome extension transport. It also includes the revised contract and future account design. + +| Stage | Evidence | +| --- | --- | +| Local implementation | Database policy defaults disabled. Guest limit is 20 top-level files per rolling 24 hours. | +| Local extension checks | 30 tests passed. The extension built and passed package checks. | +| Database concurrency | Multi-connection PostgreSQL tests are wired into GitHub CI. | +| Native Chrome and live Storage | Staging acceptance still required for cookie sharing and real signed uploads. | +| Production | Migration, deployment and policy activation pending. | + +The next release step is staging validation with the migration installed and the quota-aware web app and extension pointed at the same test environment. Follow [the rollout runbook](ROLLOUT.md). Account authentication and Resend are a [separate design milestone](FUTURE_AUTH_RESEND.md). diff --git a/docs/quota/MASTER_PROMPT.md b/docs/quota/MASTER_PROMPT.md new file mode 100644 index 0000000..e2c5408 --- /dev/null +++ b/docs/quota/MASTER_PROMPT.md @@ -0,0 +1,19 @@ +# Revised implementation contract + +11 November 2026. Supersedes ambiguous clauses in the reviewed LLMiser Quota/Limits/Auth/Resend prompt. Implement guest quota now; design authentication/Resend separately. Follow 00_AUDIT.md and the implementation status rather than historical MDify paths. + +1. Preserve existing conversion, deadlines, queue, storage admission, retention and result retrieval. Work only in LLMiser; use current source and docs/ai-handover/HANDOVER.md and PROGRESS.md. No STATE.yaml is assumed. +2. Exactly 20 accepted top-level files per server-issued guest identity per rolling 24 hours. Reserve before signing uploads. Count pending and started work, never child tasks. Whole batches are atomic and rejected if they do not fit. +3. Idempotency binds subject + request UUID + complete normalized file manifest. Identical replay returns the same jobs; conflicting replay returns 409. Network uncertainty is not proof of failure and cannot trigger a refund. +4. First durable worker claim starts charging permanently for the admission window. Pending expiry/release fences future claims. Started failures remain charged. New submissions are new charges; recovery of an existing job is not. +5. Preserve independent storage authorization guards. Expired quota cannot authorize worker dispatch even if an old signed URL still uploads bytes. Do not shorten byte reservations when releasing file quota. +6. Expose only service-role RPC wrappers, preferably SECURITY INVOKER with explicit table privileges. Sensitive tables can remain private. Do not attempt to call a non-exposed schema directly through the current PostgREST client. +7. Extension backend uploads are a current required path. Bootstrap server identity and explicitly test cookie sharing with host permissions. Never send app cookies or secrets to Storage. Missing/blocked identity fails with actionable UI, not a new identity per file. +8. Keep result access separate from quota enforcement and preserve old recovery links. Later account quota merges must not imply document transfer. +9. Use structured errors: DAILY_FILE_LIMIT with actual remaining, requested count, next-slot time and request-fit time; capacity errors remain distinct. Permanent quota errors are not automatic processing retries. Refresh status on focus and after outcomes. +10. Guest UI uses all six app languages, accessible announcements and explicit rolling-window text. Near-limit <=5, pending shown separately, downloads never disabled for exhaustion. +11. DB flag defaults disabled; apply additive schema before code and enable only after CI, real PostgreSQL races, native extension/browser acceptance and production configuration checks. Fail closed on unknown policy. No automatic production schema replay. +12. Keep bounded cleanup and metadata-only diagnostics. Never log tokens, signed URLs or input contents. Distinguish implemented, tested, merged, deployed, enabled and production-verified. +13. Future-only: verified Supabase account gets 50 total, not 20+50. Usage reconciliation uses immutable event IDs and one-time guest association. Supabase Auth handles passwords; Resend custom SMTP is separate. No signup, password reset, DNS changes or email credentials in this guest release. + +Deliver audit, additive SQL, server and client integration, regression/concurrency tests, operational runbook, future-auth design and honest milestone evidence. Existing broad PR/release authorization does not replace required validation. diff --git a/docs/quota/ROLLOUT.md b/docs/quota/ROLLOUT.md new file mode 100644 index 0000000..47d4984 --- /dev/null +++ b/docs/quota/ROLLOUT.md @@ -0,0 +1,22 @@ +# Guest file quota rollout + +The additive migration ships with enforcement disabled. It extends the existing job and Storage path. The guest allowance is per browser identity and uses rolling admission timestamps. Global admission and storage capacity remain independent. + +1. Run the branch checks, including `tests/integration/postgres_quota.mjs` against its disposable multi-connection PostgreSQL fixture. Inspect the exact tested branch revision. +2. Apply only `supabase/migrations/20261111000000_llmiser_guest_quota.sql` to an isolated Supabase project with the earlier migrations installed. Verify `select public.quota_policy();` shows disabled. Test the prior frontend against the additive schema. Avoid replaying the consolidated setup script against an existing deployment. +3. Configure `QUOTA_GUEST_SECRET` as a stable, independently generated random secret of at least 32 characters. Use one value per environment across instances. Rotation invalidates old guest identities and should be planned. The server refuses guest issuance if the secret is missing. +4. In staging, deploy the quota-aware app and build. Set `quota_private.policy.enabled` to true for its singleton row. Verify a real signed upload for each pool, 20 admissions followed by a rejected 21st, an entire batch rejection, resuming a successfully uploaded file, and an existing download after exhaustion. Check local-time display and keyboard operation. +5. Load the extension build in Chrome against an approved test setup. Verify the browser can share the host cookie between the app and the extension, including the browser's cookie restrictions. Use test fixtures. Verify that Storage requests omit credentials. The shipped extension targets the canonical production app and Storage origins, so use an isolated test build configured for staging for pre-release smoke tests. +6. Apply the same single migration in production before deploying this frontend. Keep policy disabled while verifying legacy uploads, recovery ticks and the new version. Make the updated extension available before enabling. Older clients receive an update-required response under enforcement. +7. Enable after the release evidence is recorded. Observe quota rejection counts, reservation expiry, orphan handling, queue delay and backend capacity through metadata-only diagnostics. Avoid logging cookies, upload URLs, filenames or file content. + +Use this operator query in the target SQL Editor after independently verifying the project and environment: + +```sql +select public.quota_policy(); +update quota_private.policy set enabled = true where singleton; +``` + +Set `enabled = false` to suspend enforcement and allow ordinary admission again. Leave the additive migration installed so outstanding reserved jobs and new frontend calls retain their contracts. Existing metered jobs still obey their own reservation state. Before re-enabling, settle unmetered jobs created during the disabled period. Do not delete ledger rows, release started slots or reset the activation timestamp as a rollback procedure. + +Signing closes after 45 minutes to leave headroom within the existing three-hour Storage guard. An existing input can still resume before its reservation expires. Unstarted quota slots release after expiry or terminal pre-start recovery. Started events remain charged for the original rolling window. The tick prunes eligible terminal ledger batches after seven days. This does not alter the 48-hour document retention policy. diff --git a/extension/PRIVACY.md b/extension/PRIVACY.md index 0a2e4e4..9294427 100644 --- a/extension/PRIVACY.md +++ b/extension/PRIVACY.md @@ -1,10 +1,12 @@ # LLMiser Chrome extension privacy -Version 0.2.0 — 24 October 2026. Operator: DevBehindYou. +Quota-aware revision — 11 November 2026. Operator: DevBehindYou. The extension has one file Converter screen in a toolbar popup. It does not capture webpages or selected text, collect analytics, monitor browsing history or send chat messages. Page extraction and its libraries were removed in version 0.2.0. -Selecting or dropping files does not upload them. Clicking Convert files requests optional access to exactly `https://llmiser.devbehindyou.com` and `https://ppmbqgecdbrezxedyeur.supabase.co`. If granted, file metadata (filename, size, content type and profile) goes to LLMiser; bytes go directly to its private Supabase Storage using a signed URL. LLMiser's existing backends process those files and Markdown is downloaded to the popup. Requests omit cookies, reject redirects and validate signed storage links against the expected project/bucket/job. No backend secret or service-role key ships in the extension. Normal service/network logs, processing and the default 48-hour retention with documented administrative exceptions apply. See https://llmiser.devbehindyou.com/privacy. +Selecting or dropping files does not upload them. Clicking Convert files requests optional access to exactly `https://llmiser.devbehindyou.com` and `https://ppmbqgecdbrezxedyeur.supabase.co`. If granted, file metadata (filename, size, content type and profile) goes to LLMiser; bytes go directly to its private Supabase Storage using a signed URL. LLMiser's existing backends process those files and Markdown is downloaded to the popup. Requests to LLMiser include its service cookie for the guest file allowance; Storage requests omit cookies. Redirects are rejected and signed storage links are validated against the expected project/bucket/job. No backend secret or service-role key ships in the extension. Normal service/network logs, processing and the default 48-hour retention with documented administrative exceptions apply. See https://llmiser.devbehindyou.com/privacy. + +When file limits are enabled, LLMiser issues a secure, HttpOnly guest cookie with a 90-day lifetime. The server stores a keyed hash, request/file identifiers, a manifest hash and quota timestamps, not the raw cookie. Quota metadata is eligible for bounded cleanup after seven days; records for active jobs remain until recovery settles. The whole selected batch is reserved before uploading. Started conversion counts even if it fails; retries of the same admitted job do not count again. Unstarted reservations expire after three hours. Existing output remains accessible when the allowance is exhausted. Cookie access depends on browser settings; blocked identity access prevents new conversion rather than bypassing limits. The `storage` permission keeps one editable file draft and up to 20 recovery records in `chrome.storage.session`. A draft contains Markdown, filename, capture time and warnings. Recovery records contain only job ID, filename and upload/processing phase; no signed URL, access token, original file bytes or browsing URL is retained in these records. Job IDs allow retrieval of those jobs; keep your browser session private. Chrome session storage is cleared when Chrome closes or the extension is disabled, reloaded or updated, and Chrome may clear it independently. Old page-capture drafts are not restored in this file-only version. diff --git a/extension/popup.html b/extension/popup.html index 0092c30..f0f70b4 100644 --- a/extension/popup.html +++ b/extension/popup.html @@ -17,6 +17,7 @@
AI DESTINATION

Detecting active tab…

Open ChatGPT, Claude or Gemini and click the LLMiser toolbar icon there. Paste fills an empty composer; you send the message.

+

Loading…

Your Markdown

diff --git a/extension/src/bridge.js b/extension/src/bridge.js index fa071ff..2c7f4ff 100644 --- a/extension/src/bridge.js +++ b/extension/src/bridge.js @@ -1,7 +1,7 @@ import { draftRecord, pendingJobRecord } from './model.js'; import { UPLOAD_ORIGINS } from './uploads.js'; import { aiSite, pasteIntoComposer } from './ai.js'; -export { convertUpload, resumeUpload } from './uploads.js'; +export { convertUpload, resumeUpload, prepareExtensionUploads as prepareUploads, readExtensionQuota as readQuota } from './uploads.js'; export const authorizeUploads = () => chrome.permissions.request({ origins: UPLOAD_ORIGINS }); export async function detectAI() { const [tab] = await chrome.tabs.query({ active: true, currentWindow: true }); diff --git a/extension/src/ui/controller.js b/extension/src/ui/controller.js index ff777db..89024f4 100644 --- a/extension/src/ui/controller.js +++ b/extension/src/ui/controller.js @@ -14,6 +14,7 @@ export async function mountPanel(doc, api) { let targetRevision = 0; let activeItem = null; let clearFailed = false; + let batchAttempt = null; const status = (text, error = false) => { el('status').textContent = text; el('status').dataset.error = String(error); }; const update = () => { const hasDraft = draft !== null; @@ -100,18 +101,30 @@ export async function mountPanel(doc, api) { const signal = uploadAbort.signal; const profile = el('profile').value; let sessionSaveFailed = false; + let canReadQuota = false; try { // Called directly from the click gesture so Chrome can show its optional // permission prompt. Denial sends no file or job metadata. const granted = await api.authorizeUploads(); if (attempt !== revision) return; if (!granted) { status('File-converter access was not granted. Your files were not uploaded.', true); return; } + canReadQuota = true; + const fresh = queue.filter(item => ['pending','retry'].includes(item.state) && !item.checkpoint && !item.reservation); + if (fresh.length && api.prepareUploads) { + const identity = JSON.stringify([profile, fresh.map(item => [item.name, item.file?.size])]); + if (batchAttempt?.identity !== identity) batchAttempt = { identity, requestId: crypto.randomUUID(), fileIds: fresh.map(() => crypto.randomUUID()) }; + const prepared = await api.prepareUploads(fresh.map(item => item.file), profile, { ...batchAttempt, signal }); + if (attempt !== revision) return; + prepared.reservations.forEach((reservation,index) => { fresh[index].reservation = reservation; }); + const indicator = el('quota-status'); + if (indicator) indicator.textContent = prepared.quota?.enabled ? `${prepared.quota.used} of ${prepared.quota.limit} used; ${prepared.quota.reserved} reserved; ${prepared.quota.remaining} remaining in the rolling 24-hour window.` : ''; + } for (const item of queue.filter(value => ['pending','retry'].includes(value.state))) { if (attempt !== revision) break; item.state = 'running'; item.message = 'Starting…'; renderQueue(); status(`Converting ${item.name}…`); try { - const options = { signal, onCheckpoint: async checkpoint => { + const options = { signal, reservation: item.reservation, onCheckpoint: async checkpoint => { if (attempt !== revision) throw new DOMException('Aborted','AbortError'); await api.savePendingJob(checkpoint); if (attempt !== revision) throw new DOMException('Aborted','AbortError'); @@ -141,8 +154,17 @@ export async function mountPanel(doc, api) { const failed = queue.filter(item => ['error','retry'].includes(item.state)).length; status(sessionSaveFailed ? 'Converted results are available, but session saving failed. Export them before closing this popup.' : failed ? `${failed} file(s) could not finish. Resume uploaded jobs, or choose interrupted files again.` : 'Files converted. Review your Markdown, then download or paste.', sessionSaveFailed || failed > 0); } - } catch { if (attempt === revision) status('Chrome could not grant file-converter access. No new upload was started.', true); } - finally { if (attempt === revision) { busy = false; uploadAbort = null; renderQueue(); } } + } catch (error) { if (attempt === revision) status(error.message || 'Could not reserve this selection. No new upload was started.', true); } + finally { + if (canReadQuota && api.readQuota) { + try { + const quota = await api.readQuota(); + if (attempt === revision && el('quota-status')) el('quota-status').textContent = quota.enabled + ? `${quota.used} of ${quota.limit} used; ${quota.reserved} reserved; ${quota.remaining} remaining in the rolling 24-hour window.` : ''; + } catch { /* A failed refresh never hides a conversion result. */ } + } + if (attempt === revision) { busy = false; uploadAbort = null; renderQueue(); } + } }); const detectTarget = async () => { const attempt = ++targetRevision; diff --git a/extension/src/uploads.js b/extension/src/uploads.js index ebd7ced..b9c0224 100644 --- a/extension/src/uploads.js +++ b/extension/src/uploads.js @@ -1,6 +1,7 @@ import { startUploadedJob, waitForJob, fetchResultMarkdown } from '../../frontend/lib/models/conversionService.js'; import { PROFILES, validateUpload } from '../../frontend/lib/formats.js'; import { MAX_MARKDOWN, pendingJobRecord } from './model.js'; +import { prepareUploads, readQuota } from '../../frontend/lib/models/quotaClient.js'; export const APP_ORIGIN = 'https://llmiser.devbehindyou.com'; export const STORAGE_ORIGIN = 'https://ppmbqgecdbrezxedyeur.supabase.co'; @@ -8,6 +9,9 @@ export const UPLOAD_ORIGINS = [`${APP_ORIGIN}/*`, `${STORAGE_ORIGIN}/*`]; const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/; const BUCKET = 'mdify-pro-files'; // Existing production compatibility contract. +export const prepareExtensionUploads = (files, profile, options = {}) => prepareUploads(files, profile, { ...options, origin: APP_ORIGIN }); +export const readExtensionQuota = () => readQuota({ origin: APP_ORIGIN }); + export function signedStorageUrl(value, jobId, upload = false) { let url; try { url = new URL(value); } catch { throw new Error('The converter returned an invalid storage link.'); } @@ -39,7 +43,7 @@ async function boundedText(response, maxBytes) { } finally { reader.releaseLock(); } } -// No cookies, authorization keys, arbitrary URLs or redirects. The permission +// Guest cookies go only to APP_ORIGIN. No cookies or keys go to Storage. // is optional; it is requested only by the Convert files button in the popup. export const convertUpload = (file, profile, options) => runConversion(file, profile, options); export async function resumeUpload(checkpoint, options) { @@ -48,7 +52,7 @@ export async function resumeUpload(checkpoint, options) { return runConversion({ name: record.filename }, null, options, record); } async function runConversion(file, profile, { signal, onProgress, onCheckpoint, fetchImpl = fetch, - sleepImpl, now } = {}, resumeJob = null) { + sleepImpl, now, reservation } = {}, resumeJob = null) { if (!resumeJob) { const invalid = validateUpload(file); if (invalid) throw new Error(invalid); @@ -62,7 +66,7 @@ async function runConversion(file, profile, { signal, onProgress, onCheckpoint, const timer = setTimeout(abort, 300_000); try { const response = await fetchImpl(url, { ...init, signal: controller.signal, - credentials: 'omit', redirect: 'error', cache: 'no-store', referrerPolicy: 'no-referrer' }); + credentials: new URL(url).origin === APP_ORIGIN ? 'include' : 'omit', redirect: 'error', cache: 'no-store', referrerPolicy: 'no-referrer' }); // Keep the timeout active while reading the body, not just the headers. const limit = new URL(url).origin === APP_ORIGIN ? 512_000 : 2_000_000; const text = await boundedText(response, limit); @@ -73,17 +77,19 @@ async function runConversion(file, profile, { signal, onProgress, onCheckpoint, if (!resumeJob) { const created = await send(`${APP_ORIGIN}/api/uploads/create`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ filename: file.name, size: file.size, content_type: file.type || null, profile }), + body: JSON.stringify({ filename: file.name, size: file.size, content_type: file.type || null, profile, ...reservation }), }); job = await created.json().catch(() => ({})); if (!created.ok) throw new Error(String(job.detail || `Could not start upload (${created.status}).`).slice(0, 400)); if (!UUID.test(job.job_id || '')) throw new Error('The converter returned an invalid job. Please retry.'); - const uploadUrl = signedStorageUrl(job.upload_url, job.job_id, true); - await onCheckpoint?.({ jobId: job.job_id, filename: file.name, phase: 'uploading' }); - const form = new FormData(); form.append('cacheControl', '3600'); form.append('', file); - onProgress?.('Uploading…'); - const uploaded = await send(uploadUrl, { method: 'PUT', body: form }); - if (!uploaded.ok) throw new Error(`Upload failed (${uploaded.status}). Please retry.`); + if (job.upload_url) { + const uploadUrl = signedStorageUrl(job.upload_url, job.job_id, true); + await onCheckpoint?.({ jobId: job.job_id, filename: file.name, phase: 'uploading' }); + const form = new FormData(); form.append('cacheControl', '3600'); form.append('', file); + onProgress?.('Uploading…'); + const uploaded = await send(uploadUrl, { method: 'PUT', body: form }); + if (!uploaded.ok) throw new Error(`Upload failed (${uploaded.status}). Please retry.`); + } await onCheckpoint?.({ jobId: job.job_id, filename: file.name, phase: 'processing' }); } const apiFetch = (url, init) => { diff --git a/extension/test/uploads.test.mjs b/extension/test/uploads.test.mjs index 5cae8a5..88291a9 100644 --- a/extension/test/uploads.test.mjs +++ b/extension/test/uploads.test.mjs @@ -9,11 +9,11 @@ const output=signed('sign')+'output/result.md?token=test-only'; const json=(value,status=200)=>Response.json(value,{status}); const file=()=>new File(['synthetic fixture'], 'sample.txt', {type:'text/plain'}); -test('file conversion uses private signed storage and existing job APIs, with no cookies or redirects',async()=>{ +test('file conversion sends guest cookies only to the app, never Storage or redirects',async()=>{ const calls=[]; const result=await convertUpload(file(),'Clean',{fetchImpl:async(url,init)=>{ calls.push({url,init}); - assert.equal(init.credentials,'omit'); assert.equal(init.redirect,'error'); + assert.equal(init.credentials,new URL(url).origin===APP_ORIGIN?'include':'omit'); assert.equal(init.redirect,'error'); assert.equal(init.referrerPolicy,'no-referrer'); assert.equal(new Headers(init.headers).has('authorization'),false); if(url.endsWith('/api/uploads/create')) return json({job_id:id,upload_url:upload},201); diff --git a/frontend/app/ConverterClient.js b/frontend/app/ConverterClient.js index bc17114..ff119ea 100644 --- a/frontend/app/ConverterClient.js +++ b/frontend/app/ConverterClient.js @@ -16,6 +16,7 @@ import ThreeColumnWorkspace from '../components/converter/ThreeColumnWorkspace'; import MobileWorkspace from '../components/converter/MobileWorkspace'; import OfflineBanner from '../components/converter/OfflineBanner'; import Toast from '../components/converter/Toast'; +import QuotaIndicator from '../components/converter/QuotaIndicator'; import { useConverterScreenViewModel } from '../viewmodels/useConverterScreenViewModel'; import { useMediaQuery } from '../viewmodels/useMediaQuery'; import { ACCEPT_ATTRIBUTE } from '../lib/formats'; @@ -81,6 +82,7 @@ export default function ConverterClient({ children }) {

{uiText(HERO_TITLE)}

+ {isDesktop !== false && (
+
+ {quota?.enabled && <> +

{uiText('{used} of {limit} files used in the last 24 hours', { used: quota.used, limit: quota.limit })}

+

{uiText('{reserved} reserved · {remaining} remaining', { reserved: quota.reserved, remaining: quota.remaining })}

+ {quota.remaining <= 5 &&

{uiText(quota.remaining === 0 ? 'No file slots remain. Your existing results are still available.' : 'Your file allowance is nearly used. Check the remaining count before uploading.')}

} + {nextLabel &&

{uiText('Next slot release scheduled for {time} (your local time).', { time: nextLabel })}

} +

{uiText('Up to 20 files per batch. Your rolling allowance is separate; slots return individually.')}

+ } + {error &&

{uiText(error)}

} +
+ +
; +} diff --git a/frontend/lib/i18n/messages/de.json b/frontend/lib/i18n/messages/de.json index 0721cde..39bf743 100644 --- a/frontend/lib/i18n/messages/de.json +++ b/frontend/lib/i18n/messages/de.json @@ -155,7 +155,9 @@ "Could not build the ZIP file": "Die ZIP-Datei konnte nicht erstellt werden", "Could not download the converted file ({v0}). Please try again.": "Die konvertierte Datei konnte nicht heruntergeladen werden ({v0}). Bitte versuchen Sie es erneut.", "Could not download the converted file. Check your connection and retry.": "Die konvertierte Datei konnte nicht heruntergeladen werden. Prüfen Sie die Verbindung und versuchen Sie es erneut.", + "Could not load the complete file list": "Die vollständige Dateiliste konnte nicht geladen werden", "Could not reach the converter. Check your connection and retry.": "Konverter nicht erreichbar. Verbindung prüfen und erneut versuchen.", + "Could not refresh file limits. They will be checked before upload.": "Dateilimits konnten nicht aktualisiert werden. Sie werden vor dem Hochladen geprüft.", "Could not retrieve the saved result. Check your connection and retry.": "Das gespeicherte Ergebnis konnte nicht abgerufen werden. Prüfen Sie die Verbindung und versuchen Sie es erneut.", "Counting page views, to see which pages people use and how they find LLMiser. Legal basis: our legitimate interest in improving the service (Art. 6(1)(f) GDPR). The counts are anonymous and need no cookies.": "Seitenaufrufe zählen, um Nutzung und Zugangswege zu verstehen. Rechtsgrundlage: unser berechtigtes Interesse an der Verbesserung des Dienstes (Art. 6 Abs. 1 lit. f DSGVO). Die Zahlen sind anonym und benötigen keine Cookies.", "Created": "Erstellt", @@ -194,6 +196,7 @@ "EXPORT AREA": "EXPORTBEREICH", "Empty all stored conversion sessions from local storage": "Alle gespeicherten Konvertierungen aus dem lokalen Speicher entfernen", "Empty document content": "Dokumentinhalt ist leer", + "Enable cookies for LLMiser and retry. Update the extension if you use it.": "Aktivieren Sie Cookies für LLMiser und versuchen Sie es erneut. Aktualisieren Sie gegebenenfalls die Erweiterung.", "End of list": "Ende der Liste", "Engine": "Engine", "Enter both admin keys.": "Beide Administratorschlüssel eingeben.", @@ -210,7 +213,9 @@ "FREE · NO SIGN-UP · OPEN SOURCE": "KOSTENLOS · OHNE REGISTRIERUNG · OPEN SOURCE", "Failed": "Fehlgeschlagen", "Fast 1-click restore": "Mit einem Klick wiederherstellen", + "File allowance": "Dateikontingent", "File details: name, type and size.": "Dateiangaben: Name, Typ und Größe.", + "File limits are temporarily unavailable. Please try again shortly.": "Dateilimits sind vorübergehend nicht verfügbar. Versuchen Sie es in Kürze erneut.", "File names: deleted together with the files. After that, a job record keeps only the file type, size, timings and outcome, with nothing that identifies you.": "Dateinamen werden mit den Dateien gelöscht. Danach enthält der Auftragsdatensatz nur Typ, Größe, Zeiten und Ergebnis, ohne identifizierende Angaben.", "File picker opened (⌘O)": "Dateiauswahl geöffnet (⌘O)", "Files": "Dateien", @@ -291,6 +296,7 @@ "LLMiser's source code is published under the GNU General Public License v3.0. That licence governs your use of the code. These terms govern the hosted service.": "Der Quellcode von LLMiser steht unter GNU GPL v3.0. Diese Lizenz regelt die Codenutzung, diese Bedingungen hingegen den gehosteten Dienst.", "LLMiser: Free LLM Cost Optimizer for Documents": "LLMiser: Kostenloser LLM-Kostenoptimierer für Dokumente", "Language": "Sprache", + "Large document: formatted preview is paused to keep editing responsive. The complete Markdown is available in Raw mode and exports.": "Großes Dokument: Die formatierte Vorschau ist pausiert, damit die Bearbeitung flüssig bleibt. Das vollständige Markdown ist im Modus „Quelltext“ und in Exporten verfügbar.", "Last updated": "Zuletzt aktualisiert", "Legal": "Rechtliches", "Limit": "Grenze", @@ -298,6 +304,7 @@ "Load Sample Report": "Beispielbericht laden", "Load more": "Mehr laden", "Loaded \"{v0}\" from recent sessions": "„{v0}“ aus dem Verlauf geladen", + "Loaded: {v0} · Total: {v1}": "Geladen: {v0} · Gesamt: {v1}", "Loading formatted preview…": "Formatierte Vorschau wird geladen…", "Loading language…": "Sprache wird geladen…", "Loading preview…": "Vorschau wird geladen…", @@ -314,11 +321,13 @@ "Menu": "Menü", "Minimizes token density": "Reduziert die Tokenanzahl", "Monospace source code": "Quelltext in Festbreitenschrift", + "Next slot release scheduled for {time} (your local time).": "Nächste Freigabe voraussichtlich um {time} (Ortszeit).", "No ads, no tracking cookies, only anonymous page-view counts. Nobody trains AI models on your files.": "Keine Werbung, keine Tracking-Cookies, nur anonyme Seitenaufrufzahlen. Niemand trainiert KI-Modelle mit Ihren Dateien.", "No audit entries yet.": "Noch keine Protokolleinträge.", "No backend instances are configured.": "Keine Backend-Instanzen konfiguriert.", "No converted Markdown to copy yet": "Noch kein konvertiertes Markdown zum Kopieren", "No document converted yet. Choose or drop a file to export.": "Noch kein Dokument konvertiert. Zum Exportieren Datei auswählen oder ablegen.", + "No file slots remain. Your existing results are still available.": "Keine Dateiplätze mehr verfügbar. Bisherige Ergebnisse bleiben zugänglich.", "No files in queue yet.": "Noch keine Dateien in der Warteschlange.", "No files registered.": "Keine Dateien registriert.", "No files.": "Keine Dateien.", @@ -358,6 +367,7 @@ "Partial results": "Teilergebnisse", "Parts": "Teile", "Parts done": "Teile abgeschlossen", + "Pause formatted preview": "Formatierte Vorschau pausieren", "Pool": "Pool", "Prepare useful context before you spend tokens. LLMiser converts PDFs, Office files, images and ZIP projects to editable Markdown. Choose a profile, review the output, and send only what your AI task needs.": "Bereiten Sie nützlichen Kontext vor, bevor Sie Token verbrauchen. LLMiser konvertiert PDFs, Office-Dateien, Bilder und ZIP-Projekte in bearbeitbares Markdown. Wählen Sie ein Profil, prüfen Sie die Ausgabe und senden Sie nur, was Ihre KI-Aufgabe benötigt.", "Preview": "Vorschau", @@ -402,10 +412,13 @@ "Record the exact model, tokenizer, billable input and output usage, caching and image charges.": "Genaues Modell, Tokenizer, abrechenbare Ein- und Ausgabe, Cache- und Bildkosten erfassen.", "Recording that you accepted the Terms and this policy, so we can show which version you agreed to. Legal basis: Art. 6(1)(b) and (f) GDPR.": "Ihre Zustimmung zu Bedingungen und Datenschutzerklärung samt Version dokumentieren. Rechtsgrundlage: Art. 6 Abs. 1 lit. b und f DSGVO.", "Refresh": "Aktualisieren", + "Refresh file allowance": "Dateikontingent aktualisieren", "Refreshes every 30 s while this tab is open.": "Wird bei geöffneter Registerkarte alle 30 Sekunden aktualisiert.", + "Reload the controller to use paginated job details.": "Laden Sie den Controller neu, um Auftragsdetails seitenweise anzuzeigen.", "Remove from history": "Aus Verlauf entfernen", "Remove {v0}": "{v0} entfernen", "Removed from recent sessions": "Aus dem Verlauf entfernt", + "Render full preview (may take a moment)": "Vollständige Vorschau rendern (kann einen Moment dauern)", "Rendered": "Formatiert", "Rendered Markdown view": "Formatierte Markdown-Vorschau", "Rendered with GFM": "Mit GFM formatiert", @@ -446,6 +459,7 @@ "Status": "Status", "Storage": "Speicher", "Stored": "Gespeichert", + "Stored files changed. Refresh and try again.": "Die gespeicherten Dateien haben sich geändert. Aktualisieren Sie die Ansicht und versuchen Sie es erneut.", "Stripped of metadata & extra line breaks": "Ohne Metadaten und zusätzliche Zeilenumbrüche", "Strips metadata & extra lines": "Entfernt Metadaten und zusätzliche Zeilen", "Supported documents and output": "Unterstützte Dokumente und Ausgabe", @@ -473,7 +487,9 @@ "These are the original converted files. Use .md or .zip above to export your edits. Server copies are available until automatic deletion.": "Dies sind die ursprünglich konvertierten Dateien. Exportieren Sie Ihre Änderungen oben über .md oder .zip. Serverkopien sind bis zur automatischen Löschung verfügbar.", "These items are needed for features you use, so the EU ePrivacy rules don't require a separate cookie consent for them.": "Diese Angaben sind für die genutzten Funktionen erforderlich; nach den EU-ePrivacy-Regeln benötigen sie keine gesonderte Cookie-Einwilligung.", "They're deleted automatically 48 hours after upload, with no account needed.": "Sie werden 48 Stunden nach dem Upload automatisch gelöscht; ein Konto ist nicht nötig.", + "This batch exceeds your remaining file limit. Remove files and try again.": "Dieser Stapel überschreitet Ihr Restkontingent. Entfernen Sie Dateien und versuchen Sie es erneut.", "This saved result is no longer available. Remove this entry and choose the original file to convert it again.": "Dieses gespeicherte Ergebnis ist nicht mehr verfügbar. Entfernen Sie den Eintrag und wählen Sie die Originaldatei für eine neue Konvertierung.", + "This upload reservation expired. Choose the files again.": "Diese Upload-Reservierung ist abgelaufen. Wählen Sie die Dateien erneut aus.", "Time": "Zeit", "To report content you believe is illegal, send us: why you think it's illegal, the file name or job reference and the time, your name and email, and a statement that your report is accurate and made in good faith. We'll review it without undue delay and tell you what we decided. If we restrict content or access, we explain the reason to the person affected.": "Für eine Meldung nennen Sie den vermuteten Rechtsverstoß, Dateinamen oder Auftragsreferenz und Zeitpunkt, Ihren Namen und Ihre E-Mail sowie eine Erklärung, dass die Meldung richtig und nach bestem Wissen erfolgt. Wir prüfen sie unverzüglich und teilen die Entscheidung mit. Bei Inhalts- oder Zugangsbeschränkungen erklären wir betroffenen Personen die Gründe.", "Toggle Recent Conversion Sessions Sidebar": "Seitenleiste mit letzten Konvertierungen umschalten", @@ -485,6 +501,8 @@ "Too many requests. Please wait and try again.": "Zu viele Anfragen. Bitte warten und erneut versuchen.", "Total characters: {v0} (without spaces: {v1})": "Zeichen insgesamt: {v0} (ohne Leerzeichen: {v1})", "Total words counted: {v0}": "Gezählte Wörter insgesamt: {v0}", + "Totals can change while a job runs. Refresh to update all sections.": "Die Gesamtzahlen können sich während der Verarbeitung ändern. Aktualisieren Sie alle Abschnitte über „Aktualisieren“.", + "Tree and status counts show loaded records only.": "Baum und Statuszahlen zeigen nur geladene Einträge.", "Tries": "Versuche", "Turn any document into clean Markdown.": "Dokumente in sauberes Markdown umwandeln.", "Type": "Typ", @@ -492,6 +510,7 @@ "UPLOAD DOCUMENTS": "DOKUMENTE HOCHLADEN", "Under the GDPR you can ask us to:": "Nach der DSGVO können Sie von uns verlangen:", "Unsupported format: .{v0}": "Nicht unterstütztes Format: .{v0}", + "Up to 20 files per batch. Your rolling allowance is separate; slots return individually.": "Bis zu 20 Dateien pro Stapel. Das rollierende Kontingent gilt zusätzlich; Plätze werden einzeln wieder frei.", "Updated": "Aktualisiert", "Upload & preview": "Hochladen und Vorschau", "Upload and convert any document to see live rendered Markdown alongside raw code.": "Dokument hochladen und konvertieren, um Markdown-Vorschau und Quelltext nebeneinander zu sehen.", @@ -516,6 +535,7 @@ "What happens to uploaded files?": "Was passiert mit hochgeladenen Dateien?", "What is LLMiser?": "Was ist LLMiser?", "When": "Zeitpunkt", + "When guest file limits are enabled, a secure service cookie identifies your browser for the rolling file allowance. It lasts up to 90 days and is not used for advertising. We retain a keyed hash and quota event identifiers and timestamps, not the raw cookie. Quota metadata is eligible for cleanup after seven days. Active-job records remain until recovery settles. Clearing the cookie creates a new guest identity and does not delete previously uploaded files.": "Wenn Dateilimits für Gäste aktiviert sind, identifiziert ein sicheres Service-Cookie Ihren Browser für das rollierende Kontingent. Es bleibt bis zu 90 Tage gültig und dient nicht der Werbung. Wir speichern einen schlüsselbasierten Hash sowie Kennungen und Zeitstempel der Kontingentereignisse, nicht das ursprüngliche Cookie. Kontingentdaten können nach sieben Tagen bereinigt werden. Datensätze aktiver Aufträge bleiben bis zum Abschluss der Wiederherstellung erhalten. Das Löschen des Cookies erzeugt eine neue Gastidentität und löscht keine zuvor hochgeladenen Dateien.", "Whenever you convert a document, your last 5 conversions are automatically stored here for instant recall, side-by-side editing, and quick downloads.": "Die letzten 5 Konvertierungen werden hier automatisch gespeichert – zum schnellen Öffnen, Bearbeiten nebeneinander und Herunterladen.", "Which version of these documents you accepted, and when.": "Welche Version dieser Dokumente Sie wann akzeptiert haben.", "Why": "Warum", @@ -536,6 +556,7 @@ "You keep every right to the files you upload and to the Markdown LLMiser produces from them.": "Sie behalten sämtliche Rechte an Ihren Dateien und dem daraus erzeugten Markdown.", "Your Markdown appears here": "Hier erscheint Ihr Markdown", "Your app language choice.": "Ihre Auswahl der App-Sprache.", + "Your file allowance is nearly used. Check the remaining count before uploading.": "Ihr Dateikontingent ist fast aufgebraucht. Prüfen Sie die verbleibende Anzahl vor dem Hochladen.", "Your last 5 conversions (the Markdown text and file details), so you can reopen them. Clear them any time from the Recent panel.": "Ihre letzten 5 Konvertierungen mit Markdown und Dateiangaben, damit Sie sie erneut öffnen können. Im Verlauf jederzeit löschbar.", "Your last 5 conversions: the Markdown text when it fits, file details and a reference to the completed conversion. Clear them any time from the Recent panel.": "Ihre letzten 5 Konvertierungen: Markdown-Text, sofern er hineinpasst, Dateiangaben und ein Verweis auf die abgeschlossene Konvertierung. Sie können diese Angaben jederzeit im Verlaufsbereich löschen.", "Your light or dark theme choice.": "Ihre Auswahl des hellen oder dunklen Designs.", @@ -601,6 +622,8 @@ "upload malware or files built to attack or crash the service,": "Schadsoftware oder Dateien zum Angriff auf oder Absturz des Dienstes hochzuladen,", "with OCR pages": "mit OCR-Seiten", "words": "Wörter", + "{reserved} reserved · {remaining} remaining": "{reserved} reserviert · {remaining} verfügbar", + "{used} of {limit} files used in the last 24 hours": "{used} von {limit} Dateien in den letzten 24 Stunden verwendet", "{v0} already in queue": "{v0} bereits in Warteschlange", "{v0} done, {v1} failed: {v2}": "{v0} erledigt, {v1} fehlgeschlagen: {v2}", "{v0} job(s) updated": "{v0} Aufträge aktualisiert", @@ -626,14 +649,5 @@ "✓ Markdown Copied": "✓ Markdown kopiert", "✓ done": "✓ erledigt", "📄 Terms of Service": "📄 Nutzungsbedingungen", - "🔒 Privacy Policy": "🔒 Datenschutzerklärung", - "Large document: formatted preview is paused to keep editing responsive. The complete Markdown is available in Raw mode and exports.": "Großes Dokument: Die formatierte Vorschau ist pausiert, damit die Bearbeitung flüssig bleibt. Das vollständige Markdown ist im Modus „Quelltext“ und in Exporten verfügbar.", - "Render full preview (may take a moment)": "Vollständige Vorschau rendern (kann einen Moment dauern)", - "Pause formatted preview": "Formatierte Vorschau pausieren", - "Loaded: {v0} · Total: {v1}": "Geladen: {v0} · Gesamt: {v1}", - "Totals can change while a job runs. Refresh to update all sections.": "Die Gesamtzahlen können sich während der Verarbeitung ändern. Aktualisieren Sie alle Abschnitte über „Aktualisieren“.", - "Tree and status counts show loaded records only.": "Baum und Statuszahlen zeigen nur geladene Einträge.", - "Stored files changed. Refresh and try again.": "Die gespeicherten Dateien haben sich geändert. Aktualisieren Sie die Ansicht und versuchen Sie es erneut.", - "Could not load the complete file list": "Die vollständige Dateiliste konnte nicht geladen werden", - "Reload the controller to use paginated job details.": "Laden Sie den Controller neu, um Auftragsdetails seitenweise anzuzeigen." + "🔒 Privacy Policy": "🔒 Datenschutzerklärung" } diff --git a/frontend/lib/i18n/messages/en-US.json b/frontend/lib/i18n/messages/en-US.json index 8e3eb7a..4c17869 100644 --- a/frontend/lib/i18n/messages/en-US.json +++ b/frontend/lib/i18n/messages/en-US.json @@ -155,7 +155,9 @@ "Could not build the ZIP file": "Could not build the ZIP file", "Could not download the converted file ({v0}). Please try again.": "Could not download the converted file ({v0}). Please try again.", "Could not download the converted file. Check your connection and retry.": "Could not download the converted file. Check your connection and retry.", + "Could not load the complete file list": "Could not load the complete file list", "Could not reach the converter. Check your connection and retry.": "Could not reach the converter. Check your connection and retry.", + "Could not refresh file limits. They will be checked before upload.": "Could not refresh file limits. They will be checked before upload.", "Could not retrieve the saved result. Check your connection and retry.": "Could not retrieve the saved result. Check your connection and retry.", "Counting page views, to see which pages people use and how they find LLMiser. Legal basis: our legitimate interest in improving the service (Art. 6(1)(f) GDPR). The counts are anonymous and need no cookies.": "Counting page views, to see which pages people use and how they find LLMiser. Legal basis: our legitimate interest in improving the service (Art. 6(1)(f) GDPR). The counts are anonymous and need no cookies.", "Created": "Created", @@ -194,6 +196,7 @@ "EXPORT AREA": "EXPORT AREA", "Empty all stored conversion sessions from local storage": "Empty all stored conversion sessions from local storage", "Empty document content": "Empty document content", + "Enable cookies for LLMiser and retry. Update the extension if you use it.": "Enable cookies for LLMiser and retry. Update the extension if you use it.", "End of list": "End of list", "Engine": "Engine", "Enter both admin keys.": "Enter both admin keys.", @@ -210,7 +213,9 @@ "FREE · NO SIGN-UP · OPEN SOURCE": "FREE · NO SIGN-UP · OPEN SOURCE", "Failed": "Failed", "Fast 1-click restore": "Fast 1-click restore", + "File allowance": "File allowance", "File details: name, type and size.": "File details: name, type and size.", + "File limits are temporarily unavailable. Please try again shortly.": "File limits are temporarily unavailable. Please try again shortly.", "File names: deleted together with the files. After that, a job record keeps only the file type, size, timings and outcome, with nothing that identifies you.": "File names: deleted together with the files. After that, a job record keeps only the file type, size, timings and outcome, with nothing that identifies you.", "File picker opened (⌘O)": "File picker opened (⌘O)", "Files": "Files", @@ -291,6 +296,7 @@ "LLMiser's source code is published under the GNU General Public License v3.0. That licence governs your use of the code. These terms govern the hosted service.": "LLMiser's source code is published under the GNU General Public License v3.0. That licence governs your use of the code. These terms govern the hosted service.", "LLMiser: Free LLM Cost Optimizer for Documents": "LLMiser: Free LLM Cost Optimizer for Documents", "Language": "Language", + "Large document: formatted preview is paused to keep editing responsive. The complete Markdown is available in Raw mode and exports.": "Large document: formatted preview is paused to keep editing responsive. The complete Markdown is available in Raw mode and exports.", "Last updated": "Last updated", "Legal": "Legal", "Limit": "Limit", @@ -298,6 +304,7 @@ "Load Sample Report": "Load Sample Report", "Load more": "Load more", "Loaded \"{v0}\" from recent sessions": "Loaded \"{v0}\" from recent sessions", + "Loaded: {v0} · Total: {v1}": "Loaded: {v0} · Total: {v1}", "Loading formatted preview…": "Loading formatted preview…", "Loading language…": "Loading language…", "Loading preview…": "Loading preview…", @@ -314,11 +321,13 @@ "Menu": "Menu", "Minimizes token density": "Minimizes token density", "Monospace source code": "Monospace source code", + "Next slot release scheduled for {time} (your local time).": "Next slot release scheduled for {time} (your local time).", "No ads, no tracking cookies, only anonymous page-view counts. Nobody trains AI models on your files.": "No ads, no tracking cookies, only anonymous page-view counts. Nobody trains AI models on your files.", "No audit entries yet.": "No audit entries yet.", "No backend instances are configured.": "No backend instances are configured.", "No converted Markdown to copy yet": "No converted Markdown to copy yet", "No document converted yet. Choose or drop a file to export.": "No document converted yet. Choose or drop a file to export.", + "No file slots remain. Your existing results are still available.": "No file slots remain. Your existing results are still available.", "No files in queue yet.": "No files in queue yet.", "No files registered.": "No files registered.", "No files.": "No files.", @@ -358,6 +367,7 @@ "Partial results": "Partial results", "Parts": "Parts", "Parts done": "Parts done", + "Pause formatted preview": "Pause formatted preview", "Pool": "Pool", "Prepare useful context before you spend tokens. LLMiser converts PDFs, Office files, images and ZIP projects to editable Markdown. Choose a profile, review the output, and send only what your AI task needs.": "Prepare useful context before you spend tokens. LLMiser converts PDFs, Office files, images and ZIP projects to editable Markdown. Choose a profile, review the output, and send only what your AI task needs.", "Preview": "Preview", @@ -402,10 +412,13 @@ "Record the exact model, tokenizer, billable input and output usage, caching and image charges.": "Record the exact model, tokenizer, billable input and output usage, caching and image charges.", "Recording that you accepted the Terms and this policy, so we can show which version you agreed to. Legal basis: Art. 6(1)(b) and (f) GDPR.": "Recording that you accepted the Terms and this policy, so we can show which version you agreed to. Legal basis: Art. 6(1)(b) and (f) GDPR.", "Refresh": "Refresh", + "Refresh file allowance": "Refresh file allowance", "Refreshes every 30 s while this tab is open.": "Refreshes every 30 s while this tab is open.", + "Reload the controller to use paginated job details.": "Reload the controller to use paginated job details.", "Remove from history": "Remove from history", "Remove {v0}": "Remove {v0}", "Removed from recent sessions": "Removed from recent sessions", + "Render full preview (may take a moment)": "Render full preview (may take a moment)", "Rendered": "Rendered", "Rendered Markdown view": "Rendered Markdown view", "Rendered with GFM": "Rendered with GFM", @@ -446,6 +459,7 @@ "Status": "Status", "Storage": "Storage", "Stored": "Stored", + "Stored files changed. Refresh and try again.": "Stored files changed. Refresh and try again.", "Stripped of metadata & extra line breaks": "Stripped of metadata & extra line breaks", "Strips metadata & extra lines": "Strips metadata & extra lines", "Supported documents and output": "Supported documents and output", @@ -473,7 +487,9 @@ "These are the original converted files. Use .md or .zip above to export your edits. Server copies are available until automatic deletion.": "These are the original converted files. Use .md or .zip above to export your edits. Server copies are available until automatic deletion.", "These items are needed for features you use, so the EU ePrivacy rules don't require a separate cookie consent for them.": "These items are needed for features you use, so the EU ePrivacy rules don't require a separate cookie consent for them.", "They're deleted automatically 48 hours after upload, with no account needed.": "They're deleted automatically 48 hours after upload, with no account needed.", + "This batch exceeds your remaining file limit. Remove files and try again.": "This batch exceeds your remaining file limit. Remove files and try again.", "This saved result is no longer available. Remove this entry and choose the original file to convert it again.": "This saved result is no longer available. Remove this entry and choose the original file to convert it again.", + "This upload reservation expired. Choose the files again.": "This upload reservation expired. Choose the files again.", "Time": "Time", "To report content you believe is illegal, send us: why you think it's illegal, the file name or job reference and the time, your name and email, and a statement that your report is accurate and made in good faith. We'll review it without undue delay and tell you what we decided. If we restrict content or access, we explain the reason to the person affected.": "To report content you believe is illegal, send us: why you think it's illegal, the file name or job reference and the time, your name and email, and a statement that your report is accurate and made in good faith. We'll review it without undue delay and tell you what we decided. If we restrict content or access, we explain the reason to the person affected.", "Toggle Recent Conversion Sessions Sidebar": "Toggle Recent Conversion Sessions Sidebar", @@ -485,6 +501,8 @@ "Too many requests. Please wait and try again.": "Too many requests. Please wait and try again.", "Total characters: {v0} (without spaces: {v1})": "Total characters: {v0} (without spaces: {v1})", "Total words counted: {v0}": "Total words counted: {v0}", + "Totals can change while a job runs. Refresh to update all sections.": "Totals can change while a job runs. Refresh to update all sections.", + "Tree and status counts show loaded records only.": "Tree and status counts show loaded records only.", "Tries": "Tries", "Turn any document into clean Markdown.": "Turn any document into clean Markdown.", "Type": "Type", @@ -492,6 +510,7 @@ "UPLOAD DOCUMENTS": "UPLOAD DOCUMENTS", "Under the GDPR you can ask us to:": "Under the GDPR you can ask us to:", "Unsupported format: .{v0}": "Unsupported format: .{v0}", + "Up to 20 files per batch. Your rolling allowance is separate; slots return individually.": "Up to 20 files per batch. Your rolling allowance is separate; slots return individually.", "Updated": "Updated", "Upload & preview": "Upload & preview", "Upload and convert any document to see live rendered Markdown alongside raw code.": "Upload and convert any document to see live rendered Markdown alongside raw code.", @@ -516,6 +535,7 @@ "What happens to uploaded files?": "What happens to uploaded files?", "What is LLMiser?": "What is LLMiser?", "When": "When", + "When guest file limits are enabled, a secure service cookie identifies your browser for the rolling file allowance. It lasts up to 90 days and is not used for advertising. We retain a keyed hash and quota event identifiers and timestamps, not the raw cookie. Quota metadata is eligible for cleanup after seven days. Active-job records remain until recovery settles. Clearing the cookie creates a new guest identity and does not delete previously uploaded files.": "When guest file limits are enabled, a secure service cookie identifies your browser for the rolling file allowance. It lasts up to 90 days and is not used for advertising. We retain a keyed hash and quota event identifiers and timestamps, not the raw cookie. Quota metadata is eligible for cleanup after seven days. Active-job records remain until recovery settles. Clearing the cookie creates a new guest identity and does not delete previously uploaded files.", "Whenever you convert a document, your last 5 conversions are automatically stored here for instant recall, side-by-side editing, and quick downloads.": "Whenever you convert a document, your last 5 conversions are automatically stored here for instant recall, side-by-side editing, and quick downloads.", "Which version of these documents you accepted, and when.": "Which version of these documents you accepted, and when.", "Why": "Why", @@ -536,6 +556,7 @@ "You keep every right to the files you upload and to the Markdown LLMiser produces from them.": "You keep every right to the files you upload and to the Markdown LLMiser produces from them.", "Your Markdown appears here": "Your Markdown appears here", "Your app language choice.": "Your app language choice.", + "Your file allowance is nearly used. Check the remaining count before uploading.": "Your file allowance is nearly used. Check the remaining count before uploading.", "Your last 5 conversions (the Markdown text and file details), so you can reopen them. Clear them any time from the Recent panel.": "Your last 5 conversions (the Markdown text and file details), so you can reopen them. Clear them any time from the Recent panel.", "Your last 5 conversions: the Markdown text when it fits, file details and a reference to the completed conversion. Clear them any time from the Recent panel.": "Your last 5 conversions: the Markdown text when it fits, file details and a reference to the completed conversion. Clear them any time from the Recent panel.", "Your light or dark theme choice.": "Your light or dark theme choice.", @@ -601,6 +622,8 @@ "upload malware or files built to attack or crash the service,": "upload malware or files built to attack or crash the service,", "with OCR pages": "with OCR pages", "words": "words", + "{reserved} reserved · {remaining} remaining": "{reserved} reserved · {remaining} remaining", + "{used} of {limit} files used in the last 24 hours": "{used} of {limit} files used in the last 24 hours", "{v0} already in queue": "{v0} already in queue", "{v0} done, {v1} failed: {v2}": "{v0} done, {v1} failed: {v2}", "{v0} job(s) updated": "{v0} job(s) updated", @@ -626,14 +649,5 @@ "✓ Markdown Copied": "✓ Markdown Copied", "✓ done": "✓ done", "📄 Terms of Service": "📄 Terms of Service", - "🔒 Privacy Policy": "🔒 Privacy Policy", - "Large document: formatted preview is paused to keep editing responsive. The complete Markdown is available in Raw mode and exports.": "Large document: formatted preview is paused to keep editing responsive. The complete Markdown is available in Raw mode and exports.", - "Render full preview (may take a moment)": "Render full preview (may take a moment)", - "Pause formatted preview": "Pause formatted preview", - "Loaded: {v0} · Total: {v1}": "Loaded: {v0} · Total: {v1}", - "Totals can change while a job runs. Refresh to update all sections.": "Totals can change while a job runs. Refresh to update all sections.", - "Tree and status counts show loaded records only.": "Tree and status counts show loaded records only.", - "Stored files changed. Refresh and try again.": "Stored files changed. Refresh and try again.", - "Could not load the complete file list": "Could not load the complete file list", - "Reload the controller to use paginated job details.": "Reload the controller to use paginated job details." + "🔒 Privacy Policy": "🔒 Privacy Policy" } diff --git a/frontend/lib/i18n/messages/es.json b/frontend/lib/i18n/messages/es.json index 196b9e3..e97d388 100644 --- a/frontend/lib/i18n/messages/es.json +++ b/frontend/lib/i18n/messages/es.json @@ -155,7 +155,9 @@ "Could not build the ZIP file": "No se pudo crear el archivo ZIP", "Could not download the converted file ({v0}). Please try again.": "No se pudo descargar el archivo convertido ({v0}). Inténtalo de nuevo.", "Could not download the converted file. Check your connection and retry.": "No se pudo descargar el archivo convertido. Comprueba la conexión y reintenta.", + "Could not load the complete file list": "No se pudo cargar la lista completa de archivos", "Could not reach the converter. Check your connection and retry.": "No se pudo conectar al conversor. Comprueba la conexión y reintenta.", + "Could not refresh file limits. They will be checked before upload.": "No se pudo actualizar el cupo. Se comprobará antes de subir archivos.", "Could not retrieve the saved result. Check your connection and retry.": "No se pudo recuperar el resultado guardado. Comprueba la conexión y reintenta.", "Counting page views, to see which pages people use and how they find LLMiser. Legal basis: our legitimate interest in improving the service (Art. 6(1)(f) GDPR). The counts are anonymous and need no cookies.": "Contar visitas para conocer qué páginas se usan y cómo se encuentra LLMiser. Base jurídica: interés legítimo en mejorar el servicio (art. 6.1.f RGPD). Los recuentos son anónimos y no necesitan cookies.", "Created": "Creado", @@ -194,6 +196,7 @@ "EXPORT AREA": "ÁREA DE EXPORTACIÓN", "Empty all stored conversion sessions from local storage": "Eliminar todas las conversiones del almacenamiento local", "Empty document content": "Contenido del documento vacío", + "Enable cookies for LLMiser and retry. Update the extension if you use it.": "Activa las cookies de LLMiser y reinténtalo. Actualiza la extensión si la usas.", "End of list": "Fin de la lista", "Engine": "Motor", "Enter both admin keys.": "Introduce ambas claves de administración.", @@ -210,7 +213,9 @@ "FREE · NO SIGN-UP · OPEN SOURCE": "GRATIS · SIN REGISTRO · CÓDIGO ABIERTO", "Failed": "Fallido", "Fast 1-click restore": "Restauración con un clic", + "File allowance": "Cupo de archivos", "File details: name, type and size.": "Detalles del archivo: nombre, tipo y tamaño.", + "File limits are temporarily unavailable. Please try again shortly.": "El cupo no está disponible temporalmente. Reinténtalo en breve.", "File names: deleted together with the files. After that, a job record keeps only the file type, size, timings and outcome, with nothing that identifies you.": "Los nombres se borran junto con los archivos. Después, el registro solo conserva tipo, tamaño, tiempos y resultado, sin datos que te identifiquen.", "File picker opened (⌘O)": "Selector de archivos abierto (⌘O)", "Files": "Archivos", @@ -291,6 +296,7 @@ "LLMiser's source code is published under the GNU General Public License v3.0. That licence governs your use of the code. These terms govern the hosted service.": "El código de LLMiser se publica bajo GNU GPL v3.0. Esa licencia rige el uso del código; estos términos, el servicio alojado.", "LLMiser: Free LLM Cost Optimizer for Documents": "LLMiser: optimizador gratuito de costes de LLM para documentos", "Language": "Idioma", + "Large document: formatted preview is paused to keep editing responsive. The complete Markdown is available in Raw mode and exports.": "Documento grande: la vista previa con formato está en pausa para mantener la edición fluida. El Markdown completo está disponible en el modo Código y en las exportaciones.", "Last updated": "Última actualización", "Legal": "Información legal", "Limit": "Límite", @@ -298,6 +304,7 @@ "Load Sample Report": "Cargar informe de ejemplo", "Load more": "Cargar más", "Loaded \"{v0}\" from recent sessions": "Se cargó «{v0}» del historial", + "Loaded: {v0} · Total: {v1}": "Cargados: {v0} · Total: {v1}", "Loading formatted preview…": "Cargando vista previa con formato…", "Loading language…": "Cargando idioma…", "Loading preview…": "Cargando vista previa…", @@ -314,11 +321,13 @@ "Menu": "Menú", "Minimizes token density": "Reduce la cantidad de tokens", "Monospace source code": "Código fuente monoespaciado", + "Next slot release scheduled for {time} (your local time).": "Próxima liberación prevista: {time} (hora local).", "No ads, no tracking cookies, only anonymous page-view counts. Nobody trains AI models on your files.": "Sin anuncios ni cookies de seguimiento; solo recuentos anónimos de visitas. Nadie entrena modelos de IA con tus archivos.", "No audit entries yet.": "Aún no hay entradas de auditoría.", "No backend instances are configured.": "No hay servidores configurados.", "No converted Markdown to copy yet": "Aún no hay Markdown convertido para copiar", "No document converted yet. Choose or drop a file to export.": "Aún no has convertido documentos. Elige o arrastra un archivo para exportarlo.", + "No file slots remain. Your existing results are still available.": "No quedan plazas. Tus resultados anteriores siguen disponibles.", "No files in queue yet.": "Aún no hay archivos en la cola.", "No files registered.": "No hay archivos registrados.", "No files.": "No hay archivos.", @@ -358,6 +367,7 @@ "Partial results": "Resultados parciales", "Parts": "Partes", "Parts done": "Partes completadas", + "Pause formatted preview": "Pausar la vista previa con formato", "Pool": "Grupo", "Prepare useful context before you spend tokens. LLMiser converts PDFs, Office files, images and ZIP projects to editable Markdown. Choose a profile, review the output, and send only what your AI task needs.": "Prepara contexto útil antes de gastar tokens. LLMiser convierte PDF, archivos Office, imágenes y proyectos ZIP en Markdown editable. Elige un perfil, revisa el resultado y envía solo lo que necesita tu tarea de IA.", "Preview": "Vista previa", @@ -402,10 +412,13 @@ "Record the exact model, tokenizer, billable input and output usage, caching and image charges.": "Registra el modelo, tokenizador, uso facturable de entrada y salida, caché y cargos por imágenes.", "Recording that you accepted the Terms and this policy, so we can show which version you agreed to. Legal basis: Art. 6(1)(b) and (f) GDPR.": "Registrar la aceptación de los términos y esta política y la versión aceptada. Base jurídica: art. 6.1.b y f RGPD.", "Refresh": "Actualizar", + "Refresh file allowance": "Actualizar cupo", "Refreshes every 30 s while this tab is open.": "Se actualiza cada 30 s mientras esta pestaña esté abierta.", + "Reload the controller to use paginated job details.": "Vuelve a cargar el controlador para ver los detalles del trabajo por páginas.", "Remove from history": "Quitar del historial", "Remove {v0}": "Quitar {v0}", "Removed from recent sessions": "Eliminado del historial", + "Render full preview (may take a moment)": "Mostrar la vista previa completa (puede tardar un momento)", "Rendered": "Renderizado", "Rendered Markdown view": "Vista de Markdown renderizado", "Rendered with GFM": "Renderizado con GFM", @@ -446,6 +459,7 @@ "Status": "Estado", "Storage": "Almacenamiento", "Stored": "Guardado", + "Stored files changed. Refresh and try again.": "Los archivos almacenados han cambiado. Actualiza e inténtalo de nuevo.", "Stripped of metadata & extra line breaks": "Sin metadatos ni saltos de línea adicionales", "Strips metadata & extra lines": "Elimina metadatos y líneas adicionales", "Supported documents and output": "Documentos admitidos y resultados", @@ -473,7 +487,9 @@ "These are the original converted files. Use .md or .zip above to export your edits. Server copies are available until automatic deletion.": "Estos son los archivos convertidos originales. Usa .md o .zip arriba para exportar tus cambios. Las copias del servidor están disponibles hasta su eliminación automática.", "These items are needed for features you use, so the EU ePrivacy rules don't require a separate cookie consent for them.": "Estos datos son necesarios para las funciones que utilizas; las normas ePrivacy de la UE no exigen consentimiento de cookies separado para ellos.", "They're deleted automatically 48 hours after upload, with no account needed.": "Se eliminan automáticamente 48 horas después de subirlos. No necesitas cuenta.", + "This batch exceeds your remaining file limit. Remove files and try again.": "Este lote supera tu cupo restante. Quita archivos e inténtalo de nuevo.", "This saved result is no longer available. Remove this entry and choose the original file to convert it again.": "Este resultado guardado ya no está disponible. Elimina esta entrada y elige el archivo original para volver a convertirlo.", + "This upload reservation expired. Choose the files again.": "La reserva de subida ha caducado. Selecciona los archivos de nuevo.", "Time": "Tiempo", "To report content you believe is illegal, send us: why you think it's illegal, the file name or job reference and the time, your name and email, and a statement that your report is accurate and made in good faith. We'll review it without undue delay and tell you what we decided. If we restrict content or access, we explain the reason to the person affected.": "Para denunciar, indica por qué crees que es ilegal, archivo o referencia del trabajo y hora, tu nombre y correo, y declara que la información es exacta y de buena fe. Revisaremos sin demora indebida y comunicaremos la decisión. Si restringimos contenido o acceso, explicaremos el motivo a la persona afectada.", "Toggle Recent Conversion Sessions Sidebar": "Alternar la barra de conversiones recientes", @@ -485,6 +501,8 @@ "Too many requests. Please wait and try again.": "Demasiadas solicitudes. Espera y vuelve a intentarlo.", "Total characters: {v0} (without spaces: {v1})": "Caracteres totales: {v0} (sin espacios: {v1})", "Total words counted: {v0}": "Total de palabras: {v0}", + "Totals can change while a job runs. Refresh to update all sections.": "Los totales pueden cambiar mientras se ejecuta un trabajo. Actualiza para renovar todas las secciones.", + "Tree and status counts show loaded records only.": "El árbol y los recuentos por estado solo muestran los registros cargados.", "Tries": "Intentos", "Turn any document into clean Markdown.": "Convierte documentos en Markdown limpio.", "Type": "Tipo", @@ -492,6 +510,7 @@ "UPLOAD DOCUMENTS": "SUBIR DOCUMENTOS", "Under the GDPR you can ask us to:": "Conforme al RGPD puedes pedirnos:", "Unsupported format: .{v0}": "Formato no compatible: .{v0}", + "Up to 20 files per batch. Your rolling allowance is separate; slots return individually.": "Hasta 20 archivos por lote. El cupo móvil es independiente; las plazas se recuperan una a una.", "Updated": "Actualizado", "Upload & preview": "Subida y vista previa", "Upload and convert any document to see live rendered Markdown alongside raw code.": "Sube y convierte un documento para ver Markdown renderizado junto al código fuente.", @@ -516,6 +535,7 @@ "What happens to uploaded files?": "¿Qué ocurre con los archivos subidos?", "What is LLMiser?": "¿Qué es LLMiser?", "When": "Cuándo", + "When guest file limits are enabled, a secure service cookie identifies your browser for the rolling file allowance. It lasts up to 90 days and is not used for advertising. We retain a keyed hash and quota event identifiers and timestamps, not the raw cookie. Quota metadata is eligible for cleanup after seven days. Active-job records remain until recovery settles. Clearing the cookie creates a new guest identity and does not delete previously uploaded files.": "Cuando se activan los límites para invitados, una cookie segura identifica tu navegador para gestionar el cupo móvil. Dura hasta 90 días y no se usa para publicidad. Guardamos un hash con clave, identificadores de eventos del cupo y marcas de tiempo, no la cookie original. Los metadatos del cupo pueden eliminarse después de siete días. Los registros de trabajos activos se conservan hasta que termine la recuperación. Borrar la cookie crea una nueva identidad de invitado y no elimina los archivos ya subidos.", "Whenever you convert a document, your last 5 conversions are automatically stored here for instant recall, side-by-side editing, and quick downloads.": "Tus últimas 5 conversiones se guardan aquí automáticamente para reabrirlas, editarlas en paralelo y descargarlas rápidamente.", "Which version of these documents you accepted, and when.": "Qué versión de estos documentos aceptaste y cuándo.", "Why": "Ventajas", @@ -536,6 +556,7 @@ "You keep every right to the files you upload and to the Markdown LLMiser produces from them.": "Conservas todos los derechos sobre tus archivos y el Markdown generado a partir de ellos.", "Your Markdown appears here": "Tu Markdown aparecerá aquí", "Your app language choice.": "Tu idioma de la aplicación.", + "Your file allowance is nearly used. Check the remaining count before uploading.": "Tu cupo está casi agotado. Comprueba cuántos archivos quedan antes de subirlos.", "Your last 5 conversions (the Markdown text and file details), so you can reopen them. Clear them any time from the Recent panel.": "Tus últimas 5 conversiones, con Markdown y detalles del archivo, para reabrirlas. Puedes borrarlas desde el panel de recientes.", "Your last 5 conversions: the Markdown text when it fits, file details and a reference to the completed conversion. Clear them any time from the Recent panel.": "Tus últimas 5 conversiones: el texto Markdown cuando cabe, los detalles del archivo y una referencia a la conversión completada. Puedes borrarlas en cualquier momento desde el panel Recientes.", "Your light or dark theme choice.": "Tu elección de tema claro u oscuro.", @@ -601,6 +622,8 @@ "upload malware or files built to attack or crash the service,": "subir malware o archivos diseñados para atacar o interrumpir el servicio,", "with OCR pages": "con páginas OCR", "words": "palabras", + "{reserved} reserved · {remaining} remaining": "{reserved} reservados · {remaining} disponibles", + "{used} of {limit} files used in the last 24 hours": "{used} de {limit} archivos usados en las últimas 24 horas", "{v0} already in queue": "{v0} ya están en la cola", "{v0} done, {v1} failed: {v2}": "{v0} completados, {v1} fallidos: {v2}", "{v0} job(s) updated": "{v0} trabajos actualizados", @@ -626,14 +649,5 @@ "✓ Markdown Copied": "✓ Markdown copiado", "✓ done": "✓ listo", "📄 Terms of Service": "📄 Términos de servicio", - "🔒 Privacy Policy": "🔒 Política de privacidad", - "Large document: formatted preview is paused to keep editing responsive. The complete Markdown is available in Raw mode and exports.": "Documento grande: la vista previa con formato está en pausa para mantener la edición fluida. El Markdown completo está disponible en el modo Código y en las exportaciones.", - "Render full preview (may take a moment)": "Mostrar la vista previa completa (puede tardar un momento)", - "Pause formatted preview": "Pausar la vista previa con formato", - "Loaded: {v0} · Total: {v1}": "Cargados: {v0} · Total: {v1}", - "Totals can change while a job runs. Refresh to update all sections.": "Los totales pueden cambiar mientras se ejecuta un trabajo. Actualiza para renovar todas las secciones.", - "Tree and status counts show loaded records only.": "El árbol y los recuentos por estado solo muestran los registros cargados.", - "Stored files changed. Refresh and try again.": "Los archivos almacenados han cambiado. Actualiza e inténtalo de nuevo.", - "Could not load the complete file list": "No se pudo cargar la lista completa de archivos", - "Reload the controller to use paginated job details.": "Vuelve a cargar el controlador para ver los detalles del trabajo por páginas." + "🔒 Privacy Policy": "🔒 Política de privacidad" } diff --git a/frontend/lib/i18n/messages/ja.json b/frontend/lib/i18n/messages/ja.json index ea5c41f..f2afae9 100644 --- a/frontend/lib/i18n/messages/ja.json +++ b/frontend/lib/i18n/messages/ja.json @@ -155,7 +155,9 @@ "Could not build the ZIP file": "ZIPファイルを作成できませんでした", "Could not download the converted file ({v0}). Please try again.": "変換済みファイルをダウンロードできませんでした({v0})。再試行してください。", "Could not download the converted file. Check your connection and retry.": "変換済みファイルをダウンロードできませんでした。接続を確認して再試行してください。", + "Could not load the complete file list": "完全なファイル一覧を読み込めませんでした", "Could not reach the converter. Check your connection and retry.": "変換サービスに接続できません。接続を確認して再試行してください。", + "Could not refresh file limits. They will be checked before upload.": "ファイル枠を更新できませんでした。アップロード前に再確認します。", "Could not retrieve the saved result. Check your connection and retry.": "保存された結果を取得できませんでした。接続を確認して再試行してください。", "Counting page views, to see which pages people use and how they find LLMiser. Legal basis: our legitimate interest in improving the service (Art. 6(1)(f) GDPR). The counts are anonymous and need no cookies.": "どのページが利用され、どのようにLLMiserに到達するかを把握するための閲覧数集計。法的根拠:サービス改善の正当な利益(GDPR第6条1項(f))。統計は匿名でCookieを必要としません。", "Created": "作成日時", @@ -194,6 +196,7 @@ "EXPORT AREA": "エクスポート", "Empty all stored conversion sessions from local storage": "ローカルストレージの変換履歴をすべて削除", "Empty document content": "文書の内容が空です", + "Enable cookies for LLMiser and retry. Update the extension if you use it.": "LLMiserのCookieを有効にして再試行してください。拡張機能をご利用の場合は更新してください。", "End of list": "リストの末尾", "Engine": "エンジン", "Enter both admin keys.": "2つの管理者キーを入力してください。", @@ -210,7 +213,9 @@ "FREE · NO SIGN-UP · OPEN SOURCE": "無料・登録不要・オープンソース", "Failed": "失敗", "Fast 1-click restore": "ワンクリックで復元", + "File allowance": "ファイル利用枠", "File details: name, type and size.": "ファイル情報:名前、種類、サイズ。", + "File limits are temporarily unavailable. Please try again shortly.": "ファイル枠を一時的に確認できません。しばらくしてから再試行してください。", "File names: deleted together with the files. After that, a job record keeps only the file type, size, timings and outcome, with nothing that identifies you.": "ファイル名はファイルと一緒に削除されます。その後のジョブ記録には、種類、サイズ、処理時間、結果のみを残し、個人を識別できる情報は含めません。", "File picker opened (⌘O)": "ファイル選択を開きました(⌘O)", "Files": "ファイル", @@ -291,6 +296,7 @@ "LLMiser's source code is published under the GNU General Public License v3.0. That licence governs your use of the code. These terms govern the hosted service.": "LLMiserのソースコードはGNU General Public License v3.0で公開されています。コードの利用には同ライセンス、ホストされたサービスには本規約が適用されます。", "LLMiser: Free LLM Cost Optimizer for Documents": "LLMiser:文書向けの無料LLMコスト最適化ツール", "Language": "言語", + "Large document: formatted preview is paused to keep editing responsive. The complete Markdown is available in Raw mode and exports.": "大きなドキュメントのため、快適に編集できるよう整形プレビューを一時停止しています。Markdown 全文はソースモードとエクスポートで利用できます。", "Last updated": "最終更新", "Legal": "法的情報", "Limit": "上限", @@ -298,6 +304,7 @@ "Load Sample Report": "サンプルレポートを開く", "Load more": "さらに読み込む", "Loaded \"{v0}\" from recent sessions": "履歴から「{v0}」を読み込みました", + "Loaded: {v0} · Total: {v1}": "読み込み済み: {v0} · 合計: {v1}", "Loading formatted preview…": "書式付きプレビューを読み込み中…", "Loading language…": "言語を読み込み中…", "Loading preview…": "プレビューを読み込み中…", @@ -314,11 +321,13 @@ "Menu": "メニュー", "Minimizes token density": "トークン数を抑制", "Monospace source code": "等幅フォントのソースコード", + "Next slot release scheduled for {time} (your local time).": "次の枠の解放予定:{time}(現地時間)。", "No ads, no tracking cookies, only anonymous page-view counts. Nobody trains AI models on your files.": "広告や追跡Cookieはなく、匿名の閲覧数のみ集計します。ファイルはAIモデルの学習に使用されません。", "No audit entries yet.": "監査ログはまだありません。", "No backend instances are configured.": "バックエンドのインスタンスが設定されていません。", "No converted Markdown to copy yet": "コピーできる変換済みMarkdownはまだありません", "No document converted yet. Choose or drop a file to export.": "まだ文書を変換していません。ファイルを選択またはドロップしてください。", + "No file slots remain. Your existing results are still available.": "ファイル枠がありません。既存の結果は引き続き利用できます。", "No files in queue yet.": "キューにファイルはありません。", "No files registered.": "登録されたファイルはありません。", "No files.": "ファイルはありません。", @@ -358,6 +367,7 @@ "Partial results": "部分的な結果", "Parts": "パート", "Parts done": "完了パート数", + "Pause formatted preview": "整形プレビューを一時停止", "Pool": "プール", "Prepare useful context before you spend tokens. LLMiser converts PDFs, Office files, images and ZIP projects to editable Markdown. Choose a profile, review the output, and send only what your AI task needs.": "トークンを使う前に、必要なコンテキストを整えましょう。LLMiserはPDF、Office文書、画像、ZIPプロジェクトを編集可能なMarkdownに変換します。プロファイルを選び、結果を確認して、AIの作業に必要な内容だけを送れます。", "Preview": "プレビュー", @@ -402,10 +412,13 @@ "Record the exact model, tokenizer, billable input and output usage, caching and image charges.": "モデル、トークナイザー、課金対象の入出力量、キャッシュや画像の料金を記録します。", "Recording that you accepted the Terms and this policy, so we can show which version you agreed to. Legal basis: Art. 6(1)(b) and (f) GDPR.": "利用規約と本ポリシーへの同意、および同意した版を記録するため。法的根拠:GDPR第6条1項(b)および(f)。", "Refresh": "更新", + "Refresh file allowance": "ファイル枠を更新", "Refreshes every 30 s while this tab is open.": "このタブが開いている間、30秒ごとに更新されます。", + "Reload the controller to use paginated job details.": "ジョブの詳細をページごとに表示するには、コントローラーを再読み込みしてください。", "Remove from history": "履歴から削除", "Remove {v0}": "{v0}を削除", "Removed from recent sessions": "履歴から削除しました", + "Render full preview (may take a moment)": "全文のプレビューを表示(時間がかかる場合があります)", "Rendered": "表示", "Rendered Markdown view": "Markdownの表示", "Rendered with GFM": "GFMで表示", @@ -446,6 +459,7 @@ "Status": "状態", "Storage": "ストレージ", "Stored": "保存済み", + "Stored files changed. Refresh and try again.": "保存済みファイルが変更されました。更新してもう一度お試しください。", "Stripped of metadata & extra line breaks": "メタデータと余分な改行を削除", "Strips metadata & extra lines": "メタデータと余分な行を削除", "Supported documents and output": "対応する文書と出力", @@ -473,7 +487,9 @@ "These are the original converted files. Use .md or .zip above to export your edits. Server copies are available until automatic deletion.": "これらは変換直後の元のファイルです。編集内容の書き出しには上の.mdまたは.zipを使ってください。サーバー上のコピーは自動削除まで利用できます。", "These items are needed for features you use, so the EU ePrivacy rules don't require a separate cookie consent for them.": "これらは利用する機能に必要な情報のため、EUのePrivacy規則に基づく別個のCookie同意は不要です。", "They're deleted automatically 48 hours after upload, with no account needed.": "アップロードから48時間後に自動削除されます。アカウントは不要です。", + "This batch exceeds your remaining file limit. Remove files and try again.": "このバッチは残り枠を超えています。ファイルを減らして再試行してください。", "This saved result is no longer available. Remove this entry and choose the original file to convert it again.": "この保存結果は利用できなくなりました。項目を削除し、元のファイルを選んで再変換してください。", + "This upload reservation expired. Choose the files again.": "アップロード予約の期限が切れました。ファイルを選び直してください。", "Time": "時間", "To report content you believe is illegal, send us: why you think it's illegal, the file name or job reference and the time, your name and email, and a statement that your report is accurate and made in good faith. We'll review it without undue delay and tell you what we decided. If we restrict content or access, we explain the reason to the person affected.": "違法と思われる内容の報告には、違法と考える理由、ファイル名またはジョブ番号と時刻、ご自身の氏名・メールアドレス、正確かつ誠実な報告である旨をお送りください。不当に遅滞することなく確認し、判断をお知らせします。内容やアクセスを制限する場合は、対象者に理由を説明します。", "Toggle Recent Conversion Sessions Sidebar": "変換履歴サイドバーを切り替え", @@ -485,6 +501,8 @@ "Too many requests. Please wait and try again.": "リクエストが多すぎます。しばらく待って再試行してください。", "Total characters: {v0} (without spaces: {v1})": "文字数合計:{v0}(空白を除く:{v1})", "Total words counted: {v0}": "単語数合計:{v0}", + "Totals can change while a job runs. Refresh to update all sections.": "ジョブの実行中は合計が変わることがあります。更新してすべてのセクションを最新にしてください。", + "Tree and status counts show loaded records only.": "ツリーとステータス件数には読み込み済みのレコードのみが表示されます。", "Tries": "試行回数", "Turn any document into clean Markdown.": "文書を整ったMarkdownに変換。", "Type": "種類", @@ -492,6 +510,7 @@ "UPLOAD DOCUMENTS": "文書をアップロード", "Under the GDPR you can ask us to:": "GDPRに基づき、次のことを請求できます:", "Unsupported format: .{v0}": "未対応の形式:.{v0}", + "Up to 20 files per batch. Your rolling allowance is separate; slots return individually.": "1回につき最大20件。直近24時間の枠は別に適用され、1件ずつ回復します。", "Updated": "更新", "Upload & preview": "アップロードとプレビュー", "Upload and convert any document to see live rendered Markdown alongside raw code.": "文書をアップロードして変換すると、Markdownの表示とソースを並べて確認できます。", @@ -516,6 +535,7 @@ "What happens to uploaded files?": "アップロードしたファイルはどう扱われますか?", "What is LLMiser?": "LLMiserとは?", "When": "日時", + "When guest file limits are enabled, a secure service cookie identifies your browser for the rolling file allowance. It lasts up to 90 days and is not used for advertising. We retain a keyed hash and quota event identifiers and timestamps, not the raw cookie. Quota metadata is eligible for cleanup after seven days. Active-job records remain until recovery settles. Clearing the cookie creates a new guest identity and does not delete previously uploaded files.": "ゲストのファイル制限が有効な場合、安全なサービスCookieでブラウザーを識別し、直近の利用枠を管理します。有効期間は最大90日で、広告には使用しません。サーバーにはCookie自体ではなく、鍵付きハッシュ、利用枠イベントの識別子と日時を保存します。利用枠のメタデータは7日後から削除対象になります。処理中のジョブの記録は復旧処理が完了するまで保持します。Cookieを削除すると新しいゲスト識別子になりますが、アップロード済みのファイルは削除されません。", "Whenever you convert a document, your last 5 conversions are automatically stored here for instant recall, side-by-side editing, and quick downloads.": "変換すると直近5件が自動保存されます。すぐに再表示し、並べて編集したりダウンロードしたりできます。", "Which version of these documents you accepted, and when.": "同意した文書のバージョンと同意日時。", "Why": "特長", @@ -536,6 +556,7 @@ "You keep every right to the files you upload and to the Markdown LLMiser produces from them.": "アップロードしたファイルと、そこから生成したMarkdownのすべての権利は利用者に帰属します。", "Your Markdown appears here": "ここにMarkdownが表示されます", "Your app language choice.": "アプリの表示言語の選択。", + "Your file allowance is nearly used. Check the remaining count before uploading.": "ファイル枠が残り少なくなっています。アップロード前に残数を確認してください。", "Your last 5 conversions (the Markdown text and file details), so you can reopen them. Clear them any time from the Recent panel.": "再度開けるよう、直近5件の変換(Markdown本文とファイル情報)。履歴パネルからいつでも削除できます。", "Your last 5 conversions: the Markdown text when it fits, file details and a reference to the completed conversion. Clear them any time from the Recent panel.": "直近5件の変換:容量に収まる場合のMarkdown本文、ファイル情報、完了した変換の参照情報。履歴パネルからいつでも消去できます。", "Your light or dark theme choice.": "ライトまたはダークテーマの選択。", @@ -601,6 +622,8 @@ "upload malware or files built to attack or crash the service,": "マルウェアや、サービスへの攻撃・障害を目的とするファイルのアップロード、", "with OCR pages": "OCRページを含む", "words": "単語", + "{reserved} reserved · {remaining} remaining": "{reserved}件を予約済み · 残り{remaining}件", + "{used} of {limit} files used in the last 24 hours": "過去24時間に{limit}件中{used}件を使用", "{v0} already in queue": "{v0}はすでにキューにあります", "{v0} done, {v1} failed: {v2}": "{v0}件完了、{v1}件失敗:{v2}", "{v0} job(s) updated": "{v0}件のジョブを更新", @@ -626,14 +649,5 @@ "✓ Markdown Copied": "✓ Markdownコピー済み", "✓ done": "✓ 完了", "📄 Terms of Service": "📄 利用規約", - "🔒 Privacy Policy": "🔒 プライバシーポリシー", - "Large document: formatted preview is paused to keep editing responsive. The complete Markdown is available in Raw mode and exports.": "大きなドキュメントのため、快適に編集できるよう整形プレビューを一時停止しています。Markdown 全文はソースモードとエクスポートで利用できます。", - "Render full preview (may take a moment)": "全文のプレビューを表示(時間がかかる場合があります)", - "Pause formatted preview": "整形プレビューを一時停止", - "Loaded: {v0} · Total: {v1}": "読み込み済み: {v0} · 合計: {v1}", - "Totals can change while a job runs. Refresh to update all sections.": "ジョブの実行中は合計が変わることがあります。更新してすべてのセクションを最新にしてください。", - "Tree and status counts show loaded records only.": "ツリーとステータス件数には読み込み済みのレコードのみが表示されます。", - "Stored files changed. Refresh and try again.": "保存済みファイルが変更されました。更新してもう一度お試しください。", - "Could not load the complete file list": "完全なファイル一覧を読み込めませんでした", - "Reload the controller to use paginated job details.": "ジョブの詳細をページごとに表示するには、コントローラーを再読み込みしてください。" + "🔒 Privacy Policy": "🔒 プライバシーポリシー" } diff --git a/frontend/lib/i18n/messages/ru.json b/frontend/lib/i18n/messages/ru.json index 8d337a6..74548f1 100644 --- a/frontend/lib/i18n/messages/ru.json +++ b/frontend/lib/i18n/messages/ru.json @@ -155,7 +155,9 @@ "Could not build the ZIP file": "Не удалось создать ZIP-файл", "Could not download the converted file ({v0}). Please try again.": "Не удалось скачать преобразованный файл ({v0}). Повторите попытку.", "Could not download the converted file. Check your connection and retry.": "Не удалось скачать преобразованный файл. Проверьте соединение и повторите попытку.", + "Could not load the complete file list": "Не удалось загрузить полный список файлов", "Could not reach the converter. Check your connection and retry.": "Не удалось связаться с конвертером. Проверьте соединение и повторите.", + "Could not refresh file limits. They will be checked before upload.": "Не удалось обновить лимит. Он будет проверен перед загрузкой.", "Could not retrieve the saved result. Check your connection and retry.": "Не удалось получить сохранённый результат. Проверьте соединение и повторите попытку.", "Counting page views, to see which pages people use and how they find LLMiser. Legal basis: our legitimate interest in improving the service (Art. 6(1)(f) GDPR). The counts are anonymous and need no cookies.": "Подсчёт просмотров для понимания использования страниц и источников перехода. Основание: законный интерес в улучшении сервиса (ст. 6(1)(f) GDPR). Подсчёты анонимны и не требуют cookies.", "Created": "Создано", @@ -194,6 +196,7 @@ "EXPORT AREA": "ЭКСПОРТ", "Empty all stored conversion sessions from local storage": "Удалить все преобразования из локального хранилища", "Empty document content": "Документ пуст", + "Enable cookies for LLMiser and retry. Update the extension if you use it.": "Разрешите cookie для LLMiser и повторите попытку. Если используете расширение, обновите его.", "End of list": "Конец списка", "Engine": "Движок", "Enter both admin keys.": "Введите оба ключа администратора.", @@ -210,7 +213,9 @@ "FREE · NO SIGN-UP · OPEN SOURCE": "БЕСПЛАТНО · БЕЗ РЕГИСТРАЦИИ · ОТКРЫТЫЙ КОД", "Failed": "Ошибка", "Fast 1-click restore": "Восстановление в один клик", + "File allowance": "Лимит файлов", "File details: name, type and size.": "Сведения о файле: имя, тип и размер.", + "File limits are temporarily unavailable. Please try again shortly.": "Лимиты временно недоступны. Повторите попытку позже.", "File names: deleted together with the files. After that, a job record keeps only the file type, size, timings and outcome, with nothing that identifies you.": "Имена удаляются вместе с файлами. Затем в записи задания остаются только тип, размер, время и результат без данных, позволяющих установить вашу личность.", "File picker opened (⌘O)": "Открыт выбор файлов (⌘O)", "Files": "Файлы", @@ -291,6 +296,7 @@ "LLMiser's source code is published under the GNU General Public License v3.0. That licence governs your use of the code. These terms govern the hosted service.": "Исходный код LLMiser опубликован под GNU GPL v3.0. Лицензия регулирует использование кода, эти условия — размещённого сервиса.", "LLMiser: Free LLM Cost Optimizer for Documents": "LLMiser: бесплатная оптимизация расходов на LLM для документов", "Language": "Язык", + "Large document: formatted preview is paused to keep editing responsive. The complete Markdown is available in Raw mode and exports.": "Большой документ: предпросмотр с форматированием приостановлен, чтобы редактирование оставалось отзывчивым. Полный Markdown доступен в режиме «Исходный» и при экспорте.", "Last updated": "Последнее обновление", "Legal": "Правовая информация", "Limit": "Лимит", @@ -298,6 +304,7 @@ "Load Sample Report": "Загрузить пример отчёта", "Load more": "Загрузить ещё", "Loaded \"{v0}\" from recent sessions": "Из истории загружен файл «{v0}»", + "Loaded: {v0} · Total: {v1}": "Загружено: {v0} · Всего: {v1}", "Loading formatted preview…": "Загрузка форматированного просмотра…", "Loading language…": "Загрузка языка…", "Loading preview…": "Загрузка предпросмотра…", @@ -314,11 +321,13 @@ "Menu": "Меню", "Minimizes token density": "Уменьшает количество токенов", "Monospace source code": "Моноширинный исходный код", + "Next slot release scheduled for {time} (your local time).": "Следующее освобождение места запланировано на {time} (местное время).", "No ads, no tracking cookies, only anonymous page-view counts. Nobody trains AI models on your files.": "Без рекламы и отслеживающих cookies; только анонимная статистика просмотров. Ваши файлы не используются для обучения ИИ.", "No audit entries yet.": "Записей аудита пока нет.", "No backend instances are configured.": "Серверные экземпляры не настроены.", "No converted Markdown to copy yet": "Преобразованного Markdown для копирования пока нет", "No document converted yet. Choose or drop a file to export.": "Документы ещё не преобразованы. Выберите или перетащите файл для экспорта.", + "No file slots remain. Your existing results are still available.": "Лимит исчерпан. Предыдущие результаты по-прежнему доступны.", "No files in queue yet.": "В очереди пока нет файлов.", "No files registered.": "Зарегистрированных файлов нет.", "No files.": "Файлов нет.", @@ -358,6 +367,7 @@ "Partial results": "Частичные результаты", "Parts": "Части", "Parts done": "Части завершены", + "Pause formatted preview": "Приостановить предпросмотр с форматированием", "Pool": "Пул", "Prepare useful context before you spend tokens. LLMiser converts PDFs, Office files, images and ZIP projects to editable Markdown. Choose a profile, review the output, and send only what your AI task needs.": "Подготовьте полезный контекст до расходования токенов. LLMiser преобразует PDF, файлы Office, изображения и ZIP-проекты в редактируемый Markdown. Выберите профиль, проверьте результат и отправьте только то, что нужно вашей задаче ИИ.", "Preview": "Предпросмотр", @@ -402,10 +412,13 @@ "Record the exact model, tokenizer, billable input and output usage, caching and image charges.": "Запишите модель, токенизатор, оплачиваемые вход и выход, использование кеша и стоимость изображений.", "Recording that you accepted the Terms and this policy, so we can show which version you agreed to. Legal basis: Art. 6(1)(b) and (f) GDPR.": "Учёт согласия с условиями и политикой, чтобы показать принятую версию. Основание: ст. 6(1)(b) и (f) GDPR.", "Refresh": "Обновить", + "Refresh file allowance": "Обновить лимит", "Refreshes every 30 s while this tab is open.": "Обновляется каждые 30 с, пока вкладка открыта.", + "Reload the controller to use paginated job details.": "Перезагрузите панель управления для постраничного просмотра задания.", "Remove from history": "Удалить из истории", "Remove {v0}": "Удалить {v0}", "Removed from recent sessions": "Удалено из истории", + "Render full preview (may take a moment)": "Показать полный предпросмотр (может занять некоторое время)", "Rendered": "Форматированный", "Rendered Markdown view": "Форматированный Markdown", "Rendered with GFM": "Отображено с GFM", @@ -446,6 +459,7 @@ "Status": "Статус", "Storage": "Хранилище", "Stored": "Сохранено", + "Stored files changed. Refresh and try again.": "Сохранённые файлы изменились. Обновите страницу и повторите попытку.", "Stripped of metadata & extra line breaks": "Без метаданных и лишних переносов строк", "Strips metadata & extra lines": "Удаляет метаданные и лишние строки", "Supported documents and output": "Поддерживаемые документы и результаты", @@ -473,7 +487,9 @@ "These are the original converted files. Use .md or .zip above to export your edits. Server copies are available until automatic deletion.": "Это исходные файлы после преобразования. Для экспорта правок используйте .md или .zip выше. Серверные копии доступны до автоматического удаления.", "These items are needed for features you use, so the EU ePrivacy rules don't require a separate cookie consent for them.": "Эти данные необходимы для используемых функций, поэтому правила ePrivacy ЕС не требуют отдельного согласия на cookies для них.", "They're deleted automatically 48 hours after upload, with no account needed.": "Они автоматически удаляются через 48 часов после загрузки. Аккаунт не нужен.", + "This batch exceeds your remaining file limit. Remove files and try again.": "Пакет превышает оставшийся лимит. Уберите часть файлов и повторите попытку.", "This saved result is no longer available. Remove this entry and choose the original file to convert it again.": "Этот сохранённый результат больше недоступен. Удалите запись и выберите исходный файл для повторного преобразования.", + "This upload reservation expired. Choose the files again.": "Срок резервирования истёк. Выберите файлы заново.", "Time": "Время", "To report content you believe is illegal, send us: why you think it's illegal, the file name or job reference and the time, your name and email, and a statement that your report is accurate and made in good faith. We'll review it without undue delay and tell you what we decided. If we restrict content or access, we explain the reason to the person affected.": "Для сообщения укажите причину предполагаемой незаконности, имя файла или номер задания и время, ваши имя и email, а также заявление о точности и добросовестности сообщения. Мы рассмотрим его без неоправданной задержки и сообщим решение. При ограничении контента или доступа объясним причину затронутому лицу.", "Toggle Recent Conversion Sessions Sidebar": "Переключить панель недавних преобразований", @@ -485,6 +501,8 @@ "Too many requests. Please wait and try again.": "Слишком много запросов. Подождите и повторите.", "Total characters: {v0} (without spaces: {v1})": "Всего символов: {v0} (без пробелов: {v1})", "Total words counted: {v0}": "Всего слов: {v0}", + "Totals can change while a job runs. Refresh to update all sections.": "Итоговые значения могут меняться во время выполнения задания. Обновите все разделы.", + "Tree and status counts show loaded records only.": "Дерево и счётчики статусов показывают только загруженные записи.", "Tries": "Попытки", "Turn any document into clean Markdown.": "Преобразуйте документы в чистый Markdown.", "Type": "Тип", @@ -492,6 +510,7 @@ "UPLOAD DOCUMENTS": "ЗАГРУЗКА ДОКУМЕНТОВ", "Under the GDPR you can ask us to:": "В соответствии с GDPR вы можете попросить нас:", "Unsupported format: .{v0}": "Неподдерживаемый формат: .{v0}", + "Up to 20 files per batch. Your rolling allowance is separate; slots return individually.": "До 20 файлов за раз. Скользящий лимит действует отдельно; места освобождаются по одному.", "Updated": "Обновлено", "Upload & preview": "Загрузка и просмотр", "Upload and convert any document to see live rendered Markdown alongside raw code.": "Загрузите и преобразуйте документ, чтобы увидеть Markdown рядом с исходным кодом.", @@ -516,6 +535,7 @@ "What happens to uploaded files?": "Что происходит с загруженными файлами?", "What is LLMiser?": "Что такое LLMiser?", "When": "Когда", + "When guest file limits are enabled, a secure service cookie identifies your browser for the rolling file allowance. It lasts up to 90 days and is not used for advertising. We retain a keyed hash and quota event identifiers and timestamps, not the raw cookie. Quota metadata is eligible for cleanup after seven days. Active-job records remain until recovery settles. Clearing the cookie creates a new guest identity and does not delete previously uploaded files.": "Когда включены ограничения для гостей, защищённый служебный cookie определяет браузер для скользящего лимита файлов. Он хранится до 90 дней и не используется для рекламы. Мы сохраняем хеш с ключом, идентификаторы событий лимита и временные отметки, а не исходный cookie. Метаданные лимита подлежат очистке после семи дней. Записи активных заданий сохраняются до завершения восстановления. Удаление cookie создаёт новую гостевую идентичность и не удаляет ранее загруженные файлы.", "Whenever you convert a document, your last 5 conversions are automatically stored here for instant recall, side-by-side editing, and quick downloads.": "Последние 5 преобразований сохраняются здесь автоматически для быстрого открытия, параллельного редактирования и скачивания.", "Which version of these documents you accepted, and when.": "Принятая версия этих документов и время принятия.", "Why": "Зачем", @@ -536,6 +556,7 @@ "You keep every right to the files you upload and to the Markdown LLMiser produces from them.": "Вы сохраняете все права на загруженные файлы и созданный из них Markdown.", "Your Markdown appears here": "Здесь появится Markdown", "Your app language choice.": "Выбранный язык приложения.", + "Your file allowance is nearly used. Check the remaining count before uploading.": "Лимит почти исчерпан. Проверьте остаток перед загрузкой.", "Your last 5 conversions (the Markdown text and file details), so you can reopen them. Clear them any time from the Recent panel.": "Последние 5 преобразований с текстом Markdown и сведениями о файлах для повторного открытия. Их можно удалить в панели истории.", "Your last 5 conversions: the Markdown text when it fits, file details and a reference to the completed conversion. Clear them any time from the Recent panel.": "Последние 5 преобразований: текст Markdown, если он помещается, сведения о файле и ссылка на завершённое преобразование. Их можно в любой момент очистить в панели недавних преобразований.", "Your light or dark theme choice.": "Выбранная светлая или тёмная тема.", @@ -601,6 +622,8 @@ "upload malware or files built to attack or crash the service,": "загрузки вредоносных программ или файлов для атаки или вывода сервиса из строя,", "with OCR pages": "со страницами OCR", "words": "слов", + "{reserved} reserved · {remaining} remaining": "Зарезервировано: {reserved} · Осталось: {remaining}", + "{used} of {limit} files used in the last 24 hours": "За последние 24 часа использовано файлов: {used} из {limit}", "{v0} already in queue": "Уже в очереди: {v0}", "{v0} done, {v1} failed: {v2}": "Готово: {v0}, ошибок: {v1}: {v2}", "{v0} job(s) updated": "Обновлено заданий: {v0}", @@ -626,14 +649,5 @@ "✓ Markdown Copied": "✓ Markdown скопирован", "✓ done": "✓ готово", "📄 Terms of Service": "📄 Условия использования", - "🔒 Privacy Policy": "🔒 Политика конфиденциальности", - "Large document: formatted preview is paused to keep editing responsive. The complete Markdown is available in Raw mode and exports.": "Большой документ: предпросмотр с форматированием приостановлен, чтобы редактирование оставалось отзывчивым. Полный Markdown доступен в режиме «Исходный» и при экспорте.", - "Render full preview (may take a moment)": "Показать полный предпросмотр (может занять некоторое время)", - "Pause formatted preview": "Приостановить предпросмотр с форматированием", - "Loaded: {v0} · Total: {v1}": "Загружено: {v0} · Всего: {v1}", - "Totals can change while a job runs. Refresh to update all sections.": "Итоговые значения могут меняться во время выполнения задания. Обновите все разделы.", - "Tree and status counts show loaded records only.": "Дерево и счётчики статусов показывают только загруженные записи.", - "Stored files changed. Refresh and try again.": "Сохранённые файлы изменились. Обновите страницу и повторите попытку.", - "Could not load the complete file list": "Не удалось загрузить полный список файлов", - "Reload the controller to use paginated job details.": "Перезагрузите панель управления для постраничного просмотра задания." + "🔒 Privacy Policy": "🔒 Политика конфиденциальности" } diff --git a/frontend/lib/i18n/messages/zh-CN.json b/frontend/lib/i18n/messages/zh-CN.json index 1b8cd47..ba5e31b 100644 --- a/frontend/lib/i18n/messages/zh-CN.json +++ b/frontend/lib/i18n/messages/zh-CN.json @@ -155,7 +155,9 @@ "Could not build the ZIP file": "无法生成ZIP文件", "Could not download the converted file ({v0}). Please try again.": "无法下载转换文件({v0})。请重试。", "Could not download the converted file. Check your connection and retry.": "无法下载转换文件。请检查网络连接后重试。", + "Could not load the complete file list": "无法加载完整的文件列表", "Could not reach the converter. Check your connection and retry.": "无法连接转换服务。请检查网络后重试。", + "Could not refresh file limits. They will be checked before upload.": "无法刷新文件额度。上传前将重新检查。", "Could not retrieve the saved result. Check your connection and retry.": "无法获取已保存的结果。请检查网络连接后重试。", "Counting page views, to see which pages people use and how they find LLMiser. Legal basis: our legitimate interest in improving the service (Art. 6(1)(f) GDPR). The counts are anonymous and need no cookies.": "统计页面浏览量,了解用户使用哪些页面及如何找到LLMiser。法律依据:改进服务的合法利益(GDPR第6(1)(f)条)。统计匿名进行,无需Cookie。", "Created": "创建时间", @@ -194,6 +196,7 @@ "EXPORT AREA": "导出区域", "Empty all stored conversion sessions from local storage": "清除本地存储中的全部转换记录", "Empty document content": "文档内容为空", + "Enable cookies for LLMiser and retry. Update the extension if you use it.": "请启用 LLMiser 的 Cookie 后重试。如使用扩展程序,请先更新。", "End of list": "列表末尾", "Engine": "引擎", "Enter both admin keys.": "请输入两个管理员密钥。", @@ -210,7 +213,9 @@ "FREE · NO SIGN-UP · OPEN SOURCE": "免费 · 无需注册 · 开源", "Failed": "失败", "Fast 1-click restore": "一键快速恢复", + "File allowance": "文件额度", "File details: name, type and size.": "文件信息:名称、类型和大小。", + "File limits are temporarily unavailable. Please try again shortly.": "暂时无法查询文件额度。请稍后重试。", "File names: deleted together with the files. After that, a job record keeps only the file type, size, timings and outcome, with nothing that identifies you.": "文件名会随文件一同删除。此后任务记录仅保留文件类型、大小、处理时间和结果,不包含可识别您身份的信息。", "File picker opened (⌘O)": "已打开文件选择器(⌘O)", "Files": "文件", @@ -291,6 +296,7 @@ "LLMiser's source code is published under the GNU General Public License v3.0. That licence governs your use of the code. These terms govern the hosted service.": "LLMiser源码以GNU通用公共许可证v3.0发布。该许可证规范代码使用,本条款规范托管服务。", "LLMiser: Free LLM Cost Optimizer for Documents": "LLMiser:免费的文档LLM成本优化工具", "Language": "语言", + "Large document: formatted preview is paused to keep editing responsive. The complete Markdown is available in Raw mode and exports.": "文档较大:为保持编辑流畅,已暂停格式化预览。完整 Markdown 可在源码模式和导出文件中查看。", "Last updated": "最后更新", "Legal": "法律信息", "Limit": "限制", @@ -298,6 +304,7 @@ "Load Sample Report": "加载示例报告", "Load more": "加载更多", "Loaded \"{v0}\" from recent sessions": "已从最近记录加载“{v0}”", + "Loaded: {v0} · Total: {v1}": "已加载:{v0} · 总计:{v1}", "Loading formatted preview…": "正在加载格式化预览…", "Loading language…": "正在加载语言…", "Loading preview…": "正在加载预览…", @@ -314,11 +321,13 @@ "Menu": "菜单", "Minimizes token density": "尽量减少词元数量", "Monospace source code": "等宽字体源代码", + "Next slot release scheduled for {time} (your local time).": "下一个额度预计于 {time} 释放(本地时间)。", "No ads, no tracking cookies, only anonymous page-view counts. Nobody trains AI models on your files.": "无广告、无跟踪Cookie,仅统计匿名页面浏览量。不会使用您的文件训练AI模型。", "No audit entries yet.": "暂无审计记录。", "No backend instances are configured.": "未配置后端实例。", "No converted Markdown to copy yet": "暂无可复制的转换后Markdown", "No document converted yet. Choose or drop a file to export.": "尚未转换文档。选择或拖放文件以导出。", + "No file slots remain. Your existing results are still available.": "文件额度已用完。已有结果仍可访问。", "No files in queue yet.": "队列中暂无文件。", "No files registered.": "暂无登记文件。", "No files.": "暂无文件。", @@ -358,6 +367,7 @@ "Partial results": "部分结果", "Parts": "分片", "Parts done": "已完成分片", + "Pause formatted preview": "暂停格式化预览", "Pool": "服务池", "Prepare useful context before you spend tokens. LLMiser converts PDFs, Office files, images and ZIP projects to editable Markdown. Choose a profile, review the output, and send only what your AI task needs.": "在消耗词元前,先准备有用的上下文。LLMiser可将PDF、Office文件、图像和ZIP项目转换为可编辑的Markdown。选择配置方案、检查结果,只向AI发送任务所需内容。", "Preview": "预览", @@ -402,10 +412,13 @@ "Record the exact model, tokenizer, billable input and output usage, caching and image charges.": "记录具体模型、分词器、计费输入输出用量、缓存及图像费用。", "Recording that you accepted the Terms and this policy, so we can show which version you agreed to. Legal basis: Art. 6(1)(b) and (f) GDPR.": "记录您同意的条款和政策版本。法律依据:GDPR第6(1)(b)及(f)条。", "Refresh": "刷新", + "Refresh file allowance": "刷新文件额度", "Refreshes every 30 s while this tab is open.": "此页打开时每30秒刷新一次。", + "Reload the controller to use paginated job details.": "请重新加载控制台以分页查看任务详情。", "Remove from history": "从历史记录移除", "Remove {v0}": "移除{v0}", "Removed from recent sessions": "已从最近记录移除", + "Render full preview (may take a moment)": "显示完整预览(可能需要一些时间)", "Rendered": "渲染", "Rendered Markdown view": "Markdown渲染视图", "Rendered with GFM": "使用GFM渲染", @@ -446,6 +459,7 @@ "Status": "状态", "Storage": "存储", "Stored": "已存储", + "Stored files changed. Refresh and try again.": "已存储的文件发生变化。请刷新后重试。", "Stripped of metadata & extra line breaks": "移除元数据和多余换行", "Strips metadata & extra lines": "移除元数据和多余空行", "Supported documents and output": "支持的文档与输出", @@ -473,7 +487,9 @@ "These are the original converted files. Use .md or .zip above to export your edits. Server copies are available until automatic deletion.": "这些是原始转换文件。请使用上方的.md或.zip导出您的修改。服务器副本在自动删除前可用。", "These items are needed for features you use, so the EU ePrivacy rules don't require a separate cookie consent for them.": "这些信息是您使用相关功能所必需的,因此欧盟ePrivacy规则不要求为其单独取得Cookie同意。", "They're deleted automatically 48 hours after upload, with no account needed.": "上传48小时后自动删除,无需账户。", + "This batch exceeds your remaining file limit. Remove files and try again.": "此批次超出剩余额度。请移除部分文件后重试。", "This saved result is no longer available. Remove this entry and choose the original file to convert it again.": "此保存结果已不可用。请移除此记录,然后选择原始文件重新转换。", + "This upload reservation expired. Choose the files again.": "上传预留已过期。请重新选择文件。", "Time": "时间", "To report content you believe is illegal, send us: why you think it's illegal, the file name or job reference and the time, your name and email, and a statement that your report is accurate and made in good faith. We'll review it without undue delay and tell you what we decided. If we restrict content or access, we explain the reason to the person affected.": "举报您认为非法的内容时,请提供:涉嫌非法的原因、文件名或任务编号及时间、您的姓名和邮箱,以及举报准确且出于善意的声明。我们会及时审查并告知决定。如限制内容或访问,将向受影响者说明原因。", "Toggle Recent Conversion Sessions Sidebar": "切换最近转换侧栏", @@ -485,6 +501,8 @@ "Too many requests. Please wait and try again.": "请求过多,请稍后重试。", "Total characters: {v0} (without spaces: {v1})": "总字符数:{v0}(不含空格:{v1})", "Total words counted: {v0}": "总词数:{v0}", + "Totals can change while a job runs. Refresh to update all sections.": "任务运行时总数可能发生变化。请刷新以更新所有部分。", + "Tree and status counts show loaded records only.": "目录树和状态计数仅显示已加载的记录。", "Tries": "尝试次数", "Turn any document into clean Markdown.": "将文档转换为整洁的Markdown。", "Type": "类型", @@ -492,6 +510,7 @@ "UPLOAD DOCUMENTS": "上传文档", "Under the GDPR you can ask us to:": "根据GDPR,您可向我们提出以下请求:", "Unsupported format: .{v0}": "不支持的格式:.{v0}", + "Up to 20 files per batch. Your rolling allowance is separate; slots return individually.": "每批最多20个文件。滚动额度单独计算,并逐个恢复。", "Updated": "更新于", "Upload & preview": "上传与预览", "Upload and convert any document to see live rendered Markdown alongside raw code.": "上传并转换文档,即可并排查看Markdown渲染效果和源码。", @@ -516,6 +535,7 @@ "What happens to uploaded files?": "上传的文件会如何处理?", "What is LLMiser?": "什么是LLMiser?", "When": "时间", + "When guest file limits are enabled, a secure service cookie identifies your browser for the rolling file allowance. It lasts up to 90 days and is not used for advertising. We retain a keyed hash and quota event identifiers and timestamps, not the raw cookie. Quota metadata is eligible for cleanup after seven days. Active-job records remain until recovery settles. Clearing the cookie creates a new guest identity and does not delete previously uploaded files.": "启用访客文件限制时,安全的服务 Cookie 会识别您的浏览器,以管理滚动文件额度。其有效期最长为90天,不用于广告。我们保存带密钥的哈希值、额度事件标识符和时间戳,而非原始 Cookie。额度元数据在七天后可被清理。活动任务的记录会保留到恢复处理结束。清除 Cookie 会创建新的访客身份,但不会删除之前上传的文件。", "Whenever you convert a document, your last 5 conversions are automatically stored here for instant recall, side-by-side editing, and quick downloads.": "最近5次转换会自动保存在此处,便于快速恢复、并排编辑和下载。", "Which version of these documents you accepted, and when.": "您同意的文档版本及时间。", "Why": "用途", @@ -536,6 +556,7 @@ "You keep every right to the files you upload and to the Markdown LLMiser produces from them.": "您保留上传文件及LLMiser据此生成的Markdown的全部权利。", "Your Markdown appears here": "Markdown将显示在此处", "Your app language choice.": "您选择的应用语言。", + "Your file allowance is nearly used. Check the remaining count before uploading.": "文件额度即将用完。上传前请检查剩余额度。", "Your last 5 conversions (the Markdown text and file details), so you can reopen them. Clear them any time from the Recent panel.": "最近5次转换(Markdown文本和文件信息),以便重新打开。您可随时从最近记录面板清除。", "Your last 5 conversions: the Markdown text when it fits, file details and a reference to the completed conversion. Clear them any time from the Recent panel.": "最近5次转换:容量允许时保存的Markdown文本、文件信息及已完成转换的引用。您可随时在最近记录面板中清除。", "Your light or dark theme choice.": "您选择的浅色或深色主题。", @@ -601,6 +622,8 @@ "upload malware or files built to attack or crash the service,": "上传恶意软件或用于攻击、使服务崩溃的文件,", "with OCR pages": "包含OCR页面", "words": "词", + "{reserved} reserved · {remaining} remaining": "已预留 {reserved} 个 · 剩余 {remaining} 个", + "{used} of {limit} files used in the last 24 hours": "过去24小时已使用 {used}/{limit} 个文件", "{v0} already in queue": "{v0}已在队列中", "{v0} done, {v1} failed: {v2}": "完成{v0}个,失败{v1}个:{v2}", "{v0} job(s) updated": "已更新{v0}个任务", @@ -626,14 +649,5 @@ "✓ Markdown Copied": "✓ Markdown已复制", "✓ done": "✓ 完成", "📄 Terms of Service": "📄 服务条款", - "🔒 Privacy Policy": "🔒 隐私政策", - "Large document: formatted preview is paused to keep editing responsive. The complete Markdown is available in Raw mode and exports.": "文档较大:为保持编辑流畅,已暂停格式化预览。完整 Markdown 可在源码模式和导出文件中查看。", - "Render full preview (may take a moment)": "显示完整预览(可能需要一些时间)", - "Pause formatted preview": "暂停格式化预览", - "Loaded: {v0} · Total: {v1}": "已加载:{v0} · 总计:{v1}", - "Totals can change while a job runs. Refresh to update all sections.": "任务运行时总数可能发生变化。请刷新以更新所有部分。", - "Tree and status counts show loaded records only.": "目录树和状态计数仅显示已加载的记录。", - "Stored files changed. Refresh and try again.": "已存储的文件发生变化。请刷新后重试。", - "Could not load the complete file list": "无法加载完整的文件列表", - "Reload the controller to use paginated job details.": "请重新加载控制台以分页查看任务详情。" + "🔒 Privacy Policy": "🔒 隐私政策" } diff --git a/frontend/lib/legal/policies.js b/frontend/lib/legal/policies.js index d39ee51..ff9cafc 100644 --- a/frontend/lib/legal/policies.js +++ b/frontend/lib/legal/policies.js @@ -84,6 +84,7 @@ export const PRIVACY_POLICY = { id: 'device', title: '5. Data kept on your device', blocks: [ + { p: 'When guest file limits are enabled, a secure service cookie identifies your browser for the rolling file allowance. It lasts up to 90 days and is not used for advertising. We retain a keyed hash and quota event identifiers and timestamps, not the raw cookie. Quota metadata is eligible for cleanup after seven days. Active-job records remain until recovery settles. Clearing the cookie creates a new guest identity and does not delete previously uploaded files.' }, { p: 'LLMiser stores a few items in your browser\'s local storage. Saved Markdown text stays on your device when you reopen it:' }, { ul: [ 'Your light or dark theme choice.', diff --git a/frontend/lib/models/conversionService.js b/frontend/lib/models/conversionService.js index 92012c4..0c197d4 100644 --- a/frontend/lib/models/conversionService.js +++ b/frontend/lib/models/conversionService.js @@ -9,10 +9,11 @@ // Supabase isn't configured): POST /api/convert with the file. export class ConversionError extends Error { - constructor(message, { status = null, network = false } = {}) { + constructor(message, { status = null, network = false, code = null } = {}) { super(message); this.name = 'ConversionError'; this.status = status; + this.code = code; /** True when the backend could not be reached at all. */ this.network = network; } @@ -79,18 +80,23 @@ async function request(url, init, fallbackMessage) { } const failure = (res, data) => - new ConversionError(data.detail || data.error || `Conversion failed (${res.status})`, { status: res.status }); + new ConversionError(data.detail || data.error || `Conversion failed (${res.status})`, { status: res.status, code: data.code }); // null = unknown until the first attempt; false = server has no Storage. let storageAvailable = null; -async function convertViaStorage(file, profile, signal, onProgress, onResultReady) { - const { res: created, data: job } = await request('/api/uploads/create', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ filename: file.name, size: file.size, content_type: file.type || null, profile }), - signal, - }); +async function convertViaStorage(file, profile, signal, onProgress, onResultReady, reservation) { + let created, job; + for (let attempt = 0; ; attempt++) { + ({ res: created, data: job } = await request('/api/uploads/create', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ filename: file.name, size: file.size, content_type: file.type || null, profile, ...reservation }), + signal, + })); + if (!reservation || ![429, 503].includes(created.status) || job.code === 'DAILY_FILE_LIMIT' || attempt >= 3) break; + await sleep(retryDelay(created, 1000), signal); + } if (created.status === 501) { storageAvailable = false; return null; @@ -99,17 +105,19 @@ async function convertViaStorage(file, profile, signal, onProgress, onResultRead storageAvailable = true; // Same request shape as @supabase/storage-js uploadToSignedUrl. - const form = new FormData(); - form.append('cacheControl', '3600'); - form.append('', file); - let uploaded; - try { - uploaded = await fetch(job.upload_url, { method: 'PUT', body: form, signal }); - } catch (err) { - if (err?.name === 'AbortError') throw err; - throw new ConversionError('Upload failed. Check your connection and retry.', { network: true }); + if (job.upload_url) { + const form = new FormData(); + form.append('cacheControl', '3600'); + form.append('', file); + let uploaded; + try { + uploaded = await fetch(job.upload_url, { method: 'PUT', body: form, signal }); + } catch (err) { + if (err?.name === 'AbortError') throw err; + throw new ConversionError('Upload failed. Check your connection and retry.', { network: true }); + } + if (!uploaded.ok) throw new ConversionError(`Upload failed (${uploaded.status})`, { status: uploaded.status }); } - if (!uploaded.ok) throw new ConversionError(`Upload failed (${uploaded.status})`, { status: uploaded.status }); onProgress?.(UPLOADED_PROGRESS); @@ -189,6 +197,7 @@ export async function startUploadedJob(jobId, { signal, fetchImpl = fetch, sleep res = null; } if (res?.ok) return data; + if (data.code === 'DAILY_FILE_LIMIT') throw failure(res, data); if (res && res.status < 500 && res.status !== 429) throw failure(res, data); if (attempt >= 8 || now() >= deadline) { throw new ConversionError(data.detail || 'The uploaded file could not be started. Please try again later.', { status: res?.status, network: !res }); @@ -222,6 +231,7 @@ export async function waitForJob(jobId, first, { signal, onProgress, fetchImpl = if (err?.name === 'AbortError') throw err; res = null; } + if (data.code === 'DAILY_FILE_LIMIT') throw failure(res, data); if (res?.ok) { status = data; failures = 0; @@ -243,9 +253,9 @@ export async function waitForJob(jobId, first, { signal, onProgress, fetchImpl = * a ConversionError for every other failure. `onProgress(percent)` reports * upload and processing progress for multi-part jobs. */ -export async function convertFile(file, profile, { signal, onProgress, onResultReady } = {}) { +export async function convertFile(file, profile, { signal, onProgress, onResultReady, reservation } = {}) { if (storageAvailable !== false) { - const result = await convertViaStorage(file, profile, signal, onProgress, onResultReady); + const result = await convertViaStorage(file, profile, signal, onProgress, onResultReady, reservation); if (result) return result; } diff --git a/frontend/lib/models/quotaClient.js b/frontend/lib/models/quotaClient.js new file mode 100644 index 0000000..a3c2a39 --- /dev/null +++ b/frontend/lib/models/quotaClient.js @@ -0,0 +1,40 @@ +// Shared web/extension quota protocol. Server responses alone authorize work. +export class QuotaClientError extends Error { + constructor(data, status) { + super(data.detail || 'Could not check file limits. Please try again.'); + this.code = data.code; this.status = status; this.quota = data; + } +} +async function fetchQuota({ fetchImpl = fetch, origin = '', signal } = {}) { + const response = await fetchImpl(`${origin}/api/quota`, { credentials: 'include', cache: 'no-store', redirect: 'error', signal }); + const data = await response.json(); + if (!response.ok) throw new QuotaClientError(data, response.status); + if (typeof data.enabled !== 'boolean') throw new Error('Could not verify file limits.'); + return data; +} +export async function readQuota(options = {}) { + // Serialize first-cookie bootstrap across same-origin tabs, where supported. + if (typeof navigator !== 'undefined' && navigator.locks?.request) { + return navigator.locks.request('llmiser-guest-bootstrap', () => fetchQuota(options)); + } + return fetchQuota(options); +} +export async function prepareUploads(files, profile, { fetchImpl = fetch, origin = '', signal, + requestId = crypto.randomUUID(), fileIds = files.map(() => crypto.randomUUID()) } = {}) { + const quota = await readQuota({ fetchImpl, origin, signal }); + if (!quota.enabled) return { quota, reservations: files.map(() => null) }; + const manifest = files.map((file, index) => ({ file_id: fileIds[index], filename: file.name, + size: file.size, content_type: file.type || null, profile })); + const response = await fetchImpl(`${origin}/api/uploads/reserve`, { method: 'POST', credentials: 'include', + cache: 'no-store', redirect: 'error', signal, headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ request_id: requestId, files: manifest }) }); + const result = await response.json(); + if (!response.ok) throw new QuotaClientError(result, response.status); + // A policy change during preflight must not turn into an unmetered fallback. + if (result.allowed !== true || result.files?.length !== files.length) throw new Error('File limits changed. Please retry the same selection.'); + return { quota: result.quota, reservations: fileIds.map(fileId => { + const record = result.files.find(f => f.file_id === fileId); + if (!record?.job_id) throw new Error('The batch reservation was incomplete.'); + return { request_id: requestId, file_id: fileId, job_id: record.job_id }; + }) }; +} diff --git a/frontend/lib/server/quotaService.js b/frontend/lib/server/quotaService.js new file mode 100644 index 0000000..c94b0b5 --- /dev/null +++ b/frontend/lib/server/quotaService.js @@ -0,0 +1,105 @@ +import { createHmac, randomBytes, timingSafeEqual } from 'node:crypto'; +import { maxFileSizeFor, poolForExtension, splitFileName, PROFILES } from '../formats.js'; +import { getPoolConfig } from './dispatcher.js'; +import { inputPath, sourceTypeFor, storageBudgetBytes } from './jobService.js'; + +export const GUEST_COOKIE = '__Host-llmiser_guest'; +const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; +const PROFILE = { Standard: 'standard', Clean: 'clean', Compact: 'compact', 'RAG-ready': 'rag_ready' }; +export class QuotaError extends Error { + constructor(code, status, detail, quota = null) { super(detail); Object.assign(this, { code, status, quota }); } +} +const unavailable = () => new QuotaError('QUOTA_UNAVAILABLE', 503, 'File limits are temporarily unavailable. Please try again shortly.'); +const secret = env => { + if (!env.QUOTA_GUEST_SECRET || env.QUOTA_GUEST_SECRET.length < 32) throw unavailable(); + return env.QUOTA_GUEST_SECRET; +}; +const digest = (value, env) => createHmac('sha256', secret(env)).update(value).digest('hex'); +export function issueGuest(env = process.env) { + const nonce = randomBytes(32).toString('hex'); + return `${nonce}.${digest(`cookie:${nonce}`, env)}`; +} +export function guestSubject(request, env = process.env) { + const token = request.headers.get('cookie')?.split(';').map(s => s.trim()).find(s => s.startsWith(`${GUEST_COOKIE}=`))?.slice(GUEST_COOKIE.length + 1); + if (!token || !/^[a-f0-9]{64}\.[a-f0-9]{64}$/.test(token)) return null; + const [nonce, signature] = token.split('.'); + if (!timingSafeEqual(Buffer.from(signature, 'hex'), Buffer.from(digest(`cookie:${nonce}`, env), 'hex'))) return null; + return digest(`subject:${nonce}`, env); +} +export function guestCookie(token) { + return `${GUEST_COOKIE}=${token}; Path=/; Max-Age=7776000; Secure; HttpOnly; SameSite=Lax`; +} +export function assertQuotaOrigin(request) { + const origin = request.headers.get('origin'); + const appOrigin = new URL(request.url).origin; + if (origin && origin !== appOrigin && !/^chrome-extension:\/\/[a-p]{32}$/.test(origin)) { + throw new QuotaError('ORIGIN_NOT_ALLOWED', 403, 'Open LLMiser to start this conversion.'); + } + if (request.headers.get('sec-fetch-site') === 'cross-site' && !origin?.startsWith('chrome-extension://')) { + throw new QuotaError('ORIGIN_NOT_ALLOWED', 403, 'Open LLMiser to start this conversion.'); + } +} +export async function quotaPolicy(db) { + let policy; + try { policy = await db.rpc('quota_policy', {}); } catch { throw unavailable(); } + if (typeof policy?.enabled !== 'boolean') throw unavailable(); + return policy; +} +export function requireGuest(request, env = process.env) { + assertQuotaOrigin(request); + const subject = guestSubject(request, env); + if (!subject) throw new QuotaError('GUEST_IDENTITY_REQUIRED', 428, 'Enable cookies for LLMiser and retry. Update the extension if you use it.'); + return subject; +} +export function normalizedManifest(files, env = process.env) { + if (!Array.isArray(files) || files.length < 1 || files.length > 20) throw new QuotaError('INVALID_BATCH', 400, 'Choose between 1 and 20 files.'); + const seen = new Set(); + return files.map(file => { + const fileId = typeof file?.file_id === 'string' ? file.file_id.toLowerCase() : ''; + if (!UUID.test(fileId) || seen.has(fileId)) throw new QuotaError('INVALID_BATCH', 400, 'Each file needs a unique identifier.'); + seen.add(fileId); + const { base, ext } = splitFileName(String(file.filename || '')); + const pool = poolForExtension(ext); + if (!pool || !base || !Number.isSafeInteger(file.size) || file.size <= 0 || file.size > maxFileSizeFor(ext) || !PROFILES.includes(file.profile)) { + throw new QuotaError('INVALID_FILE', 400, 'Check file types, sizes and the selected profile.'); + } + if (!getPoolConfig(env)[pool].length) throw new QuotaError('BACKEND_UNAVAILABLE', 503, 'This conversion type is temporarily unavailable.'); + return { file_id: fileId, filename: base, extension: ext, size: file.size, + content_type: typeof file.content_type === 'string' ? file.content_type.slice(0, 200) : null, + profile: PROFILE[file.profile], source_type: sourceTypeFor(ext), workload_type: pool.toUpperCase() }; + }).sort((a, b) => a.file_id.localeCompare(b.file_id)); +} +function accepted(result) { + if (result?.allowed === true) return result; + const code = result?.code; + if (code === 'DAILY_FILE_LIMIT') throw new QuotaError(code, 429, 'This batch exceeds your remaining file limit. Remove files and try again.', result); + if (code === 'IDEMPOTENCY_CONFLICT') throw new QuotaError(code, 409, 'This request identifier was already used for different files.'); + if (['QUOTA_RESERVATION_EXPIRED', 'UPLOAD_WINDOW_EXPIRED', 'RESULT_EXPIRED'].includes(code)) throw new QuotaError(code, 410, 'This upload reservation expired. Choose the files again.'); + if (code === 'QUOTA_RESERVATION_REQUIRED') throw new QuotaError(code, 428, 'Refresh LLMiser or update the extension before uploading.'); + if (code === 'BATCH_CAPACITY') throw new QuotaError(code, 503, 'LLMiser is handling many files. No files in this batch were admitted. Try again shortly.'); + throw unavailable(); +} +export async function reserveBatch(db, request, input, env = process.env) { + const subject = requireGuest(request, env); + if (!UUID.test(input?.request_id || '')) throw new QuotaError('INVALID_BATCH', 400, 'A stable request identifier is required.'); + const files = normalizedManifest(input.files, env); + return accepted(await db.rpc('reserve_quota_batch', { p_subject_hash: subject, p_request_id: input.request_id, + p_files: files, p_bucket: db.bucket, p_budget_bytes: storageBudgetBytes(env) })); +} +export async function quotaUpload(db, request, input, env = process.env) { + const subject = requireGuest(request, env); + if (!UUID.test(input?.request_id || '') || !UUID.test(input?.file_id || '')) throw new QuotaError('QUOTA_RESERVATION_REQUIRED', 428, 'Reserve the selected batch before uploading.'); + const job = accepted(await db.rpc('quota_upload', { p_subject_hash: subject, p_request_id: input.request_id, p_file_id: input.file_id })); + const path = inputPath(job.job_id, job.extension); + if (job.upload_required === false) return { job_id: job.job_id, status: job.status, object_path: path, upload_url: null }; + if (job.upload_required !== true) throw unavailable(); + const upload = await db.signedUploadUrl(path); + return { job_id: job.job_id, status: job.status, object_path: path, upload_url: upload.url }; +} +export function quotaResponse(error) { + if (!(error instanceof QuotaError)) return null; + const headers = { 'Cache-Control': 'no-store' }; + const retryAt = error.quota?.requestedAvailableAt; + if (retryAt) headers['Retry-After'] = String(Math.max(1, Math.ceil((Date.parse(retryAt) - Date.parse(error.quota.serverTime)) / 1000))); + return Response.json({ ...(error.quota || {}), code: error.code, detail: error.message }, { status: error.status, headers }); +} diff --git a/frontend/test/publicRoutes.test.mjs b/frontend/test/publicRoutes.test.mjs index 44c80a9..38bb325 100644 --- a/frontend/test/publicRoutes.test.mjs +++ b/frontend/test/publicRoutes.test.mjs @@ -98,15 +98,16 @@ test('upload JSON is bounded and rejects null/arrays before creating any rows',a })); test('multipart validation errors release their lease before returning',async()=>isolated(async()=>{ - const calls=[]; globalThis.fetch=async(url)=>{calls.push(url);return json(url.endsWith('admit_public_request')?{allowed:true,lease_id:lease}:true);}; + const calls=[]; globalThis.fetch=async(url)=>{calls.push(url);if(url.endsWith('quota_policy'))return json({enabled:false});return json(url.endsWith('admit_public_request')?{allowed:true,lease_id:lease}:true);}; const response=await(await route('convert')).POST(uploadRequest('{}')); - assert.equal(response.status,400); assert.equal(calls.length,2); assert.match(calls[1],/release_public_multipart$/); + assert.equal(response.status,400); assert.equal(calls.length,3); assert.match(calls[2],/release_public_multipart$/); })); test('successful multipart dispatch releases the lease; timeout retains it for expiry',async()=>isolated(async()=>{ const handler=await route('convert'); let timeout=false; const calls=[]; globalThis.fetch=async(url)=>{ calls.push(url); + if(url.endsWith('quota_policy'))return json({enabled:false}); if(url.endsWith('admit_public_request'))return json({allowed:true,lease_id:lease}); if(url.endsWith('release_public_multipart'))return json(true); assert.match(url,/internal\/convert$/); @@ -115,7 +116,7 @@ test('successful multipart dispatch releases the lease; timeout retains it for e }; assert.equal((await handler.POST(multipart())).status,200); assert.match(calls.at(-1),/release_public_multipart$/); calls.length=0; timeout=true; - assert.equal((await handler.POST(multipart())).status,504); assert.equal(calls.length,2); + assert.equal((await handler.POST(multipart())).status,504); assert.equal(calls.length,3); assert.ok(calls.every(url=>!url.endsWith('release_public_multipart'))); })); @@ -123,6 +124,7 @@ test('a successful peer retry conservatively retains the lease for the uncertain process.env.NORMAL_BACKEND_URLS='http://backend.test,http://peer.test'; let attempts=0;let released=false; globalThis.fetch=async(url)=>{ + if(url.endsWith('quota_policy'))return json({enabled:false}); if(url.endsWith('admit_public_request'))return json({allowed:true,lease_id:lease}); if(url.endsWith('release_public_multipart')){released=true;return json(true);} attempts++;return attempts===1?json({detail:'upstream failed'},502):json({filename:'fixture.md',content:'synthetic text'}); @@ -137,6 +139,7 @@ test('full or missing active-job admission returns safe Retry-After without sign const calls=[]; globalThis.fetch=async(url)=>{ calls.push(url); + if(url.endsWith('quota_policy'))return json({enabled:false}); if(url.endsWith('admit_public_request'))return json({allowed:true,lease_id:null}); if(url.endsWith('create_reserved_upload_job'))return unavailable?json({message:'private missing function'},404):json({allowed:false,retry_after:30}); assert.fail('Unexpected Storage or database call: '+url); diff --git a/frontend/test/quotaClient.test.mjs b/frontend/test/quotaClient.test.mjs new file mode 100644 index 0000000..3f71601 --- /dev/null +++ b/frontend/test/quotaClient.test.mjs @@ -0,0 +1,18 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { prepareUploads } from '../lib/models/quotaClient.js'; +test('denied batch uploads no file bytes and preserves structured shortage', async () => { + const calls=[]; + await assert.rejects(prepareUploads([new File(['fixture'],'a.txt')],'Standard',{fetchImpl:async (url,init)=>{ + calls.push(url); + if(url==='/api/quota') return Response.json({enabled:true}); + assert.equal(init.credentials,'include'); + assert.equal(JSON.parse(init.body).files.length,1); + return Response.json({code:'DAILY_FILE_LIMIT',remaining:0,detail:'Remove files'},{status:429}); + }}),error=>error.code==='DAILY_FILE_LIMIT'); + assert.deepEqual(calls,['/api/quota','/api/uploads/reserve']); +}); +test('disabled quota leaves the existing transport intact',async()=>{ + const result=await prepareUploads([new File(['x'],'a.txt')],'Standard',{fetchImpl:async()=>Response.json({enabled:false})}); + assert.deepEqual(result.reservations,[null]); +}); diff --git a/frontend/test/quotaService.test.mjs b/frontend/test/quotaService.test.mjs new file mode 100644 index 0000000..363667b --- /dev/null +++ b/frontend/test/quotaService.test.mjs @@ -0,0 +1,23 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { issueGuest, guestSubject, guestCookie, requireGuest, quotaResponse, QuotaError, normalizedManifest } from '../lib/server/quotaService.js'; +const env = { QUOTA_GUEST_SECRET: 'test-only-secret-with-at-least-thirty-two-characters', BACKEND_URLS: 'https://normal.example' }; +test('opaque guest cookie is signed, host-only and never accepts an arbitrary identity', () => { + const token = issueGuest(env); + const request = new Request('https://llmiser.devbehindyou.com/api/quota', { headers: { Cookie: `__Host-llmiser_guest=${token}` } }); + assert.match(guestSubject(request,env),/^[a-f0-9]{64}$/); + assert.equal(requireGuest(request,env),guestSubject(request,env)); + assert.equal(guestSubject(new Request(request.url,{headers:{Cookie:`__Host-llmiser_guest=${'0'.repeat(64)}.${'0'.repeat(64)}`}}),env),null); + assert.match(guestCookie(token),/Secure; HttpOnly; SameSite=Lax/); + assert.doesNotMatch(guestCookie(token),/Domain=/); + assert.throws(()=>requireGuest(new Request(request.url,{headers:{Cookie:`__Host-llmiser_guest=${token}`,Origin:'https://attacker.example'}}),env),/Open LLMiser/); +}); +test('quota exhaustion keeps real remaining and uses the batch-fit retry time', async () => { + const res=quotaResponse(new QuotaError('DAILY_FILE_LIMIT',429,'Remove files',{remaining:1,serverTime:'2026-11-11T00:00:00Z',requestedAvailableAt:'2026-11-11T01:00:00Z'})); + assert.equal(res.headers.get('retry-after'),'3600'); + assert.equal((await res.json()).remaining,1); +}); +test('invalid file manifests fail before any database admission', () => { + assert.throws(()=>normalizedManifest([],env),/between 1 and 20/); + assert.throws(()=>normalizedManifest([{file_id:'forged'}],env),/unique identifier/); +}); diff --git a/frontend/test/sql/quota.test.mjs b/frontend/test/sql/quota.test.mjs new file mode 100644 index 0000000..0b3450e --- /dev/null +++ b/frontend/test/sql/quota.test.mjs @@ -0,0 +1,110 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { randomUUID } from 'node:crypto'; +import { freshDb } from './pgliteDb.mjs'; + +const subject = 'a'.repeat(64); +const manifest = n => Array.from({ length: n }, (_, i) => ({ file_id: randomUUID(), filename: `fixture-${i}.txt`, extension: 'txt', size: 12, content_type: 'text/plain', profile: 'standard', source_type: 'DOCUMENT', workload_type: 'NORMAL' })); +test('quota admission, lifecycle, permissions and expiry use shipped SQL', async t => { + const db = await freshDb(); + t.after(() => db.close()); + const snapshot = async () => (await db.query('select public.quota_snapshot($1) as result', [subject])).rows[0].result; + const reserve = async (files, id = randomUUID()) => (await db.query('select public.reserve_quota_batch($1,$2,$3,\'mdify-pro-files\') as result', [subject, id, JSON.stringify(files)])).rows[0].result; + const reset = async () => db.exec('truncate public.jobs cascade; truncate public.job_storage_reservations; truncate quota_private.batches cascade; update quota_private.policy set enabled=true;'); + assert.equal((await db.query('select public.quota_policy() as p')).rows[0].p.enabled, false); + + await t.test('20 files reserve once; conflicting replay and 21st are denied', async () => { + await reset(); + const files = manifest(20), id = randomUUID(); + const first = await reserve(files, id); + assert.equal(first.allowed, true); + assert.equal(first.files.length, 20); + assert.deepEqual((await reserve(files, id)).files, first.files); + assert.equal((await reserve(manifest(1), id)).code, 'IDEMPOTENCY_CONFLICT'); + const denied = await reserve(manifest(1)); + assert.equal(denied.code, 'DAILY_FILE_LIMIT'); + assert.equal(denied.remaining, 0); + assert.equal((await snapshot()).reserved, 20); + assert.equal((await db.query('select count(*)::int n from public.jobs')).rows[0].n, 20); + }); + await t.test('whole selection rejects with actual remaining; release is idempotent', async () => { + await reset(); + const id = randomUUID(); + await reserve(manifest(19), id); + const denied = await reserve(manifest(2)); + assert.equal(denied.remaining, 1); + assert.equal(denied.requested, 2); + assert.equal((await db.query('select count(*)::int n from public.jobs')).rows[0].n, 19); + assert.equal((await db.query('select public.release_quota_batch($1,$2) as n', [subject,id])).rows[0].n, 19); + assert.equal((await db.query('select public.release_quota_batch($1,$2) as n', [subject,id])).rows[0].n, 0); + assert.equal((await snapshot()).remaining, 20); + assert.equal((await db.query('select count(*)::int n from public.job_storage_reservations')).rows[0].n, 19, 'byte guards are not refunded'); + }); + await t.test('worker claim charges once, including retries; started slots cannot refund', async () => { + await reset(); + const id = randomUUID(); + const { files } = await reserve(manifest(1),id); + const job = files[0].job_id; + await db.query("select public.start_uploaded_job($1,'mdify-pro-files',12)",[job]); + assert.equal((await snapshot()).used,0); + const claim = await db.query("select * from public.claim_work_items('normal',4,1,$1)",[job]); + assert.equal(claim.rows.length,1); + assert.equal((await snapshot()).used,1); + assert.equal((await snapshot()).reserved,0); + assert.equal((await db.query('select public.release_quota_batch($1,$2) as n',[subject,id])).rows[0].n,0); + await db.query("update public.work_items set status='QUEUED' where job_id=$1",[job]); + await db.query("select * from public.claim_work_items('normal',4,1,$1)",[job]); + assert.equal((await snapshot()).used,1); + await db.exec("update quota_private.slots set admitted_at=clock_timestamp()-interval '24 hours 1 second'"); + assert.equal((await snapshot()).remaining,20); + }); + await t.test('retry resumes an existing upload after its signing window closes', async () => { + await reset(); + const id = randomUUID(); + const { files: [file] } = await reserve(manifest(1), id); + const authorization = async () => (await db.query('select public.quota_upload($1,$2,$3) as result', + [subject, id, file.file_id])).rows[0].result; + assert.equal((await authorization()).upload_required, true); + await db.exec("update quota_private.slots set admitted_at=clock_timestamp()-interval '46 minutes'"); + assert.equal((await authorization()).code, 'UPLOAD_WINDOW_EXPIRED'); + await db.query("insert into storage.objects(bucket_id,name,metadata) values('mdify-pro-files',$1,'{\"size\":12}')", + [`jobs/${file.job_id}/input/source.txt`]); + const replay = await authorization(); + assert.equal(replay.job_id, file.job_id); + assert.equal(replay.upload_required, false); + assert.equal((await snapshot()).reserved, 1); + }); + await t.test('expired reservation cannot sign or dispatch and does not starve valid work', async () => { + await reset(); + const id = randomUUID(), old = await reserve(manifest(1), id); + await db.query("select public.start_uploaded_job($1,'mdify-pro-files',12)",[old.files[0].job_id]); + await db.exec("update quota_private.slots set expires_at=clock_timestamp()-interval '1 second'"); + assert.equal((await snapshot()).remaining,20); + assert.equal((await reserve(manifest(1),id)).code,'IDEMPOTENCY_CONFLICT'); + const signed = (await db.query('select public.quota_upload($1,$2,$3) as r',[subject,id,old.files[0].file_id])).rows[0].r; + assert.equal(signed.code,'QUOTA_RESERVATION_EXPIRED'); + const fresh = await reserve(manifest(1)); + await db.query("select public.start_uploaded_job($1,'mdify-pro-files',12)",[fresh.files[0].job_id]); + const claim = await db.query("select * from public.claim_work_items('normal',4,1)"); + assert.equal(claim.rows.length,1); + assert.equal(claim.rows[0].job_id,fresh.files[0].job_id); + }); + await t.test('legacy inserts and anonymous RPCs cannot mint quota jobs', async () => { + await reset(); + await assert.rejects(db.query("select public.create_reserved_upload_job('mdify-pro-files','a.txt','txt',12,null,'standard','DOCUMENT','NORMAL')"),/QUOTA_RESERVATION_REQUIRED/); + await db.exec('set role anon'); + try { + await assert.rejects(db.query('select public.quota_snapshot($1)',[subject]),/permission denied/); + await assert.rejects(db.query('select * from quota_private.slots'),/permission denied/); + } finally { await db.exec('reset role'); } + }); + await t.test('existing capacity failure rolls back all files and quota slots', async () => { + await reset(); + await db.exec('update quota_private.policy set enabled=false'); + await db.exec("insert into public.jobs(status) select 'UPLOADING' from generate_series(1,31)"); + await db.exec('update quota_private.policy set enabled=true'); + assert.equal((await reserve(manifest(2))).code,'BATCH_CAPACITY'); + assert.equal((await snapshot()).reserved,0); + assert.equal((await db.query('select count(*)::int n from public.jobs')).rows[0].n,31); + }); +}); diff --git a/frontend/viewmodels/useConverterViewModel.js b/frontend/viewmodels/useConverterViewModel.js index cc93988..e1dd6f1 100644 --- a/frontend/viewmodels/useConverterViewModel.js +++ b/frontend/viewmodels/useConverterViewModel.js @@ -11,6 +11,7 @@ import { selectConvertingItem, } from '../lib/models/queueModel'; import { MAX_QUEUE_FILES } from '../lib/formats'; +import { prepareUploads, readQuota } from '../lib/models/quotaClient'; // Two requests in flight halves batch time without stacking many large // parses on a single self-hosted Node process. @@ -40,6 +41,21 @@ export function useConverterViewModel({ onConverted, onResultRetained, onNetwork const [state, dispatch] = useReducer(queueReducer, initialQueueState); const [profile, setProfile] = useState('Standard'); const [isRunning, setRunning] = useState(false); + const [quota, setQuota] = useState(null); + const [quotaError, setQuotaError] = useState(''); + const reservedRef = useRef(new Map()); + const batchRef = useRef(null); + const refreshQuota = useCallback(async () => { + try { setQuota(await readQuota()); setQuotaError(''); } + catch { setQuotaError('Could not refresh file limits. They will be checked before upload.'); } + }, []); + useEffect(() => { + refreshQuota(); + window.addEventListener('focus', refreshQuota); + const channel = typeof BroadcastChannel !== 'undefined' ? new BroadcastChannel('llmiser-quota') : null; + if (channel) channel.onmessage = refreshQuota; + return () => { window.removeEventListener('focus', refreshQuota); channel?.close(); }; + }, [refreshQuota]); // Latest values for async commands, so the commands themselves can stay // referentially stable and memoized views don't re-render. @@ -75,6 +91,7 @@ export function useConverterViewModel({ onConverted, onResultRetained, onNetwork try { const options = { + reservation: reservedRef.current.get(item.id), signal: controller.signal, onProgress: (progress) => dispatch({ type: 'jobProgress', id: item.id, progress }), onResultReady: (result) => { @@ -95,6 +112,20 @@ export function useConverterViewModel({ onConverted, onResultRetained, onNetwork if (err.network) callbacksRef.current.onNetworkFailure?.(); } finally { controllersRef.current.delete(item.id); + refreshQuota(); + } + }, [refreshQuota]); + + const reserveItems = useCallback(async (items) => { + const fresh = items.filter(item => !item.recovery?.job_id && !reservedRef.current.has(item.id)); + if (!fresh.length) return; + const identity = JSON.stringify([profileRef.current, fresh.map(item => item.id)]); + if (batchRef.current?.identity !== identity) batchRef.current = { identity, requestId: crypto.randomUUID(), fileIds: fresh.map(() => crypto.randomUUID()) }; + const result = await prepareUploads(fresh.map(item => item.file), profileRef.current, batchRef.current); + result.reservations.forEach((reservation, index) => { if (reservation) reservedRef.current.set(fresh[index].id, reservation); }); + setQuota(result.quota); setQuotaError(''); + if (typeof BroadcastChannel !== 'undefined') { + const channel = new BroadcastChannel('llmiser-quota'); channel.postMessage('changed'); channel.close(); } }, []); @@ -114,19 +145,30 @@ export function useConverterViewModel({ onConverted, onResultRetained, onNetwork } }; try { + await reserveItems(queue); await Promise.all(Array.from({ length: Math.min(CONCURRENCY, queue.length) }, worker)); + } catch (error) { + if (error.quota?.limit) setQuota(error.quota); + setQuotaError(error.message); + callbacksRef.current.onNotice?.(error.message); } finally { runningRef.current = false; setRunning(false); } - }, [runJob]); + }, [runJob, reserveItems]); const retry = useCallback( - (id) => { + async (id) => { + if (runningRef.current) return; const item = stateRef.current.items.find((i) => i.id === id); - if (item && (item.file || item.recovery?.job_id)) runJob(item); + if (item && (item.file || item.recovery?.job_id)) { + runningRef.current = true; setRunning(true); + try { await reserveItems([item]); await runJob(item); } + catch (error) { setQuotaError(error.message); callbacksRef.current.onNotice?.(error.message); } + finally { runningRef.current = false; setRunning(false); } + } }, - [runJob] + [runJob, reserveItems] ); const cancel = useCallback((id) => { @@ -167,6 +209,7 @@ export function useConverterViewModel({ onConverted, onResultRetained, onNetwork }, [state, isRunning]); return { + quota, quotaError, refreshQuota, items: state.items, results: state.results, activeResultId: derived.activeResult?.id ?? null, diff --git a/supabase/MDIFY_SETUP.sql b/supabase/MDIFY_SETUP.sql index 494d5a3..861d514 100644 --- a/supabase/MDIFY_SETUP.sql +++ b/supabase/MDIFY_SETUP.sql @@ -2,7 +2,7 @@ -- Paste into Supabase Dashboard → SQL Editor → Run. One transaction: if any -- statement fails, nothing is applied. Generated by -- frontend/scripts/build-setup-sql.mjs; edit the migrations, not this file. --- Includes: 20260926000000_mdify_init.sql, 20260927000000_mdify_work_queue.sql, 20260928000000_mdify_admin.sql, 20260928120000_mdify_keepwarm.sql, 20261001000000_mdify_atomic_jobs.sql, 20261001010000_mdify_cleanup_recovery.sql, 20261004000000_mdify_public_admission.sql, 20261004010000_mdify_active_jobs.sql, 20261007000000_mdify_storage_reservations.sql, 20261023000000_mdify_cron_efficiency.sql +-- Includes: 20260926000000_mdify_init.sql, 20260927000000_mdify_work_queue.sql, 20260928000000_mdify_admin.sql, 20260928120000_mdify_keepwarm.sql, 20261001000000_mdify_atomic_jobs.sql, 20261001010000_mdify_cleanup_recovery.sql, 20261004000000_mdify_public_admission.sql, 20261004010000_mdify_active_jobs.sql, 20261007000000_mdify_storage_reservations.sql, 20261023000000_mdify_cron_efficiency.sql, 20261111000000_llmiser_guest_quota.sql begin; @@ -2155,4 +2155,332 @@ end $$; revoke all on function public.record_scheduled_http_responses(), public.dispatch_jobs_tick(), public.keepwarm_ping() from public, anon, authenticated, service_role; +-- ════ 20261111000000_llmiser_guest_quota.sql ════ + +-- Apply before quota-aware frontend. Enforcement remains OFF until verified. +begin; +create schema if not exists quota_private; +revoke all on schema quota_private from public, anon, authenticated; +grant usage on schema quota_private to service_role; + +create table if not exists quota_private.policy ( + singleton boolean primary key default true check(singleton), + enabled boolean not null default false, + activated_at timestamptz, + guest_limit integer not null default 20 check(guest_limit between 1 and 100), + version integer not null default 1 check(version > 0) +); +insert into quota_private.policy(singleton) values(true) on conflict do nothing; +create or replace function quota_private.activate_policy() returns trigger +language plpgsql security invoker set search_path='' as $$ +begin + new.activated_at := old.activated_at; + if new.enabled and new.activated_at is null then new.activated_at := clock_timestamp(); end if; + return new; +end $$; +drop trigger if exists quota_activation on quota_private.policy; +create trigger quota_activation before update on quota_private.policy +for each row execute function quota_private.activate_policy(); + +create table if not exists quota_private.batches ( + subject_hash text not null check(subject_hash ~ '^[a-f0-9]{64}$'), + request_id uuid not null, + manifest_hash text not null check(manifest_hash ~ '^[a-f0-9]{64}$'), + admitted_at timestamptz not null, + primary key(subject_hash,request_id) +); +create table if not exists quota_private.slots ( + slot_id uuid primary key default gen_random_uuid(), + subject_hash text not null, + request_id uuid not null, + file_id uuid not null, + job_id uuid unique, + state text not null default 'reserved' check(state in ('reserved','started','released','expired')), + admitted_at timestamptz not null, + expires_at timestamptz not null, + started_at timestamptz, + unique(subject_hash,request_id,file_id), + foreign key(subject_hash,request_id) references quota_private.batches on delete cascade, + check ((state='started') = (started_at is not null)) +); +create index if not exists quota_subject_window on quota_private.slots(subject_hash,admitted_at); +create index if not exists quota_batch_expiry on quota_private.batches(admitted_at); +alter table public.jobs add column if not exists quota_slot_id uuid; +-- Deliberately no cascading job FK: deleting a result cannot refund usage. +alter table quota_private.policy enable row level security; +alter table quota_private.batches enable row level security; +alter table quota_private.slots enable row level security; +revoke all on all tables in schema quota_private from public,anon,authenticated; +grant select on quota_private.policy to service_role; +grant select,insert,update,delete on quota_private.batches,quota_private.slots to service_role; + +create or replace function public.quota_policy() returns jsonb +language sql security invoker set search_path='' as $$ + select jsonb_build_object('enabled',enabled,'limit',guest_limit,'windowHours',24,'policyVersion',version) + from quota_private.policy where singleton; +$$; + +create or replace function public.quota_snapshot(p_subject_hash text,p_requested integer default 1) returns jsonb +language plpgsql security invoker set search_path='' as $$ +declare p quota_private.policy; t timestamptz; used_n integer; reserved_n integer; n integer; + next_at timestamptz; fit_at timestamptz; +begin + if p_subject_hash is null or p_subject_hash !~ '^[a-f0-9]{64}$' or p_requested not between 1 and 20 then raise exception 'invalid quota request'; end if; + perform pg_advisory_xact_lock(hashtextextended('llmiser-quota:'||p_subject_hash,0)); + t:=clock_timestamp(); + select * into strict p from quota_private.policy where singleton; + select count(*) filter(where state='started'),count(*) filter(where state='reserved') into used_n,reserved_n + from quota_private.slots where subject_hash=p_subject_hash and admitted_at>t-interval '24 hours' + and (state='started' or (state='reserved' and expires_at>t)); + n:=used_n+reserved_n; + with releases as ( + select case when state='started' then admitted_at+interval '24 hours' else least(expires_at,admitted_at+interval '24 hours') end as at + from quota_private.slots where subject_hash=p_subject_hash and admitted_at>t-interval '24 hours' + and (state='started' or (state='reserved' and expires_at>t)) + ), ordered as (select at,row_number() over(order by at) as rn from releases) + select min(at),min(at) filter(where rn=greatest(1,n+p_requested-p.guest_limit)) into next_at,fit_at from ordered; + return jsonb_build_object('enabled',p.enabled,'tier','guest','limit',p.guest_limit,'used',used_n,'reserved',reserved_n, + 'remaining',greatest(0,p.guest_limit-n),'windowHours',24,'requested',p_requested, + 'nextSlotAvailableAt',next_at,'requestedAvailableAt',case when n+p_requested<=p.guest_limit then t else fit_at end, + 'serverTime',t,'policyVersion',p.version); +end $$; + +-- All legacy job creators must pass through a slot when policy is enabled. +create or replace function quota_private.bind_job() returns trigger +language plpgsql security invoker set search_path='' as $$ +declare sid uuid; s quota_private.slots; +begin + sid:=nullif(current_setting('llmiser.quota_slot',true),'')::uuid; + if sid is null and not (select enabled from quota_private.policy where singleton) then return new; end if; + select * into s from quota_private.slots where slot_id=sid; + if s.slot_id is null or s.job_id is not null or s.state<>'reserved' or s.expires_at<=clock_timestamp() then + raise exception using errcode='PT428',message='QUOTA_RESERVATION_REQUIRED'; + end if; + new.quota_slot_id:=sid; + return new; +end $$; +drop trigger if exists llmiser_quota_job on public.jobs; +create trigger llmiser_quota_job before insert on public.jobs for each row execute function quota_private.bind_job(); + +create or replace function public.reserve_quota_batch(p_subject_hash text,p_request_id uuid,p_files jsonb,p_bucket text,p_budget_bytes bigint default 838860800) +returns jsonb language plpgsql security invoker set search_path='' as $$ +declare snap jsonb; b quota_private.batches; f jsonb; sid uuid; job jsonb; result jsonb; t timestamptz; +begin + if p_request_id is null or jsonb_typeof(p_files) is distinct from 'array' then raise exception 'invalid quota manifest'; end if; + if jsonb_array_length(p_files) not between 1 and 20 then raise exception 'invalid quota batch size'; end if; + if (select count(distinct value->>'file_id') from jsonb_array_elements(p_files))<>jsonb_array_length(p_files) then raise exception 'duplicate file IDs'; end if; + snap:=public.quota_snapshot(p_subject_hash,jsonb_array_length(p_files)); + if not (snap->>'enabled')::boolean then return jsonb_build_object('enabled',false); end if; + select * into b from quota_private.batches where subject_hash=p_subject_hash and request_id=p_request_id; + if found then + if b.manifest_hash<>encode(sha256(convert_to(p_files::text,'UTF8')),'hex') then return jsonb_build_object('allowed',false,'code','IDEMPOTENCY_CONFLICT','status',409); end if; + if exists(select 1 from quota_private.slots where subject_hash=p_subject_hash and request_id=p_request_id + and (state in ('expired','released') or (state='reserved' and expires_at<=clock_timestamp()))) then + return jsonb_build_object('allowed',false,'code','QUOTA_RESERVATION_EXPIRED','status',410); + end if; + else + if (snap->>'remaining')::integer>'file_id')::uuid,t,t+interval '3 hours') returning slot_id into sid; + perform set_config('llmiser.quota_slot',sid::text,true); + job:=public.create_reserved_upload_job(p_bucket,f->>'filename',f->>'extension',(f->>'size')::bigint, + f->>'content_type',f->>'profile',f->>'source_type',f->>'workload_type',p_budget_bytes); + if (job->>'allowed')::boolean is distinct from true then + raise exception using errcode='PT503',message='BATCH_CAPACITY'; + end if; + update quota_private.slots set job_id=(job->>'job_id')::uuid where slot_id=sid; + end loop; + perform set_config('llmiser.quota_slot','',true); + end if; + select jsonb_agg(jsonb_build_object('file_id',file_id,'job_id',job_id) order by file_id) into result + from quota_private.slots where subject_hash=p_subject_hash and request_id=p_request_id; + return jsonb_build_object('enabled',true,'allowed',true,'request_id',p_request_id,'files',result,'quota',public.quota_snapshot(p_subject_hash)); +exception when sqlstate 'PT503' then + -- The entire subtransaction (all new jobs/slots) rolls back, never a partial batch. + return jsonb_build_object('allowed',false,'code','BATCH_CAPACITY','status',503); +end $$; + +-- A slot authorizes exactly one job. Re-signing after 45 minutes is prohibited: +-- the original three-hour byte guard must outlive every two-hour upload URL. +create or replace function public.quota_upload(p_subject_hash text,p_request_id uuid,p_file_id uuid) returns jsonb +language plpgsql security invoker set search_path='' as $$ +declare s quota_private.slots; j public.jobs; t timestamptz; uploaded boolean; +begin + perform pg_advisory_xact_lock(hashtextextended('llmiser-quota:'||p_subject_hash,0)); + t:=clock_timestamp(); + select * into s from quota_private.slots where subject_hash=p_subject_hash and request_id=p_request_id and file_id=p_file_id; + if s.slot_id is null then return jsonb_build_object('allowed',false,'code','QUOTA_RESERVATION_REQUIRED','status',428); end if; + if s.state in ('released','expired') or (s.state='reserved' and s.expires_at<=t) then + return jsonb_build_object('allowed',false,'code','QUOTA_RESERVATION_EXPIRED','status',410); + end if; + select * into j from public.jobs where job_id=s.job_id; + if j.job_id is null or j.files_deleted_at is not null then return jsonb_build_object('allowed',false,'code','RESULT_EXPIRED','status',410); end if; + -- An upload can succeed even if the client loses the PUT response. Resume + -- the existing object through start_uploaded_job's size validation. + select exists(select 1 from public.file_objects f join storage.objects o + on o.bucket_id=f.bucket and o.name=f.object_path + where f.job_id=j.job_id and f.kind='INPUT') into uploaded; + if j.status='UPLOADING' and not uploaded and t>=s.admitted_at+interval '45 minutes' then + return jsonb_build_object('allowed',false,'code','UPLOAD_WINDOW_EXPIRED','status',410); + end if; + return jsonb_build_object('allowed',true,'job_id',j.job_id,'status',j.status,'extension',j.source_extension,'upload_required',j.status='UPLOADING' and not uploaded, + 'object_path','jobs/'||j.job_id||'/input/source.'||j.source_extension); +end $$; + +-- Runs inside the existing durable claim transaction. Returning NULL skips +-- an expired/released work item, so the scheduler never dispatches its bytes. +create or replace function quota_private.start_work() returns trigger +language plpgsql security invoker set search_path='' as $$ +declare sid uuid; sh text; s quota_private.slots; p quota_private.policy; created timestamptz; t timestamptz; +begin + if new.status<>'RUNNING' or (tg_op='UPDATE' and old.status='RUNNING') then return new; end if; + select quota_slot_id,created_at into sid,created from public.jobs where job_id=new.job_id; + select * into strict p from quota_private.policy where singleton; + if sid is null then + if p.enabled and created>=p.activated_at then return null; end if; + return new; -- pre-activation recovery remains compatible + end if; + select subject_hash into sh from quota_private.slots where slot_id=sid; + if sh is null then return null; end if; + -- A claim can touch several subjects in queue order. Skip contention instead + -- of waiting while holding another subject or pool lock. + if not pg_try_advisory_xact_lock(hashtextextended('llmiser-quota:'||sh,0)) then return null; end if; + t:=clock_timestamp(); + select * into s from quota_private.slots where slot_id=sid; + if s.state='started' then return new; end if; + if s.state<>'reserved' or s.expires_at<=t then return null; end if; + update quota_private.slots set state='started',started_at=t where slot_id=sid; + return new; +end $$; +drop trigger if exists llmiser_quota_work on public.work_items; +create trigger llmiser_quota_work before insert or update of status on public.work_items +for each row execute function quota_private.start_work(); + +create or replace function public.release_quota_batch(p_subject_hash text,p_request_id uuid) returns integer +language plpgsql security invoker set search_path='' as $$ +declare n integer; +begin + perform pg_advisory_xact_lock(hashtextextended('llmiser-quota:'||p_subject_hash,0)); + update quota_private.slots set state='released' where subject_hash=p_subject_hash and request_id=p_request_id and state='reserved'; + get diagnostics n=row_count; + return n; +end $$; + +-- Bounded metadata cleanup; never deletes file objects or refunds started jobs. +create or replace function public.prune_quota_ledger() returns integer +language plpgsql security invoker set search_path='' as $$ +declare n integer; candidate record; +begin + for candidate in select distinct s.subject_hash from quota_private.slots s + left join public.jobs j on j.job_id=s.job_id + where s.state='reserved' and (s.expires_at<=clock_timestamp() or j.status in ('FAILED','CANCELLED','DELETED') or j.job_id is null) + order by s.subject_hash limit 200 loop + perform pg_advisory_xact_lock(hashtextextended('llmiser-quota:'||candidate.subject_hash,0)); + update quota_private.slots s set state=case when s.expires_at<=clock_timestamp() then 'expired' else 'released' end + where s.subject_hash=candidate.subject_hash and s.state='reserved' + and (s.expires_at<=clock_timestamp() or not exists(select 1 from public.jobs j where j.job_id=s.job_id and j.status not in ('FAILED','CANCELLED','DELETED'))); + end loop; + with stale as ( + select b.subject_hash,b.request_id from quota_private.batches b where b.admitted_at now(); + v_slots := least(greatest(p_limit, 0), greatest(p_capacity - v_inflight, 0)); + if v_slots = 0 then + return; + end if; + + return query + with ranked as ( + select w.work_item_id, + row_number() over (partition by w.job_id order by w.priority, w.sequence_index, w.created_at) as rn, + j.created_at as job_created + from public.work_items w + join public.jobs j on j.job_id = w.job_id + where w.pool = p_pool + and w.status = 'QUEUED' + and j.status in ('QUEUED','PROCESSING') + and ( + (j.quota_slot_id is null and (not (select enabled from quota_private.policy where singleton) + or j.created_at < (select activated_at from quota_private.policy where singleton))) + or exists (select 1 from quota_private.slots qs where qs.slot_id=j.quota_slot_id + and (qs.state='started' or (qs.state='reserved' and qs.expires_at>clock_timestamp()))) + ) + and (p_job_id is null or w.job_id = p_job_id) + ), + picked as ( + select w.work_item_id + from public.work_items w + join ranked r on r.work_item_id = w.work_item_id + order by r.rn, r.job_created, w.priority, w.sequence_index + limit v_slots + for update of w skip locked + ), + claimed as ( + update public.work_items w + set status = 'RUNNING', + attempt_count = w.attempt_count + 1, + claimed_at = now(), + lease_until = now() + p_lease, + error_code = null, + error_message = null + from picked p + where w.work_item_id = p.work_item_id + returning w.* + ), + -- Data-modifying CTEs run exactly once whether or not the final SELECT reads them. + touched as ( + update public.jobs j + set status = 'PROCESSING', + started_at = coalesce(j.started_at, now()) + where j.job_id in (select c.job_id from claimed c) + returning j.job_id + ), + nodes as ( + update public.content_nodes n + set status = 'PROCESSING' + from claimed c + where n.node_id = c.node_id and n.status = 'PENDING' + returning n.node_id + ) + select c.* from claimed c; +end; +$$; +commit; + commit; diff --git a/supabase/migrations/20261111000000_llmiser_guest_quota.sql b/supabase/migrations/20261111000000_llmiser_guest_quota.sql new file mode 100644 index 0000000..2a183d3 --- /dev/null +++ b/supabase/migrations/20261111000000_llmiser_guest_quota.sql @@ -0,0 +1,325 @@ +-- Apply before quota-aware frontend. Enforcement remains OFF until verified. +begin; +create schema if not exists quota_private; +revoke all on schema quota_private from public, anon, authenticated; +grant usage on schema quota_private to service_role; + +create table if not exists quota_private.policy ( + singleton boolean primary key default true check(singleton), + enabled boolean not null default false, + activated_at timestamptz, + guest_limit integer not null default 20 check(guest_limit between 1 and 100), + version integer not null default 1 check(version > 0) +); +insert into quota_private.policy(singleton) values(true) on conflict do nothing; +create or replace function quota_private.activate_policy() returns trigger +language plpgsql security invoker set search_path='' as $$ +begin + new.activated_at := old.activated_at; + if new.enabled and new.activated_at is null then new.activated_at := clock_timestamp(); end if; + return new; +end $$; +drop trigger if exists quota_activation on quota_private.policy; +create trigger quota_activation before update on quota_private.policy +for each row execute function quota_private.activate_policy(); + +create table if not exists quota_private.batches ( + subject_hash text not null check(subject_hash ~ '^[a-f0-9]{64}$'), + request_id uuid not null, + manifest_hash text not null check(manifest_hash ~ '^[a-f0-9]{64}$'), + admitted_at timestamptz not null, + primary key(subject_hash,request_id) +); +create table if not exists quota_private.slots ( + slot_id uuid primary key default gen_random_uuid(), + subject_hash text not null, + request_id uuid not null, + file_id uuid not null, + job_id uuid unique, + state text not null default 'reserved' check(state in ('reserved','started','released','expired')), + admitted_at timestamptz not null, + expires_at timestamptz not null, + started_at timestamptz, + unique(subject_hash,request_id,file_id), + foreign key(subject_hash,request_id) references quota_private.batches on delete cascade, + check ((state='started') = (started_at is not null)) +); +create index if not exists quota_subject_window on quota_private.slots(subject_hash,admitted_at); +create index if not exists quota_batch_expiry on quota_private.batches(admitted_at); +alter table public.jobs add column if not exists quota_slot_id uuid; +-- Deliberately no cascading job FK: deleting a result cannot refund usage. +alter table quota_private.policy enable row level security; +alter table quota_private.batches enable row level security; +alter table quota_private.slots enable row level security; +revoke all on all tables in schema quota_private from public,anon,authenticated; +grant select on quota_private.policy to service_role; +grant select,insert,update,delete on quota_private.batches,quota_private.slots to service_role; + +create or replace function public.quota_policy() returns jsonb +language sql security invoker set search_path='' as $$ + select jsonb_build_object('enabled',enabled,'limit',guest_limit,'windowHours',24,'policyVersion',version) + from quota_private.policy where singleton; +$$; + +create or replace function public.quota_snapshot(p_subject_hash text,p_requested integer default 1) returns jsonb +language plpgsql security invoker set search_path='' as $$ +declare p quota_private.policy; t timestamptz; used_n integer; reserved_n integer; n integer; + next_at timestamptz; fit_at timestamptz; +begin + if p_subject_hash is null or p_subject_hash !~ '^[a-f0-9]{64}$' or p_requested not between 1 and 20 then raise exception 'invalid quota request'; end if; + perform pg_advisory_xact_lock(hashtextextended('llmiser-quota:'||p_subject_hash,0)); + t:=clock_timestamp(); + select * into strict p from quota_private.policy where singleton; + select count(*) filter(where state='started'),count(*) filter(where state='reserved') into used_n,reserved_n + from quota_private.slots where subject_hash=p_subject_hash and admitted_at>t-interval '24 hours' + and (state='started' or (state='reserved' and expires_at>t)); + n:=used_n+reserved_n; + with releases as ( + select case when state='started' then admitted_at+interval '24 hours' else least(expires_at,admitted_at+interval '24 hours') end as at + from quota_private.slots where subject_hash=p_subject_hash and admitted_at>t-interval '24 hours' + and (state='started' or (state='reserved' and expires_at>t)) + ), ordered as (select at,row_number() over(order by at) as rn from releases) + select min(at),min(at) filter(where rn=greatest(1,n+p_requested-p.guest_limit)) into next_at,fit_at from ordered; + return jsonb_build_object('enabled',p.enabled,'tier','guest','limit',p.guest_limit,'used',used_n,'reserved',reserved_n, + 'remaining',greatest(0,p.guest_limit-n),'windowHours',24,'requested',p_requested, + 'nextSlotAvailableAt',next_at,'requestedAvailableAt',case when n+p_requested<=p.guest_limit then t else fit_at end, + 'serverTime',t,'policyVersion',p.version); +end $$; + +-- All legacy job creators must pass through a slot when policy is enabled. +create or replace function quota_private.bind_job() returns trigger +language plpgsql security invoker set search_path='' as $$ +declare sid uuid; s quota_private.slots; +begin + sid:=nullif(current_setting('llmiser.quota_slot',true),'')::uuid; + if sid is null and not (select enabled from quota_private.policy where singleton) then return new; end if; + select * into s from quota_private.slots where slot_id=sid; + if s.slot_id is null or s.job_id is not null or s.state<>'reserved' or s.expires_at<=clock_timestamp() then + raise exception using errcode='PT428',message='QUOTA_RESERVATION_REQUIRED'; + end if; + new.quota_slot_id:=sid; + return new; +end $$; +drop trigger if exists llmiser_quota_job on public.jobs; +create trigger llmiser_quota_job before insert on public.jobs for each row execute function quota_private.bind_job(); + +create or replace function public.reserve_quota_batch(p_subject_hash text,p_request_id uuid,p_files jsonb,p_bucket text,p_budget_bytes bigint default 838860800) +returns jsonb language plpgsql security invoker set search_path='' as $$ +declare snap jsonb; b quota_private.batches; f jsonb; sid uuid; job jsonb; result jsonb; t timestamptz; +begin + if p_request_id is null or jsonb_typeof(p_files) is distinct from 'array' then raise exception 'invalid quota manifest'; end if; + if jsonb_array_length(p_files) not between 1 and 20 then raise exception 'invalid quota batch size'; end if; + if (select count(distinct value->>'file_id') from jsonb_array_elements(p_files))<>jsonb_array_length(p_files) then raise exception 'duplicate file IDs'; end if; + snap:=public.quota_snapshot(p_subject_hash,jsonb_array_length(p_files)); + if not (snap->>'enabled')::boolean then return jsonb_build_object('enabled',false); end if; + select * into b from quota_private.batches where subject_hash=p_subject_hash and request_id=p_request_id; + if found then + if b.manifest_hash<>encode(sha256(convert_to(p_files::text,'UTF8')),'hex') then return jsonb_build_object('allowed',false,'code','IDEMPOTENCY_CONFLICT','status',409); end if; + if exists(select 1 from quota_private.slots where subject_hash=p_subject_hash and request_id=p_request_id + and (state in ('expired','released') or (state='reserved' and expires_at<=clock_timestamp()))) then + return jsonb_build_object('allowed',false,'code','QUOTA_RESERVATION_EXPIRED','status',410); + end if; + else + if (snap->>'remaining')::integer>'file_id')::uuid,t,t+interval '3 hours') returning slot_id into sid; + perform set_config('llmiser.quota_slot',sid::text,true); + job:=public.create_reserved_upload_job(p_bucket,f->>'filename',f->>'extension',(f->>'size')::bigint, + f->>'content_type',f->>'profile',f->>'source_type',f->>'workload_type',p_budget_bytes); + if (job->>'allowed')::boolean is distinct from true then + raise exception using errcode='PT503',message='BATCH_CAPACITY'; + end if; + update quota_private.slots set job_id=(job->>'job_id')::uuid where slot_id=sid; + end loop; + perform set_config('llmiser.quota_slot','',true); + end if; + select jsonb_agg(jsonb_build_object('file_id',file_id,'job_id',job_id) order by file_id) into result + from quota_private.slots where subject_hash=p_subject_hash and request_id=p_request_id; + return jsonb_build_object('enabled',true,'allowed',true,'request_id',p_request_id,'files',result,'quota',public.quota_snapshot(p_subject_hash)); +exception when sqlstate 'PT503' then + -- The entire subtransaction (all new jobs/slots) rolls back, never a partial batch. + return jsonb_build_object('allowed',false,'code','BATCH_CAPACITY','status',503); +end $$; + +-- A slot authorizes exactly one job. Re-signing after 45 minutes is prohibited: +-- the original three-hour byte guard must outlive every two-hour upload URL. +create or replace function public.quota_upload(p_subject_hash text,p_request_id uuid,p_file_id uuid) returns jsonb +language plpgsql security invoker set search_path='' as $$ +declare s quota_private.slots; j public.jobs; t timestamptz; uploaded boolean; +begin + perform pg_advisory_xact_lock(hashtextextended('llmiser-quota:'||p_subject_hash,0)); + t:=clock_timestamp(); + select * into s from quota_private.slots where subject_hash=p_subject_hash and request_id=p_request_id and file_id=p_file_id; + if s.slot_id is null then return jsonb_build_object('allowed',false,'code','QUOTA_RESERVATION_REQUIRED','status',428); end if; + if s.state in ('released','expired') or (s.state='reserved' and s.expires_at<=t) then + return jsonb_build_object('allowed',false,'code','QUOTA_RESERVATION_EXPIRED','status',410); + end if; + select * into j from public.jobs where job_id=s.job_id; + if j.job_id is null or j.files_deleted_at is not null then return jsonb_build_object('allowed',false,'code','RESULT_EXPIRED','status',410); end if; + -- An upload can succeed even if the client loses the PUT response. Resume + -- the existing object through start_uploaded_job's size validation. + select exists(select 1 from public.file_objects f join storage.objects o + on o.bucket_id=f.bucket and o.name=f.object_path + where f.job_id=j.job_id and f.kind='INPUT') into uploaded; + if j.status='UPLOADING' and not uploaded and t>=s.admitted_at+interval '45 minutes' then + return jsonb_build_object('allowed',false,'code','UPLOAD_WINDOW_EXPIRED','status',410); + end if; + return jsonb_build_object('allowed',true,'job_id',j.job_id,'status',j.status,'extension',j.source_extension,'upload_required',j.status='UPLOADING' and not uploaded, + 'object_path','jobs/'||j.job_id||'/input/source.'||j.source_extension); +end $$; + +-- Runs inside the existing durable claim transaction. Returning NULL skips +-- an expired/released work item, so the scheduler never dispatches its bytes. +create or replace function quota_private.start_work() returns trigger +language plpgsql security invoker set search_path='' as $$ +declare sid uuid; sh text; s quota_private.slots; p quota_private.policy; created timestamptz; t timestamptz; +begin + if new.status<>'RUNNING' or (tg_op='UPDATE' and old.status='RUNNING') then return new; end if; + select quota_slot_id,created_at into sid,created from public.jobs where job_id=new.job_id; + select * into strict p from quota_private.policy where singleton; + if sid is null then + if p.enabled and created>=p.activated_at then return null; end if; + return new; -- pre-activation recovery remains compatible + end if; + select subject_hash into sh from quota_private.slots where slot_id=sid; + if sh is null then return null; end if; + -- A claim can touch several subjects in queue order. Skip contention instead + -- of waiting while holding another subject or pool lock. + if not pg_try_advisory_xact_lock(hashtextextended('llmiser-quota:'||sh,0)) then return null; end if; + t:=clock_timestamp(); + select * into s from quota_private.slots where slot_id=sid; + if s.state='started' then return new; end if; + if s.state<>'reserved' or s.expires_at<=t then return null; end if; + update quota_private.slots set state='started',started_at=t where slot_id=sid; + return new; +end $$; +drop trigger if exists llmiser_quota_work on public.work_items; +create trigger llmiser_quota_work before insert or update of status on public.work_items +for each row execute function quota_private.start_work(); + +create or replace function public.release_quota_batch(p_subject_hash text,p_request_id uuid) returns integer +language plpgsql security invoker set search_path='' as $$ +declare n integer; +begin + perform pg_advisory_xact_lock(hashtextextended('llmiser-quota:'||p_subject_hash,0)); + update quota_private.slots set state='released' where subject_hash=p_subject_hash and request_id=p_request_id and state='reserved'; + get diagnostics n=row_count; + return n; +end $$; + +-- Bounded metadata cleanup; never deletes file objects or refunds started jobs. +create or replace function public.prune_quota_ledger() returns integer +language plpgsql security invoker set search_path='' as $$ +declare n integer; candidate record; +begin + for candidate in select distinct s.subject_hash from quota_private.slots s + left join public.jobs j on j.job_id=s.job_id + where s.state='reserved' and (s.expires_at<=clock_timestamp() or j.status in ('FAILED','CANCELLED','DELETED') or j.job_id is null) + order by s.subject_hash limit 200 loop + perform pg_advisory_xact_lock(hashtextextended('llmiser-quota:'||candidate.subject_hash,0)); + update quota_private.slots s set state=case when s.expires_at<=clock_timestamp() then 'expired' else 'released' end + where s.subject_hash=candidate.subject_hash and s.state='reserved' + and (s.expires_at<=clock_timestamp() or not exists(select 1 from public.jobs j where j.job_id=s.job_id and j.status not in ('FAILED','CANCELLED','DELETED'))); + end loop; + with stale as ( + select b.subject_hash,b.request_id from quota_private.batches b where b.admitted_at now(); + v_slots := least(greatest(p_limit, 0), greatest(p_capacity - v_inflight, 0)); + if v_slots = 0 then + return; + end if; + + return query + with ranked as ( + select w.work_item_id, + row_number() over (partition by w.job_id order by w.priority, w.sequence_index, w.created_at) as rn, + j.created_at as job_created + from public.work_items w + join public.jobs j on j.job_id = w.job_id + where w.pool = p_pool + and w.status = 'QUEUED' + and j.status in ('QUEUED','PROCESSING') + and ( + (j.quota_slot_id is null and (not (select enabled from quota_private.policy where singleton) + or j.created_at < (select activated_at from quota_private.policy where singleton))) + or exists (select 1 from quota_private.slots qs where qs.slot_id=j.quota_slot_id + and (qs.state='started' or (qs.state='reserved' and qs.expires_at>clock_timestamp()))) + ) + and (p_job_id is null or w.job_id = p_job_id) + ), + picked as ( + select w.work_item_id + from public.work_items w + join ranked r on r.work_item_id = w.work_item_id + order by r.rn, r.job_created, w.priority, w.sequence_index + limit v_slots + for update of w skip locked + ), + claimed as ( + update public.work_items w + set status = 'RUNNING', + attempt_count = w.attempt_count + 1, + claimed_at = now(), + lease_until = now() + p_lease, + error_code = null, + error_message = null + from picked p + where w.work_item_id = p.work_item_id + returning w.* + ), + -- Data-modifying CTEs run exactly once whether or not the final SELECT reads them. + touched as ( + update public.jobs j + set status = 'PROCESSING', + started_at = coalesce(j.started_at, now()) + where j.job_id in (select c.job_id from claimed c) + returning j.job_id + ), + nodes as ( + update public.content_nodes n + set status = 'PROCESSING' + from claimed c + where n.node_id = c.node_id and n.status = 'PENDING' + returning n.node_id + ) + select c.* from claimed c; +end; +$$; +commit; diff --git a/tests/integration/postgres_quota.mjs b/tests/integration/postgres_quota.mjs new file mode 100644 index 0000000..e46560d --- /dev/null +++ b/tests/integration/postgres_quota.mjs @@ -0,0 +1,42 @@ +// Run after postgres_recovery.mjs against its disposable localhost CI database. +import { execFile } from 'node:child_process'; +import { promisify } from 'node:util'; +import { randomUUID } from 'node:crypto'; +import assert from 'node:assert/strict'; +if (process.env.PGDATABASE !== 'mdify_ci' || !['127.0.0.1','localhost'].includes(process.env.PGHOST)) throw new Error('Requires disposable mdify_ci on localhost'); +const run = promisify(execFile); +const sql = async s => (await run('psql',['--no-psqlrc','-v','ON_ERROR_STOP=1','-At','-c',s],{timeout:30_000})).stdout.trim(); +const subject='c'.repeat(64); +const files=n=>Array.from({length:n},(_,i)=>({file_id:randomUUID(),filename:`quota-${i}.txt`,extension:'txt',size:12,profile:'standard',source_type:'DOCUMENT',workload_type:'NORMAL'})); +const reserve=(manifest,id=randomUUID())=>sql(`select public.reserve_quota_batch('${subject}','${id}','${JSON.stringify(manifest)}','mdify-pro-files')`).then(JSON.parse); +const snapshot=()=>sql(`select public.quota_snapshot('${subject}')`).then(JSON.parse); +const reset=()=>sql('truncate public.jobs cascade; truncate public.job_storage_reservations; truncate quota_private.batches cascade; update quota_private.policy set enabled=true;'); +await reset(); +const racing=await Promise.all(Array.from({length:10},()=>reserve(files(3)))); +assert.equal(racing.filter(r=>r.allowed).length,6); +assert.equal((await snapshot()).reserved,18); +const last=await Promise.all(Array.from({length:10},()=>reserve(files(1)))); +assert.equal(last.filter(r=>r.allowed).length,2); +assert.equal((await snapshot()).remaining,0); +assert.equal(await sql('select count(*) from public.jobs'),'20'); +console.log('PostgreSQL quota: parallel batches and last-slot races never exceed 20.'); +await reset(); +const manifest=files(2), id=randomUUID(); +const replay=await Promise.all(Array.from({length:10},()=>reserve(manifest,id))); +for(const result of replay) assert.deepEqual(result.files,replay[0].files); +assert.equal(await sql('select count(*) from public.jobs'),'2'); +assert.equal((await reserve(files(2),id)).code,'IDEMPOTENCY_CONFLICT'); +console.log('PostgreSQL quota: concurrent identical replays create two jobs once.'); +await reset(); +const raceId=randomUUID(); +const admitted=await reserve(files(1),raceId); +const job=admitted.files[0].job_id; +await sql(`select public.start_uploaded_job('${job}','mdify-pro-files',12)`); +const [claimed,released]=await Promise.all([ + sql(`select count(*) from public.claim_work_items('normal',4,1,'${job}')`), + sql(`select public.release_quota_batch('${subject}','${raceId}')`), +]); +assert.equal(Number(claimed)+Number(released),1); +assert.equal((await snapshot()).used,Number(claimed)); +console.log('PostgreSQL quota: first claim versus release has exactly one winner.'); +await sql('update quota_private.policy set enabled=false'); From 50616d62c05800db48f270ef05ce43947198cbce Mon Sep 17 00:00:00 2001 From: DevBehindYou Date: Thu, 12 Nov 2026 23:17:44 +0530 Subject: [PATCH 2/2] fix: retry throttled extension quota uploads --- docs/quota/IMPLEMENTATION_STATUS.md | 7 +++--- extension/src/uploads.js | 15 ++++++++----- extension/test/uploads.test.mjs | 28 ++++++++++++++++++++++++ frontend/lib/models/conversionService.js | 19 ++++++++++------ 4 files changed, 53 insertions(+), 16 deletions(-) diff --git a/docs/quota/IMPLEMENTATION_STATUS.md b/docs/quota/IMPLEMENTATION_STATUS.md index 2468908..503227f 100644 --- a/docs/quota/IMPLEMENTATION_STATUS.md +++ b/docs/quota/IMPLEMENTATION_STATUS.md @@ -5,9 +5,10 @@ | Stage | Evidence | | --- | --- | | Local implementation | Database policy defaults disabled. Guest limit is 20 top-level files per rolling 24 hours. | -| Local extension checks | 30 tests passed. The extension built and passed package checks. | -| Database concurrency | Multi-connection PostgreSQL tests are wired into GitHub CI. | -| Native Chrome and live Storage | Staging acceptance still required for cookie sharing and real signed uploads. | +| Local extension checks | 31 tests passed. The extension built and passed package checks. | +| Database concurrency | Multi-connection PostgreSQL CI verified parallel batches, last-slot races, idempotent replay and claim-versus-release. | +| Native Chromium | A disposable browser profile with a native extension context and loopback fixtures verified shared guest identity in both bootstrap orders, missing-cookie rejection, batch rejection, the 21st-file denial, idempotent upload replay and download after exhaustion. A 20-file batch initially exposed a short-term request throttle. After the retry fix, all 20 files completed and the quota showed 20 used and zero reserved. | +| Hosted Storage | Staging acceptance still required with hosted Supabase Storage and the target Chrome configuration. The browser fixture used the app handlers and SQL migrations with simulated Storage signing and conversion workers. | | Production | Migration, deployment and policy activation pending. | The next release step is staging validation with the migration installed and the quota-aware web app and extension pointed at the same test environment. Follow [the rollout runbook](ROLLOUT.md). Account authentication and Resend are a [separate design milestone](FUTURE_AUTH_RESEND.md). diff --git a/extension/src/uploads.js b/extension/src/uploads.js index b9c0224..2d6ca84 100644 --- a/extension/src/uploads.js +++ b/extension/src/uploads.js @@ -1,4 +1,4 @@ -import { startUploadedJob, waitForJob, fetchResultMarkdown } from '../../frontend/lib/models/conversionService.js'; +import { startUploadedJob, waitForJob, fetchResultMarkdown, retryReservedUpload } from '../../frontend/lib/models/conversionService.js'; import { PROFILES, validateUpload } from '../../frontend/lib/formats.js'; import { MAX_MARKDOWN, pendingJobRecord } from './model.js'; import { prepareUploads, readQuota } from '../../frontend/lib/models/quotaClient.js'; @@ -75,11 +75,14 @@ async function runConversion(file, profile, { signal, onProgress, onCheckpoint, }; let job = resumeJob ? { job_id: resumeJob.jobId } : null; if (!resumeJob) { - const created = await send(`${APP_ORIGIN}/api/uploads/create`, { - method: 'POST', headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ filename: file.name, size: file.size, content_type: file.type || null, profile, ...reservation }), - }); - job = await created.json().catch(() => ({})); + const { res: created, data } = await retryReservedUpload(async () => { + const res = await send(`${APP_ORIGIN}/api/uploads/create`, { + method: 'POST', headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ filename: file.name, size: file.size, content_type: file.type || null, profile, ...reservation }), + }); + return { res, data: await res.json().catch(() => ({})) }; + }, { reservation, signal, sleepImpl, onWait: () => onProgress?.('Waiting for upload capacity…') }); + job = data; if (!created.ok) throw new Error(String(job.detail || `Could not start upload (${created.status}).`).slice(0, 400)); if (!UUID.test(job.job_id || '')) throw new Error('The converter returned an invalid job. Please retry.'); if (job.upload_url) { diff --git a/extension/test/uploads.test.mjs b/extension/test/uploads.test.mjs index 88291a9..006a89d 100644 --- a/extension/test/uploads.test.mjs +++ b/extension/test/uploads.test.mjs @@ -43,6 +43,34 @@ test('invalid files and profiles make no requests; failed admission sends no byt await assert.rejects(convertUpload(file(),'Standard',{fetchImpl}),/Busy/);assert.equal(requests,1); }); +test('a reserved upload waits for short-term capacity and replays the same slot', async () => { + const reservation = { request_id: crypto.randomUUID(), file_id: crypto.randomUUID(), job_id: id }; + const attempts = [], waits = []; + let uploads = 0; + const result = await convertUpload(file(), 'Standard', { + reservation, + sleepImpl: async ms => { waits.push(ms); }, + fetchImpl: async (url, init) => { + if (url.endsWith('/api/uploads/create')) { + attempts.push(JSON.parse(init.body)); + if (attempts.length === 1) return Response.json({ detail: 'Wait' }, { status: 429, headers: { 'Retry-After': '6' } }); + return json({ job_id: id, upload_url: upload }, 201); + } + if (url === upload) { uploads++; return json({}); } + if (url.endsWith('/start')) return json({ status: 'COMPLETED', source_type: 'DOCUMENT', result: { download_url: output } }); + assert.equal(url, output); + return new Response('# Converted'); + }, + }); + assert.deepEqual(waits, [6000]); + assert.equal(attempts.length, 2); + assert.deepEqual(attempts[0], attempts[1]); + assert.equal(attempts[1].request_id, reservation.request_id); + assert.equal(attempts[1].file_id, reservation.file_id); + assert.equal(uploads, 1); + assert.equal(result.markdown, '# Converted'); +}); + test('archive parts are fetched in order',async()=>{ const first=signed('sign')+'output/project-part-001.md?token=test-only'; const second=signed('sign')+'output/project-part-002.md?token=test-only'; diff --git a/frontend/lib/models/conversionService.js b/frontend/lib/models/conversionService.js index 0c197d4..8e3b122 100644 --- a/frontend/lib/models/conversionService.js +++ b/frontend/lib/models/conversionService.js @@ -86,17 +86,12 @@ const failure = (res, data) => let storageAvailable = null; async function convertViaStorage(file, profile, signal, onProgress, onResultReady, reservation) { - let created, job; - for (let attempt = 0; ; attempt++) { - ({ res: created, data: job } = await request('/api/uploads/create', { + const { res: created, data: job } = await retryReservedUpload(() => request('/api/uploads/create', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ filename: file.name, size: file.size, content_type: file.type || null, profile, ...reservation }), signal, - })); - if (!reservation || ![429, 503].includes(created.status) || job.code === 'DAILY_FILE_LIMIT' || attempt >= 3) break; - await sleep(retryDelay(created, 1000), signal); - } + }), { reservation, signal }); if (created.status === 501) { storageAvailable = false; return null; @@ -183,6 +178,16 @@ function retryDelay(res, fallback) { return Math.max(fallback, Math.min(330, seconds) * 1000); } +/** A reserved upload can safely replay signing without creating a second job. */ +export async function retryReservedUpload(send, { reservation, signal, sleepImpl = sleep, onWait } = {}) { + for (let attempt = 0; ; attempt++) { + const result = await send(); + if (!reservation || ![429, 503].includes(result.res.status) || result.data.code === 'DAILY_FILE_LIMIT' || attempt >= 3) return result; + onWait?.(); + await sleepImpl(retryDelay(result.res, 1000), signal); + } +} + /** Retry an already uploaded job's idempotent start without uploading again. */ export async function startUploadedJob(jobId, { signal, fetchImpl = fetch, sleepImpl = sleep, now = Date.now } = {}) { const deadline = now() + JOB_WAIT_LIMIT_MS;