Skip to content

paperless: Add native Paperless-ngx attachment filing - #6

Open
marcodejongh wants to merge 8 commits into
mainfrom
feat/paperless-attachments
Open

marcodejongh wants to merge 8 commits into
mainfrom
feat/paperless-attachments

Conversation

@marcodejongh

@marcodejongh marcodejongh commented Oct 4, 2026 •

Copy link
Copy Markdown
Owner

Add Paperless-ngx as an attachment filing destination for each mailbox. Users can save attachments manually or use automatic save/skip decisions, while Paperless handles document organization and consumption.

  • Connect an instance with an encrypted API token and choose Paperless or the existing cloud destination. Cloud folder setup selects only connected Google/Microsoft drives. Public HTTPS is the default, with an explicit trusted-LAN opt-in for self-hosting.
  • Upload original attachment bytes, persist accepted tasks, and show processing, confirmation, completion links, and actionable errors. Reconcile tasks once per minute; uncertain upload outcomes require review before a user retries. Instance changes and upload-start claims share a short database lock to prevent cross-instance task races.
  • Add account-scoped actions, native save/skip confirmations and notifications, a save/skip AI prompt, migration, deployment cron configuration, and a setup guide. Retry preserves notification intent and protects existing cloud files in both manual and automatic paths. Email and messaging completion delivery retry independently, with persisted per-channel delivery receipts and a renewable owned reconciliation lease. Preview excludes unsupported Paperless files before applying its three-file limit. API responses are streamed with a 1 MiB limit.

Validation:

  • 119 focused tests passed across 13 files, including real PostgreSQL token encryption, concurrent saves, persisted messaging receipts, overlapping cron sweeps, lease renewal/recovery, HTTP uploads, independent email/messaging retries, supported-file previews, and existing cloud filing notifications/replies.
  • All 295 migrations applied to a fresh isolated database; Prisma generation, changed-file TypeScript, and Biome checks passed.
  • Independent subagent review completed; all findings were fixed and verified with regression tests.
  • Paperless browser scenarios passed on earlier PR heads, including cloud folder creation after connecting Paperless, saving while paused, confirmation before upload, and consumed-document links. Processing, saved, and confirmation screenshots were inspected. All 35 CI checks passed on final review-fix head e616632b5.
  • Live AI evals were skipped because provider credentials were unavailable. All six earlier automated review findings were fixed and answered; fresh automated reviews are unavailable because the review service reported a usage limit.

Runtime: automatic Paperless filing adds document extraction, one AI selection, and one upload per selected attachment. Manual saves bypass AI. Database locks cover short state transitions, with network requests outside the transactions. Cron reconciles at most ten records per invocation, with three concurrent workers and one lease renewal write every 30 seconds per active worker; the activity UI polls every five seconds while processing. Existing cloud filing remains the default.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 4, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-04T04:50:35.958945Z e0de4a9 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: d32b2295b2

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread apps/web/utils/paperless/connections.ts Outdated
create: {
emailAccountId,
email: emailAccount.email,
provider: "paperless",

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Keep Paperless out of cloud connection selection

When a cloud-filing user connects Paperless without selecting it as the destination, this newly created connection is normally first in /api/user/drive/connections because that route orders by createdAt DESC. AllowedFolders.tsx:70 and DriveSetup.tsx:92,707 assume connections[0] is a Google or Microsoft drive, so they pass the Paperless connection ID to cloud folder creation; createDriveProviderWithRefresh then rejects it because it has no cloud refresh token. This can block cloud setup—especially for an empty drive where creating the first folder is required—so cloud consumers must filter to Google/Microsoft connections rather than selecting the first shared connection.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 9eeeb82: DriveSetup filters to connected Google/Microsoft connections before selecting the default, and AllowedFolders applies the same restriction. Added browser coverage that connects Paperless, keeps Cloud drives selected, and successfully creates a cloud folder before switching to Paperless. Changed-file TypeScript and Biome checks pass; CI is validating the browser regression.

@marcodejongh

Copy link
Copy Markdown
Owner Author

@chatgpt-codex-connector[bot] — addressing the review summarized at #6 (comment): cloud setup and allowed-folder creation now select only connected Google or Microsoft drives. The Paperless browser scenarios also create a cloud folder after connecting Paperless and before switching destinations. Changed-file TypeScript and Biome checks pass; CI will exercise the added browser regression.

@chatgpt-codex-connector

Copy link
Copy Markdown

To use Codex here, create an environment for this repo.

@marcodejongh

Copy link
Copy Markdown
Owner Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 9eeeb82ace

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread apps/web/utils/paperless/connections.ts Outdated
Comment on lines +24 to +28
OR: [
{ status: "PROCESSING" },
{ status: "PENDING" },
{ status: "ERROR", paperlessUploadStartedAt: { not: null } },
],

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Exclude resolved failures from the URL-change blocker

When Paperless reports a consumption failure, reconciliation sets the filing to ERROR but retains paperlessUploadStartedAt, so this predicate counts that row forever. Because the error UI only offers retry and disconnecting Paperless preserves the filing, a document the old instance cannot consume—or an unavailable old instance—can permanently prevent the user from connecting a different Paperless URL. Only genuinely in-flight or unknown-outcome uploads should block an instance change, or users need a way to discard the failed filing.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in e0de4a9: a confirmed consumption failure clears the upload-in-flight marker while retaining the task ID and error history. Such resolved failures no longer match the URL-change blocker. Processing tasks and genuinely unknown upload outcomes still require review before changing instances. The focused reconciliation regression, Paperless tests, TypeScript, and Biome checks pass.

Comment on lines +71 to +79
if (
manual &&
existing &&
existing.driveConnection.provider !== "paperless"
) {
return {
success: false,
error: "This attachment was already filed to a cloud drive.",
};

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Allow manual saves after a prior cloud skip

If this attachment previously produced a cloud PREVIEW, PENDING, REJECTED, or ERROR record and the user later switches the mailbox to Paperless, the new Save to Paperless button always hits this provider guard and reports that the attachment was already filed, even though those states have no successfully uploaded cloud file. The unique filing key means every later attempt finds the same row, so manual saving remains permanently blocked; reserve this rejection for an actually FILED cloud record and reclaim other non-filed states for Paperless.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in e0de4a9: manual Paperless saves can atomically reclaim cloud PREVIEW, PENDING, REJECTED, and ERROR records with no uploaded file. A conditional claim checks the original status, timestamp, provider, and empty file ID before changing destinations; existing cloud files and PROCESSING/FILED records remain protected. Regressions cover all four reclaimable states, both protected states, and an ERROR record with a cloud file ID. The focused tests, TypeScript, and Biome checks pass.

@marcodejongh

Copy link
Copy Markdown
Owner Author

@chatgpt-codex-connector[bot] — the review summarized at #6 (comment) is addressed in e0de4a9. Confirmed consumption failures release the URL-change block, and manual Paperless saves can reclaim prior cloud skips/decisions/errors while protecting saved files and active cloud uploads. Focused regressions, TypeScript, and Biome checks pass.

The environment guidance at #6 (comment) is acknowledged; this PR has received a completed automated review and the findings have been answered.

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: e0de4a9d73

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +20 to +21
if (existing && existing.baseUrl !== url) {
const pending = await prisma.documentFiling.count({

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Make URL changes atomic with upload claims

When auto-filing starts after this count but before the later upsert—a window enlarged by the two validation requests—it can upload using the old in-memory connection and persist that instance's task ID after the connection row has changed to the new URL. Reconciliation then queries the new instance for the old task, loses track of the accepted upload, and a retry can create a second copy. Fresh evidence in the final revision is that the pending check and URL update remain separated by validateConnection(), so changing the URL must be mutually exclusive with starting an upload.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 5239095: connection upserts and upload-start claims share a mailbox-scoped PostgreSQL advisory lock in static transactions. The upsert rechecks unresolved filings under that lock, and upload claims verify the cached instance URL before POST. Real database regressions cover an accepted upload arriving during URL validation, stale cached connections after a URL change, and concurrent saves. No network operation runs under the database lock; all 99 focused tests, TypeScript, and Biome checks pass.

Comment thread apps/web/utils/paperless/filing.ts Outdated
? "PENDING"
: "PROCESSING",
wasAsked: shouldAsk,
paperlessNotifyOnCompletion: !manual || !!existing?.wasAsked,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve completion notifications across retries

When an automatically selected, high-confidence filing fails and the user clicks Retry, the retry invokes this path with manual=true and existing.wasAsked=false, so this assignment clears the prior completion-notification intent. If the retry later succeeds, reconciliation marks it filed without sending the configured email or messaging notification. Preserve the existing paperlessNotifyOnCompletion value for retries rather than deriving it only from manual and wasAsked.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 5239095: filing lookup includes the completion-notification intent, manual retries preserve it, and confirmed consumption failures retain it for a later retry. A focused regression covers a high-confidence automatic filing retried manually without wasAsked. All 99 focused tests, TypeScript, and Biome checks pass.

Comment thread apps/web/utils/paperless/client.ts Outdated
Comment on lines +178 to +180
private async readJson(response: Awaited<ReturnType<typeof fetchPaperless>>) {
try {
return await response.json();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Bound Paperless response bodies before parsing

An authenticated user can configure a public endpoint they control and have it return an arbitrarily large body; response.json() buffers the entire response before Zod validation, so the 15-second timeout does not prevent a fast response from exhausting server memory. Apply a small byte limit while reading the documents, tasks, and upload responses, rejecting oversized bodies before materializing them.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 5239095: Paperless JSON responses are streamed with a 1 MiB limit, oversized declared lengths are rejected before reading, and oversized streams are cancelled before parsing. The shared parser covers connection validation, tasks, and upload responses. Regressions cover declared/undeclared oversized bodies and stream cancellation; all 99 focused tests, TypeScript, and Biome checks pass.

@marcodejongh

Copy link
Copy Markdown
Owner Author

@chatgpt-codex-connector[bot] — all findings in the review summarized at #6 (comment) are addressed in 5239095. Upload-start claims and instance changes now share a database lock and recheck instance/filing state; retries retain notification intent; API responses have a streamed 1 MiB limit. All 99 focused tests passed, including real Postgres race/concurrency tests, with TypeScript and Biome checks passing.

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

@marcodejongh

Copy link
Copy Markdown
Owner Author

@chatgpt-codex-connector[bot] — acknowledging the review usage-limit notice at #6 (comment). All six earlier code findings have been fixed, validated, and answered. On 5239095, CI has 35 passing checks and 9 skipped checks; all 99 focused local regressions, changed-file TypeScript, and Biome checks passed. Account credits and settings have not been changed.

@chatgpt-codex-connector

Copy link
Copy Markdown

To use Codex here, create an environment for this repo.

@marcodejongh

Copy link
Copy Markdown
Owner Author

Acknowledged the informational environment-setup notice from chatgpt-codex-connector[bot] at #6 (comment). The final automated-review limitation is already recorded in the PR description. All prior code findings have been fixed and answered, and CI remains green on 5239095.

@imulator

Copy link
Copy Markdown

I saw your recent PR adding JMAP support to Inbox Zero. It's a shame it wasn't merged! Was long-term maintenance really the main concern, or were there other reasons? JMAP support would have been a great addition.

Integrating Paperless-ngx with Inbox Zero is also going to be a huge time-saver.

One security consideration regarding PAPERLESS_ALLOW_PRIVATE_IPS=true:

Would it make sense to introduce an explicit hostname or origin allowlist, such as PAPERLESS_ALLOWED_HOSTS, rather than broadly permitting private IPs?

This would preserve support for self-hosted Paperless instances running over Docker networks, LANs, or WireGuard while restricting outbound requests to operator-approved destinations.

It would also help reduce the potential SSRF attack surface, particularly in multi-user deployments.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants