Skip to content

feat(collections): manage personal collections through v2 - #386

Merged
Quick104 merged 6 commits into
mainfrom
apiv2-stack/38-personal-collections-v2
Sep 23, 2026
Merged

Quick104 merged 6 commits into
mainfrom
apiv2-stack/38-personal-collections-v2

Conversation

@Quick104

@Quick104 Quick104 commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Problem

The personal Collections screen still used /api/v1/collections for every action: list, create, move to a group, delete, and group create, rename and delete. The collection detail grid read /api/v1/collections/{id}/items once, with offset=0&limit=200, so a collection with more than 200 items was cut off. A 1.0 server answers all of these with 410.

v2 changes the write contract. Collection and group edits need an If-Match taken from a fresh read of that collection or group. A stale tag gets 412 stale_version, and a missing tag gets 428. Stores without group support (SQLite user stores) answer every group operation with 501 capability_unsupported, yet the screen showed group controls on those stores too.

Inventory rows: 69, 70, 72, 73, 74, 75, 76, 77.

Solution

  • Reads. SiloAPI.collections() reads GET /api/v2/collections ({items, groups}). The call fails if the list says more items follow, so a cut-off list is never shown as complete. collectionItems(collectionId:) reads the display cards from GET /api/v2/catalog?source=user_collection&collection_id=…. It follows the opaque cursor pages under the first page's owner, stops at 100 pages, and sends the tvOS image size. Both reads are dropped if the owner changes before they return.
  • Editors (rows 73, 74, 76, 77). Opening a Move, Rename group, Delete group or Delete collection sheet reads the canonical GET /api/v2/collections/{id} or /collections/groups/{id}. The client keeps the read's strong ETag and refuses a missing or weak one. The write sends that tag as If-Match under the owner that made the read. Swipe-to-delete used to delete immediately; it now opens a confirmation sheet, because the delete needs that read first. Move uses PATCH and sends an explicit group_id: null for Ungrouped. Group rename uses PATCH. Both deletes require exactly 204.
  • Creates (rows 72, 75). POST /api/v2/collections (collection_type: manual) and POST /api/v2/collections/groups (name only) require 201. Each is sent once.
  • Groups capability. GET /api/v2/collections/capabilities gates the group controls: the new-group button, the section header menu, and the Move swipe. They show only when the response has allowed, state == available and groups. If the capability read fails, the controls stay hidden and the page shows "Collection groups couldn't be checked." with Retry. The failure is not treated as "unsupported", so audit F48 (fail-closed) does not carry over. An earlier definite answer survives a later failed refresh. A 501 from any group operation hides the controls.
  • Sheet-scoped outcomes. Each write records which sheet started it. If the user dismisses a sheet while its write is in flight, a success still updates the list, but the answer never shows an error in, locks, or closes a sheet opened afterwards. A dismissed write with an uncertain outcome, or one answered 404, re-reads the list instead. A new sheet cannot send until the earlier write finishes. A 404 from an edit closes the sheet and re-reads the list, as Reload does.
  • Shared failure classifier. The new APIv2MutationOutcome sorts a failed v2 mutation into definite, notSent, uncertain or ownerChanged(beforeDispatch:) for every lane, using the single never-sent transport list APIv2Client.neverConnected (which gains badURL and unsupportedURL). A non-2xx answer is definite; an undeclared 2xx, an unreadable answer or cancellation is uncertain. An owner-change error counts as before dispatch only when an HTTPDispatchRecord proves nothing was sent, because HTTPClient raises the same requestIdentityChanged when it discards an answer. Before this, Collections treated that error as a definite failure after POST /api/v2/collections had been answered, told the user the create failed, and invited a duplicate. collectionRequest passes a dispatch record and reports a refusal before sending as APIv2OwnerChangedBeforeDispatch (moved here from the diagnostics lane). CollectionsViewModel.outcomeIsUncertain maps from the shared result.
  • Client layout. All collection requests go through one fenced primitive, APIv2Client.collectionRequest. It checks the owner, runs inside withOwnerFence, adds optional If-Match, and asserts the one expected status. The typed operations live in APIv2Client+Collections.swift, which also absorbs APIv2CollectionCardRead.swift. The models live in APIv2CollectionModels.swift. The unused generic collectionEditor(_:), mutateCollection and deleteCollection(version:) are replaced, along with CollectionEditVersion and CollectionEditor, and APIv2Error.missingCollectionVersion is replaced by the existing missingEntityTag. All v1 collection methods are deleted from SiloAPI.
  • docs/collections-api-v2.md now covers the 428, lost-answer and capability-failure behavior.

Failure outcomes (all writes are non_retryable in openapi)

Outcome Create collection / group Move, rename group, delete collection / group
Definite success (201 / 200 / 204) Close the sheet; re-read the list (collection) or insert the group locally Apply the returned item, or remove it locally; write through the screen cache; close the sheet
Definite failure: any non-2xx or problem answer, a transport error that never reached the server, or a refusal before dispatch because the owner changed Keep the sheet and draft; show the error once Keep the sheet and draft; show the error. 412: "This changed on another device…", and submission is blocked until Reload. 428: logged as a client bug, Reload required. 404: the item is gone, so the sheet closes and the list is re-read, as Reload does. 501 on a group operation: hide group controls
Uncertain: sent with no answer, an undeclared 2xx, an unreadable answer, or an owner change after the request was sent Keep the draft, say "Silo couldn't confirm this was created. Check the list before trying again.", and re-read the list. Never resent Keep the sheet, log it, and block submission until Reload. Reload re-reads the item; a 404 means the earlier write landed, so the sheet closes and the list is re-read. Never resent

The never-sent transport errors are those in APIv2Client.neverConnected: no connection, host not found, cannot connect, DNS failure, bad or unsupported URL, and TLS or certificate failures.

Validation

  • iOS, tvOS and macOS builds passed, before and after the review fixes.
  • Focused tests passed on iOS and tvOS: CollectionsV2Tests, CollectionsViewModelTests and CatalogPagingAPITests. The four view-model tests added with the sheet-scoping fix fail against the code before that fix.
  • CollectionsV2Tests cover the list decode and a refused has_more; capability gating (available, no groups, not_configured); the create body and exact 201, sent once even after a transport failure; If-Match on move, rename and both deletes; the explicit null group; 412 and 428 surfaced without replay; a version from another owner refused before dispatch with APIv2OwnerChangedBeforeDispatch; a missing or weak ETag refused; an editor ID mismatch refused; percent-encoded IDs; and card paging, image size and the owner fence.
  • CollectionsViewModelTests cover:
    • a failed capability read that gives a retryable state, and Retry recovering
    • groups: false and a 501 hiding the group controls
    • after a 412, the sheet stays open and nothing is sent until Reload, which sends the new tag
    • an unknown delete outcome keeps the item and is not replayed; a Reload that gets 404 closes the sheet and re-reads the list
    • a move whose PATCH gets 404 closes the sheet and re-reads the list
    • a delete answered (lost answer, 412 or 204) after its sheet was dismissed and a rename sheet opened leaves the rename sheet open, unlocked and without an error; a lost answer re-reads the list
    • the uncertain/definite classification
  • The new APIv2MutationOutcomeTests, which cover the shared classifier, ran in the full-suite runs below.
  • scripts/ci/check-no-api-v1.sh passed. SiloAPI.swift has eight fewer v1 literals.
  • The final stack passed the full suites (iOS 1981 tests and tvOS 1792 tests, 0 failures), the macOS build and the v1 path guard. Every branch in the stack, this one included, builds on its own.
  • CI flake fix: on some CI runs, testCreateAnsweredAfterAnOwnerChangeIsUncertainAndRereadsTheList failed with an empty list. The test queued the list reply in the stub's path-blind sequence, and the uncertain-outcome re-read sends the list and capabilities reads concurrently, so the capabilities read sometimes took the list reply. The test now answers the list by path and keeps every assertion. The app code was already correct. After the fix, 2,000 of 2,000 stress iterations passed on iOS and on tvOS.
  • Not run: manual checks on a simulator or device against a bridge server, including a SQLite-backed account.

Risks and follow-ups

  • UX change: swipe-to-delete on a collection now asks for confirmation (iOS and macOS; tvOS has no swipe actions).
  • Fence count: the grep count of withOwnerFence lines in iosApp/iosApp goes from 61 to 60. Before, two functions were fenced (editor read and mutation), and nothing in the app called them. Now one collectionRequest fences all ten collection operations, and SiloAPI.collections() and collectionItems(collectionId:) add post-read isCurrentOwner checks. No collection request is unfenced.
  • Shared classifier adoption: APIv2MutationOutcome lands here, but lanes lower in the stack keep their own classification. Later PRs map onto it (W5-E's MutationDelivery, W5-P's request mutations and W5-Q's subtitle dispatch); W5-M's favorite/watchlist/watched dispatcher keeps its own list until W5-E replaces it.
  • On a fresh page, group controls stay hidden until the capability read returns.
  • Not verified: the allowed value the live server sends for a SQLite-backed account. The server builds state from the capability's own capabilityState() (always available when configured). Group support comes only from groups, which the client also checks.
  • The editor read uses the server's canonical GET /collections/{id}. That read omits the presigned poster, which this screen does not show.
  • No expected conflicts with open PRs.

AI disclosure

Code and description written by Claude Opus 5.5 (claude-opus-5-5) agents in Claude Code (T3 Code), orchestrated by a Claude Code workflow.


Part 38 of 50 in the Apple API v2 stack. Base: apiv2-stack/37-favorites-watchlist-lists-v2. Merge in order from the bottom of the stack. The plan and full index are in PR 01.

🤖 Generated with Claude Code

@greptile-apps greptile-apps 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.

Quick104 has reached the 50-credit limit for trial accounts. To continue receiving code reviews, upgrade your plan.

@coderabbitai

coderabbitai Bot commented Sep 23, 2026 •

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Advanced

Run ID: 276d9555-e3e0-4022-84f6-bf6e95803bda

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 23, 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-09-23T13:25:05.455899Z 83b1a84 New commits
ℹ️ 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.

@Quick104

Copy link
Copy Markdown
Contributor Author

Code review summary

Reviewed head: f6c22f86 (apiv2-stack/38-personal-collections-v2).

Process: an adversarial review of this PR's diff with each candidate finding independently verified before any fix, a simplify pass for medium and larger PRs, and a whole-stack review across contract conformance, authority and failure handling, data integrity, user-visible behavior and cross-PR integration.

Verified findings, all fixed on this branch:

  • minor: A write from a dismissed sheet changes the state of the next sheet
  • minor: A 404 from the write leaves the sheet stuck while a 404 on Reload closes it
  • whole-stack review: Collections treats an owner change raised after the response as a definite failure, and its test pins that
  • whole-stack review: Five separate classifiers decide whether a failed mutation reached the server, and they disagree

Note: Personal collection create, rename and delete have no navigation entry point on iOS (the same on main), so they were covered by tests, not by runtime validation.

Validation: this branch builds on its own for iOS, tvOS and macOS, and its focused tests passed. The completed stack passed the full iOS suite (1981 tests) and tvOS suite (1792 tests) with 0 failures, the macOS build and the v1 path guard. The final stack was also exercised on iOS and tvOS simulators against a v1/v2 bridge server: sign-in (password and QR), restore, browse, search, detail, favorites and watchlist, playback (direct play, transcode, subtitles, stop), audiobooks, downloads with offline playback, settings, requests, profiles, push registration and diagnostics. Server logs showed no /api/v1 request from the new builds except the retained health probe.

Remaining: no open verified findings. Merge in stack order.

Mergeability: 8/10 — conditional. The approach holds up and every verified finding is fixed. Conditions: this PR's CI must pass (it was pending at review time), and the owner still plans a physical-device check of the completed stack.

Review by Claude Opus 5.5 (claude-opus-5-5) agents in Claude Code (T3 Code).

@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: f6c22f8664

ℹ️ 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 +251 to +252
replaceGroup(editor.value)
editorVersion = editor.version

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 Seed edit drafts from the canonical read

When a group or collection changes after the list load but before this editor read, the code pairs the fresh ETag with a draft that GroupActionSheet still initializes from the stale enum value. For example, if another device renames a group from A to B, this read installs B's ETag while the text field remains A; tapping Save submits A with the fresh tag, so the server accepts the overwrite instead of returning 412. Update the active sheet's name or move target from editor.value before enabling confirmation.

Useful? React with 👍 / 👎.

Comment on lines +220 to 222
_ = try await api.createCollection(name: name)
newCollectionName = ""
showCreateSheet = false

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 Scope collection-create completion to its originating sheet

If the user cancels or interactively dismisses the create sheet while its POST is in flight and then opens a new create sheet, the old request's success clears newCollectionName and closes the newly opened sheet; its failure similarly publishes an error into that new sheet. Capture a create-sheet generation, as the group-action flow does, and only mutate sheet-local state when the originating generation is still active.

Useful? React with 👍 / 👎.

@Quick104
Quick104 force-pushed the apiv2-stack/37-favorites-watchlist-lists-v2 branch from 9dc91f4 to 8af5c19 Compare September 23, 2026 13:19
@Quick104
Quick104 force-pushed the apiv2-stack/38-personal-collections-v2 branch from f6c22f8 to 83b1a84 Compare September 23, 2026 13:19

@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: 83b1a84f2d

ℹ️ 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".

break
case .rename(let group), .delete(let group):
let editor = try await api.collectionGroupEditor(id: group.id)
guard pendingGroupAction?.id == action.id else { return }

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 Scope editor reads to the sheet generation

If an edit sheet is dismissed and the same action for the same item is reopened before its first editor read finishes, this ID check still succeeds because both sheets have the same action.id. The earlier request can therefore install its ETag, clear reload state, or handle a 404 against the newly opened sheet; it may even enable confirmation while the new sheet's own read is still pending. Capture and validate sheetGeneration (or an editor-request token) across the await rather than comparing only the stable action ID.

Useful? React with 👍 / 👎.

Comment on lines +165 to +166
let capabilities = try await api.collectionCapabilities()
groupSupport = capabilities.supportsGroups ? .available : .unavailable

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 a concurrent 501 capability verdict

When a capability refresh is already in flight while a group mutation returns 501, markGroupsUnsupported sets .unavailable, but the older capability response can subsequently reach this assignment and restore .available. This is possible on a previously loaded page because loadCollections() retains the prior available state while refreshing, so group controls remain usable during the request; a stale groups: true response then defeats the definitive mutation result and exposes operations that continue to fail. Tokenize capability reads or make the 501 verdict sticky against requests started earlier.

Useful? React with 👍 / 👎.

@Quick104
Quick104 force-pushed the apiv2-stack/37-favorites-watchlist-lists-v2 branch from 8af5c19 to 0c0a415 Compare September 23, 2026 13:43
The personal Collections screen listed, created, moved, renamed and deleted
collections and groups through /api/v1/collections, and the collection
detail grid read /api/v1/collections/{id}/items with offset 0 and limit 200.
v2 guards every collection and group edit with an ETag, returns 412 when
the item changed and 428 when the precondition is missing, and answers 501
for groups on stores without group support. The screen showed group
controls unconditionally.

The screen now uses v2 only. SiloAPI reads the list, the groups capability,
and the detail cards (catalog source=user_collection, every cursor page
under one owner) through the shared v2 client, and the v1 methods are gone.
Move, rename and both deletes read the canonical collection or group when
their sheet opens and send its strong ETag as If-Match under the same
owner; swipe-to-delete now opens a confirmation sheet for that read. A 412,
a 428, or a lost answer keeps the sheet and draft and blocks submission
until the user reloads; nothing is resent. Creates are dispatched once and
a lost answer re-reads the list. Group controls appear only when the
capability reports groups; a failed capability read shows a Retry notice
instead of treating groups as unsupported, and a 501 hides them.

All collection requests go through one fenced primitive in APIv2Client;
the typed operations live in APIv2Client+Collections.swift.

Stack-PR: W5-O
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Base automatically changed from apiv2-stack/37-favorites-watchlist-lists-v2 to main September 23, 2026 13:43
Quick104 and others added 5 commits September 23, 2026 09:43
Fold the duplicated item-id check into the shared editor read and drop a
redundant type annotation on the create call.

Stack-PR: W5-O
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
A write kept running after its sheet was cancelled, and its outcome
landed on whatever sheet was open next: a 412 or lost answer showed the
wrong message and locked that sheet until Reload, and a success closed
it. A dismissed delete with a lost answer also never re-read the list.
Separately, a 404 from the write itself was shown as an ordinary error
with Delete or Move still enabled, while the same 404 on Reload closed
the sheet and re-read the list.

Each write now records which sheet started it. The list still updates
on success, but the sheet error, reload lock and dismissal apply only
while that sheet is open; a dismissed write with an uncertain outcome
re-reads the list instead. A 404 from an edit closes the sheet and
re-reads the list, matching Reload.

Stack-PR: W5-O
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Several lanes each kept their own list of "never sent" transport errors
and their own rules for owner changes and unexpected 2xx answers, and
they gave different answers for the same error. Collections, for one,
treated HTTPError.requestIdentityChanged as a definite failure, but
HTTPClient also raises it after a POST /api/v2/collections was answered.
The user was then told the create failed and invited to make a
duplicate.

APIv2MutationOutcome now classifies a failed mutation as definite,
notSent, uncertain or ownerChanged(beforeDispatch:), using the one
never-sent list (APIv2Client.neverConnected, now with badURL and
unsupportedURL). An owner-change error counts as before dispatch only
with proof from an HTTPDispatchRecord; a non-2xx answer is definite
(plan section 9) and an undeclared 2xx is uncertain.

collectionRequest passes a dispatch record and reports a refusal before
sending as APIv2OwnerChangedBeforeDispatch (moved down from the
diagnostics lane); creates without a captured owner report the same.
CollectionsViewModel.outcomeIsUncertain maps from the shared result, so
an answer discarded after sending shows the "couldn't confirm" message
and re-reads the list.

Stack-PR: W5-O
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…delete

The shared v2 write classifier now reports an owner change caught before
the request reaches the URL session as APIv2OwnerChangedBeforeDispatch.
The collection delete test still expected HTTPError.requestIdentityChanged
and failed on iOS and tvOS. Expect the pre-dispatch error instead.

Stack-PR: W5-O
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
The uncertain-create test queued the POST's 201 and the list body in the
stub's one-shot queue, which answers requests in arrival order whatever
their path. The re-read in loadCollections() sends the list GET and the
capabilities GET at the same time. When the capabilities GET arrived
first it took the list body, and the list GET fell through to the
stub's "{}" fallback, so the list failed to decode and stayed empty
with exactly one list GET recorded. That happened in about 1 in 125 to
300 runs locally and failed CI on several stack PRs.

Queue only the POST's reply, and answer the list by path once the held
POST has taken its reply. The assertions are unchanged.

Stack-PR: W5-O
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@Quick104
Quick104 force-pushed the apiv2-stack/38-personal-collections-v2 branch from 83b1a84 to 08038f1 Compare September 23, 2026 13:43
@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.

@Quick104
Quick104 merged commit 017b984 into main Sep 23, 2026
3 of 6 checks passed
@Quick104
Quick104 deleted the apiv2-stack/38-personal-collections-v2 branch September 23, 2026 13:43
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.

1 participant