diff --git a/docs/superpowers/plans/2026-04-16-postbox-to-telegramengine-refactor-wave-1.md b/docs/superpowers/plans/2026-04-16-postbox-to-telegramengine-refactor-wave-1.md deleted file mode 100644 index 26d958661b..0000000000 --- a/docs/superpowers/plans/2026-04-16-postbox-to-telegramengine-refactor-wave-1.md +++ /dev/null @@ -1,983 +0,0 @@ -# Postbox → TelegramEngine refactor, wave 1 — Implementation Plan - -> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. - -**Goal:** Drop the direct `import Postbox` dependency from the first 10 leaf consumer submodules (one file each), routing data access through `TelegramEngine` while preserving behavior exactly. - -**Architecture:** For each of the 10 modules, apply the same deterministic playbook: inventory every Postbox reference in its single Postbox-importing file, swap bare Postbox type names for their engine typealiases (`PeerId` → `EnginePeer.Id`, etc.), replace imperative Postbox calls with existing engine methods or new thin engine wrappers added to TelegramCore in a preparatory commit, remove `import Postbox` and the Bazel dep, and run the full project build to verify. - -**Tech Stack:** Swift, Bazel (primary build system), Postbox (storage lib being made opaque), TelegramCore + TelegramEngine (the public facade), SSignalKit (signals). - -**Spec:** [docs/superpowers/specs/2026-04-16-postbox-to-telegramengine-refactor-wave-1-design.md](../specs/2026-04-16-postbox-to-telegramengine-refactor-wave-1-design.md) - ---- - -## Background the executor needs - -There are no unit tests in this project (`CLAUDE.md`: "No tests are used at the moment"). **The only verification is the full project build.** Every task ends with a full build that must go green before the next task starts. - -### The full build command - -Run from the repo root (`/Users/ali/build/telegram/telegram-ios`): - -```bash -source ~/.zshrc 2>/dev/null; \ -PATH=/opt/homebrew/opt/ruby/bin:`gem environment gemdir`/bin:$PATH \ - python3 build-system/Make/Make.py --overrideXcodeVersion \ - --cacheDir ~/telegram-bazel-cache \ - build \ - --configurationPath build-system/appstore-configuration.json \ - --gitCodesigningRepository git@gitlab.com:peter-iakovlev/fastlanematch.git \ - --gitCodesigningType development \ - --gitCodesigningUseCurrent \ - --buildNumber 1 \ - --configuration debug_sim_arm64 -``` - -(`source ~/.zshrc` picks up `TELEGRAM_CODESIGNING_GIT_PASSWORD` and other env exports that the Claude Code bash shell doesn't inherit by default.) - -It is slow. Do not shortcut it with `bazel build //submodules/X` — the spec chose full build per module. - -### Engine typealias cheat sheet (already in TelegramCore) - -When removing `import Postbox`, bare Postbox names in the file must be swapped for their engine equivalents. The ones that exist as typealiases today (confirmed by grep over `submodules/TelegramCore/Sources/TelegramEngine/`): - -- `PeerId` → `EnginePeer.Id` -- `MessageId` → `EngineMessage.Id` -- `MessageIndex` → `EngineMessage.Index` -- `MessageTags` → `EngineMessage.Tags` -- `MessageAttribute` → `EngineMessage.Attribute` -- `MessageFlags` → `EngineMessage.Flags` -- `MessageForwardInfo` → `EngineMessage.ForwardInfo` -- `MediaId` → `EngineMedia.Id` -- `PreferencesEntry` → `EnginePreferencesEntry` -- `TempBox` (the singleton helper) → `EngineTempBox` -- `PinnedItemId` → `EngineChatList.PinnedItem.Id` - -If a task needs a Postbox type that has **no** existing engine typealias, the task may add one in `TelegramCore` (trivial `public typealias EngineX = X`) in the preparatory commit — this is explicitly allowed by the spec. - -### Engine wrapper locations (per the spec) - -- Data reads / subscriptions → new `TelegramEngine.EngineData.Item..` in `submodules/TelegramCore/Sources/TelegramEngine/Data/Data.swift`. -- Imperative signal-returning calls → new method on `Peers` / `Messages` / `Resources` / `AccountData` under `submodules/TelegramCore/Sources/TelegramEngine//`. -- Media-resource access → extend `engine.resources` (e.g. `engine.resources.data(...)`, `engine.resources.status(...)`), forwarding to `account.postbox.mediaBox.*` internally. -- Consumer-run `account.postbox.transaction { ... }` → a specific purpose-built engine method. No generic transaction escape hatch. - -### Static-check commands (run before the build in every task) - -```bash -grep -R "^import Postbox" submodules//Sources # must return empty -grep "submodules/Postbox" submodules//BUILD # must return empty -``` - -### Commit convention - -Per module, up to two commits (optional first, required second): - -1. `TelegramCore: add ` — only if new engine wrappers were needed. -2. `: drop direct Postbox dependency` — consumer edits + BUILD change. - -Always use a HEREDOC commit body. No `--amend`. Every commit must build. - -**TelegramCore wrapper commit template** (used by any task's Step 2a when engine wrappers/typealiases are added): - -```bash -git add submodules/TelegramCore/... -git commit -m "$(cat <<'EOF' -TelegramCore: add - -Prepares for to drop Postbox. -Searched TelegramEngine/ for existing equivalents: . - - -Co-Authored-By: Claude Opus 4.6 -EOF -)" -``` - -### Build-failure handling (applies to every task's Step 6) - -When the full build fails after a consumer edit: - -- Read the **first** compiler error in the build output. -- If it's a name-resolution or type error in the module file being refactored, fix the mapping in that file and rebuild. -- If it's in a **different** module that depends on the module being refactored, a public signature changed unexpectedly. Either (a) revert that signature change so the public surface stays identical, or (b) if the new surface is genuinely better, extend the fix to the downstream call site **in the same commit**. -- If fixing would require editing a module outside the wave-1 list — or would require aliasing an umbrella type banned by spec rule 2 (`Postbox`, `Account`, `MediaBox`) — revert all changes from the current task and mark the module **Abandoned** in its task body with a one-line reason. Do NOT substitute a different module; the wave's done-count simply goes down by one. - -### The 10 modules (from the spec's deterministic selection rule) - -Reverse-dep count (over the 30-candidate pool) ascending, alphabetical tiebreak. Verified by running the selection script in Task 0: - -1. ActionSheetPeerItem — **ABANDONED** (see Task 1 body). Public init takes `postbox: Postbox`; ShareController caller is out-of-wave. -2. ChatInterfaceState — `submodules/ChatInterfaceState/Sources/ChatInterfaceState.swift` — DONE -3. ChatListSearchRecentPeersNode — **ABANDONED** (see Task 3 body). Public init takes `postbox: Postbox`; ShareController + ChatListUI callers are out-of-wave. -4. ChatSendMessageActionUI — `submodules/ChatSendMessageActionUI/Sources/ChatSendMessageContextScreen.swift` -5. ContactListUI — `submodules/ContactListUI/Sources/ContactListNode.swift` -6. DirectMediaImageCache — **ABANDONED** (see Task 6 body). Public init takes `account: Account`; six out-of-wave callers. -7. DrawingUI — `submodules/DrawingUI/Sources/DrawingScreen.swift` -8. FetchManagerImpl — **ABANDONED** (see Task 8 body). Public init takes `postbox: Postbox`; TelegramUI caller is out-of-wave. -9. GalleryData — **ABANDONED** (see Task 9 body). Four public functions take `Media`/`Message` as parameters; refactor cascades into many out-of-wave downstream types (`AvatarGalleryEntry`, `MessageReference`, etc.). Good candidate for a bespoke future wave that migrates the domain types together. -10. ICloudResources — **ABANDONED** (see Task 10 body). Class conforms to `TelegramMediaResource` and inherits `isEqual(to: MediaResource)`; overriding that without aliasing the `MediaResource` protocol isn't possible. - -**Wave-1 done-count: 4** (Tasks 2, 4, 5, 7 done; Tasks 1, 3, 6, 8, 9, 10 abandoned). - -Per the spec's **abandonment protocol**, if a module hits an unresolvable blocker (requires aliasing an umbrella type such as `Postbox`/`Account`/`MediaBox`, or requires editing a module outside the wave-1 list), it is marked Abandoned in its task body and **not substituted**. The wave's done-count goes down by one; fallback modules are not pulled into the wave mid-execution. A later wave can revisit the abandoned module with tools not available in wave 1 (e.g. a real engine wrapper rather than a typealias, or a refactor that migrates the caller first). - ---- - -## Task 0: Verify selection and baseline build - -**Files:** -- Read: `submodules//BUILD` - -- [ ] **Step 1: Re-run the selection script to confirm the 10** - -Save and run this Python snippet from the repo root. It should output exactly the 10 modules listed above, in that order. - -```bash -python3 <<'EOF' -import os, re -pool = ["ActionSheetPeerItem","ChatInterfaceState","ChatListSearchRecentPeersNode","ChatSendMessageActionUI","ContactListUI","DirectMediaImageCache","DrawingUI","FetchManagerImpl","GalleryData","HorizontalPeerItem","ICloudResources","InAppPurchaseManager","InstantPageCache","InviteLinksUI","ItemListAvatarAndNameInfoItem","ItemListPeerItem","ItemListStickerPackItem","MapResourceToAvatarSizes","PhotoResources","PlatformRestrictionMatching","PresentationDataUtils","PromptUI","SaveToCameraRoll","SelectablePeerNode","ShareItems","SoftwareVideo","StickerPeekUI","StickerResources","TelegramIntents","TelegramNotices"] -deps = {} -for m in pool: - p = f"submodules/{m}/BUILD" - txt = open(p).read() if os.path.exists(p) else "" - deps[m] = {o for o in pool if o != m and re.search(rf'//submodules/{re.escape(o)}(:|"|$)', txt)} -rdep = {m:0 for m in pool} -for m,ds in deps.items(): - for d in ds: rdep[d]+=1 -for m in sorted(pool, key=lambda m:(rdep[m],m))[:10]: - print(m, rdep[m]) -EOF -``` - -Expected output (one per line): `ActionSheetPeerItem 0`, `ChatInterfaceState 0`, `ChatListSearchRecentPeersNode 0`, `ChatSendMessageActionUI 0`, `ContactListUI 0`, `DirectMediaImageCache 0`, `DrawingUI 0`, `FetchManagerImpl 0`, `GalleryData 0`, `ICloudResources 0`. - -If the output differs, stop and investigate — someone changed a BUILD file since the spec was written. - -- [ ] **Step 2: Run the baseline full build** - -Run the full build command above. Expected: PASS (green master). If it fails, stop — we need a green baseline before changing anything. Do not attempt to fix pre-existing build breakage as part of this plan. - -- [ ] **Step 3: No commit** - -Task 0 produces no code changes. - ---- - -## Task 1: Refactor `ActionSheetPeerItem` — **ABANDONED** - -**Status:** Abandoned for wave 1. No code changes in this repo from this task. - -**Reason:** Refactoring this module requires either (a) typealiasing the `Postbox` class itself (banned — see spec §Guiding rules rule 2: umbrella-type typealiases rename without encapsulating) or (b) editing `submodules/ShareController/` which is not in the wave-1 list. The module's designated init takes `postbox: Postbox` as a parameter and its sole out-of-wave caller (ShareController) passes `info.account.stateManager.postbox` directly, so there is no path to drop the `import Postbox` here without crossing the wave boundary or violating rule 2. Per the spec's **abandonment protocol**, the module is skipped for this wave. Wave-1 done-count is therefore 9, not 10. - -**Original task body (retained for audit trail, do not implement):** - -**Files:** -- Modify: `submodules/ActionSheetPeerItem/Sources/ActionSheetPeerItem.swift` -- Modify: `submodules/ActionSheetPeerItem/BUILD` - -**Starting inventory** (computed during planning): - -Grep for common Postbox API/type names in `ActionSheetPeerItem.swift` returned zero hits on `mediaBox`, `transaction`, `PostboxView`, `combinedView`, `PeerId`, `MessageId`, `MediaResource`, `CachedPeerData`, etc. The `import Postbox` line appears unused. Confirm this during inventory — it's the most likely case, but other Postbox symbols (e.g. types referenced inside a parameter type) may still be present. (Subsequent inventory discovered the module does take `postbox: Postbox` as a parameter type — this is what makes the module unrefactorable under the wave-1 rules.) - -- [ ] **Step 1: Inventory** - -Read `submodules/ActionSheetPeerItem/Sources/ActionSheetPeerItem.swift` top to bottom. Record every identifier that is Postbox-owned. If the inventory is empty, skip straight to Step 4. - -Run this helper grep too: - -```bash -grep -nE "\b(PeerId|MessageId|MessageIndex|MessageTags|MessageAttribute|MessageFlags|Peer|Media|MediaId|MediaResource|PostboxView|CachedPeerData|PreferencesEntry|ChatListIndex|PeerReference|TelegramMediaFile|TelegramMediaImage|Namespaces|TempBox)\b" submodules/ActionSheetPeerItem/Sources/ActionSheetPeerItem.swift -``` - -- [ ] **Step 2: Map each reference to a replacement** - -For each finding from Step 1, decide: existing engine typealias (see cheat sheet), existing engine method, existing TelegramCore non-Postbox export, or new engine wrapper. Record the mapping in your working notes. If a new wrapper is needed, it is added in Task 1a before Task 1 continues. - -- [ ] **Step 2a: (Only if Step 2 identified a missing engine wrapper/typealias) Add to TelegramCore** - -Edit the relevant file under `submodules/TelegramCore/Sources/TelegramEngine//` or `submodules/TelegramCore/Sources/TelegramEngine/Data/Data.swift`, following the wrapper-location rules in the Background section. Keep the wrapper minimal: a single typealias for name-only adds, or a thin method that forwards to the underlying Postbox call for imperative ones. - -Run the full build. It must pass. Commit: - -```bash -git add submodules/TelegramCore/... -git commit -m "$(cat <<'EOF' -TelegramCore: add - -Prepares for ActionSheetPeerItem to drop Postbox. - - -Co-Authored-By: Claude Opus 4.6 -EOF -)" -``` - -Skip this step if Step 2 didn't identify any missing wrappers. - -- [ ] **Step 3: Edit the consumer file** - -In `submodules/ActionSheetPeerItem/Sources/ActionSheetPeerItem.swift`: - -- Apply every mapping from Step 2. -- Remove the line `import Postbox`. - -- [ ] **Step 4: Drop the Bazel dep** - -Edit `submodules/ActionSheetPeerItem/BUILD`. Remove the line `"//submodules/Postbox:Postbox",` from the `deps` array. Leave the rest of the BUILD untouched. - -- [ ] **Step 5: Static checks** - -Run: - -```bash -grep -R "^import Postbox" submodules/ActionSheetPeerItem/Sources # expect: empty -grep "submodules/Postbox" submodules/ActionSheetPeerItem/BUILD # expect: empty -``` - -Both must return no output. If either produces a hit, go back to Step 3 or Step 4. - -- [ ] **Step 6: Full project build** - -Run the full build command from the Background section. Expected: PASS. - -If it fails: -- Read the first error. If it's a name-resolution error in `ActionSheetPeerItem.swift`, fix the mapping and rebuild. -- If it's in a *different* module that depends on `ActionSheetPeerItem`, you changed a public signature unexpectedly; either revert that signature change or, if it's genuinely better, extend the fix to that downstream call site in the same commit. -- If the fix would require editing a module outside the wave-1 list, revert all Task 1 changes and skip to the next fallback module listed in the Background section. - -- [ ] **Step 7: Commit** - -```bash -git add submodules/ActionSheetPeerItem/ -git commit -m "$(cat <<'EOF' -ActionSheetPeerItem: drop direct Postbox dependency - -Route data access through TelegramEngine/TelegramCore; remove the -Postbox import and Bazel dep. Behavior-preserving. - -Co-Authored-By: Claude Opus 4.6 -EOF -)" -``` - ---- - -## Task 2: Refactor `ChatInterfaceState` - -**Files:** -- Modify: `submodules/ChatInterfaceState/Sources/ChatInterfaceState.swift` -- Modify: `submodules/ChatInterfaceState/BUILD` - -**Starting inventory** (computed during planning): file references `MessageId` (×2) and `MediaResource` (×3). No `mediaBox`, `transaction`, `combinedView`, or `PostboxView` usage. This is a **type-reference-only** case — expected replacements are `MessageId` → `EngineMessage.Id` and `MediaResource` stays as-is only if a typealias exists, otherwise a typealias `EngineMediaResource = MediaResource` is added in TelegramCore. - -- [ ] **Step 1: Inventory** - -Read `submodules/ChatInterfaceState/Sources/ChatInterfaceState.swift`. Confirm the grep below matches the planning inventory and records exact line numbers and declaration contexts (parameter types, property types, return types, generic arguments). - -```bash -grep -nE "\b(PeerId|MessageId|MessageIndex|MessageTags|MessageAttribute|MessageFlags|Peer|Media|MediaId|MediaResource|PostboxView|CachedPeerData|PreferencesEntry|ChatListIndex|PeerReference|TelegramMediaFile|TelegramMediaImage|Namespaces|TempBox)\b" submodules/ChatInterfaceState/Sources/ChatInterfaceState.swift -``` - -- [ ] **Step 2: Map each reference** - -- `MessageId` → `EngineMessage.Id` (existing typealias, no wrapper needed). -- `MediaResource`: search `submodules/TelegramCore/Sources/TelegramEngine/` for a `public typealias Engine.*Resource.*= MediaResource`. If present, use it. If absent, proceed to Step 2a and add a typealias `public typealias EngineMediaResource = MediaResource` in `submodules/TelegramCore/Sources/TelegramEngine/Resources/` (new file `EngineMediaResource.swift`, or the most natural existing file in that folder). - -- [ ] **Step 2a: (Only if needed) Add engine typealias(es) in TelegramCore** - -For each Postbox type without an engine typealias, add a `public typealias Engine = ` in the appropriate TelegramEngine area file. Do not introduce any new wrapper structs. - -Run full build, expect PASS. Commit: - -```bash -git add submodules/TelegramCore/... -git commit -m "$(cat <<'EOF' -TelegramCore: add engine typealiases for - -Prepares for ChatInterfaceState to drop Postbox. - -Co-Authored-By: Claude Opus 4.6 -EOF -)" -``` - -- [ ] **Step 3: Edit the consumer file** - -Apply the mappings from Step 2 to every reference. Remove the line `import Postbox`. - -- [ ] **Step 4: Drop the Bazel dep** - -Edit `submodules/ChatInterfaceState/BUILD`. Remove `"//submodules/Postbox:Postbox",` from `deps`. - -- [ ] **Step 5: Static checks** - -```bash -grep -R "^import Postbox" submodules/ChatInterfaceState/Sources # expect: empty -grep "submodules/Postbox" submodules/ChatInterfaceState/BUILD # expect: empty -``` - -- [ ] **Step 6: Full project build** - -Run the full build command. Expected: PASS. Handle failures per the rules in Task 1 Step 6. - -- [ ] **Step 7: Commit** - -```bash -git add submodules/ChatInterfaceState/ -git commit -m "$(cat <<'EOF' -ChatInterfaceState: drop direct Postbox dependency - -Switch remaining Postbox-typed references to engine typealiases; -remove the Postbox import and Bazel dep. Behavior-preserving. - -Co-Authored-By: Claude Opus 4.6 -EOF -)" -``` - ---- - -## Task 3: Refactor `ChatListSearchRecentPeersNode` — **ABANDONED** - -**Status:** Abandoned for wave 1. No code changes in this repo from this task. - -**Reason:** The module's public `init` at line 207 takes `postbox: Postbox` as a parameter. Two out-of-wave callers (`submodules/ShareController/Sources/ShareControllerRecentPeersGridItem.swift`, `submodules/ChatListUI/Sources/ChatListRecentPeersListItem.swift`) use this init. Refactoring requires either typealiasing the `Postbox` class (banned by spec rule 2) or editing those two out-of-wave modules (banned by wave boundary). Per the abandonment protocol, the module is skipped. - -**Original task body (retained for audit trail, do not implement):** - -**Files:** -- Modify: `submodules/ChatListSearchRecentPeersNode/Sources/ChatListSearchRecentPeersNode.swift` -- Modify: `submodules/ChatListSearchRecentPeersNode/BUILD` - -**Starting inventory** (computed during planning): file uses `postbox.transaction { ... }` (×2), `postbox.combinedView(...)` (×1), and references `TelegramMedia*` types (×3). This is the **first hard module** in the wave — it has real imperative Postbox calls that require engine wrappers, not just typealiases. - -- [ ] **Step 1: Inventory** - -Read the whole file. For each Postbox call, capture: -- The call site (line number, containing function). -- The `PostboxViewKey`(s) passed to `combinedView`. -- What the closure body of each `transaction` does — the *intent*, not just the code. (This determines which engine method to add.) - -Run: - -```bash -grep -nE "\b(postbox\.|mediaBox|transaction\s*\{|combinedView|PostboxView|PostboxViewKey|Namespaces\.|TelegramMedia|PeerId|MessageId)\b" submodules/ChatListSearchRecentPeersNode/Sources/ChatListSearchRecentPeersNode.swift -``` - -- [ ] **Step 2: Map each reference** - -- `TelegramMedia*` — these classes are defined in `TelegramCore` (check `submodules/TelegramCore/Sources/`), not Postbox. After `import Postbox` is removed they remain reachable via `import TelegramCore`, which the file already imports. No action beyond confirming. -- Each `postbox.combinedView` / view subscription → map to an existing `TelegramEngine.data.subscribe(...)` item if one exists for the same `PostboxViewKey`; if not, add an `EngineData.Item` under `submodules/TelegramCore/Sources/TelegramEngine/Data/Data.swift`. -- Each `postbox.transaction { ... }` → a specific new method on the matching engine area (e.g. `TelegramEngine.Peers.recordRecentPeer(id:)` if that's what the closure does). Do **not** add a generic transaction passthrough. - -Write the mapping down before editing. Each new engine method is small and focused. - -- [ ] **Step 2a: Add engine wrappers in TelegramCore** - -For each new `EngineData.Item` or engine method identified in Step 2: - -- Add it to the appropriate file under `submodules/TelegramCore/Sources/TelegramEngine//` (or `…/Data/Data.swift` for data items). -- Keep the body to a minimal pass-through: the new engine method opens a transaction internally and calls the same Postbox code that the consumer was running; the new `EngineData.Item` forwards a `PostboxViewKey` in `keys()` and extracts its `PostboxView` in `extract()`. -- Return engine-typed values where existing engine types are available; otherwise return primitives or `Void`. Do not return bare Postbox types. - -Before editing TelegramCore, grep for existing wrappers covering the same need: - -```bash -grep -rn "\|" submodules/TelegramCore/Sources/TelegramEngine/ -``` - -Record "searched for X, found/not found" in the commit message. - -Run the full build. Expected: PASS. - -Commit: - -```bash -git add submodules/TelegramCore/... -git commit -m "$(cat <<'EOF' -TelegramCore: add - -Prepares for ChatListSearchRecentPeersNode to drop Postbox. -Searched TelegramEngine/ for existing equivalents: not found. - - -Co-Authored-By: Claude Opus 4.6 -EOF -)" -``` - -- [ ] **Step 3: Edit the consumer file** - -Replace each `postbox.transaction` and `postbox.combinedView` call with the engine method/subscription added in Step 2a. Swap any Postbox-typed names for engine typealiases per the cheat sheet. Remove `import Postbox`. - -- [ ] **Step 4: Drop the Bazel dep** - -Edit `submodules/ChatListSearchRecentPeersNode/BUILD`. Remove `"//submodules/Postbox:Postbox",` from `deps`. - -- [ ] **Step 5: Static checks** - -```bash -grep -R "^import Postbox" submodules/ChatListSearchRecentPeersNode/Sources # expect: empty -grep "submodules/Postbox" submodules/ChatListSearchRecentPeersNode/BUILD # expect: empty -``` - -- [ ] **Step 6: Full project build** - -Run the full build command. Expected: PASS. Handle failures per the Build-failure handling rules in the Background section. - -- [ ] **Step 7: Commit** - -```bash -git add submodules/ChatListSearchRecentPeersNode/ -git commit -m "$(cat <<'EOF' -ChatListSearchRecentPeersNode: drop direct Postbox dependency - -Route combined-view subscription and transactions through -TelegramEngine; remove the Postbox import and Bazel dep. -Behavior-preserving. - -Co-Authored-By: Claude Opus 4.6 -EOF -)" -``` - ---- - -## Task 4: Refactor `ChatSendMessageActionUI` - -**Files:** -- Modify: `submodules/ChatSendMessageActionUI/Sources/ChatSendMessageContextScreen.swift` -- Modify: `submodules/ChatSendMessageActionUI/BUILD` - -**Starting inventory** (computed during planning): `mediaBox` (×2), `Peer` type reference (×1), `Media` type reference (×1), `MediaResource` (×1), `Namespaces.` (×1). The mediaBox calls are the substantive work. - -- [ ] **Step 1: Inventory** - -Read the whole file. Capture every `mediaBox` call — what resource is being asked for and what is done with the result (data read, status subscription, fetch start, path access)? Capture each Postbox-typed reference's line/context. - -```bash -grep -nE "\bmediaBox\b|\bNamespaces\.|\b(Peer|Media|MediaResource)\b" submodules/ChatSendMessageActionUI/Sources/ChatSendMessageContextScreen.swift -``` - -- [ ] **Step 2: Map each reference** - -- Each `mediaBox.` call → `engine.resources.(...)`. Check for an existing method on `TelegramEngine.Resources` first: - ```bash - grep -rn "extension.*Resources\|public func" submodules/TelegramCore/Sources/TelegramEngine/Resources/ - ``` - If an equivalent exists, use it. If not, add one in Step 2a. -- `Peer`, `Media`, `MediaResource` type references → use `EnginePeer`, `EngineMedia`, or `EngineMediaResource` (add typealias if missing, per the cheat sheet). -- `Namespaces.Peer.` — defined in TelegramCore, not Postbox. Confirm via grep; no change needed. - -- [ ] **Step 2a: (Only if needed) Add engine wrappers in TelegramCore** - -Per the rules — minimal pass-through, return engine-typed values. Build, commit `TelegramCore: add ` per the template in Task 3 Step 2a. - -- [ ] **Step 3: Edit the consumer file** - -Apply mappings. Remove `import Postbox`. - -- [ ] **Step 4: Drop the Bazel dep** - -Edit `submodules/ChatSendMessageActionUI/BUILD`. Remove `"//submodules/Postbox:Postbox",` from `deps`. - -- [ ] **Step 5: Static checks** - -```bash -grep -R "^import Postbox" submodules/ChatSendMessageActionUI/Sources # expect: empty -grep "submodules/Postbox" submodules/ChatSendMessageActionUI/BUILD # expect: empty -``` - -- [ ] **Step 6: Full project build** - -Run the full build. Expected: PASS. Handle failures per the Build-failure handling rules in the Background section. - -- [ ] **Step 7: Commit** - -```bash -git add submodules/ChatSendMessageActionUI/ -git commit -m "$(cat <<'EOF' -ChatSendMessageActionUI: drop direct Postbox dependency - -Route MediaBox calls through TelegramEngine.resources and switch -type references to engine typealiases; remove the Postbox import -and Bazel dep. Behavior-preserving. - -Co-Authored-By: Claude Opus 4.6 -EOF -)" -``` - ---- - -## Task 5: Refactor `ContactListUI` - -**Files:** -- Modify: `submodules/ContactListUI/Sources/ContactListNode.swift` -- Modify: `submodules/ContactListUI/BUILD` - -**Starting inventory** (computed during planning): `postbox.transaction { ... }` (×4), `Peer` references (×15), `Namespaces.` (×1). Transactions are the substantive work; the 15 `Peer` references are likely in closures reading transaction state and will switch to engine-typed returns once the transactions are replaced. - -- [ ] **Step 1: Inventory** - -Read the whole file. For each `transaction` call, describe what the closure does — this drives what new engine methods to add. Capture every `Peer`-typed declaration. - -```bash -grep -nE "\btransaction\s*\{|account\.postbox|\b(Peer|PeerId|Namespaces)\b" submodules/ContactListUI/Sources/ContactListNode.swift -``` - -- [ ] **Step 2: Map each reference** - -- Each `postbox.transaction { ... }` → a dedicated engine method under `submodules/TelegramCore/Sources/TelegramEngine/{Peers,Contacts,AccountData}/` capturing the closure's intent. Never add a generic transaction passthrough. -- `Peer` type → `EnginePeer` where the value actually flows through the replaced engine method (the engine method should return `EnginePeer` / `[EnginePeer]`). For local variable types that receive the engine-method return, use the engine type. -- `Namespaces.*` — defined in TelegramCore. No change. - -Before adding methods, grep for existing engine functions that may already cover the intent: - -```bash -grep -rn "public func" submodules/TelegramCore/Sources/TelegramEngine/Contacts/ -grep -rn "public func" submodules/TelegramCore/Sources/TelegramEngine/Peers/ | head -60 -``` - -- [ ] **Step 2a: Add engine wrappers in TelegramCore** - -Add each new method. Return engine-typed values. Build; then use the TelegramCore wrapper commit template from the Background section. - -- [ ] **Step 3: Edit the consumer file** - -Replace every `transaction` call with its engine method. Switch `Peer` locals to `EnginePeer`. Remove `import Postbox`. - -- [ ] **Step 4: Drop the Bazel dep** - -Edit `submodules/ContactListUI/BUILD`. Remove `"//submodules/Postbox:Postbox",` from `deps`. - -- [ ] **Step 5: Static checks** - -```bash -grep -R "^import Postbox" submodules/ContactListUI/Sources # expect: empty -grep "submodules/Postbox" submodules/ContactListUI/BUILD # expect: empty -``` - -- [ ] **Step 6: Full project build** - -Run the full build. Expected: PASS. Handle failures per the Build-failure handling rules in the Background section. ContactListUI is imported by other submodules (TelegramUI, SettingsUI, etc.); downstream breakage is most likely here. If a downstream consumer needs a bare `Peer`, either keep the public surface returning engine types (preferred — they're typealiases under the hood) or, if the downstream change is large, revert Task 5 and skip. - -- [ ] **Step 7: Commit** - -```bash -git add submodules/ContactListUI/ -git commit -m "$(cat <<'EOF' -ContactListUI: drop direct Postbox dependency - -Replace direct postbox.transaction calls with dedicated engine -methods; switch peer references to engine-typed equivalents; -remove the Postbox import and Bazel dep. Behavior-preserving. - -Co-Authored-By: Claude Opus 4.6 -EOF -)" -``` - ---- - -## Task 6: Refactor `DirectMediaImageCache` — **ABANDONED** - -**Status:** Abandoned for wave 1. No code changes in this repo from this task. - -**Reason:** The module's public `init(account: Account)` at line 241 takes `account: Account` (an umbrella type banned by spec rule 2). Out-of-wave callers include `submodules/CalendarMessageScreen/`, four TelegramUI components (`StoryContainerScreen`, `ShareWithPeersScreen`, `PeerInfoVisualMediaPaneNode` × 2), and `submodules/TelegramUI/Sources/AccountContext.swift`. Refactoring requires either aliasing `Account` (banned) or editing all those out-of-wave callers (banned). Per the abandonment protocol, the module is skipped. - -**Original task body (retained for audit trail, do not implement):** - -**Files:** -- Modify: `submodules/DirectMediaImageCache/Sources/DirectMediaImageCache.swift` -- Modify: `submodules/DirectMediaImageCache/BUILD` - -**Starting inventory** (computed during planning): `mediaBox` (×11), `PeerReference` (×6), `MediaResource` (×1), `TelegramMedia*` (×13), `Media`/`Message` type references. This module is **mediaBox-heavy** and is the canonical shape for the `engine.resources.*` extension work. - -- [ ] **Step 1: Inventory** - -Read the whole file. For each `mediaBox` call, record the method (`resourceData`, `resourceStatus`, `cachedResourceRepresentation`, `storeCachedResourceRepresentation`, `fetchedResource`, etc.) and whether it reads, writes, or subscribes. - -```bash -grep -nE "\bmediaBox\b|\b(PeerReference|MediaResource|TelegramMedia)" submodules/DirectMediaImageCache/Sources/DirectMediaImageCache.swift -``` - -- [ ] **Step 2: Map each reference** - -Each distinct `mediaBox.` signature → a method on `TelegramEngine.Resources`. Expected additions (names are suggestions — match existing naming if anything close already exists): - -- `engine.resources.data(_:pathExtension:option:attemptSynchronously:) -> Signal` -- `engine.resources.status(_:approximateSynchronousValue:) -> Signal` -- `engine.resources.cachedRepresentationData(_:representation:complete:) -> Signal<...>` -- `engine.resources.storeCachedRepresentation(_:representation:data:) -> Signal` - -Before adding any of these, grep `submodules/TelegramCore/Sources/TelegramEngine/Resources/` for existing equivalents and only add what's missing. - -`PeerReference`, `TelegramMedia*`, `MediaResource` — check each: `TelegramMedia*` types live in `TelegramCore` (not Postbox). `PeerReference` lives in `TelegramCore`. `MediaResource` is a Postbox protocol; add `EngineMediaResource = MediaResource` typealias if not already present. - -- [ ] **Step 2a: Add engine wrappers in TelegramCore** - -Add all missing methods on `Resources` and any missing typealiases. Each method is a one-line forward to `account.postbox.mediaBox.*`. Build; then commit using the TelegramCore wrapper commit template from the Background section, recording "searched Resources/ for equivalents: found/not found" in the message. - -- [ ] **Step 3: Edit the consumer file** - -Replace every `mediaBox.*` with `engine.resources.*`. This likely requires adding an `engine: TelegramEngine` parameter to a few internal functions in the file (or surfacing it from an existing `AccountContext` already in scope — prefer that). Switch types to engine typealiases. Remove `import Postbox`. - -- [ ] **Step 4: Drop the Bazel dep** - -Edit `submodules/DirectMediaImageCache/BUILD`. Remove `"//submodules/Postbox:Postbox",` from `deps`. - -- [ ] **Step 5: Static checks** - -```bash -grep -R "^import Postbox" submodules/DirectMediaImageCache/Sources # expect: empty -grep "submodules/Postbox" submodules/DirectMediaImageCache/BUILD # expect: empty -``` - -- [ ] **Step 6: Full project build** - -Run the full build. Expected: PASS. Handle failures per the Build-failure handling rules in the Background section. - -- [ ] **Step 7: Commit** - -```bash -git add submodules/DirectMediaImageCache/ -git commit -m "$(cat <<'EOF' -DirectMediaImageCache: drop direct Postbox dependency - -Route MediaBox calls through TelegramEngine.resources; remove the -Postbox import and Bazel dep. Behavior-preserving. - -Co-Authored-By: Claude Opus 4.6 -EOF -)" -``` - ---- - -## Task 7: Refactor `DrawingUI` - -**Files:** -- Modify: `submodules/DrawingUI/Sources/DrawingScreen.swift` -- Modify: `submodules/DrawingUI/BUILD` - -**Starting inventory** (computed during planning): `transaction` (×3), `Media` type references (×13), `Namespaces.` (×4). Transactions are the substantive work; `Media`/`Namespaces` are mostly referencing TelegramCore-defined types already. - -- [ ] **Step 1: Inventory** - -Read the whole file. For each `transaction` call, describe what the closure does. Capture every `Media`-typed declaration and every `Namespaces.*` reference. - -```bash -grep -nE "\btransaction\s*\{|account\.postbox|\b(Media|MediaId|Namespaces)\b" submodules/DrawingUI/Sources/DrawingScreen.swift -``` - -- [ ] **Step 2: Map each reference** - -- Each `postbox.transaction` → dedicated engine method. Inspect the closure to find the right home (`Stickers`, `Messages`, `Peers`, …). -- `Media` → `EngineMedia` where the value flows through new engine methods; keep as `Media` (TelegramCore re-defined concrete classes like `TelegramMediaFile` live in TelegramCore and are fine) where the type is already TelegramCore's. -- `Namespaces.*` — TelegramCore. No change. - -- [ ] **Step 2a: Add engine wrappers in TelegramCore** - -Add each new transaction-replacing method. Build; then use the TelegramCore wrapper commit template from the Background section. - -- [ ] **Step 3: Edit the consumer file** - -Apply mappings. Remove `import Postbox`. - -- [ ] **Step 4: Drop the Bazel dep** - -Edit `submodules/DrawingUI/BUILD`. Remove `"//submodules/Postbox:Postbox",` from `deps`. - -- [ ] **Step 5: Static checks** - -```bash -grep -R "^import Postbox" submodules/DrawingUI/Sources # expect: empty -grep "submodules/Postbox" submodules/DrawingUI/BUILD # expect: empty -``` - -- [ ] **Step 6: Full project build** - -Run the full build. Expected: PASS. Handle failures per the Build-failure handling rules in the Background section. - -- [ ] **Step 7: Commit** - -```bash -git add submodules/DrawingUI/ -git commit -m "$(cat <<'EOF' -DrawingUI: drop direct Postbox dependency - -Replace direct postbox.transaction calls with dedicated engine -methods; switch type references to engine equivalents; remove the -Postbox import and Bazel dep. Behavior-preserving. - -Co-Authored-By: Claude Opus 4.6 -EOF -)" -``` - ---- - -## Task 8: Refactor `FetchManagerImpl` — **ABANDONED** - -**Status:** Abandoned for wave 1. No code changes in this repo from this task. - -**Reason:** The module's public `init(postbox: Postbox, storeManager: DownloadedMediaStoreManager?)` at line 708 takes `postbox: Postbox`. Out-of-wave caller: `submodules/TelegramUI/Sources/AccountContext.swift:296`. Refactoring requires either aliasing the `Postbox` class (banned by spec rule 2) or editing TelegramUI (banned by wave boundary). Per the abandonment protocol, the module is skipped. - -**Original task body (retained for audit trail, do not implement):** - -**Files:** -- Modify: `submodules/FetchManagerImpl/Sources/FetchManagerImpl.swift` -- Modify: `submodules/FetchManagerImpl/BUILD` - -**Starting inventory** (computed during planning): `mediaBox` (×8), `MediaResource` (×4), `TelegramMedia` (×1). Shape is similar to DirectMediaImageCache — heavy `mediaBox` usage, no transactions. - -- [ ] **Step 1: Inventory** - -Read the whole file. For each `mediaBox` call, record the method and direction (read / subscribe / fetch-start). - -```bash -grep -nE "\bmediaBox\b|\b(MediaResource|TelegramMedia)\b" submodules/FetchManagerImpl/Sources/FetchManagerImpl.swift -``` - -- [ ] **Step 2: Map each reference** - -Reuse every `engine.resources.*` method added in Task 6 — do not re-add them. Grep: - -```bash -grep -rn "extension.*Resources\|public func" submodules/TelegramCore/Sources/TelegramEngine/Resources/ -``` - -If this task needs a `mediaBox` operation that Task 6 did not add (e.g. `cancelInteractiveResourceFetch`, `completeInteractiveResourceFetch`), add it now in the same pattern. - -`MediaResource` → `EngineMediaResource` typealias (already added in an earlier task if needed). `TelegramMedia` — TelegramCore type, no change. - -- [ ] **Step 2a: (Only if needed) Add missing engine methods** - -Minimal pass-through on `TelegramEngine.Resources`. Build, commit. - -- [ ] **Step 3: Edit the consumer file** - -Replace every `mediaBox.*` with `engine.resources.*`. Thread an `engine` argument through internal functions as needed (prefer reading it off an existing `AccountContext` already in scope). Remove `import Postbox`. - -- [ ] **Step 4: Drop the Bazel dep** - -Edit `submodules/FetchManagerImpl/BUILD`. Remove `"//submodules/Postbox:Postbox",` from `deps`. - -- [ ] **Step 5: Static checks** - -```bash -grep -R "^import Postbox" submodules/FetchManagerImpl/Sources # expect: empty -grep "submodules/Postbox" submodules/FetchManagerImpl/BUILD # expect: empty -``` - -- [ ] **Step 6: Full project build** - -Run the full build. Expected: PASS. Handle failures per the Build-failure handling rules in the Background section. - -- [ ] **Step 7: Commit** - -```bash -git add submodules/FetchManagerImpl/ -git commit -m "$(cat <<'EOF' -FetchManagerImpl: drop direct Postbox dependency - -Route MediaBox fetch/status calls through TelegramEngine.resources; -remove the Postbox import and Bazel dep. Behavior-preserving. - -Co-Authored-By: Claude Opus 4.6 -EOF -)" -``` - ---- - -## Task 9: Refactor `GalleryData` — **ABANDONED** - -**Status:** Abandoned for wave 1. No code changes in this repo from this task. - -**Reason:** Four public functions take `Media` (Postbox protocol) and/or `Message` (Postbox class) as parameters, called from TelegramUI and ChatListUI (out-of-wave). Refactoring to `EngineMedia` / `EngineMessage` requires `.init(_:)` / `._asMedia()` / `._asMessage()` coercions threaded through many local variables (e.g. `var galleryMedia: Media?` in `chatMessageGalleryControllerData` is reassigned from various `TelegramMedia*` casts and passed to `MessageReference(...)` chains and enum cases), which would cascade into `AvatarGalleryEntry`, `MessageReference`, and other out-of-wave types. The narrow-utility alias path is ruled out because `Media` and especially `Message` are domain types, not utilities. Per the abandonment protocol, the module is skipped. - -**Original task body (retained for audit trail, do not implement):** - -**Files:** -- Modify: `submodules/GalleryData/Sources/GalleryData.swift` -- Modify: `submodules/GalleryData/BUILD` - -**Starting inventory** (computed during planning): `Peer` (×1), `Media` (×9), `Message` (×4), `Namespaces.` (×3), `TelegramMedia*` (×30). No `mediaBox`, no `transaction`, no `combinedView`. This is a **type-reference-only** case at scale. - -- [ ] **Step 1: Inventory** - -Read the whole file. Record every declaration that uses a Postbox-owned type (`Peer`, `Media`, `Message`, `MessageId`, etc.) — note that `TelegramMedia*` and `Namespaces` are TelegramCore, not Postbox, and do **not** need changing. - -```bash -grep -nE "\b(Peer|Media|Message|MessageId|MessageIndex)\b" submodules/GalleryData/Sources/GalleryData.swift | head -60 -``` - -- [ ] **Step 2: Map each reference** - -- `Peer` → `EnginePeer` at the call-site level where the value is newly produced; for existing public signatures that already accept a `Peer` from elsewhere, prefer `EnginePeer` **only if** downstream consumers accept it. Otherwise leave the signature alone and swap only the internal uses. -- `Media`, `Message`, `MessageId` → engine typealiases per the cheat sheet. -- `TelegramMedia*`, `Namespaces.*` — no change. - -- [ ] **Step 2a: (Only if needed) Add engine typealiases** - -Add any missing typealias in `submodules/TelegramCore/Sources/TelegramEngine/…`. Build, commit. - -- [ ] **Step 3: Edit the consumer file** - -Apply mappings. Remove `import Postbox`. - -- [ ] **Step 4: Drop the Bazel dep** - -Edit `submodules/GalleryData/BUILD`. Remove `"//submodules/Postbox:Postbox",` from `deps`. - -- [ ] **Step 5: Static checks** - -```bash -grep -R "^import Postbox" submodules/GalleryData/Sources # expect: empty -grep "submodules/Postbox" submodules/GalleryData/BUILD # expect: empty -``` - -- [ ] **Step 6: Full project build** - -Run the full build. Expected: PASS. Handle failures per the Build-failure handling rules in the Background section. - -- [ ] **Step 7: Commit** - -```bash -git add submodules/GalleryData/ -git commit -m "$(cat <<'EOF' -GalleryData: drop direct Postbox dependency - -Switch Postbox-typed references to engine typealiases; remove the -Postbox import and Bazel dep. Behavior-preserving. - -Co-Authored-By: Claude Opus 4.6 -EOF -)" -``` - ---- - -## Task 10: Refactor `ICloudResources` — **ABANDONED** - -**Status:** Abandoned for wave 1. No code changes in this repo from this task. - -**Reason:** The module declares `public class ICloudFileResource: TelegramMediaResource` and thus must implement `func isEqual(to: MediaResource) -> Bool` (protocol requirement inherited from `MediaResource`). That override's parameter type is fixed at `MediaResource`, which can only be named by importing Postbox or adding a typealias for the raw `MediaResource` protocol. The protocol-alias would be borderline per rule 2; user directed to skip. Per the abandonment protocol, the module is skipped. - -**Original task body (retained for audit trail, do not implement):** - -### Original Task 10 - -**Files:** -- Modify: `submodules/ICloudResources/Sources/ICloudResources.swift` -- Modify: `submodules/ICloudResources/BUILD` - -**Starting inventory** (computed during planning): `MediaResource` (×2), `TelegramMedia` (×1). No `mediaBox`, no `transaction`. Small type-reference-only module. The `MediaResource` uses may be a custom `MediaResource`-conforming class defined in this file — confirm during inventory. - -- [ ] **Step 1: Inventory** - -Read the whole file. `MediaResource` is a Postbox protocol; `ICloudResources` likely declares a custom class conforming to it. Capture whether (a) the file declares new `MediaResource`-conforming types, (b) it only references the protocol, or both. - -```bash -grep -nE "\b(MediaResource|TelegramMedia)\b|class.*:.*MediaResource|struct.*:.*MediaResource" submodules/ICloudResources/Sources/ICloudResources.swift -``` - -- [ ] **Step 2: Map each reference** - -- If the file declares a type conforming to `MediaResource`, use the `EngineMediaResource` typealias in the declaration (`class FooResource: EngineMediaResource { ... }`). Because typealiases are transparent, this keeps protocol conformance identical. -- All other `MediaResource` references → `EngineMediaResource`. -- `TelegramMedia*` — TelegramCore, no change. - -Add `EngineMediaResource` typealias in TelegramCore if not already present (Task 2 / Task 6 may have added it; check first). - -- [ ] **Step 2a: (Only if needed) Add `EngineMediaResource` typealias** - -```swift -// submodules/TelegramCore/Sources/TelegramEngine/Resources/EngineMediaResource.swift -import Postbox -public typealias EngineMediaResource = MediaResource -``` - -Build, commit. - -- [ ] **Step 3: Edit the consumer file** - -Apply mappings. Remove `import Postbox`. - -- [ ] **Step 4: Drop the Bazel dep** - -Edit `submodules/ICloudResources/BUILD`. Remove `"//submodules/Postbox:Postbox",` from `deps`. - -- [ ] **Step 5: Static checks** - -```bash -grep -R "^import Postbox" submodules/ICloudResources/Sources # expect: empty -grep "submodules/Postbox" submodules/ICloudResources/BUILD # expect: empty -``` - -- [ ] **Step 6: Full project build** - -Run the full build. Expected: PASS. Handle failures per the Build-failure handling rules in the Background section. - -- [ ] **Step 7: Commit** - -```bash -git add submodules/ICloudResources/ -git commit -m "$(cat <<'EOF' -ICloudResources: drop direct Postbox dependency - -Switch MediaResource references to EngineMediaResource; remove the -Postbox import and Bazel dep. Behavior-preserving. - -Co-Authored-By: Claude Opus 4.6 -EOF -)" -``` - ---- - -## Task 11: Wave-1 completion verification - -**Files:** No code changes. - -- [ ] **Step 1: Static check across all 10 modules** - -```bash -for m in ActionSheetPeerItem ChatInterfaceState ChatListSearchRecentPeersNode ChatSendMessageActionUI ContactListUI DirectMediaImageCache DrawingUI FetchManagerImpl GalleryData ICloudResources; do - echo "=== $m ===" - grep -R "^import Postbox" submodules/$m/Sources && echo "FAIL: import in $m" - grep "submodules/Postbox" submodules/$m/BUILD && echo "FAIL: dep in $m" -done -``` - -Expected: no `FAIL` lines printed. If any appear, return to the corresponding task and fix. - -- [ ] **Step 2: Final full build** - -Run the full build one more time from a clean state. Expected: PASS. (If it passed at the end of Task 10 and nothing else has changed, this should be cached and fast.) - -- [ ] **Step 3: Review the commit log** - -```bash -git log --oneline master..HEAD -``` - -Expected: a run of commits matching the pattern `TelegramCore: add …` (optional) and `: drop direct Postbox dependency` (one per module done). If any module was skipped per the fallback rule, verify the fallback ran and a replacement module completed so the total is 10. - -- [ ] **Step 4: No commit** - -Verification only. - ---- - -## What's explicitly NOT in this plan - -- Any edits to `TelegramCore`, `Postbox`, or the 64 modules outside the chosen 10 (except the minimum engine-wrapper / typealias additions to `TelegramCore` that the chosen modules need). -- Any new `Engine*` wrapper *structs* (only typealiases and forwarding methods are in scope this wave). -- Any generic `engine.transaction { postbox in … }` escape hatch. -- Any behavior change, performance tweak, or "while we're here" cleanup. -- Any test work — there are no tests in this project. diff --git a/docs/superpowers/plans/2026-04-17-listview-pin-to-edge.md b/docs/superpowers/plans/2026-04-17-listview-pin-to-edge.md deleted file mode 100644 index e250e25aef..0000000000 --- a/docs/superpowers/plans/2026-04-17-listview-pin-to-edge.md +++ /dev/null @@ -1,223 +0,0 @@ -# ListView pin-to-edge Implementation Plan - -> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. - -**Goal:** Implement the first-pinned-item-to-bottom-edge behavior in `ListView` by adding a `calculatePinToEdgeTopInset()` helper and wiring it into `snapToBounds` and `updateScroller`, matching the design in [docs/superpowers/specs/2026-04-17-listview-pin-to-edge-design.md](../specs/2026-04-17-listview-pin-to-edge-design.md). - -**Architecture:** Heights-based virtual-top-inset adjustment. A new private helper on `ListViewImpl` computes `max(0, visibleArea - ΣheightsAboveAndIncludingPinned)`. Two call sites add this to `effectiveInsets.top` via the existing `max(…)` chain alongside `stackFromBottomInsetItemFactor`. - -**Tech Stack:** Swift, ASDisplayKit, Bazel build system. - -**Scope:** Single file — `submodules/Display/Source/ListView.swift`. No protocol change (`pinToEdgeWithInset` is already declared on `ListViewItem`). No consumer changes. Because no item overrides `pinToEdgeWithInset` from its default `false`, the existing app surface's behavior is unchanged after this plan lands; the feature will be exercised only by a future consumer in a separate change. - -**No unit tests** exist in this project (per `CLAUDE.md`). Verification is via the full project build. - ---- - -## Task 1: Add `calculatePinToEdgeTopInset` helper and integrate at both call sites - -**Files:** -- Modify: `submodules/Display/Source/ListView.swift` - -The helper, both call-site edits, and the build verification land in one commit because they are tightly coupled: committing the helper without any call site is a no-op, and committing only one of the two call sites would cause `updateScroller` and `snapToBounds` to disagree about `effectiveInsets.top`, producing scroll-position desync whenever pinning is engaged. - ---- - -- [ ] **Step 1: Insert the `calculatePinToEdgeTopInset` helper after `calculateAdditionalTopInverseInset`** - -Use the Edit tool. The helper goes immediately after `calculateAdditionalTopInverseInset`'s closing brace (line 1090) and before `areAllItemsOnScreen` (line 1092). - -old_string: -```swift - private func calculateAdditionalTopInverseInset() -> CGFloat { - var additionalInverseTopInset: CGFloat = 0.0 - if !self.stackFromBottomInsetItemFactor.isZero { - var remainingFactor = self.stackFromBottomInsetItemFactor - for itemNode in self.itemNodes { - if remainingFactor.isLessThanOrEqualTo(0.0) { - break - } - - let itemFactor: CGFloat - if CGFloat(1.0).isLessThanOrEqualTo(remainingFactor) { - itemFactor = 1.0 - } else { - itemFactor = remainingFactor - } - - additionalInverseTopInset += floor(itemNode.apparentBounds.height * itemFactor) - - remainingFactor -= 1.0 - } - } - return additionalInverseTopInset - } - - private func areAllItemsOnScreen() -> Bool { -``` - -new_string: -```swift - private func calculateAdditionalTopInverseInset() -> CGFloat { - var additionalInverseTopInset: CGFloat = 0.0 - if !self.stackFromBottomInsetItemFactor.isZero { - var remainingFactor = self.stackFromBottomInsetItemFactor - for itemNode in self.itemNodes { - if remainingFactor.isLessThanOrEqualTo(0.0) { - break - } - - let itemFactor: CGFloat - if CGFloat(1.0).isLessThanOrEqualTo(remainingFactor) { - itemFactor = 1.0 - } else { - itemFactor = remainingFactor - } - - additionalInverseTopInset += floor(itemNode.apparentBounds.height * itemFactor) - - remainingFactor -= 1.0 - } - } - return additionalInverseTopInset - } - - private func calculatePinToEdgeTopInset() -> CGFloat { - var lowestPinnedIndex: Int = Int.max - for itemNode in self.itemNodes { - guard let index = itemNode.index else { continue } - if index < lowestPinnedIndex && self.items[index].pinToEdgeWithInset { - lowestPinnedIndex = index - } - } - guard lowestPinnedIndex != Int.max else { return 0.0 } - - var totalAboveAndPinned: CGFloat = 0.0 - var sawIndexZero = false - for itemNode in self.itemNodes { - guard let index = itemNode.index else { continue } - if index == 0 { - sawIndexZero = true - } - if index <= lowestPinnedIndex { - totalAboveAndPinned += itemNode.apparentBounds.height - } - } - guard sawIndexZero else { return 0.0 } - - let visibleArea = self.visibleSize.height - self.insets.top - self.insets.bottom - return max(0.0, visibleArea - totalAboveAndPinned) - } - - private func areAllItemsOnScreen() -> Bool { -``` - -- [ ] **Step 2: Integrate at the `snapToBounds` call site** - -Use the Edit tool. The block at lines 1181-1185 in `snapToBounds` gets a new `pinToEdgeTopInset` stanza after the existing `stackFromBottomInsetItemFactor` branch. Include the following line (` ` + `if topItemFound {`) in the old_string to disambiguate from the structurally-identical block in `areAllItemsOnScreen` at line 1110. - -old_string: -```swift - var effectiveInsets = self.insets - if topItemFound && !self.stackFromBottomInsetItemFactor.isZero { - let additionalInverseTopInset = self.calculateAdditionalTopInverseInset() - effectiveInsets.top = max(effectiveInsets.top, self.visibleSize.height - additionalInverseTopInset) - } - - if topItemFound { -``` - -new_string: -```swift - var effectiveInsets = self.insets - if topItemFound && !self.stackFromBottomInsetItemFactor.isZero { - let additionalInverseTopInset = self.calculateAdditionalTopInverseInset() - effectiveInsets.top = max(effectiveInsets.top, self.visibleSize.height - additionalInverseTopInset) - } - let pinToEdgeTopInset = self.calculatePinToEdgeTopInset() - if pinToEdgeTopInset > 0.0 { - effectiveInsets.top = max(effectiveInsets.top, self.insets.top + pinToEdgeTopInset) - } - - if topItemFound { -``` - -- [ ] **Step 3: Integrate at the `updateScroller` call site** - -Use the Edit tool. The block at lines 1612-1616 in `updateScroller` is nested one extra level (12-space indent rather than 8-space), so the string alone is unique and the old_string doesn't need extra context. - -old_string: -```swift - var effectiveInsets = self.insets - if topItemFound && !self.stackFromBottomInsetItemFactor.isZero { - let additionalInverseTopInset = self.calculateAdditionalTopInverseInset() - effectiveInsets.top = max(effectiveInsets.top, self.visibleSize.height - additionalInverseTopInset) - } - - completeHeight = effectiveInsets.top + effectiveInsets.bottom -``` - -new_string: -```swift - var effectiveInsets = self.insets - if topItemFound && !self.stackFromBottomInsetItemFactor.isZero { - let additionalInverseTopInset = self.calculateAdditionalTopInverseInset() - effectiveInsets.top = max(effectiveInsets.top, self.visibleSize.height - additionalInverseTopInset) - } - let pinToEdgeTopInset = self.calculatePinToEdgeTopInset() - if pinToEdgeTopInset > 0.0 { - effectiveInsets.top = max(effectiveInsets.top, self.insets.top + pinToEdgeTopInset) - } - - completeHeight = effectiveInsets.top + effectiveInsets.bottom -``` - -- [ ] **Step 4: Run the full project build** - -Use the Bash tool. The build takes several minutes; run it in the foreground so the agent waits for completion and surfaces failures immediately. The `source ~/.zshrc` prefix picks up `TELEGRAM_CODESIGNING_GIT_PASSWORD` per the build-environment quirk documented in `CLAUDE.md`. - -``` -source ~/.zshrc 2>/dev/null; PATH=/opt/homebrew/opt/ruby/bin:`gem environment gemdir`/bin:$PATH python3 build-system/Make/Make.py --overrideXcodeVersion --cacheDir ~/telegram-bazel-cache build --configurationPath build-system/appstore-configuration.json --gitCodesigningRepository git@gitlab.com:peter-iakovlev/fastlanematch.git --gitCodesigningType development --gitCodesigningUseCurrent --buildNumber 1 --configuration debug_sim_arm64 -``` - -Expected: successful build. No warnings or errors touching `ListView.swift`. - -If the build fails: -- Swift syntax error → re-read `ListView.swift` around the edited regions; compare against the plan's old_string/new_string; fix and re-run. -- "`pinToEdgeWithInset` has no member" → the protocol property wasn't found; verify `submodules/Display/Source/ListViewItem.swift:80` still declares `var pinToEdgeWithInset: Bool { get }` and the default implementation at `ListViewItem.swift:102` is intact. If intact but the error persists, check that the `items` array's element type is `ListViewItem` (it is — see `public final var items: [ListViewItem]` in `ListView.swift`). -- Any other failure in unrelated files → not caused by this plan; investigate separately. - -- [ ] **Step 5: Commit** - -```bash -git add submodules/Display/Source/ListView.swift -git commit -m "$(cat <<'EOF' -Display/ListView: pin first pinToEdgeWithInset item to bottom edge - -Adds calculatePinToEdgeTopInset() and wires it into snapToBounds and -updateScroller. When the smallest-index item with pinToEdgeWithInset=true -plus all items above it have a combined apparentBounds height less than -the available scrolling area, the helper returns a positive top-inset -contribution that pushes the pinned item's maxY to visibleSize.height - -insets.bottom. Once items above reach the available area, the -contribution is zero and scrolling is fully ordinary. - -Spec: docs/superpowers/specs/2026-04-17-listview-pin-to-edge-design.md - -Co-Authored-By: Claude Opus 4.7 (1M context) -EOF -)" -``` - -Verify with `git status` that the tree is clean after the commit. - ---- - -## Rationale for task granularity - -This plan has a single task. I considered splitting "add helper" from "apply at two call sites" into two commits: - -- **For splitting:** one commit per "unit of change" is more bisectable. -- **Against splitting:** the helper alone is unused (runtime no-op, and Swift does not warn on unused private methods). Applying at one call site without the other would produce a live bug — `snapToBounds` and `updateScroller` would disagree whenever pinning engages, and `updateScroller` is what sets `scroller.contentSize`/`contentOffset`. Three commits land an internally-consistent state only at the third commit. - -Bundling all edits preserves bisectability at the feature-level boundary (the commit either introduces pin-to-edge support or it doesn't) and keeps the repo free of intermediate broken states. diff --git a/docs/superpowers/plans/2026-04-17-mediaresource-to-enginemediaresource-wave-2.md b/docs/superpowers/plans/2026-04-17-mediaresource-to-enginemediaresource-wave-2.md deleted file mode 100644 index 94b5f43479..0000000000 --- a/docs/superpowers/plans/2026-04-17-mediaresource-to-enginemediaresource-wave-2.md +++ /dev/null @@ -1,880 +0,0 @@ -# MediaResource → EngineMediaResource Refactor (Wave 2) — Implementation Plan - -> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. - -**Goal:** Drive raw `MediaResource` (Postbox protocol) out of the `TelegramEngine` public facade by changing facade-function signatures in-place to take/return `EngineMediaResource`, bridging to the existing `_internal_*` Postbox-facing implementations via wrap/unwrap helpers. In the same commit as each facade change, update every call site. Follow up with a first small batch of consumer type-reference migrations. - -**Architecture:** `TelegramEngine` facade methods live alongside `_internal_*` Postbox-using implementations in `submodules/TelegramCore/Sources/TelegramEngine//`. Today the facade methods already bridge (storing an `Account` and delegating), but their public signatures still expose raw `MediaResource`. The fix: change facade signatures to `EngineMediaResource` (including the `mapResourceToAvatarSizes` closure types) and add the two-line wrap/unwrap bridging. `_internal_*` functions stay on raw `MediaResource` — they are the Postbox-facing layer and must remain so. Consumer call sites swap `MediaResource` → `EngineMediaResource` (usually via `EngineMediaResource(raw)` wrap or `engineResource._asResource()` unwrap at a nearby boundary). - -**Tech Stack:** Swift, Bazel, Postbox (opaque storage), TelegramCore (public facade), SSignalKit. - -**Design constraint (IMPORTANT):** `TelegramCore` is shared with the Telegram-Mac codebase and must **not** import UIKit/Display. Any UIKit-requiring logic (image scaling, `UIImage`, `generateScaledImage`, etc.) stays in consumer-side submodules. Engine API additions must not pull in UIKit. - -**Why not overloads:** An earlier iteration of this plan added opt-in `EngineMediaResource` overloads and kept the raw overloads. That was rejected: duplicate signatures fragment the public API and leave raw-`MediaResource` leaks forever. The correct pattern is to change the single facade function in-place so it takes engine types and bridges inside, forcing callers to migrate in the same commit. - ---- - -## Background the executor needs - -### The full build command - -Run from the repo root (`/Users/ali/build/telegram/telegram-ios`): - -```bash -source ~/.zshrc 2>/dev/null; \ -PATH=/opt/homebrew/opt/ruby/bin:`gem environment gemdir`/bin:$PATH \ - python3 build-system/Make/Make.py --overrideXcodeVersion \ - --cacheDir ~/telegram-bazel-cache \ - build \ - --configurationPath build-system/appstore-configuration.json \ - --gitCodesigningRepository git@gitlab.com:peter-iakovlev/fastlanematch.git \ - --gitCodesigningType development \ - --gitCodesigningUseCurrent \ - --buildNumber 1 \ - --configuration debug_sim_arm64 -``` - -The build is the only verification (no unit tests per `CLAUDE.md`). Every task ends with a full build that must go green before the next task starts. - -### What `EngineMediaResource` gives you today (bridge primitives) - -Defined in [TelegramEngineResources.swift](../../../submodules/TelegramCore/Sources/TelegramEngine/Resources/TelegramEngineResources.swift): - -```swift -public final class EngineMediaResource: Equatable { - public init(_ resource: MediaResource) - public func _asResource() -> MediaResource - public var id: Id - public struct Id: Equatable, Hashable { - public init(_ id: MediaResourceId) - public init(_ stringRepresentation: String) - } - public final class ResourceData { - public let path: String; public let availableSize: Int64; public let isComplete: Bool - } - public enum FetchStatus: Equatable { /* Remote/Local/Fetching/Paused */ } -} -public extension EngineMediaResource.ResourceData { - convenience init(_ data: MediaResourceData) -} -``` - -### The bridging pattern - -For each facade function whose public signature contains `MediaResource`: - -**Before** (raw-protocol leak): - -```swift -public func uploadedPeerPhoto(resource: MediaResource) -> Signal { - return _internal_uploadedPeerPhoto(postbox: self.account.postbox, network: self.account.network, resource: resource) -} -``` - -**After** (engine-typed facade, internal bridge): - -```swift -public func uploadedPeerPhoto(resource: EngineMediaResource) -> Signal { - return _internal_uploadedPeerPhoto(postbox: self.account.postbox, network: self.account.network, resource: resource._asResource()) -} -``` - -For closures that receive a `MediaResource`: - -**Before:** - -```swift -public func updatePeerPhoto(..., mapResourceToAvatarSizes: @escaping (MediaResource, [TelegramMediaImageRepresentation]) -> Signal<[Int: Data], NoError>) -> ... { - return _internal_updatePeerPhoto(..., mapResourceToAvatarSizes: mapResourceToAvatarSizes) -} -``` - -**After:** - -```swift -public func updatePeerPhoto(..., mapResourceToAvatarSizes: @escaping (EngineMediaResource, [TelegramMediaImageRepresentation]) -> Signal<[Int: Data], NoError>) -> ... { - return _internal_updatePeerPhoto(..., mapResourceToAvatarSizes: { rawResource, representations in - mapResourceToAvatarSizes(EngineMediaResource(rawResource), representations) - }) -} -``` - -`_internal_*` functions are **not** changed — they stay on raw `MediaResource` as the Postbox-facing layer. - -### Call-site migration pattern - -At each call site, the change is mechanical: - -- `engine.peers.uploadedPeerPhoto(resource: someRawResource)` → `engine.peers.uploadedPeerPhoto(resource: EngineMediaResource(someRawResource))`. -- `engine.peers.updatePeerPhoto(..., mapResourceToAvatarSizes: { resource, representations in ... resource ... })` — the closure's `resource` is now `EngineMediaResource`. Any expression inside the closure that previously treated `resource` as raw protocol (e.g. `postbox.mediaBox.resourceData(resource)`) must use `resource._asResource()`. - -Where the consumer was carrying a `MediaResource?` property / local purely as a pipe into one of these APIs, migrate the property itself to `EngineMediaResource?` so no unwrap/wrap churn is needed. - -### Static-check commands - -```bash -grep -R "^import Postbox" submodules//Sources # expect: empty (only when a module is being fully de-Postboxed) -grep "submodules/Postbox" submodules//BUILD # expect: empty (same condition) -``` - -### Commit convention - -- One commit per engine API family: `TelegramCore: migrate to EngineMediaResource` — bundles facade-signature change **and** all call sites updated in the same commit. The repo must build on every commit. -- Consumer-only type-ref commits: `: migrate MediaResource property to EngineMediaResource` or `: drop direct Postbox dependency`. -- Always use HEREDOC bodies. No `--amend`. - -### What is explicitly out of scope - -- Classes that **conform to `TelegramMediaResource`** (must implement `isEqual(to: MediaResource)`): remain `import Postbox`. Enumerated: - - `submodules/ICloudResources/Sources/ICloudResources.swift` — `ICloudFileResource` - - `submodules/InstantPageUI/Sources/InstantPageExternalMediaResource.swift` — `InstantPageExternalMediaResource` - - `submodules/LocalMediaResources/Sources/LocalMediaResources.swift` — `VideoLibraryMediaResource` - - `submodules/TelegramUniversalVideoContent/Sources/YoutubeEmbedImplementation.swift` — `YoutubeEmbedStoryboardMediaResource` -- TelegramCore-internal `MediaResource` usage (SyncCore, Fetch, `_internal_*` functions, etc.) — Postbox-facing layer. -- Modules already abandoned in wave 1 for non-MediaResource reasons (`FetchManagerImpl` / `ICloudResources` have other umbrella-type blockers). -- The heavy-leak modules in the "Future waves" table at the bottom (`PassportUI`, `TelegramUI`, etc.). -- Importing UIKit/Display into TelegramCore under any circumstance. - ---- - -## Task 0: Baseline verification - -**Files:** No code changes. - -- [ ] **Step 1: Confirm tree state** - -```bash -git status -git log --oneline -5 -``` - -Expected: working tree clean apart from pre-existing untracked (`build-system/tulsi/`, `submodules/TgVoip/`, `third-party/libx264/`) and submodule-content drift on `build-system/bazel-rules/sourcekit-bazel-bsp`. HEAD on `master`. - -- [ ] **Step 2: Baseline build** - -Run the full build command above. Expected: PASS. - -If it fails, stop — a non-green baseline is out of scope. - -- [ ] **Step 3: No commit.** - ---- - -## Task 1: Record the new rules in CLAUDE.md - -**Files:** -- Modify: `CLAUDE.md` - -- [ ] **Step 1: Add the "TelegramCore no UIKit" rule** - -In `CLAUDE.md`, inside the `## Postbox → TelegramEngine refactor (in progress)` section, under `### Rules that apply to every wave`, append a new numbered rule after the existing rule 6: - -```markdown -7. **TelegramCore never imports UIKit/Display.** `TelegramCore` is shared with the Telegram-Mac codebase; its Bazel `deps` and source files must not reference UIKit, Display, or any Apple-UI framework. UIKit-needing helpers (image scaling, rendering, etc.) stay in consumer-side submodules. -``` - -- [ ] **Step 2: Add the MediaResource → EngineMediaResource migration pattern** - -After the `### Engine typealias cheat sheet (existing aliases)` block (which ends with the `MediaResource` / `TelegramMediaResource` note), insert a new section: - -```markdown -### MediaResource → EngineMediaResource consumer migration - -`EngineMediaResource` is a `final class` in `TelegramCore` wrapping a `MediaResource` value. Unlike the typealiases above it is **not** interchangeable with the protocol, but it does provide wrap/unwrap helpers: - -- `EngineMediaResource(rawResource)` — wrap a raw `MediaResource`. -- `engineResource._asResource()` — unwrap to the raw `MediaResource`. -- `EngineMediaResource.ResourceData(rawResourceData)` — wrap `MediaResourceData`. -- `EngineMediaResource.Id(rawMediaResourceId)` — wrap `MediaResourceId`. - -**Pattern for facade functions:** when a `TelegramEngine.` method leaks raw `MediaResource` in its public signature, **change the facade signature in place** to `EngineMediaResource` (and change any closure parameter types the same way). Bridge inside the facade body by calling the existing `_internal_*` function with `engineResource._asResource()` / wrapping raw inputs from inner closures with `EngineMediaResource(rawResource)`. Update all call sites in the same commit. The `_internal_*` function stays on raw `MediaResource` — it is the Postbox-facing layer. - -Do **not** add opt-in `EngineMediaResource` overloads alongside raw-`MediaResource` overloads. Duplicate signatures fragment the public API and leave the leak in place forever. - -For consumer modules, prefer `EngineMediaResource` as the type in properties, locals, generic arguments and function parameters when the usage is a pure type reference. Do **not** try to use `EngineMediaResource` where a class must conform to `TelegramMediaResource` (Postbox protocol) or override `isEqual(to: MediaResource)` — those remain `import Postbox`. -``` - -- [ ] **Step 3: Full build (sanity — docs only)** - -Run the full build. Expected: PASS. - -- [ ] **Step 4: Commit** - -```bash -git add CLAUDE.md -git commit -m "$(cat <<'EOF' -CLAUDE.md: record TelegramCore-no-UIKit rule and EngineMediaResource migration pattern - -Wave-2 preparation. Codifies that TelegramCore is shared with -Telegram-Mac and must stay UIKit-free, and documents the -modify-in-place / bridge-inside pattern for migrating -MediaResource-leaking facade functions to EngineMediaResource. - -Co-Authored-By: Claude Opus 4.6 -EOF -)" -``` - ---- - -## Task 2: Migrate `TelegramEngine.Peers` photo APIs to `EngineMediaResource` - -**Files:** -- Modify: `submodules/TelegramCore/Sources/TelegramEngine/Peers/TelegramEnginePeers.swift` -- Modify: all call sites (13 + 11 + 7, with heavy overlap — see Step 2 grep). - -**Functions migrated in this task:** -- `uploadedPeerPhoto(resource:)` (line 704) — `MediaResource` → `EngineMediaResource` -- `uploadedPeerVideo(resource:)` (line 708) — `MediaResource` → `EngineMediaResource` -- `updatePeerPhoto(..., mapResourceToAvatarSizes:)` (line 712) — closure parameter `MediaResource` → `EngineMediaResource` - -- [ ] **Step 1: Read the current signatures** - -Read lines 704–720 of `submodules/TelegramCore/Sources/TelegramEngine/Peers/TelegramEnginePeers.swift`. Confirm the three functions match the pattern `return _internal_(postbox: self.account.postbox, ..., resource: resource)` or equivalent. - -- [ ] **Step 2: Enumerate call sites** - -```bash -grep -rnE "\\.(uploadedPeerPhoto|uploadedPeerVideo|updatePeerPhoto)\(" submodules/ \ - | grep -v "submodules/TelegramCore" -``` - -Capture every hit — file path, line number, approximate surrounding context (what resource expression is passed in / what the closure body does). The distribution as of planning: - -- `uploadedPeerPhoto`: 11 call sites (spread across TelegramUI, TelegramCallsUI, AuthorizationUI, etc.) -- `uploadedPeerVideo`: 7 -- `updatePeerPhoto`: 13 - -Many call sites chain these (e.g. `updatePeerPhoto(photo: engine.peers.uploadedPeerPhoto(resource: ...))`) so a single file often touches two or three of them in one call. - -- [ ] **Step 3: Change the facade signatures + bridge** - -In `TelegramEnginePeers.swift`, change the three functions to: - -```swift -public func uploadedPeerPhoto(resource: EngineMediaResource) -> Signal { - return _internal_uploadedPeerPhoto(postbox: self.account.postbox, network: self.account.network, resource: resource._asResource()) -} - -public func uploadedPeerVideo(resource: EngineMediaResource) -> Signal { - return _internal_uploadedPeerVideo(postbox: self.account.postbox, network: self.account.network, messageMediaPreuploadManager: self.account.messageMediaPreuploadManager, resource: resource._asResource()) -} - -public func updatePeerPhoto(peerId: PeerId, photo: Signal?, video: Signal? = nil, videoStartTimestamp: Double? = nil, markup: UploadPeerPhotoMarkup? = nil, mapResourceToAvatarSizes: @escaping (EngineMediaResource, [TelegramMediaImageRepresentation]) -> Signal<[Int: Data], NoError>) -> Signal { - return _internal_updatePeerPhoto(postbox: self.account.postbox, network: self.account.network, stateManager: self.account.stateManager, accountPeerId: self.account.peerId, peerId: peerId, photo: photo, video: video, videoStartTimestamp: videoStartTimestamp, markup: markup, mapResourceToAvatarSizes: { rawResource, representations in - return mapResourceToAvatarSizes(EngineMediaResource(rawResource), representations) - }) -} -``` - -**Before editing, re-read the existing bodies** — the exact arg names passed into `_internal_updatePeerPhoto` etc. must match what's already there (the skeletons above reproduce what's in the file at planning time, but the executor should preserve every argument the current implementation passes). Only the outer signature and the closure-wrapping change. - -- [ ] **Step 4: Update every call site** (same commit) - -For each hit from Step 2, rewrite the call site per the patterns: - -**Pattern A — passing a raw resource to `uploadedPeerPhoto` / `uploadedPeerVideo`:** - -```swift -// Before: -engine.peers.uploadedPeerPhoto(resource: someRawResource) -// After: -engine.peers.uploadedPeerPhoto(resource: EngineMediaResource(someRawResource)) -``` - -**Pattern B — the `mapResourceToAvatarSizes` closure of `updatePeerPhoto`:** - -```swift -// Before: -mapResourceToAvatarSizes: { resource, representations in - return mapResourceToAvatarSizes(postbox: postbox, resource: resource, representations: representations) -} -// After (if the helper is still raw-MediaResource-facing at this point): -mapResourceToAvatarSizes: { resource, representations in - return mapResourceToAvatarSizes(postbox: postbox, resource: resource._asResource(), representations: representations) -} -``` - -Task 6 will change `mapResourceToAvatarSizes` itself to accept `EngineMediaResource` and drop the `_asResource()` call. Until Task 6 lands, keep the `_asResource()` here. This keeps the build green between tasks. - -**Pattern C — the consumer was already carrying the resource as a `MediaResource?` local purely as a pipe:** - -If a nearby local/property typed `MediaResource?` only exists to feed `uploadedPeerPhoto(resource:)` or similar, change the local's type to `EngineMediaResource?` at the same time. This avoids wrap/unwrap churn at the call site. - -- [ ] **Step 5: Full build** - -Run the full build. Expected: PASS. - -If it fails, the first error locates the broken call site. Apply Pattern A / B / C at that site and rebuild. If a file imports Postbox only for `MediaResource` and now has no other Postbox identifier, you may optionally remove `import Postbox` in the same commit — but that is not required here; it is a separate goal. - -- [ ] **Step 6: Commit** - -```bash -git add submodules/TelegramCore/Sources/TelegramEngine/Peers/TelegramEnginePeers.swift submodules/ -git commit -m "$(cat <<'EOF' -TelegramCore: migrate peer-photo facade to EngineMediaResource - -Change TelegramEngine.Peers.uploadedPeerPhoto / uploadedPeerVideo / -updatePeerPhoto so their public signatures take EngineMediaResource -instead of raw MediaResource (and the mapResourceToAvatarSizes closure -receives EngineMediaResource). The facade bridges to the existing -_internal_* Postbox-facing implementations via _asResource() / -EngineMediaResource(_:). All call sites updated in this commit. - -Part of the MediaResource -> EngineMediaResource migration (wave 2). -No behavior change. - -Co-Authored-By: Claude Opus 4.6 -EOF -)" -``` - ---- - -## Task 3: Migrate `TelegramEngine.AccountData.updateAccountPhoto` and `updateFallbackPhoto` - -**Files:** -- Modify: `submodules/TelegramCore/Sources/TelegramEngine/AccountData/TelegramEngineAccountData.swift` -- Modify: all call sites (5 + 4). - -- [ ] **Step 1: Read the current signatures** - -Read lines 55–90 of `submodules/TelegramCore/Sources/TelegramEngine/AccountData/TelegramEngineAccountData.swift`. Confirm both functions match the expected pattern. - -- [ ] **Step 2: Enumerate call sites** - -```bash -grep -rnE "\\.(updateAccountPhoto|updateFallbackPhoto)\(" submodules/ \ - | grep -v "submodules/TelegramCore" -``` - -- [ ] **Step 3: Change the facade signatures + bridge** - -Change both functions in place: - -```swift -public func updateAccountPhoto(resource: EngineMediaResource?, videoResource: EngineMediaResource?, videoStartTimestamp: Double?, markup: UploadPeerPhotoMarkup?, mapResourceToAvatarSizes: @escaping (EngineMediaResource, [TelegramMediaImageRepresentation]) -> Signal<[Int: Data], NoError>) -> Signal { - return _internal_updateAccountPhoto(account: self.account, resource: resource?._asResource(), videoResource: videoResource?._asResource(), videoStartTimestamp: videoStartTimestamp, markup: markup, mapResourceToAvatarSizes: { rawResource, representations in - return mapResourceToAvatarSizes(EngineMediaResource(rawResource), representations) - }) -} - -public func updateFallbackPhoto(resource: EngineMediaResource?, videoResource: EngineMediaResource?, videoStartTimestamp: Double?, markup: UploadPeerPhotoMarkup?, mapResourceToAvatarSizes: @escaping (EngineMediaResource, [TelegramMediaImageRepresentation]) -> Signal<[Int: Data], NoError>) -> Signal { - return _internal_updateFallbackPhoto(account: self.account, resource: resource?._asResource(), videoResource: videoResource?._asResource(), videoStartTimestamp: videoStartTimestamp, markup: markup, mapResourceToAvatarSizes: { rawResource, representations in - return mapResourceToAvatarSizes(EngineMediaResource(rawResource), representations) - }) -} -``` - -**Before editing, verify the exact argument names passed to `_internal_updateAccountPhoto` / `_internal_updateFallbackPhoto`** in the current file. Copy those argument spellings verbatim (only the outer signature and inner closure wrapping change). - -- [ ] **Step 4: Update every call site** (same commit) - -Apply Pattern A/B/C from Task 2 to every hit. Wrap `EngineMediaResource(...)` around raw-resource args; add `._asResource()` inside any `mapResourceToAvatarSizes:` closure body where it hands the value onward to a still-raw helper (removed in Task 6). - -- [ ] **Step 5: Full build** - -Run the full build. Expected: PASS. - -- [ ] **Step 6: Commit** - -```bash -git add submodules/TelegramCore/Sources/TelegramEngine/AccountData/TelegramEngineAccountData.swift submodules/ -git commit -m "$(cat <<'EOF' -TelegramCore: migrate account-photo facade to EngineMediaResource - -Change TelegramEngine.AccountData.updateAccountPhoto and -updateFallbackPhoto so their public signatures take EngineMediaResource -(and the mapResourceToAvatarSizes closure receives -EngineMediaResource). Bridges to _internal_* functions via -_asResource()/EngineMediaResource(_:). All call sites updated in this -commit. - -Part of the MediaResource -> EngineMediaResource migration (wave 2). -No behavior change. - -Co-Authored-By: Claude Opus 4.6 -EOF -)" -``` - ---- - -## Task 4: Migrate `TelegramEngine.Contacts.updateContactPhoto` - -**Files:** -- Modify: `submodules/TelegramCore/Sources/TelegramEngine/Contacts/TelegramEngineContacts.swift` -- Modify: all call sites (8). - -- [ ] **Step 1: Read the current signature** - -Read around line 33 of `submodules/TelegramCore/Sources/TelegramEngine/Contacts/TelegramEngineContacts.swift`. - -- [ ] **Step 2: Enumerate call sites** - -```bash -grep -rn "\.updateContactPhoto(" submodules/ | grep -v "submodules/TelegramCore" -``` - -- [ ] **Step 3: Change the facade signature + bridge** - -```swift -public func updateContactPhoto(peerId: PeerId, resource: EngineMediaResource?, videoResource: EngineMediaResource?, videoStartTimestamp: Double?, markup: UploadPeerPhotoMarkup?, mode: SetCustomPeerPhotoMode, mapResourceToAvatarSizes: @escaping (EngineMediaResource, [TelegramMediaImageRepresentation]) -> Signal<[Int: Data], NoError>) -> Signal { - return _internal_updateContactPhoto(account: self.account, peerId: peerId, resource: resource?._asResource(), videoResource: videoResource?._asResource(), videoStartTimestamp: videoStartTimestamp, markup: markup, mode: mode, mapResourceToAvatarSizes: { rawResource, representations in - return mapResourceToAvatarSizes(EngineMediaResource(rawResource), representations) - }) -} -``` - -Verify the `_internal_updateContactPhoto` call spelling against the existing file before committing. - -- [ ] **Step 4: Update every call site** (same commit) - -Pattern A/B/C as in Task 2. - -- [ ] **Step 5: Full build** - -Run the full build. Expected: PASS. - -- [ ] **Step 6: Commit** - -```bash -git add submodules/TelegramCore/Sources/TelegramEngine/Contacts/TelegramEngineContacts.swift submodules/ -git commit -m "$(cat <<'EOF' -TelegramCore: migrate updateContactPhoto facade to EngineMediaResource - -Change TelegramEngine.Contacts.updateContactPhoto so its public -signature takes EngineMediaResource parameters and the -mapResourceToAvatarSizes closure receives EngineMediaResource. Bridges -to _internal_updateContactPhoto via _asResource()/EngineMediaResource(_:). -All call sites updated in this commit. - -Part of the MediaResource -> EngineMediaResource migration (wave 2). -No behavior change. - -Co-Authored-By: Claude Opus 4.6 -EOF -)" -``` - ---- - -## Task 5: Migrate `TelegramEngine.Auth.uploadedPeerVideo` - -**Files:** -- Modify: `submodules/TelegramCore/Sources/TelegramEngine/Auth/TelegramEngineAuth.swift` -- Modify: call sites that route through `TelegramEngine.Auth.uploadedPeerVideo` (separate from `TelegramEngine.Peers.uploadedPeerVideo`). - -- [ ] **Step 1: Read the current signature** - -Read around line 51 of `submodules/TelegramCore/Sources/TelegramEngine/Auth/TelegramEngineAuth.swift`. - -- [ ] **Step 2: Enumerate call sites** - -```bash -grep -rn "engine\.auth\.uploadedPeerVideo\|\.auth\.uploadedPeerVideo" submodules/ | grep -v "submodules/TelegramCore" -``` - -The call site count is small (the sign-up flow). If zero, skip Step 4. - -- [ ] **Step 3: Change the facade signature + bridge** - -```swift -public func uploadedPeerVideo(resource: EngineMediaResource) -> Signal { - return _internal_uploadedPeerVideo(postbox: self.account.postbox, network: self.account.network, messageMediaPreuploadManager: self.account.messageMediaPreuploadManager, resource: resource._asResource()) -} -``` - -Preserve the exact argument spellings from the existing function body. - -- [ ] **Step 4: Update call sites** (same commit) - -Pattern A. - -- [ ] **Step 5: Full build** - -Run the full build. Expected: PASS. - -- [ ] **Step 6: Commit** - -```bash -git add submodules/TelegramCore/Sources/TelegramEngine/Auth/TelegramEngineAuth.swift submodules/ -git commit -m "$(cat <<'EOF' -TelegramCore: migrate Auth.uploadedPeerVideo facade to EngineMediaResource - -Signature change + call sites. - -Part of the MediaResource -> EngineMediaResource migration (wave 2). -No behavior change. - -Co-Authored-By: Claude Opus 4.6 -EOF -)" -``` - ---- - -## Task 6: Migrate `mapResourceToAvatarSizes` utility and drop `import Postbox` from `MapResourceToAvatarSizes` - -**Files:** -- Modify: `submodules/MapResourceToAvatarSizes/Sources/MapResourceToAvatarSizes.swift` -- Modify: `submodules/MapResourceToAvatarSizes/BUILD` -- Modify: all 27 call sites of the old `mapResourceToAvatarSizes(postbox:resource:representations:)`. - -**Preconditions:** Tasks 2–5 have landed, so every `mapResourceToAvatarSizes:` closure at call sites now receives an `EngineMediaResource` (because the facade closures were retyped). At this point the inner `mapResourceToAvatarSizes(postbox: …, resource: …._asResource(), …)` unwrap becomes avoidable. - -- [ ] **Step 1: Read the current file** - -``` -submodules/MapResourceToAvatarSizes/Sources/MapResourceToAvatarSizes.swift -``` - -Confirm the function body uses `postbox.mediaBox.resourceData(resource)` and requires `UIImage` / `generateScaledImage` / `jpegData(compressionQuality:)`. - -- [ ] **Step 2: Enumerate call sites** - -```bash -grep -rn "mapResourceToAvatarSizes(postbox:" submodules/ | grep -v "submodules/MapResourceToAvatarSizes" -``` - -Expected: 27 call sites, concentrated in `submodules/TelegramUI/...PeerInfoScreenAvatarSetup.swift` (19), `TelegramCallsUI/...VideoChatScreenParticipantContextMenu.swift` (5), and three other TelegramUI files (1 each). - -- [ ] **Step 3: Rewrite the function to use `EngineMediaResource` + `TelegramEngine.Resources.data`** - -Replace the body of `submodules/MapResourceToAvatarSizes/Sources/MapResourceToAvatarSizes.swift` with: - -```swift -import Foundation -import UIKit -import SwiftSignalKit -import TelegramCore -import Display - -public func mapResourceToAvatarSizes(engine: TelegramEngine, resource: EngineMediaResource, representations: [TelegramMediaImageRepresentation]) -> Signal<[Int: Data], NoError> { - return engine.resources.data(id: resource.id) - |> take(1) - |> map { data -> [Int: Data] in - guard data.isComplete, let image = UIImage(contentsOfFile: data.path) else { - return [:] - } - var result: [Int: Data] = [:] - for i in 0 ..< representations.count { - let size: CGSize - if representations[i].dimensions.width == 80 { - size = CGSize(width: 160.0, height: 160.0) - } else { - size = representations[i].dimensions.cgSize - } - if let scaledImage = generateScaledImage(image: image, size: size, scale: 1.0), let scaledData = scaledImage.jpegData(compressionQuality: 0.8) { - result[i] = scaledData - } - } - return result - } -} -``` - -Notes: -- Signature: `(engine: TelegramEngine, resource: EngineMediaResource, representations: [TelegramMediaImageRepresentation]) -> Signal<[Int: Data], NoError>`. -- `import Postbox` is gone; replaced usage with `engine.resources.data(id:)` which returns `Signal`. -- `data.complete` → `data.isComplete` (field rename on the engine wrapper). - -- [ ] **Step 4: Drop the Bazel dep** - -Edit `submodules/MapResourceToAvatarSizes/BUILD` and remove `"//submodules/Postbox:Postbox",` from `deps`. Leave the rest untouched. - -- [ ] **Step 5: Update every call site** (same commit) - -At each of the 27 sites, two changes: - -**Pattern D — the call site already lives inside a `mapResourceToAvatarSizes:` closure on a facade function (post-Task-2/3/4, the closure's `resource` parameter is now `EngineMediaResource`):** - -```swift -// Before (from an intermediate state between tasks): -mapResourceToAvatarSizes: { resource, representations in - return mapResourceToAvatarSizes(postbox: postbox, resource: resource._asResource(), representations: representations) -} -// After: -mapResourceToAvatarSizes: { resource, representations in - return mapResourceToAvatarSizes(engine: engine, resource: resource, representations: representations) -} -``` - -The `engine` value is always reachable at the call site — it's either a stored reference used right above the closure or `context.engine` / `accountContext.engine`. Grep shows every current call site has a `postbox = context.account.postbox` (or similar) just above, so `context.engine` / the adjacent engine reference is in scope. - -**Pattern E — direct (non-closure) call with a raw `MediaResource` in scope:** - -Rare in the current code, but if you find one, wrap with `EngineMediaResource(rawResource)` at the call. - -- [ ] **Step 6: Static checks** - -```bash -grep -R "^import Postbox" submodules/MapResourceToAvatarSizes/Sources # expect: empty -grep "submodules/Postbox" submodules/MapResourceToAvatarSizes/BUILD # expect: empty -``` - -- [ ] **Step 7: Full build** - -Run the full build. Expected: PASS. - -Likely failure modes: -- A call site's surrounding scope doesn't have an `engine` in context. Fix: use `.engine` or promote `engine` to a nearby `let`. -- A consumer file passed a non-`EngineMediaResource` into the closure because it wasn't updated by Task 2/3/4. Fix forward (update it now) and record the miss. - -- [ ] **Step 8: Commit** - -```bash -git add submodules/MapResourceToAvatarSizes/ submodules/TelegramUI/ submodules/TelegramCallsUI/ -git commit -m "$(cat <<'EOF' -MapResourceToAvatarSizes: migrate to EngineMediaResource and drop Postbox - -Change the signature of mapResourceToAvatarSizes from -(postbox: Postbox, resource: MediaResource, ...) to -(engine: TelegramEngine, resource: EngineMediaResource, ...), using -engine.resources.data(id:) internally. All 27 call sites updated in -this commit. `import Postbox` and the Bazel dep are removed. -Behavior-preserving. - -Part of the MediaResource -> EngineMediaResource migration (wave 2). - -Co-Authored-By: Claude Opus 4.6 -EOF -)" -``` - ---- - -## Task 7: Migrate `AuthorizationUI` signal type - -**Files:** -- Modify: `submodules/AuthorizationUI/Sources/AuthorizationSequenceController.swift` - -**Starting inventory:** exactly one reference — `Signal` at line 1162. AuthorizationUI has six files importing Postbox overall; dropping `import Postbox` from the module as a whole is **not** in scope for this task. - -- [ ] **Step 1: Read line 1162 ± 20** - -Understand: -- What value is put into the signal? Likely some TelegramMediaResource subclass (e.g. `LocalFileMediaResource`). -- Who consumes the signal downstream? After Tasks 2–5, any facade that ultimately receives this signal's value (via `updateAccountPhoto`, `uploadedPeerVideo`, etc.) expects `EngineMediaResource`. - -- [ ] **Step 2: Change the signal type** - -```swift -// Before: -avatarVideo = Signal { subscriber in - // ... produces a TelegramMediaResource ... - subscriber.putNext(someResource) -} -// After: -avatarVideo = Signal { subscriber in - // ... produces a TelegramMediaResource ... - subscriber.putNext(someResource.flatMap { EngineMediaResource($0) }) // or wrap the non-optional path -} -``` - -The exact wrapping site depends on where the raw resource flows in. The grep + read from Step 1 tells you. - -Downstream, any call site that consumed the raw resource and handed it to an engine facade now has an `EngineMediaResource?` which it can pass directly (post-Tasks 2–5). - -- [ ] **Step 3: Full build** - -Run the full build. Expected: PASS. - -If the downstream expected a `TelegramMediaResource?` (e.g. for direct Postbox access that wasn't part of Tasks 2–5), revert this task as `Abandoned — downstream expects raw protocol` with a recorded reason. - -- [ ] **Step 4: Commit** - -```bash -git add submodules/AuthorizationUI/Sources/AuthorizationSequenceController.swift -git commit -m "$(cat <<'EOF' -AuthorizationUI: migrate avatar-video signal type to EngineMediaResource - -Single type-reference swap. Downstream engine facades already accept -EngineMediaResource after the Phase-1 migrations. Behavior-preserving. - -Part of the MediaResource -> EngineMediaResource migration (wave 2). - -Co-Authored-By: Claude Opus 4.6 -EOF -)" -``` - ---- - -## Task 8: Migrate `SaveToCameraRoll` property type — **ABANDONED** - -**Status:** Abandoned in wave 2. No code changes from this task. - -**Reason:** The planning-time grep that produced the "one reference" inventory only matched `MediaResource`/`TelegramMediaResource` tokens, not the broader set of Postbox usages. Re-inventorying the module at execution time (`grep -nE "\b(postbox|mediaBox|MediaResource)\b|^import Postbox" submodules/SaveToCameraRoll/Sources/SaveToCameraRoll.swift`) shows three public functions with `postbox: Postbox` in their signatures (`fetchMediaData`, `saveToCameraRoll`, `copyToPasteboard`) plus multiple `postbox.mediaBox.*` calls in their bodies. Per spec rule 2, `Postbox` is an umbrella type that cannot be typealiased, so those public-API signatures cannot be de-Postboxed without editing every caller; and the internal `postbox.mediaBox.*` calls require engine-side wrappers (closer to Task 6's shape) rather than a simple type swap. Scope is a full module-migration wave, not a single type swap — parked for a future wave. - -**Original task body (retained for audit trail, do not implement):** - -**Files:** -- Modify: `submodules/SaveToCameraRoll/Sources/SaveToCameraRoll.swift` -- Possibly modify: `submodules/SaveToCameraRoll/BUILD` - -**Starting inventory:** one reference — `var resource: MediaResource?` at line 19. - -- [ ] **Step 1: Read + full grep** - -```bash -grep -nE "\b(MediaResource|TelegramMediaResource|postbox|mediaBox|transaction|PostboxView|combinedView)\b|^import Postbox" submodules/SaveToCameraRoll/Sources/SaveToCameraRoll.swift -``` - -Capture every hit. - -- [ ] **Step 2: Abandon-check** - -If the grep shows Postbox usages other than the single `MediaResource?` property and an `import Postbox` line, abandon this task with a recorded reason. Do not substitute. - -If it shows only the property + import, proceed. - -- [ ] **Step 3: Swap the property type + boundary wrap/unwrap** - -Change `var resource: MediaResource?` to `var resource: EngineMediaResource?`. At each assignment/use: - -- Assignment from a raw resource: `self.resource = EngineMediaResource(rawResource)`; `self.resource = nil` unchanged. -- Read that hands to mediaBox/postbox (if any remains): `self.resource?._asResource()`. - -- [ ] **Step 4: Drop `import Postbox` if now unused** - -If Step 1 showed `import Postbox` as the only remaining Postbox reference: - -- Remove the `import Postbox` line. -- Remove `"//submodules/Postbox:Postbox",` from `submodules/SaveToCameraRoll/BUILD`. - -Static checks: - -```bash -grep -R "^import Postbox" submodules/SaveToCameraRoll/Sources # expect: empty -grep "submodules/Postbox" submodules/SaveToCameraRoll/BUILD # expect: empty -``` - -Else skip this step. - -- [ ] **Step 5: Full build** - -Run the full build. Expected: PASS. - -- [ ] **Step 6: Commit** - -If the import was removed: - -```bash -git add submodules/SaveToCameraRoll/ -git commit -m "$(cat <<'EOF' -SaveToCameraRoll: migrate resource property to EngineMediaResource and drop Postbox - -Swaps the single MediaResource? property for EngineMediaResource?, -wrapping/unwrapping at boundaries. With the only Postbox reference -gone, removes `import Postbox` and the Bazel dep. -Behavior-preserving. - -Part of the MediaResource -> EngineMediaResource migration (wave 2). - -Co-Authored-By: Claude Opus 4.6 -EOF -)" -``` - -If the import was kept: - -```bash -git add submodules/SaveToCameraRoll/Sources/SaveToCameraRoll.swift -git commit -m "$(cat <<'EOF' -SaveToCameraRoll: migrate resource property to EngineMediaResource - -Swaps the single MediaResource? property for EngineMediaResource?, -wrapping/unwrapping at boundaries. import Postbox remains because -other identifiers still need it. Behavior-preserving. - -Part of the MediaResource -> EngineMediaResource migration (wave 2). - -Co-Authored-By: Claude Opus 4.6 -EOF -)" -``` - ---- - -## Task 9: Wave-2 completion verification - -**Files:** No code changes. - -- [ ] **Step 1: Commit-log check** - -```bash -git log --oneline master..HEAD # or whatever branch this was executed on -``` - -Expected commits (some may be absent if tasks abandoned): - -- `CLAUDE.md: record TelegramCore-no-UIKit rule and EngineMediaResource migration pattern` -- `TelegramCore: migrate peer-photo facade to EngineMediaResource` -- `TelegramCore: migrate account-photo facade to EngineMediaResource` -- `TelegramCore: migrate updateContactPhoto facade to EngineMediaResource` -- `TelegramCore: migrate Auth.uploadedPeerVideo facade to EngineMediaResource` -- `MapResourceToAvatarSizes: migrate to EngineMediaResource and drop Postbox` -- `AuthorizationUI: migrate avatar-video signal type to EngineMediaResource` -- `SaveToCameraRoll: migrate resource property to EngineMediaResource[...]` - -- [ ] **Step 2: Public-API leak check** - -```bash -grep -nE "^\s*public func .*: MediaResource|public func .*MediaResource, \[" \ - submodules/TelegramCore/Sources/TelegramEngine/ -``` - -Expected: no matches in the facade files touched by Tasks 2–5 (`TelegramEngine/Peers/TelegramEnginePeers.swift`, `TelegramEngine/AccountData/TelegramEngineAccountData.swift`, `TelegramEngine/Contacts/TelegramEngineContacts.swift`, `TelegramEngine/Auth/TelegramEngineAuth.swift`). Other TelegramEngine files may still leak `MediaResource` — those are for future waves. - -- [ ] **Step 3: Final full build from clean state** - -Run the full build. Expected: PASS (cached, fast). - -- [ ] **Step 4: No commit.** Verification only. - ---- - -## Future waves (not in this plan) - -Ranked consumer modules by MediaResource/TelegramMediaResource reference count (from `grep -rE "\\b(MediaResource|TelegramMediaResource)\\b"` over `submodules//Sources/`, excluding TelegramCore/Postbox). Classifications are preliminary and must be re-audited at the start of each future wave. - -| Refs | Module | Future-wave notes | -| --- | --- | --- | -| 2 | ChatPresentationInterfaceState | Public struct field `resource: TelegramMediaResource` — needs caller audit. | -| 2 | ItemListStickerPackItem | Enum case leaks `MediaResource` — needs caller audit. | -| 2 | TelegramCallsUI | Signal locals; mostly type-refs. | -| 3 | LegacyMediaPickerUI | `thumbnailResource: TelegramMediaResource?` internal properties — likely safe. | -| 3 | ReactionSelectionNode | `customEffectResource: MediaResource?` in public func — caller audit. | -| 3 | TelegramAnimatedStickerNode | `public init(postbox: Postbox, resource: MediaResource, …)` + `public convenience init(account: Account, …)` — umbrella-type leaks; needs a paired wave. | -| 4 | GalleryUI | `private func setupStatus(resource: MediaResource)` — internal, 4 files. | -| 5 | StickerResources | Multiple public funcs take `postbox: Postbox, resource: MediaResource` / `mediaBox: MediaBox`. | -| 6 | PhotoResources | Similar to StickerResources; also `securePhoto(account: Account, resource: TelegramMediaResource, …)`. | -| 7 | MediaPlayer | `mediaBox: MediaBox, resource: MediaResource` in public init — umbrella leaks. | -| 7 | WebSearchUI | `thumbnailResource: TelegramMediaResource?` in multiple structs/inits. | -| 8 | AccountContext | Protocol surface — audit carefully. | -| 8 | SoftwareVideo | Public init takes `mediaBox: MediaBox` + `resource: MediaResource`. | -| 12 | LocalMediaResources | Contains `VideoLibraryMediaResource: TelegramMediaResource` — blocked for conformance. | -| 14 | LegacyDataImport | Legacy path; audit scope. | -| 25 | PassportUI | Large surface; break into multiple tasks. | -| 36 | TelegramUI | Umbrella module; never as one wave. | - -**Blocked-by-conformance modules, explicitly out of all waves:** - -- `submodules/ICloudResources/Sources/ICloudResources.swift` — `ICloudFileResource` -- `submodules/InstantPageUI/Sources/InstantPageExternalMediaResource.swift` — `InstantPageExternalMediaResource` -- `submodules/LocalMediaResources/Sources/LocalMediaResources.swift` — `VideoLibraryMediaResource` -- `submodules/TelegramUniversalVideoContent/Sources/YoutubeEmbedImplementation.swift` — `YoutubeEmbedStoryboardMediaResource` - -These classes must conform to `TelegramMediaResource` to satisfy the PostboxCoding serialization contract. They remain `import Postbox`. - ---- - -## What's explicitly NOT in this plan - -- Adding opt-in `EngineMediaResource` overloads alongside raw-`MediaResource` overloads. The facade is changed in place. -- Touching any class conforming to `TelegramMediaResource`. -- Editing `TelegramUI`, `PassportUI`, `LegacyDataImport`, or the other heavy-ref modules in the Future-waves table beyond what the Phase-1 call-site migrations require. -- Importing UIKit/Display into TelegramCore under any circumstance. -- Modifying `_internal_*` functions in TelegramCore — they stay on raw `MediaResource`. -- Any behavior change, performance tweak, or "while we're here" cleanup. diff --git a/docs/superpowers/plans/2026-04-18-postbox-to-telegramengine-wave-3.md b/docs/superpowers/plans/2026-04-18-postbox-to-telegramengine-wave-3.md deleted file mode 100644 index a1d8b9fbcf..0000000000 --- a/docs/superpowers/plans/2026-04-18-postbox-to-telegramengine-wave-3.md +++ /dev/null @@ -1,968 +0,0 @@ -# Postbox → TelegramEngine Wave 3 Implementation Plan - -> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. - -**Goal:** Add three thin forwarding methods on `TelegramEngine.Resources` for fetch/status/data, then migrate `SaveToCameraRoll` to use them, drop `import Postbox` from that module, and update all 23 call sites. - -**Architecture:** Two atomic commits on branch `refactor/postbox-to-engine-wave-3`. C1 adds the facades in isolation. C2 changes `SaveToCameraRoll`'s public API (drops the `postbox:` parameter, switches `FetchMediaDataState.data` payload from `MediaResourceData` to `EngineMediaResource.ResourceData`), rewrites the module's internals via `context.engine.resources.*`, removes `import Postbox`, and updates every caller in the same commit so the tree remains buildable. - -**Tech Stack:** Swift / Bazel. No unit tests exist in this repo — verification is a full project build. - -**Spec:** [docs/superpowers/specs/2026-04-18-postbox-to-telegramengine-wave-3-design.md](docs/superpowers/specs/2026-04-18-postbox-to-telegramengine-wave-3-design.md) - -**Build command (use for every "full build" step):** - -```bash -source ~/.zshrc 2>/dev/null; PATH=/opt/homebrew/opt/ruby/bin:`gem environment gemdir`/bin:$PATH python3 build-system/Make/Make.py --overrideXcodeVersion --cacheDir ~/telegram-bazel-cache build --configurationPath build-system/appstore-configuration.json --gitCodesigningRepository git@gitlab.com:peter-iakovlev/fastlanematch.git --gitCodesigningType development --gitCodesigningUseCurrent --buildNumber 1 --configuration debug_sim_arm64 -``` - -The prefix `source ~/.zshrc 2>/dev/null;` is required because `TELEGRAM_CODESIGNING_GIT_PASSWORD` lives in `~/.zshrc` and the bash tool does not source shell config by default. - ---- - -## Task 1: Add `TelegramEngine.Resources.fetch/status/data` facades (C1) - -**Files:** -- Modify: [submodules/TelegramCore/Sources/TelegramEngine/Resources/TelegramEngineResources.swift:415-417](submodules/TelegramCore/Sources/TelegramEngine/Resources/TelegramEngineResources.swift#L415) - -- [ ] **Step 1: Insert the three facade methods** - -Open `submodules/TelegramCore/Sources/TelegramEngine/Resources/TelegramEngineResources.swift`. Find the existing `applicationIcons()` method (currently the last method in the `Resources` class). Insert the three new methods immediately after it, still inside the `final class Resources` brace (before the closing `}`): - -```swift - public func applicationIcons() -> Signal { - return _internal_applicationIcons(account: account) - } - - public func fetch( - reference: MediaResourceReference, - userLocation: MediaResourceUserLocation, - userContentType: MediaResourceUserContentType - ) -> Signal { - return fetchedMediaResource( - mediaBox: self.account.postbox.mediaBox, - userLocation: userLocation, - userContentType: userContentType, - reference: reference - ) - } - - public func status( - resource: EngineMediaResource - ) -> Signal { - return self.account.postbox.mediaBox.resourceStatus(resource._asResource()) - |> map { EngineMediaResource.FetchStatus($0) } - } - - public func data( - resource: EngineMediaResource, - pathExtension: String?, - waitUntilFetchStatus: Bool - ) -> Signal { - return self.account.postbox.mediaBox.resourceData( - resource._asResource(), - pathExtension: pathExtension, - option: .complete(waitUntilFetchStatus: waitUntilFetchStatus) - ) - |> map { EngineMediaResource.ResourceData($0) } - } - } -} -``` - -- [ ] **Step 2: Full build — verify C1 compiles cleanly** - -Run the build command from the header. Expected: build succeeds with no errors. If a `signature mismatch` or `cannot find 'fetchedMediaResource'` error appears, double-check that `FetchedMediaResource.swift` and `MediaBox.swift` already export the referenced symbols (they do as of this plan's writing — no import changes are needed in `TelegramEngineResources.swift`, which already imports `Postbox`, `SwiftSignalKit`, and `TelegramApi`). - -- [ ] **Step 3: Commit C1** - -```bash -git add submodules/TelegramCore/Sources/TelegramEngine/Resources/TelegramEngineResources.swift -git commit -m "$(cat <<'EOF' -TelegramEngine.Resources: add fetch/status/data facades - -Thin forwarders over MediaBox for the narrow surface SaveToCameraRoll -needs. Takes EngineMediaResource and returns EngineMediaResource-typed -results where applicable. Wave-3 groundwork. - -Co-Authored-By: Claude Opus 4.7 (1M context) -EOF -)" -``` - ---- - -## Task 2: Pre-flight — re-inventory call sites and verify ShareController postbox - -No code changes in this task. Its purpose is to catch drift from the spec's inventory before editing code, per CLAUDE.md's "inventory at execution time" guidance. - -**Files:** (read-only) -- Spec inventory: [docs/superpowers/specs/2026-04-18-postbox-to-telegramengine-wave-3-design.md](docs/superpowers/specs/2026-04-18-postbox-to-telegramengine-wave-3-design.md) -- Definition to verify: `submodules/ShareController/Sources/ShareController.swift` around line 2403 and `ShareControllerAppAccountContext` - -- [ ] **Step 1: Re-grep the current call-site set** - -Run: - -```bash -grep -rnE "(fetchMediaData|saveToCameraRoll|copyToPasteboard)\(" submodules --include="*.swift" \ - | grep -v "SaveToCameraRoll/Sources/SaveToCameraRoll.swift" \ - | grep -v "private func saveToCameraRoll" \ - | grep -v "self\?\.saveToCameraRoll\|strongSelf\.saveToCameraRoll" -``` - -Expected output has exactly 23 lines across 14 files, matching the spec's inventory table: - -| Module | File | Expected count | -|---|---|---| -| InstantPageUI | `Sources/InstantPageControllerNode.swift` | 2 | -| LegacyMediaPickerUI | `Sources/LegacyAttachmentMenu.swift` | 2 | -| LegacyMediaPickerUI | `Sources/LegacyAvatarPicker.swift` | 2 | -| BrowserUI | `Sources/BrowserInstantPageContent.swift` | 2 | -| GalleryUI | `Sources/Items/ChatImageGalleryItem.swift` | 2 | -| GalleryUI | `Sources/Items/UniversalVideoGalleryItem.swift` | 3 | -| TelegramUI (MediaEditorScreen) | `Components/MediaEditorScreen/Sources/MediaEditorScreen.swift` | 1 | -| TelegramUI (MediaEditorScreen) | `Components/MediaEditorScreen/Sources/EditStories.swift` | 1 | -| TelegramUI (ChatQrCodeScreen) | `Components/Chat/ChatQrCodeScreen/Sources/ChatQrCodeScreen.swift` | 1 | -| TelegramUI (StoryContainer) | `Components/Stories/StoryContainerScreen/Sources/StoryItemSetContainerComponent.swift` | 1 | -| TelegramUI (PeerInfoStoryGrid) | `Components/PeerInfo/PeerInfoStoryGridScreen/Sources/PeerInfoStoryGridScreen.swift` | 1 | -| TelegramUI | `Sources/ChatInterfaceStateContextMenus.swift` | 1 | -| TelegramUI | `Sources/SaveMediaToFiles.swift` | 1 | -| ShareController | `Sources/ShareController.swift` | 3 | - -If the count or file list has drifted meaningfully from this table, **stop**, report the drift, and request a spec revision before continuing. Additions of one or two call sites can be folded in; larger drift should pause the wave. - -- [ ] **Step 2: Verify `ShareController:2406` postbox equivalence** - -Read `submodules/ShareController/Sources/ShareController.swift` lines 2395–2420. The private helper `saveToCameraRoll(messages:completion:)` contains `let postbox = self.currentContext.stateManager.postbox` and passes it to `SaveToCameraRoll.saveToCameraRoll`. After the migration, `SaveToCameraRoll` will use `context.account.postbox.mediaBox` internally. - -The enclosing function gates on `self.currentContext as? ShareControllerAppAccountContext`. In that code path, `accountContext.context.account` is the `Account` that `ShareControllerAppAccountContext` was built from, and `self.currentContext.stateManager` is that same account's state manager. Therefore `accountContext.context.account.postbox === self.currentContext.stateManager.postbox`. - -Confirm this by reading the definition of `ShareControllerAppAccountContext` in `submodules/AccountContext/Sources/ShareController.swift` (or the file where it's defined — grep for `ShareControllerAppAccountContext` to locate). If the `stateManager` there is derived from the same `account` whose `postbox` is reachable via `context.account.postbox`, treat the two as equivalent and proceed. If they can diverge (e.g., share-extension account switching creates a separate state manager), **stop** and abandon the ShareController:2406 edit with a recorded reason before continuing — the rest of the wave still applies. - -- [ ] **Step 3: Record verification outcome** - -Write a one-line note in the executor's task log noting either "ShareController:2406 postbox equivalence confirmed" or "ShareController:2406 abandoned — reason: ...". No commit. - ---- - -## Task 3: Migrate `SaveToCameraRoll` module - -This task changes the module's public API and internals. Build will fail after this task because all callers are still passing `postbox:` — that's expected and will be fixed in Task 4, which must land in the same commit as this task. - -**Files:** -- Modify: [submodules/SaveToCameraRoll/Sources/SaveToCameraRoll.swift](submodules/SaveToCameraRoll/Sources/SaveToCameraRoll.swift) (entire file rewritten as shown below) - -- [ ] **Step 1: Rewrite `SaveToCameraRoll.swift`** - -Replace the file's contents with: - -```swift -import Foundation -import UIKit -import SwiftSignalKit -import TelegramCore -import Photos -import Display -import MobileCoreServices -import DeviceAccess -import AccountContext -import LegacyComponents - -public enum FetchMediaDataState { - case progress(Float) - case data(EngineMediaResource.ResourceData) -} - -public func fetchMediaData(context: AccountContext, userLocation: MediaResourceUserLocation, customUserContentType: MediaResourceUserContentType? = nil, mediaReference: AnyMediaReference, forceVideo: Bool = false) -> Signal<(FetchMediaDataState, Bool), NoError> { - var resource: TelegramMediaResource? - var isImage = true - var fileExtension: String? - var userContentType: MediaResourceUserContentType = .other - if let image = mediaReference.media as? TelegramMediaImage { - userContentType = .image - if let video = image.videoRepresentations.last, forceVideo { - resource = video.resource - isImage = false - } else if let representation = largestImageRepresentation(image.representations) { - resource = representation.resource - } - } else if let file = mediaReference.media as? TelegramMediaFile { - userContentType = MediaResourceUserContentType(file: file) - resource = file.resource - if file.isVideo || file.mimeType.hasPrefix("video/") { - isImage = false - } - let maybeExtension = ((file.fileName ?? "") as NSString).pathExtension - if !maybeExtension.isEmpty { - fileExtension = maybeExtension - } - } else if let webpage = mediaReference.media as? TelegramMediaWebpage, case let .Loaded(content) = webpage.content { - if let file = content.file { - resource = file.resource - if file.isVideo { - isImage = false - } - } else if let image = content.image { - if let representation = largestImageRepresentation(image.representations) { - resource = representation.resource - } - } - } - if let customUserContentType { - userContentType = customUserContentType - } - - if let resource = resource { - let engineResource = EngineMediaResource(resource) - let fetchedData: Signal = Signal { subscriber in - let fetched = context.engine.resources.fetch( - reference: mediaReference.resourceReference(resource), - userLocation: userLocation, - userContentType: userContentType - ).start() - let status = context.engine.resources.status(resource: engineResource).start(next: { status in - switch status { - case .Local: - subscriber.putNext(.progress(1.0)) - case .Remote: - subscriber.putNext(.progress(0.0)) - case let .Fetching(_, progress): - subscriber.putNext(.progress(progress)) - case let .Paused(progress): - subscriber.putNext(.progress(progress)) - } - }) - let data = context.engine.resources.data( - resource: engineResource, - pathExtension: fileExtension, - waitUntilFetchStatus: true - ).start(next: { next in - subscriber.putNext(.data(next)) - }, completed: { - subscriber.putCompletion() - }) - return ActionDisposable { - fetched.dispose() - status.dispose() - data.dispose() - } - } - return fetchedData - |> map { data in - return (data, isImage) - } - } else { - return .complete() - } -} - -public func saveToCameraRoll(context: AccountContext, userLocation: MediaResourceUserLocation, customUserContentType: MediaResourceUserContentType? = nil, mediaReference: AnyMediaReference, video: AnyMediaReference? = nil) -> Signal { - let mediaData: Signal<(FetchMediaDataState, Bool), NoError> = fetchMediaData(context: context, userLocation: userLocation, customUserContentType: customUserContentType, mediaReference: mediaReference) - let videoData: Signal - if let video { - videoData = fetchMediaData(context: context, userLocation: userLocation, customUserContentType: customUserContentType, mediaReference: video) - |> map { state, _ in - return state - } - |> map(Optional.init) - } else { - videoData = .single(nil) - } - - return combineLatest( - queue: Queue.mainQueue(), - mediaData, - videoData - ) - |> mapToSignal { stateAndIsImage, videoStateAndIsImage -> Signal in - let isImage = stateAndIsImage.1 - var mainData: EngineMediaResource.ResourceData? - var videoData: EngineMediaResource.ResourceData? - var waitForVideo = false - if let videoState = videoStateAndIsImage { - switch videoState { - case let .progress(value): - return .single(value * 0.95) - case let .data(data): - videoData = data - } - switch stateAndIsImage.0 { - case let .progress(value): - return .single(0.95 + 0.05 * value) - case let .data(data): - mainData = data - } - waitForVideo = true - } else { - switch stateAndIsImage.0 { - case let .progress(value): - return .single(value) - case let .data(data): - mainData = data - } - } - if let mainData, mainData.isComplete, videoData != nil || !waitForVideo { - return Signal { subscriber in - DeviceAccess.authorizeAccess(to: .mediaLibrary(.save), presentationData: context.sharedContext.currentPresentationData.with { $0 }, present: { c, a in - context.sharedContext.presentGlobalController(c, a) - }, openSettings: context.sharedContext.applicationBindings.openSettings, { authorized in - if !authorized { - subscriber.putCompletion() - return - } - - let tempVideoPath = NSTemporaryDirectory() + "\(Int64.random(in: Int64.min ... Int64.max)).mp4" - if isImage, let videoData, let imageData = try? Data(contentsOf: URL(fileURLWithPath: mainData.path)) { - let id = UUID().uuidString - - let jpegWithID = addAssetIdentifierToJPEG(imageData, assetIdentifier: id)! - let outputVideoURL = URL(fileURLWithPath: NSTemporaryDirectory() + "\(id).mov") - - try? FileManager.default.copyItem(atPath: videoData.path, toPath: tempVideoPath) - - addAssetIdentifierToVideo(inputURL: URL(fileURLWithPath: tempVideoPath), outputURL: outputVideoURL, assetIdentifier: id) { success in - guard success else { return } - - PHPhotoLibrary.shared().performChanges({ - let request = PHAssetCreationRequest.forAsset() - - request.addResource(with: .photo, data: jpegWithID, options: nil) - request.addResource(with: .pairedVideo, fileURL: outputVideoURL, options: nil) - }, completionHandler: { _, error in - let _ = try? FileManager.default.removeItem(atPath: tempVideoPath) - subscriber.putNext(1.0) - subscriber.putCompletion() - }) - } - } else { - PHPhotoLibrary.shared().performChanges({ - if isImage { - if let imageData = try? Data(contentsOf: URL(fileURLWithPath: mainData.path)) { - PHAssetCreationRequest.forAsset().addResource(with: .photo, data: imageData, options: nil) - } - } else { - if let _ = try? FileManager.default.copyItem(atPath: mainData.path, toPath: tempVideoPath) { - PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: URL(fileURLWithPath: tempVideoPath)) - } - } - }, completionHandler: { _, error in - if let error { - print("\(error)") - } - let _ = try? FileManager.default.removeItem(atPath: tempVideoPath) - subscriber.putNext(1.0) - subscriber.putCompletion() - }) - } - }) - - return ActionDisposable { - } - } - } else { - return .complete() - } - } -} - -public func copyToPasteboard(context: AccountContext, userLocation: MediaResourceUserLocation, mediaReference: AnyMediaReference) -> Signal { - return fetchMediaData(context: context, userLocation: userLocation, mediaReference: mediaReference) - |> mapToSignal { state, isImage -> Signal in - if case let .data(data) = state, data.isComplete { - return Signal { subscriber in - let pasteboard = UIPasteboard.general - - if mediaReference.media is TelegramMediaImage { - if let fileData = try? Data(contentsOf: URL(fileURLWithPath: data.path), options: .mappedIfSafe) { - pasteboard.setData(fileData, forPasteboardType: kUTTypeJPEG as String) - } - } - subscriber.putNext(Void()) - subscriber.putCompletion() - - return EmptyDisposable - } - } else { - return .complete() - } - } - |> mapToSignal { _ -> Signal in return .complete() } -} - -private func addAssetIdentifierToJPEG(_ imageData: Data, assetIdentifier: String) -> Data? { - guard let source = CGImageSourceCreateWithData(imageData as CFData, nil), let uti = CGImageSourceGetType(source), let cgImage = CGImageSourceCreateImageAtIndex(source, 0, nil) else { - return nil - } - - let mutableData = NSMutableData() - guard let destination = CGImageDestinationCreateWithData(mutableData, uti, 1, nil) else { - return nil - } - - var metadata = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [String: Any] ?? [:] - - var maker = metadata[kCGImagePropertyMakerAppleDictionary as String] as? [String: Any] ?? [:] - maker["17"] = assetIdentifier - metadata[kCGImagePropertyMakerAppleDictionary as String] = maker - - CGImageDestinationAddImage(destination, cgImage, metadata as CFDictionary) - CGImageDestinationFinalize(destination) - - return mutableData as Data -} - -private func addAssetIdentifierToVideo(inputURL: URL, outputURL: URL, assetIdentifier: String, completion: @escaping (Bool) -> Void) { - let asset = AVAsset(url: inputURL) - - guard let exportSession = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetPassthrough) else { - completion(false) - return - } - - let identifierItem = AVMutableMetadataItem() - identifierItem.keySpace = .quickTimeMetadata - identifierItem.key = AVMetadataKey.quickTimeMetadataKeyContentIdentifier as NSString - identifierItem.value = assetIdentifier as NSString - - let stillImageTimeItem = AVMutableMetadataItem() - let keyStillImageTime = "com.apple.quicktime.still-image-time" - let keySpaceQuickTimeMetadata = "mdta" - stillImageTimeItem.key = keyStillImageTime as (NSCopying & NSObjectProtocol)? - stillImageTimeItem.keySpace = AVMetadataKeySpace(rawValue: keySpaceQuickTimeMetadata) - stillImageTimeItem.value = 0 as (NSCopying & NSObjectProtocol)? - stillImageTimeItem.dataType = "com.apple.metadata.datatype.int8" - - exportSession.outputURL = outputURL - exportSession.outputFileType = .mov - exportSession.metadata = [identifierItem, stillImageTimeItem] - exportSession.shouldOptimizeForNetworkUse = true - - exportSession.exportAsynchronously { - completion(exportSession.status == .completed) - } -} -``` - -The key differences from the original file: - -1. `import Postbox` — removed. -2. `FetchMediaDataState.data(MediaResourceData)` → `FetchMediaDataState.data(EngineMediaResource.ResourceData)`. -3. Three public functions drop their `postbox: Postbox` parameter. -4. `var resource: MediaResource?` → `var resource: TelegramMediaResource?`. -5. Inside `fetchMediaData`: build an `EngineMediaResource(resource)` once, and call `context.engine.resources.fetch / status / data` instead of `fetchedMediaResource(...)` / `postbox.mediaBox.resourceStatus(...)` / `postbox.mediaBox.resourceData(...)`. -6. `var mainData: MediaResourceData?` / `var videoData: MediaResourceData?` → `var ...: EngineMediaResource.ResourceData?`. -7. `mainData.complete` → `mainData.isComplete`. `data.complete` (in `copyToPasteboard`) → `data.isComplete`. Field `data.path` is unchanged. - -- [ ] **Step 2: Do not build yet — proceed to Task 4** - -Builds will fail until every caller in Task 4 is migrated. Do not run the build command here. No commit yet either — Task 3 and Task 4 share a single atomic commit in Task 5. - ---- - -## Task 4: Update all 23 call sites - -Every call site does one or both of two edits: - -- **Edit A (all 23 sites):** drop `postbox: someExpression,` from the argument list. -- **Edit B (the 7 sites that destructure `fetchMediaData`):** rename `.complete` → `.isComplete` on the destructured data value; `.path` stays the same. - -Each sub-step below is one file. No builds between files. No commit. Task 5 builds everything together. - -**Sub-task 4.1 — InstantPageUI** - -- [ ] **File:** [submodules/InstantPageUI/Sources/InstantPageControllerNode.swift](submodules/InstantPageUI/Sources/InstantPageControllerNode.swift) - -At line 1027, replace: - -```swift - let _ = copyToPasteboard(context: strongSelf.context, postbox: strongSelf.context.account.postbox, userLocation: strongSelf.sourceLocation.userLocation, mediaReference: .standalone(media: media)).start() -``` - -with: - -```swift - let _ = copyToPasteboard(context: strongSelf.context, userLocation: strongSelf.sourceLocation.userLocation, mediaReference: .standalone(media: media)).start() -``` - -At line 1032, replace: - -```swift - let _ = saveToCameraRoll(context: strongSelf.context, postbox: strongSelf.context.account.postbox, userLocation: strongSelf.sourceLocation.userLocation, mediaReference: .standalone(media: media)).start() -``` - -with: - -```swift - let _ = saveToCameraRoll(context: strongSelf.context, userLocation: strongSelf.sourceLocation.userLocation, mediaReference: .standalone(media: media)).start() -``` - -**Sub-task 4.2 — LegacyMediaPickerUI / LegacyAttachmentMenu.swift** (destructures) - -- [ ] **File:** [submodules/LegacyMediaPickerUI/Sources/LegacyAttachmentMenu.swift](submodules/LegacyMediaPickerUI/Sources/LegacyAttachmentMenu.swift) - -At line 173, replace: - -```swift - let _ = (fetchMediaData(context: context, postbox: context.account.postbox, userLocation: .other, mediaReference: media) -``` - -with: - -```swift - let _ = (fetchMediaData(context: context, userLocation: .other, mediaReference: media) -``` - -In the `.start` block that follows (around line 175), replace `data.complete` with `data.isComplete` (only the `.complete` boolean access — do not touch `data.path`). - -At line 490, replace: - -```swift - let _ = (fetchMediaData(context: context, postbox: context.account.postbox, userLocation: .other, mediaReference: editCurrentMedia) -``` - -with: - -```swift - let _ = (fetchMediaData(context: context, userLocation: .other, mediaReference: editCurrentMedia) -``` - -In the destructuring block that follows (around line 492), replace `data.complete` with `data.isComplete`. - -**Sub-task 4.3 — LegacyMediaPickerUI / LegacyAvatarPicker.swift** (destructures) - -- [ ] **File:** [submodules/LegacyMediaPickerUI/Sources/LegacyAvatarPicker.swift](submodules/LegacyMediaPickerUI/Sources/LegacyAvatarPicker.swift) - -At line 58, replace: - -```swift - let imageSignal = fetchMediaData(context: context, postbox: context.account.postbox, userLocation: .other, mediaReference: media, forceVideo: false) -``` - -with: - -```swift - let imageSignal = fetchMediaData(context: context, userLocation: .other, mediaReference: media, forceVideo: false) -``` - -In the `|> map` block immediately after (line ~60), replace `data.complete` with `data.isComplete`. - -At line 67, replace: - -```swift - let videoSignal = isVideo ? fetchMediaData(context: context, postbox: context.account.postbox, userLocation: .other, mediaReference: media, forceVideo: true) -``` - -with: - -```swift - let videoSignal = isVideo ? fetchMediaData(context: context, userLocation: .other, mediaReference: media, forceVideo: true) -``` - -In the `|> map` block immediately after (line ~69), replace `data.complete` with `data.isComplete`. - -**Sub-task 4.4 — BrowserUI / BrowserInstantPageContent.swift** - -- [ ] **File:** [submodules/BrowserUI/Sources/BrowserInstantPageContent.swift](submodules/BrowserUI/Sources/BrowserInstantPageContent.swift) - -At line 1175, replace: - -```swift - let _ = copyToPasteboard(context: self.context, postbox: self.context.account.postbox, userLocation: self.sourceLocation.userLocation, mediaReference: .standalone(media: media)).start() -``` - -with: - -```swift - let _ = copyToPasteboard(context: self.context, userLocation: self.sourceLocation.userLocation, mediaReference: .standalone(media: media)).start() -``` - -At line 1180, replace: - -```swift - let _ = saveToCameraRoll(context: self.context, postbox: self.context.account.postbox, userLocation: self.sourceLocation.userLocation, mediaReference: .standalone(media: media)).start() -``` - -with: - -```swift - let _ = saveToCameraRoll(context: self.context, userLocation: self.sourceLocation.userLocation, mediaReference: .standalone(media: media)).start() -``` - -**Sub-task 4.5 — GalleryUI / ChatImageGalleryItem.swift** (one destructures) - -- [ ] **File:** [submodules/GalleryUI/Sources/Items/ChatImageGalleryItem.swift](submodules/GalleryUI/Sources/Items/ChatImageGalleryItem.swift) - -At line 732, replace: - -```swift - let _ = (fetchMediaData(context: context, postbox: context.account.postbox, userLocation: .other, mediaReference: media) -``` - -with: - -```swift - let _ = (fetchMediaData(context: context, userLocation: .other, mediaReference: media) -``` - -In the `.start` block that follows (around line 734), replace `data.complete` with `data.isComplete`. - -At line 758, replace: - -```swift - let _ = (SaveToCameraRoll.saveToCameraRoll(context: context, postbox: context.account.postbox, userLocation: .peer(message.id.peerId), mediaReference: media) -``` - -with: - -```swift - let _ = (SaveToCameraRoll.saveToCameraRoll(context: context, userLocation: .peer(message.id.peerId), mediaReference: media) -``` - -**Sub-task 4.6 — GalleryUI / UniversalVideoGalleryItem.swift** - -- [ ] **File:** [submodules/GalleryUI/Sources/Items/UniversalVideoGalleryItem.swift](submodules/GalleryUI/Sources/Items/UniversalVideoGalleryItem.swift) - -At line 3764, replace: - -```swift - let saveSignal = SaveToCameraRoll.saveToCameraRoll(context: self.context, postbox: self.context.account.postbox, userLocation: .peer(message.id.peerId), mediaReference: saveFileReference) -``` - -with: - -```swift - let saveSignal = SaveToCameraRoll.saveToCameraRoll(context: self.context, userLocation: .peer(message.id.peerId), mediaReference: saveFileReference) -``` - -At line 3810, replace: - -```swift - let _ = (SaveToCameraRoll.saveToCameraRoll(context: self.context, postbox: self.context.account.postbox, userLocation: .peer(message.id.peerId), mediaReference: .message(message: MessageReference(message), media: file)) -``` - -with: - -```swift - let _ = (SaveToCameraRoll.saveToCameraRoll(context: self.context, userLocation: .peer(message.id.peerId), mediaReference: .message(message: MessageReference(message), media: file)) -``` - -At line 3867, replace: - -```swift - let _ = (SaveToCameraRoll.saveToCameraRoll(context: context, postbox: context.account.postbox, userLocation: .peer(message.id.peerId), mediaReference: .message(message: MessageReference(message), media: image), video: videoReference) -``` - -with: - -```swift - let _ = (SaveToCameraRoll.saveToCameraRoll(context: context, userLocation: .peer(message.id.peerId), mediaReference: .message(message: MessageReference(message), media: image), video: videoReference) -``` - -**Sub-task 4.7 — TelegramUI / MediaEditorScreen / MediaEditorScreen.swift** (destructures) - -- [ ] **File:** [submodules/TelegramUI/Components/MediaEditorScreen/Sources/MediaEditorScreen.swift](submodules/TelegramUI/Components/MediaEditorScreen/Sources/MediaEditorScreen.swift) - -At line 5136, in the multi-line call starting with `let _ = (fetchMediaData(`, delete the line ` postbox: self.context.account.postbox,`. The remaining call should read: - -```swift - let _ = (fetchMediaData( - context: self.context, - userLocation: .other, - mediaReference: file - ) |> deliverOnMainQueue).start(next: { [weak self] state, _ in -``` - -Inside this closure, the destructuring is `if case let .data(data) = state { let path = data.path ... }` — `data.path` stays unchanged, and this site does not access `data.complete` (verified against the current file). No Edit B rename needed here. - -**Sub-task 4.8 — TelegramUI / MediaEditorScreen / EditStories.swift** (destructures) - -- [ ] **File:** [submodules/TelegramUI/Components/MediaEditorScreen/Sources/EditStories.swift](submodules/TelegramUI/Components/MediaEditorScreen/Sources/EditStories.swift) - -At line 37, replace: - -```swift - return fetchMediaData(context: context, postbox: context.account.postbox, userLocation: .peer(peerReference.id), customUserContentType: .story, mediaReference: .story(peer: peerReference, id: storyItem.id, media: media)) -``` - -with: - -```swift - return fetchMediaData(context: context, userLocation: .peer(peerReference.id), customUserContentType: .story, mediaReference: .story(peer: peerReference, id: storyItem.id, media: media)) -``` - -At line 39 (inside the `mapToSignal`), replace: - -```swift - guard case let .data(data) = value, data.complete else { -``` - -with: - -```swift - guard case let .data(data) = value, data.isComplete else { -``` - -(`data.path` accesses below this line remain unchanged.) - -**Sub-task 4.9 — TelegramUI / ChatQrCodeScreen / ChatQrCodeScreen.swift** (destructures) - -- [ ] **File:** [submodules/TelegramUI/Components/Chat/ChatQrCodeScreen/Sources/ChatQrCodeScreen.swift](submodules/TelegramUI/Components/Chat/ChatQrCodeScreen/Sources/ChatQrCodeScreen.swift) - -At line 2505, replace: - -```swift - let _ = (fetchMediaData(context: context, postbox: context.account.postbox, userLocation: userLocation, mediaReference: AnyMediaReference.standalone(media: media)) -``` - -with: - -```swift - let _ = (fetchMediaData(context: context, userLocation: userLocation, mediaReference: AnyMediaReference.standalone(media: media)) -``` - -At line 2507, replace: - -```swift - guard case let .data(data) = value, data.complete else { -``` - -with: - -```swift - guard case let .data(data) = value, data.isComplete else { -``` - -**Sub-task 4.10 — TelegramUI / StoryContainerScreen / StoryItemSetContainerComponent.swift** - -- [ ] **File:** [submodules/TelegramUI/Components/Stories/StoryContainerScreen/Sources/StoryItemSetContainerComponent.swift](submodules/TelegramUI/Components/Stories/StoryContainerScreen/Sources/StoryItemSetContainerComponent.swift) - -At line 5980, replace: - -```swift - let disposable = (saveToCameraRoll(context: component.context, postbox: component.context.account.postbox, userLocation: .peer(peerReference.id), customUserContentType: .story, mediaReference: .story(peer: peerReference, id: component.slice.item.storyItem.id, media: component.slice.item.storyItem.media._asMedia())) -``` - -with: - -```swift - let disposable = (saveToCameraRoll(context: component.context, userLocation: .peer(peerReference.id), customUserContentType: .story, mediaReference: .story(peer: peerReference, id: component.slice.item.storyItem.id, media: component.slice.item.storyItem.media._asMedia())) -``` - -**Sub-task 4.11 — TelegramUI / PeerInfoStoryGridScreen / PeerInfoStoryGridScreen.swift** - -- [ ] **File:** [submodules/TelegramUI/Components/PeerInfo/PeerInfoStoryGridScreen/Sources/PeerInfoStoryGridScreen.swift](submodules/TelegramUI/Components/PeerInfo/PeerInfoStoryGridScreen/Sources/PeerInfoStoryGridScreen.swift) - -At line 268, replace: - -```swift - signals.append(saveToCameraRoll(context: component.context, postbox: component.context.account.postbox, userLocation: .other, mediaReference: .story(peer: peerReference, id: item.id, media: item.media._asMedia())) -``` - -with: - -```swift - signals.append(saveToCameraRoll(context: component.context, userLocation: .other, mediaReference: .story(peer: peerReference, id: item.id, media: item.media._asMedia())) -``` - -**Sub-task 4.12 — TelegramUI / Sources / ChatInterfaceStateContextMenus.swift** - -- [ ] **File:** [submodules/TelegramUI/Sources/ChatInterfaceStateContextMenus.swift](submodules/TelegramUI/Sources/ChatInterfaceStateContextMenus.swift) - -At line 1419, replace: - -```swift - let _ = (saveToCameraRoll(context: context, postbox: context.account.postbox, userLocation: .peer(message.id.peerId), mediaReference: mediaReference) -``` - -with: - -```swift - let _ = (saveToCameraRoll(context: context, userLocation: .peer(message.id.peerId), mediaReference: mediaReference) -``` - -**Sub-task 4.13 — TelegramUI / Sources / SaveMediaToFiles.swift** (destructures) - -- [ ] **File:** [submodules/TelegramUI/Sources/SaveMediaToFiles.swift](submodules/TelegramUI/Sources/SaveMediaToFiles.swift) - -At line 27, replace: - -```swift - var signal = fetchMediaData(context: context, postbox: context.account.postbox, userLocation: .other, mediaReference: fileReference.abstract) -``` - -with: - -```swift - var signal = fetchMediaData(context: context, userLocation: .other, mediaReference: fileReference.abstract) -``` - -At line 63, replace: - -```swift - if data.complete { -``` - -with: - -```swift - if data.isComplete { -``` - -(`data.path` accesses in the block below remain unchanged.) - -**Sub-task 4.14 — ShareController / ShareController.swift** - -- [ ] **File:** [submodules/ShareController/Sources/ShareController.swift](submodules/ShareController/Sources/ShareController.swift) - -At line 2406, after verifying Task 2's postbox-equivalence, replace: - -```swift - return SaveToCameraRoll.saveToCameraRoll(context: context, postbox: postbox, userLocation: .peer(message.id.peerId), mediaReference: .message(message: MessageReference(message), media: media)) -``` - -with: - -```swift - return SaveToCameraRoll.saveToCameraRoll(context: context, userLocation: .peer(message.id.peerId), mediaReference: .message(message: MessageReference(message), media: media)) -``` - -Also delete the now-unused local binding above (line 2403): - -```swift - let postbox = self.currentContext.stateManager.postbox -``` - -(This line is used only by the `saveToCameraRoll` call on line 2406. If the build later flags it as unused instead of an error, leave it; but preferred is to remove the dead binding.) - -At line 2432, replace: - -```swift - self.controllerNode.transitionToProgressWithValue(signal: SaveToCameraRoll.saveToCameraRoll(context: context, postbox: context.account.postbox, userLocation: .other, mediaReference: .standalone(media: media)) |> map(Optional.init), dismissImmediately: true, completion: {}) -``` - -with: - -```swift - self.controllerNode.transitionToProgressWithValue(signal: SaveToCameraRoll.saveToCameraRoll(context: context, userLocation: .other, mediaReference: .standalone(media: media)) |> map(Optional.init), dismissImmediately: true, completion: {}) -``` - -At line 2441, replace: - -```swift - self.controllerNode.transitionToProgressWithValue(signal: SaveToCameraRoll.saveToCameraRoll(context: context, postbox: context.account.postbox, userLocation: .other, mediaReference: mediaReference) |> map(Optional.init), dismissImmediately: completion == nil, completion: completion ?? {}) -``` - -with: - -```swift - self.controllerNode.transitionToProgressWithValue(signal: SaveToCameraRoll.saveToCameraRoll(context: context, userLocation: .other, mediaReference: mediaReference) |> map(Optional.init), dismissImmediately: completion == nil, completion: completion ?? {}) -``` - -(The abandonment branch: if Task 2's verification found `stateManager.postbox` and `account.postbox` are non-equivalent, skip the `line 2406` edit, leave `let postbox = self.currentContext.stateManager.postbox` in place, and revert Task 3's change to the `saveToCameraRoll` public signature only for this one callsite — which is impossible without duplicate signatures, so in that case abandon the entire wave and record the reason in a new commit to the plan.) - ---- - -## Task 5: Full build and commit C2 - -- [ ] **Step 1: Run the full project build** - -Run the build command from the header. Expected: build succeeds with no errors across all modules. - -If there are failures, they fall into a few predictable categories and are fixed in place — do not split into another commit: - -- **"cannot convert value of type 'Postbox' to expected argument type"** — a call site was missed. Grep again for `postbox: ` usages in the migrated files and fix. -- **"value of type 'EngineMediaResource.ResourceData' has no member 'complete'"** — an Edit B site was missed. Rename to `isComplete`. -- **"use of unresolved identifier 'fetchedMediaResource'" or similar inside `SaveToCameraRoll.swift`** — indicates `import Postbox` was dropped but a bare Postbox top-level function is still referenced. Replace the call with the engine facade introduced in Task 1. -- **Warnings about unused local `let postbox = ...`** — delete the binding. - -Re-run the build after each fix until it succeeds. - -- [ ] **Step 2: Stage all touched files** - -```bash -git add \ - submodules/SaveToCameraRoll/Sources/SaveToCameraRoll.swift \ - submodules/InstantPageUI/Sources/InstantPageControllerNode.swift \ - submodules/LegacyMediaPickerUI/Sources/LegacyAttachmentMenu.swift \ - submodules/LegacyMediaPickerUI/Sources/LegacyAvatarPicker.swift \ - submodules/BrowserUI/Sources/BrowserInstantPageContent.swift \ - submodules/GalleryUI/Sources/Items/ChatImageGalleryItem.swift \ - submodules/GalleryUI/Sources/Items/UniversalVideoGalleryItem.swift \ - submodules/TelegramUI/Components/MediaEditorScreen/Sources/MediaEditorScreen.swift \ - submodules/TelegramUI/Components/MediaEditorScreen/Sources/EditStories.swift \ - submodules/TelegramUI/Components/Chat/ChatQrCodeScreen/Sources/ChatQrCodeScreen.swift \ - submodules/TelegramUI/Components/Stories/StoryContainerScreen/Sources/StoryItemSetContainerComponent.swift \ - submodules/TelegramUI/Components/PeerInfo/PeerInfoStoryGridScreen/Sources/PeerInfoStoryGridScreen.swift \ - submodules/TelegramUI/Sources/ChatInterfaceStateContextMenus.swift \ - submodules/TelegramUI/Sources/SaveMediaToFiles.swift \ - submodules/ShareController/Sources/ShareController.swift -``` - -- [ ] **Step 3: Verify the diff is clean** - -Run: - -```bash -git diff --staged --stat -``` - -Expected: exactly 15 files changed, with SaveToCameraRoll.swift having the largest diff (the full-file rewrite) and each call-site file showing small line-count changes. - -- [ ] **Step 4: Commit C2** - -```bash -git commit -m "$(cat <<'EOF' -SaveToCameraRoll: drop import Postbox via engine.resources facades - -Migrates SaveToCameraRoll's three public functions to take context -only (no more postbox:), switches the FetchMediaDataState.data payload -from MediaResourceData to EngineMediaResource.ResourceData, rewrites -internals via TelegramEngine.Resources.fetch/status/data, and drops -import Postbox from the module. All 23 call sites across 14 files -updated in the same commit to keep the tree buildable. - -Wave-3 of the Postbox -> TelegramEngine refactor. - -Co-Authored-By: Claude Opus 4.7 (1M context) -EOF -)" -``` - -- [ ] **Step 5: Verify branch log** - -Run: - -```bash -git log --oneline refactor/postbox-to-engine-wave-3 | head -5 -``` - -Expected: the top two commits on the branch are `SaveToCameraRoll: drop import Postbox ...` (C2) and `TelegramEngine.Resources: add fetch/status/data facades` (C1), above the previous spec commits. - -- [ ] **Step 6: Update CLAUDE.md tally** - -Open `CLAUDE.md`, find the "Modules currently free of `import Postbox`" section, and add `SaveToCameraRoll (wave 3)` to the bullet list. Also add a "Wave 3 outcome (2026-04-18)" subsection documenting: three facades added on `TelegramEngine.Resources`, `SaveToCameraRoll` fully de-Postboxed, 23 call sites migrated. If any call site was abandoned in Task 2, record the reason here. - -Commit: - -```bash -git add CLAUDE.md -git commit -m "$(cat <<'EOF' -CLAUDE.md: record wave-3 outcome - -Adds SaveToCameraRoll to the Postbox-free module tally and documents -the three new TelegramEngine.Resources facades added in wave 3. - -Co-Authored-By: Claude Opus 4.7 (1M context) -EOF -)" -``` - ---- - -## Success criteria - -- `submodules/SaveToCameraRoll/Sources/SaveToCameraRoll.swift` contains no `import Postbox`. -- `grep -rnE "(fetchMediaData|saveToCameraRoll|copyToPasteboard)\\(" submodules --include="*.swift" | grep "postbox:"` returns zero matches outside of the private `collectExternalShareResource`/`collectExternalShareItems` helpers in `ShareController.swift` (which take their own `postbox:` parameters unrelated to SaveToCameraRoll). -- Full build succeeds in `debug_sim_arm64` configuration. -- Three branch commits above the spec commits: C1 (facades), C2 (SaveToCameraRoll + callers), C3 (CLAUDE.md tally). diff --git a/docs/superpowers/plans/2026-04-18-postbox-to-telegramengine-wave-4.md b/docs/superpowers/plans/2026-04-18-postbox-to-telegramengine-wave-4.md deleted file mode 100644 index 21e88108d6..0000000000 --- a/docs/superpowers/plans/2026-04-18-postbox-to-telegramengine-wave-4.md +++ /dev/null @@ -1,500 +0,0 @@ -# Postbox → TelegramEngine Wave 4 Implementation Plan - -> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. - -**Goal:** Migrate `TelegramEngine.Stickers.uploadSticker`'s public surface — `peer: Peer → EnginePeer`, `resource: MediaResource → EngineMediaResource`, `thumbnail: MediaResource? → EngineMediaResource?`, and `UploadStickerStatus.complete(CloudDocumentMediaResource, String) → .complete(EngineMediaResource, String)` — with one atomic commit touching the facade, the internal enum, and the two call sites. - -**Architecture:** Two commits on branch `refactor/postbox-to-engine-wave-4`. C1 is the atomic four-file code change. C2 is the CLAUDE.md tally update. `_internal_uploadSticker` keeps its raw `Peer`/`MediaResource` signature; the facade does all the wrapping/unwrapping. One spec-allowed one-line exception: `_internal_uploadSticker` constructs `EngineMediaResource(uploadedResource)` at the `.complete(...)` result-construction site to keep `UploadStickerStatus` as a single enum instead of splitting into raw+engine variants. - -**Tech Stack:** Swift / Bazel. No unit tests in this repo — verification is a full project build. - -**Spec:** [docs/superpowers/specs/2026-04-18-postbox-to-telegramengine-wave-4-design.md](docs/superpowers/specs/2026-04-18-postbox-to-telegramengine-wave-4-design.md) - -**Build command** (use for every "full build" step): - -```bash -source ~/.zshrc 2>/dev/null; PATH=/opt/homebrew/opt/ruby/bin:`gem environment gemdir`/bin:$PATH python3 build-system/Make/Make.py --overrideXcodeVersion --cacheDir ~/telegram-bazel-cache build --configurationPath build-system/appstore-configuration.json --gitCodesigningRepository git@gitlab.com:peter-iakovlev/fastlanematch.git --gitCodesigningType development --gitCodesigningUseCurrent --buildNumber 1 --configuration debug_sim_arm64 -``` - -The `source ~/.zshrc` prefix is required because `TELEGRAM_CODESIGNING_GIT_PASSWORD` lives in `~/.zshrc` and the bash tool does not source shell config by default. For a background build from the controller session, prefer `run_in_background: true` and monitor by tailing the task output file (subagent-spawned background builds orphan when the subagent shell terminates). - ---- - -## Task 1: Pre-flight re-verification - -No code changes. Purpose: re-confirm the facade call-site count and the MediaEditorScreen line numbers haven't drifted. - -**Files:** (read-only) - -- [ ] **Step 1: Re-grep facade call sites** - -```bash -grep -rnE "\.uploadSticker\(" submodules --include="*.swift" \ - | grep -v "/TelegramEngine/Stickers/" \ - | grep -v "self\.uploadSticker\|strongSelf\.uploadSticker\|self\?\.uploadSticker" -``` - -Expected output: exactly 2 lines - -- `submodules/ImportStickerPackUI/Sources/ImportStickerPackController.swift:91` -- `submodules/TelegramUI/Components/MediaEditorScreen/Sources/MediaEditorScreen.swift:8099` - -If the count or line numbers have drifted meaningfully, stop and revise the plan before editing. - -- [ ] **Step 2: Re-read MediaEditorScreen block** - -```bash -sed -n '8080,8190p' submodules/TelegramUI/Components/MediaEditorScreen/Sources/MediaEditorScreen.swift -``` - -Visually confirm: -- Line ~8097 has `.complete(resource, mimeType)` inside an `if let resource = resource as? CloudDocumentMediaResource { … }` branch. -- Line ~8099 has `context.engine.stickers.uploadSticker(peer: peer._asPeer(), resource: resource, thumbnail: file.previewRepresentations.first?.resource, …)`. -- Line ~8105 has `case let .complete(resource, _):` destructuring the inner `.mapToSignal` status. -- Line ~8106 has `stickerFile(resource: resource, thumbnailResource: file.previewRepresentations.first?.resource, …)`. -- Line ~8119 has `ImportSticker(resource: .standalone(resource: resource), …)` inside `case let .createStickerPack(title):`. -- Line ~8138 has a second `ImportSticker(resource: .standalone(resource: resource), …)` inside `case let .addToStickerPack(pack, title):`. -- Line ~8178 has a second `case let .complete(resource, _):` in the outer `.startStandalone(next: …)` handler. -- Line ~8180 has `stickerFile(resource: resource, thumbnailResource: file.previewRepresentations.first?.resource, size: resource.size ?? 0, …)`. - -- [ ] **Step 3: Confirm `stickerFile` signature** - -```bash -grep -nE "^private func stickerFile\(" submodules/TelegramUI/Components/MediaEditorScreen/Sources/MediaEditorScreen.swift -``` - -Expected: `private func stickerFile(resource: TelegramMediaResource, thumbnailResource: TelegramMediaResource?, size: Int64, dimensions: PixelDimensions, duration: Double?, isVideo: Bool) -> TelegramMediaFile` at line ~9196. This confirms `stickerFile` takes `TelegramMediaResource` (requires `resource._asResource()` at every call). - -- [ ] **Step 4: Confirm ImportStickerPackController's `peer` type** - -```bash -sed -n '82,95p' submodules/ImportStickerPackUI/Sources/ImportStickerPackController.swift -``` - -Expected pattern: -```swift -let _ = (self.context.account.postbox.loadedPeerWithId(self.context.account.peerId) -|> deliverOnMainQueue).start(next: { [weak self] peer in -``` - -`postbox.loadedPeerWithId` returns `Signal`. The local `peer` is therefore a raw `Peer`, not an `EnginePeer`. The call-site edit will need `EnginePeer(peer)` to wrap. - -If any of these expectations fails to match the current source, stop and revise the plan. - ---- - -## Task 2: Migrate `UploadStickerStatus` enum and internal wrap - -No build; the project won't compile until Tasks 3–5 also land. Do not commit. - -**File:** `submodules/TelegramCore/Sources/TelegramEngine/Stickers/ImportStickers.swift` - -- [ ] **Step 1: Update enum payload (line 7–10)** - -Replace: - -```swift -public enum UploadStickerStatus { - case progress(Float) - case complete(CloudDocumentMediaResource, String) -} -``` - -with: - -```swift -public enum UploadStickerStatus { - case progress(Float) - case complete(EngineMediaResource, String) -} -``` - -- [ ] **Step 2: Update the `.complete(...)` construction in `_internal_uploadSticker` (line ~97)** - -Replace the line reading: - -```swift - return .single(.complete(uploadedResource, file.mimeType)) -``` - -with: - -```swift - return .single(.complete(EngineMediaResource(uploadedResource), file.mimeType)) -``` - -Nothing else in `_internal_uploadSticker` changes. In particular its parameter list (`peer: Peer, resource: MediaResource, thumbnail: MediaResource? = nil, …`) stays exactly as is. - ---- - -## Task 3: Migrate the public facade signature - -No build; no commit. - -**File:** `submodules/TelegramCore/Sources/TelegramEngine/Stickers/TelegramEngineStickers.swift` - -- [ ] **Step 1: Update the `uploadSticker` facade (line 85–87)** - -Replace: - -```swift - public func uploadSticker(peer: Peer, resource: MediaResource, thumbnail: MediaResource?, alt: String, dimensions: PixelDimensions, duration: Double?, mimeType: String) -> Signal { - return _internal_uploadSticker(account: self.account, peer: peer, resource: resource, thumbnail: thumbnail, alt: alt, dimensions: dimensions, duration: duration, mimeType: mimeType) - } -``` - -with: - -```swift - public func uploadSticker(peer: EnginePeer, resource: EngineMediaResource, thumbnail: EngineMediaResource?, alt: String, dimensions: PixelDimensions, duration: Double?, mimeType: String) -> Signal { - return _internal_uploadSticker(account: self.account, peer: peer._asPeer(), resource: resource._asResource(), thumbnail: thumbnail?._asResource(), alt: alt, dimensions: dimensions, duration: duration, mimeType: mimeType) - } -``` - -No other method in `TelegramEngineStickers.swift` changes. - ---- - -## Task 4: Migrate `ImportStickerPackController.swift:91` - -No build; no commit. - -**File:** `submodules/ImportStickerPackUI/Sources/ImportStickerPackController.swift` - -- [ ] **Step 1: Update the facade call (line ~91)** - -Replace: - -```swift - signals.append(strongSelf.context.engine.stickers.uploadSticker(peer: peer, resource: resource._asResource(), thumbnail: nil, alt: sticker.emojis.first ?? "", dimensions: PixelDimensions(width: 512, height: 512), duration: nil, mimeType: sticker.mimeType) -``` - -with: - -```swift - signals.append(strongSelf.context.engine.stickers.uploadSticker(peer: EnginePeer(peer), resource: resource, thumbnail: nil, alt: sticker.emojis.first ?? "", dimensions: PixelDimensions(width: 512, height: 512), duration: nil, mimeType: sticker.mimeType) -``` - -Two changes: `peer` (raw `Peer`) → `EnginePeer(peer)`, and `resource._asResource()` → `resource` (the local `resource` is an `EngineMediaResource`). - -- [ ] **Step 2: Update the destructure re-wrap (line ~99)** - -Replace: - -```swift - case let .complete(resource, mimeType): - if ["application/x-tgsticker", "video/webm"].contains(mimeType) { - return (sticker.uuid, .verified, EngineMediaResource(resource)) - } else { -``` - -with: - -```swift - case let .complete(resource, mimeType): - if ["application/x-tgsticker", "video/webm"].contains(mimeType) { - return (sticker.uuid, .verified, resource) - } else { -``` - -One change: `EngineMediaResource(resource)` → `resource`. The destructured `resource` is now already an `EngineMediaResource`. - -Nothing else in this file changes. - ---- - -## Task 5: Migrate `MediaEditorScreen.swift` sticker-upload block - -No build; no commit. This task touches multiple lines inside a single nested block (~8084–8190). The `UploadStickerStatus` payload migration cascades: wherever the code constructs or destructures `.complete(...)`, types change. - -**File:** `submodules/TelegramUI/Components/MediaEditorScreen/Sources/MediaEditorScreen.swift` - -- [ ] **Step 1: Wrap at the direct construction site (line ~8097)** - -Replace the line reading: - -```swift - return .single((.progress(1.0), nil)) |> then(.single((.complete(resource, mimeType), nil))) -``` - -with: - -```swift - return .single((.progress(1.0), nil)) |> then(.single((.complete(EngineMediaResource(resource), mimeType), nil))) -``` - -Context: this is inside `if let resource = resource as? CloudDocumentMediaResource { … }`, so `resource` here is `CloudDocumentMediaResource`; the outer tuple's `UploadStickerStatus.complete` now takes `EngineMediaResource`. - -- [ ] **Step 2: Migrate the facade call (line ~8099)** - -Replace: - -```swift - return context.engine.stickers.uploadSticker(peer: peer._asPeer(), resource: resource, thumbnail: file.previewRepresentations.first?.resource, alt: "", dimensions: dimensions, duration: duration, mimeType: mimeType) -``` - -with: - -```swift - return context.engine.stickers.uploadSticker(peer: peer, resource: EngineMediaResource(resource), thumbnail: file.previewRepresentations.first.flatMap { EngineMediaResource($0.resource) }, alt: "", dimensions: dimensions, duration: duration, mimeType: mimeType) -``` - -Three changes: `peer._asPeer()` → `peer` (local is `EnginePeer`); `resource` → `EngineMediaResource(resource)` (local is raw `MediaResource` from the outer enum destructure); `file.previewRepresentations.first?.resource` → `file.previewRepresentations.first.flatMap { EngineMediaResource($0.resource) }`. - -- [ ] **Step 3: Unwrap at inner-handler `stickerFile` call (line ~8106)** - -Replace: - -```swift - case let .complete(resource, _): - let file = stickerFile(resource: resource, thumbnailResource: file.previewRepresentations.first?.resource, size: file.size ?? 0, dimensions: dimensions, duration: file.duration, isVideo: isVideo) -``` - -with: - -```swift - case let .complete(resource, _): - let file = stickerFile(resource: resource._asResource(), thumbnailResource: file.previewRepresentations.first?.resource, size: file.size ?? 0, dimensions: dimensions, duration: file.duration, isVideo: isVideo) -``` - -The destructured `resource` is now an `EngineMediaResource`. `stickerFile` (see line 9196) takes `TelegramMediaResource`, so unwrap with `._asResource()`. `file.previewRepresentations.first?.resource` is already a `TelegramMediaResource?` — no change there. - -- [ ] **Step 4: Unwrap at `.createStickerPack` sticker construction (line ~8119)** - -Replace: - -```swift - case let .createStickerPack(title): - let sticker = ImportSticker( - resource: .standalone(resource: resource), - emojis: emojis, - dimensions: dimensions, - duration: duration, - mimeType: mimeType, - keywords: "" - ) -``` - -with: - -```swift - case let .createStickerPack(title): - let sticker = ImportSticker( - resource: .standalone(resource: resource._asResource()), - emojis: emojis, - dimensions: dimensions, - duration: duration, - mimeType: mimeType, - keywords: "" - ) -``` - -`MediaResourceReference.standalone(resource:)` takes `MediaResource`; `resource` here is the `EngineMediaResource` destructured at line ~8105. Unwrap with `._asResource()`. - -- [ ] **Step 5: Unwrap at `.addToStickerPack` sticker construction (line ~8138)** - -Replace: - -```swift - case let .addToStickerPack(pack, title): - let sticker = ImportSticker( - resource: .standalone(resource: resource), - emojis: emojis, - dimensions: dimensions, - duration: duration, - mimeType: mimeType, - keywords: "" - ) -``` - -with: - -```swift - case let .addToStickerPack(pack, title): - let sticker = ImportSticker( - resource: .standalone(resource: resource._asResource()), - emojis: emojis, - dimensions: dimensions, - duration: duration, - mimeType: mimeType, - keywords: "" - ) -``` - -Same unwrap as Step 4. - -- [ ] **Step 6: Unwrap at outer-handler `stickerFile` call (line ~8178–8180)** - -Replace: - -```swift - case let .complete(resource, _): - let navigationController = self.effectiveNavigationController as? NavigationController - - let result: MediaEditorScreenImpl.Result - switch action { - case .update: - result = MediaEditorScreenImpl.Result(media: .sticker(file: file, emoji: emojis)) - case .upload, .send: - let file = stickerFile(resource: resource, thumbnailResource: file.previewRepresentations.first?.resource, size: resource.size ?? 0, dimensions: dimensions, duration: self.preferredStickerDuration(), isVideo: isVideo) -``` - -with: - -```swift - case let .complete(resource, _): - let rawResource = resource._asResource() - let navigationController = self.effectiveNavigationController as? NavigationController - - let result: MediaEditorScreenImpl.Result - switch action { - case .update: - result = MediaEditorScreenImpl.Result(media: .sticker(file: file, emoji: emojis)) - case .upload, .send: - let file = stickerFile(resource: rawResource, thumbnailResource: file.previewRepresentations.first?.resource, size: rawResource.size ?? 0, dimensions: dimensions, duration: self.preferredStickerDuration(), isVideo: isVideo) -``` - -Two changes: introduce `let rawResource = resource._asResource()` at the top of the `case let .complete(resource, _):` block, and use `rawResource` at both the `resource:` argument and the `size: rawResource.size ?? 0` read. (`EngineMediaResource` does not expose `.size`; only the raw `MediaResource` does.) - -- [ ] **Step 7: Scan for any missed downstream use** - -Run inside the repo: - -```bash -sed -n '8080,8200p' submodules/TelegramUI/Components/MediaEditorScreen/Sources/MediaEditorScreen.swift | grep -nE "\bresource\b" -``` - -Skim the output. Every reference to the destructured `resource` inside the nested block (lines ~8084–8190) should either be the new `EngineMediaResource`-typed local or a wrapped/unwrapped form. If you spot a use that would still expect `CloudDocumentMediaResource`-specific members or raw `MediaResource` without the unwrap, stop and report. - ---- - -## Task 6: Full build and commit C1 - -- [ ] **Step 1: Run the full project build** - -Run the build command from the header. Expected: clean success. - -Typical failure modes and fixes (do them inline — do not split into another commit): - -- **"cannot convert value of type 'Peer' to expected argument type 'EnginePeer'"** — a call site was missed or the wrap is misplaced. -- **"value of type 'EngineMediaResource' has no member 'size'"** — Task 5 Step 6 wasn't applied (or similar `.size`/`.id.stringRepresentation`/`.isEqual` access on `EngineMediaResource`). -- **"cannot convert value of type 'EngineMediaResource' to expected argument type 'TelegramMediaResource'"** — an `._asResource()` is missing at a `stickerFile(...)` or `.standalone(resource:)` call. -- **"reference to enum case 'UploadStickerStatus.complete' requires that 'CloudDocumentMediaResource' conform to 'something'"** — a `.complete(...)` construction site wasn't migrated to pass `EngineMediaResource`. - -Re-run the build after each fix. - -- [ ] **Step 2: Stage the 4 files** - -```bash -git add \ - submodules/TelegramCore/Sources/TelegramEngine/Stickers/ImportStickers.swift \ - submodules/TelegramCore/Sources/TelegramEngine/Stickers/TelegramEngineStickers.swift \ - submodules/ImportStickerPackUI/Sources/ImportStickerPackController.swift \ - submodules/TelegramUI/Components/MediaEditorScreen/Sources/MediaEditorScreen.swift -``` - -- [ ] **Step 3: Verify diff scope** - -```bash -git diff --staged --stat -``` - -Expected: exactly 4 files staged, with MediaEditorScreen having the largest diff (~8 line changes), ImportStickers ~2, TelegramEngineStickers ~2, ImportStickerPackController ~2. - -- [ ] **Step 4: Commit** - -```bash -git commit -m "$(cat <<'EOF' -TelegramEngine.Stickers.uploadSticker: migrate to EnginePeer + EngineMediaResource - -Public facade and UploadStickerStatus.complete payload now use -EnginePeer and EngineMediaResource instead of raw Peer / MediaResource -/ CloudDocumentMediaResource. _internal_uploadSticker stays on raw -Postbox types with one inline EngineMediaResource(uploadedResource) -construction at the .complete result site. - -Both call sites (ImportStickerPackController, MediaEditorScreen) -updated atomically in the same commit. - -Wave-4 of the Postbox -> TelegramEngine refactor. - -Co-Authored-By: Claude Opus 4.7 (1M context) -EOF -)" -``` - -- [ ] **Step 5: Verify branch state** - -```bash -git log --oneline master..HEAD -``` - -Expected (newest at top): - -- ` TelegramEngine.Stickers.uploadSticker: migrate to EnginePeer + EngineMediaResource` -- `b6392bce7c docs(spec): wave-4 enumerate MediaEditorScreen downstream edits` -- `59a01b0d4d docs(spec): wave-4 TelegramEngine.Stickers.uploadSticker facade migration` - ---- - -## Task 7: Update CLAUDE.md tally and commit C2 - -- [ ] **Step 1: Add Wave 4 outcome subsection** - -Open `CLAUDE.md`. Find the "Wave 3 outcome (2026-04-18)" section (currently around line 96 onward). Insert a new subsection **after** Wave 3's outcome block and **before** "### Modules currently free of `import Postbox` (running tally)": - -```markdown -### Wave 4 outcome (2026-04-18) - -1 `TelegramEngine` facade migrated in place to `EnginePeer` + `EngineMediaResource` (signatures changed; `_internal_uploadSticker` keeps raw `Peer`/`MediaResource`): - -- `TelegramEngine.Stickers.uploadSticker(peer: Peer → EnginePeer, resource: MediaResource → EngineMediaResource, thumbnail: MediaResource? → EngineMediaResource?, …)` - -1 public enum payload migrated: `UploadStickerStatus.complete(CloudDocumentMediaResource, String)` → `.complete(EngineMediaResource, String)`. The internal `_internal_uploadSticker` constructs `EngineMediaResource(uploadedResource)` at the result site — a narrow, spec-allowed one-line deviation from "internal Postbox-facing stays raw", taken to keep `UploadStickerStatus` as a single public enum. - -2 call sites migrated atomically with the facade: -- `submodules/ImportStickerPackUI/Sources/ImportStickerPackController.swift:91` -- `submodules/TelegramUI/Components/MediaEditorScreen/Sources/MediaEditorScreen.swift:8099` (plus ~5 cascading sites in the same enclosing block for the new `UploadStickerStatus.complete` payload) - -No module becomes Postbox-free in this wave (both caller files import Postbox for unrelated reasons). - -Plan: `docs/superpowers/plans/2026-04-18-postbox-to-telegramengine-wave-4.md` -``` - -- [ ] **Step 2: Remove the `uploadSticker` entry from "Known future-wave candidates"** - -Still in `CLAUDE.md`, find the "Known future-wave candidates" list and delete this bullet (currently around line 143): - -```markdown -- `TelegramEngine.Stickers.uploadSticker(peer: Peer, resource: MediaResource, thumbnail: MediaResource?, …)` — same MediaResource migration as wave 2, plus `peer: Peer` which would naturally migrate to `EnginePeer` at the same time. Self-contained to a small number of call sites. -``` - -Do not touch the other bullets in that list. - -- [ ] **Step 3: Commit** - -```bash -git add CLAUDE.md -git commit -m "$(cat <<'EOF' -CLAUDE.md: record wave-4 outcome - -Documents the uploadSticker facade migration + UploadStickerStatus -payload change; removes uploadSticker from the future-wave candidates -list. - -Co-Authored-By: Claude Opus 4.7 (1M context) -EOF -)" -``` - ---- - -## Success criteria - -- `TelegramEngine.Stickers.uploadSticker`'s public signature references neither `Peer` nor `MediaResource` nor `CloudDocumentMediaResource`. -- `UploadStickerStatus.complete`'s payload is `(EngineMediaResource, String)`. -- `_internal_uploadSticker`'s signature is unchanged (still raw `Peer` / `MediaResource`). -- Full build succeeds in `debug_sim_arm64`. -- The two call sites (`ImportStickerPackController`, `MediaEditorScreen`) and the cascading sites within MediaEditorScreen's nested block compile against the new types. -- `CLAUDE.md` has a "Wave 4 outcome (2026-04-18)" subsection; the `uploadSticker` bullet is gone from "Known future-wave candidates". -- Branch `refactor/postbox-to-engine-wave-4` contains 4 commits above `master`: 2 docs (spec + spec fix), 1 code (C1), 1 tally (C2). diff --git a/docs/superpowers/plans/2026-04-18-postbox-to-telegramengine-wave-5.md b/docs/superpowers/plans/2026-04-18-postbox-to-telegramengine-wave-5.md deleted file mode 100644 index 9b77640185..0000000000 --- a/docs/superpowers/plans/2026-04-18-postbox-to-telegramengine-wave-5.md +++ /dev/null @@ -1,381 +0,0 @@ -# Postbox → TelegramEngine Wave 5 Implementation Plan - -> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. - -**Goal:** Migrate `uploadSecureIdFile`'s public surface to `(context:, engine: TelegramEngine, resource: EngineMediaResource)`, refactor `SecureIdVerificationDocumentsContext` to take `engine: TelegramEngine` in place of raw `Postbox` + `Network`, and drop `import Postbox` from that caller module. Land as one atomic code commit + one CLAUDE.md tally commit on branch `refactor/postbox-to-engine-wave-5`. - -**Architecture:** Three files land together in C1 because the facade signature change, the caller class's stored-property change, and the one instantiation site are mutually breaking. The facade body inside TelegramCore continues to access raw Postbox types via `engine.account.postbox` / `engine.account.network` — CLAUDE.md's "internal Postbox-facing stays raw" rule applies to the body, while the public signature is the clean surface. C2 updates the CLAUDE.md tally and removes the wave-5-named bullet from "Known future-wave candidates". - -**Tech Stack:** Swift / Bazel. No unit tests by repo policy — verification is a full project build. - -**Spec:** [docs/superpowers/specs/2026-04-18-postbox-to-telegramengine-wave-5-design.md](docs/superpowers/specs/2026-04-18-postbox-to-telegramengine-wave-5-design.md) - -**Build command** (use for every "full build" step): - -```bash -source ~/.zshrc 2>/dev/null; PATH=/opt/homebrew/opt/ruby/bin:`gem environment gemdir`/bin:$PATH python3 build-system/Make/Make.py --overrideXcodeVersion --cacheDir ~/telegram-bazel-cache build --configurationPath build-system/appstore-configuration.json --gitCodesigningRepository git@gitlab.com:peter-iakovlev/fastlanematch.git --gitCodesigningType development --gitCodesigningUseCurrent --buildNumber 1 --configuration debug_sim_arm64 -``` - -The `source ~/.zshrc` prefix is required because `TELEGRAM_CODESIGNING_GIT_PASSWORD` lives in `~/.zshrc` and the bash tool does not source shell config by default. For a long-running build, prefer `run_in_background: true` from the controller session (subagent-spawned background builds orphan when the subagent's shell terminates). - ---- - -## Task 1: Pre-flight re-verification - -No code changes. Confirms the inventory hasn't drifted. - -- [ ] **Step 1: Re-grep `uploadSecureIdFile` call sites** - -```bash -grep -rnE "uploadSecureIdFile\(" submodules --include="*.swift" | grep -v "/SecureId/" -``` - -Expected: exactly 1 match — `submodules/PassportUI/Sources/SecureIdVerificationDocumentsContext.swift:43`. If the count or file has drifted, stop and revise the plan. - -- [ ] **Step 2: Re-grep `SecureIdVerificationDocumentsContext(...)` instantiation sites** - -```bash -grep -rnE "SecureIdVerificationDocumentsContext\(" submodules --include="*.swift" | grep -v "final class SecureIdVerificationDocumentsContext" -``` - -Expected: exactly 1 match — `submodules/PassportUI/Sources/SecureIdDocumentFormControllerNode.swift:2172`. If drift, stop. - -- [ ] **Step 3: Confirm `AccountContext.engine` protocol requirement** - -```bash -grep -nE "var engine: TelegramEngine" submodules/AccountContext/Sources/AccountContext.swift -``` - -Expected: one line matching `var engine: TelegramEngine { get }` (the protocol requirement). This confirms `self.context.engine` will be available at the instantiation site in Task 4. - -- [ ] **Step 4: Confirm `info.resource` type** - -```bash -grep -nE "let resource:" submodules/PassportUI/Sources/SecureIdVerificationDocument.swift -``` - -Expected: two matches, both showing `resource: TelegramMediaResource`. Confirms `EngineMediaResource(info.resource)` will compile (the `EngineMediaResource(_:)` init takes `MediaResource`, which `TelegramMediaResource` inherits). - ---- - -## Task 2: Migrate `uploadSecureIdFile`'s public facade and body - -No build; no commit. Tasks 2–4 share one atomic commit in Task 5. - -**File:** `submodules/TelegramCore/Sources/TelegramEngine/SecureId/UploadSecureIdFile.swift` - -- [ ] **Step 1: Replace the function signature and body** - -Find the `uploadSecureIdFile` function (currently starts at line 90). Replace the entire function (from `public func uploadSecureIdFile` through its closing `}`) with this version: - -```swift -public func uploadSecureIdFile(context: SecureIdAccessContext, engine: TelegramEngine, resource: EngineMediaResource) -> Signal { - return engine.account.postbox.mediaBox.resourceData(resource._asResource()) - |> mapError { _ -> UploadSecureIdFileError in - } - |> mapToSignal { next -> Signal in - if !next.complete { - return .complete() - } - - guard let data = try? Data(contentsOf: URL(fileURLWithPath: next.path)) else { - return .fail(.generic) - } - - guard let encryptedData = encryptedSecureIdFile(context: context, data: data) else { - return .fail(.generic) - } - - return multipartUpload(network: engine.account.network, postbox: engine.account.postbox, source: .data(encryptedData.data), encrypt: false, tag: TelegramMediaResourceFetchTag(statsCategory: .image, userContentType: .image), hintFileSize: nil, hintFileIsLarge: false, forceNoBigParts: false) - |> mapError { _ -> UploadSecureIdFileError in - return .generic - } - |> mapToSignal { result -> Signal in - switch result { - case let .progress(value): - return .single(.progress(value)) - case let .inputFile(.inputFile(fileData)): - return .single(.result(UploadedSecureIdFile(id: fileData.id, parts: fileData.parts, md5Checksum: fileData.md5Checksum, fileHash: encryptedData.hash, encryptedSecret: encryptedData.encryptedSecret), encryptedData.data)) - default: - return .fail(.generic) - } - } - } -} -``` - -Changes from the original: - -- Signature: `(context: SecureIdAccessContext, postbox: Postbox, network: Network, resource: MediaResource)` → `(context: SecureIdAccessContext, engine: TelegramEngine, resource: EngineMediaResource)`. -- Line 1 of body: `postbox.mediaBox.resourceData(resource)` → `engine.account.postbox.mediaBox.resourceData(resource._asResource())`. -- Inside the `mapToSignal`: `multipartUpload(network: network, postbox: postbox, ...)` → `multipartUpload(network: engine.account.network, postbox: engine.account.postbox, ...)`. - -No other file in `TelegramCore/Sources/TelegramEngine/SecureId/` is touched. No imports change inside `UploadSecureIdFile.swift` — it continues to `import Foundation`, `import Postbox`, `import MtProtoKit`, `import SwiftSignalKit`, which remain correct (the body still uses raw Postbox types via `engine.account.postbox`). - ---- - -## Task 3: Migrate `SecureIdVerificationDocumentsContext` - -No build; no commit. - -**File:** `submodules/PassportUI/Sources/SecureIdVerificationDocumentsContext.swift` - -- [ ] **Step 1: Drop `import Postbox`** - -Replace the import block at the top (lines 1–4): - -```swift -import Foundation -import Postbox -import TelegramCore -import SwiftSignalKit -``` - -with: - -```swift -import Foundation -import TelegramCore -import SwiftSignalKit -``` - -Only `Postbox` is removed. The three remaining imports stay. - -- [ ] **Step 2: Replace stored properties** - -Find the `final class SecureIdVerificationDocumentsContext` block (starting around line 18). Replace lines 20–21: - -```swift - private let postbox: Postbox - private let network: Network -``` - -with: - -```swift - private let engine: TelegramEngine -``` - -- [ ] **Step 3: Update the constructor** - -Replace the `init` (lines 26–31): - -```swift - init(postbox: Postbox, network: Network, context: SecureIdAccessContext, update: @escaping (Int64, SecureIdVerificationLocalDocumentState) -> Void) { - self.postbox = postbox - self.network = network - self.context = context - self.update = update - } -``` - -with: - -```swift - init(engine: TelegramEngine, context: SecureIdAccessContext, update: @escaping (Int64, SecureIdVerificationLocalDocumentState) -> Void) { - self.engine = engine - self.context = context - self.update = update - } -``` - -- [ ] **Step 4: Update the `uploadSecureIdFile` call inside `stateUpdated`** - -Find line 43, which currently reads: - -```swift - disposable.set((uploadSecureIdFile(context: self.context, postbox: self.postbox, network: self.network, resource: info.resource) -``` - -Replace with: - -```swift - disposable.set((uploadSecureIdFile(context: self.context, engine: self.engine, resource: EngineMediaResource(info.resource)) -``` - -Two changes: -- `postbox: self.postbox, network: self.network` → `engine: self.engine`. -- `resource: info.resource` → `resource: EngineMediaResource(info.resource)`. - -No other line in this file changes. The `DocumentContext` inner class is untouched. The `stateUpdated` method's outer structure is untouched. - ---- - -## Task 4: Update the instantiation site - -No build; no commit. - -**File:** `submodules/PassportUI/Sources/SecureIdDocumentFormControllerNode.swift` - -- [ ] **Step 1: Update line 2172** - -Find line 2172, which currently reads: - -```swift - self.uploadContext = SecureIdVerificationDocumentsContext(postbox: self.context.account.postbox, network: self.context.account.network, context: self.secureIdContext, update: { id, state in -``` - -Replace with: - -```swift - self.uploadContext = SecureIdVerificationDocumentsContext(engine: self.context.engine, context: self.secureIdContext, update: { id, state in -``` - -Two removed arguments (`postbox:`, `network:`) collapse into one new argument (`engine:`). The closure body inside `update: { id, state in ... }` is unchanged. - -No other line in this file changes. The file continues to `import Postbox` for unrelated reasons — this is expected, do not remove. - ---- - -## Task 5: Full build and commit C1 - -- [ ] **Step 1: Run the full project build** - -Run the build command from the header. Expected: clean success. - -Typical failure modes and fixes (do them inline — do not split): - -- **"cannot convert value of type 'Postbox' to expected argument type 'TelegramEngine'"** — a call site was missed. Re-grep both `uploadSecureIdFile(` and `SecureIdVerificationDocumentsContext(` across the repo. -- **"cannot convert value of type 'MediaResource' to expected argument type 'EngineMediaResource'"** — Task 3 Step 4's `EngineMediaResource(info.resource)` wrap was missed. -- **"use of unresolved identifier 'Network'"** or **"use of unresolved identifier 'Postbox'"** inside `SecureIdVerificationDocumentsContext.swift`** — Tasks 3 Steps 2–3 or 4 weren't fully applied. -- **"missing argument for parameter 'engine'"** — the Task 4 call site wasn't updated. - -Re-run the build after each fix. - -- [ ] **Step 2: Stage the three files** - -```bash -git add \ - submodules/TelegramCore/Sources/TelegramEngine/SecureId/UploadSecureIdFile.swift \ - submodules/PassportUI/Sources/SecureIdVerificationDocumentsContext.swift \ - submodules/PassportUI/Sources/SecureIdDocumentFormControllerNode.swift -``` - -- [ ] **Step 3: Verify diff scope** - -```bash -git diff --staged --stat -``` - -Expected: exactly 3 files staged. Approximate line changes: -- `UploadSecureIdFile.swift`: ~3 lines (signature + 2 body sites). -- `SecureIdVerificationDocumentsContext.swift`: ~8 lines (1 import removed, stored props, constructor, call site). -- `SecureIdDocumentFormControllerNode.swift`: 1 line. - -- [ ] **Step 4: Commit C1** - -```bash -git commit -m "$(cat <<'EOF' -SecureId: migrate uploadSecureIdFile + context to TelegramEngine - -uploadSecureIdFile's public signature now takes engine: TelegramEngine -and resource: EngineMediaResource instead of raw postbox: Postbox + -network: Network + MediaResource. The function body accesses raw -Postbox types via engine.account.postbox / engine.account.network -(internal Postbox-facing layer stays raw per CLAUDE.md). - -SecureIdVerificationDocumentsContext refactored in lockstep: stores -engine: TelegramEngine instead of raw postbox + network, drops -import Postbox. The one instantiation site in -SecureIdDocumentFormControllerNode updates to pass engine: -self.context.engine. - -Wave-5 of the Postbox -> TelegramEngine refactor; completes the last -explicitly-named future-wave candidate. - -Co-Authored-By: Claude Opus 4.7 (1M context) -EOF -)" -``` - -- [ ] **Step 5: Verify branch state** - -```bash -git log --oneline master..HEAD -``` - -Expected (newest at top): -- ` SecureId: migrate uploadSecureIdFile + context to TelegramEngine` -- `b7a1a5dfb0 docs(spec): wave-5 uploadSecureIdFile facade + SecureId context migration` - ---- - -## Task 6: Update CLAUDE.md tally and commit C2 - -- [ ] **Step 1: Add `SecureIdVerificationDocumentsContext` to the Postbox-free tally** - -Open `CLAUDE.md`. Find the "Modules currently free of `import Postbox` (running tally)" section. Add `- SecureIdVerificationDocumentsContext (wave 5)` as the last bullet in the list, immediately after `- SaveToCameraRoll (wave 3)`: - -```markdown -- `MapResourceToAvatarSizes` (wave 2) -- `SaveToCameraRoll` (wave 3) -- `SecureIdVerificationDocumentsContext` (wave 5) -``` - -- [ ] **Step 2: Add a "Wave 5 outcome" subsection** - -Still in `CLAUDE.md`, find the "Wave 4 outcome (2026-04-18)" block. Insert a new "Wave 5 outcome" subsection **after** Wave 4 and **before** "Modules currently free of `import Postbox`": - -```markdown -### Wave 5 outcome (2026-04-18) - -Completes the last explicitly-named future-wave candidate from the wave-2 final review. - -`uploadSecureIdFile(context: SecureIdAccessContext, postbox: Postbox, network: Network, resource: MediaResource)` migrated in place to `(context:, engine: TelegramEngine, resource: EngineMediaResource)`. Function body accesses raw Postbox types via `engine.account.postbox` / `engine.account.network` (internal Postbox-facing layer stays raw per the standing rule). - -1 consumer submodule fully de-Postboxed: `SecureIdVerificationDocumentsContext` (PassportUI/Sources). Signature changed from `(postbox: Postbox, network: Network, context: SecureIdAccessContext, update: ...)` to `(engine: TelegramEngine, context: SecureIdAccessContext, update: ...)`; stored props collapsed into a single `engine: TelegramEngine` field. One instantiation site updated in the same commit. - -After this wave, the "Known future-wave candidates" list contains only the 4 permanently-blocked classes conforming to `TelegramMediaResource`. - -Plan: `docs/superpowers/plans/2026-04-18-postbox-to-telegramengine-wave-5.md` -``` - -- [ ] **Step 3: Remove the `uploadSecureIdFile` bullet from "Known future-wave candidates"** - -Still in `CLAUDE.md`, find the "Known future-wave candidates" list. Delete this bullet entirely: - -```markdown -- `submodules/TelegramCore/Sources/TelegramEngine/SecureId/UploadSecureIdFile.swift: public func uploadSecureIdFile(…, postbox: Postbox, …, resource: MediaResource)` — rule-2-sensitive (umbrella-type leak). Needs a paired wave with its caller(s). -``` - -Do not touch the remaining bullet about permanently-blocked classes. - -- [ ] **Step 4: Commit C2** - -```bash -git add CLAUDE.md -git commit -m "$(cat <<'EOF' -CLAUDE.md: record wave-5 outcome - -Adds SecureIdVerificationDocumentsContext to the Postbox-free module -tally, documents the uploadSecureIdFile facade migration, and removes -the uploadSecureIdFile bullet from "Known future-wave candidates". -After this wave, the candidate list contains only the 4 permanently- -blocked TelegramMediaResource-conforming classes. - -Co-Authored-By: Claude Opus 4.7 (1M context) -EOF -)" -``` - -- [ ] **Step 5: Verify final branch state** - -```bash -git log --oneline master..HEAD -``` - -Expected: -- ` CLAUDE.md: record wave-5 outcome` -- ` SecureId: migrate uploadSecureIdFile + context to TelegramEngine` -- `b7a1a5dfb0 docs(spec): wave-5 uploadSecureIdFile facade + SecureId context migration` - ---- - -## Success criteria - -- `uploadSecureIdFile`'s public signature references neither `Postbox`, `Network`, nor `MediaResource`. -- `SecureIdVerificationDocumentsContext.swift` does not contain `import Postbox`. -- Full build succeeds in `debug_sim_arm64`. -- `grep -l "import Postbox" submodules/PassportUI/Sources/SecureIdVerificationDocumentsContext.swift` returns no match. -- `CLAUDE.md`'s "Known future-wave candidates" list no longer mentions `uploadSecureIdFile`; the Postbox-free running tally includes `SecureIdVerificationDocumentsContext (wave 5)`. -- Branch `refactor/postbox-to-engine-wave-5` contains 3 commits above `master`: 1 doc (spec) + 1 code (C1) + 1 tally (C2). diff --git a/docs/superpowers/plans/2026-04-19-postbox-to-telegramengine-wave-6.md b/docs/superpowers/plans/2026-04-19-postbox-to-telegramengine-wave-6.md deleted file mode 100644 index 2693f19732..0000000000 --- a/docs/superpowers/plans/2026-04-19-postbox-to-telegramengine-wave-6.md +++ /dev/null @@ -1,374 +0,0 @@ -# Postbox → TelegramEngine Wave 6 Implementation Plan - -> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. - -**Goal:** Speculatively drop `import Postbox` from every consumer file where a plain `^import Postbox$` line appears, run a full project build, restore the import on files that fail to compile, iterate up to 3 times, commit surviving drops as one atomic commit. Then land a CLAUDE.md update with the outcome and permanent methodology guidance. - -**Architecture:** Two commits on branch `refactor/postbox-to-engine-wave-6`. C1 is the atomic batch deletion whose diff is N single-line removals (build-verified). C2 is a docs update that (a) records the outcome and (b) codifies the sweep methodology under "Wave-selection guidance" so future sweeps can be triggered directly. The project build is the safety net — anything that compiles after restoration is definitionally safe. - -**Tech Stack:** Swift / Bazel. No unit tests — verification is a full project build. - -**Spec:** [docs/superpowers/specs/2026-04-19-postbox-to-telegramengine-wave-6-design.md](docs/superpowers/specs/2026-04-19-postbox-to-telegramengine-wave-6-design.md) - -**Build command** (use for every "full build" step): - -```bash -source ~/.zshrc 2>/dev/null; PATH=/opt/homebrew/opt/ruby/bin:`gem environment gemdir`/bin:$PATH python3 build-system/Make/Make.py --overrideXcodeVersion --cacheDir ~/telegram-bazel-cache build --configurationPath build-system/appstore-configuration.json --gitCodesigningRepository git@gitlab.com:peter-iakovlev/fastlanematch.git --gitCodesigningType development --gitCodesigningUseCurrent --buildNumber 1 --configuration debug_sim_arm64 -``` - -For background execution (recommended given build length), use `run_in_background: true` from the controller session. Do not let a subagent spawn the build — when the subagent returns the process orphans. The controller owns every build invocation in this wave. - ---- - -## Task 1: Generate and record the candidate list - -Read-only setup. No code changes yet. - -- [ ] **Step 1: Generate the candidate list** - -```bash -grep -rl "^import Postbox$" submodules --include="*.swift" \ - | grep -vE "/(TelegramCore|Postbox|TelegramApi)/" \ - | sort > /tmp/wave-6-candidates.txt -wc -l /tmp/wave-6-candidates.txt -``` - -Expected: a count somewhere between 100 and 400. Record the exact number — call it `N_candidates`. If the count is outside that range, stop and investigate: either the grep is too narrow (missing `@_exported` etc. ought to be rare) or too broad (accidentally matching TelegramCore). - -- [ ] **Step 2: Snapshot baseline** - -The snapshot is implicit: every candidate file is at branch HEAD, so `git checkout -- ` always restores the pre-sweep content. Verify the working tree is clean: - -```bash -git status --short | grep -v '^??' | grep -v sourcekit-bazel-bsp -``` - -Expected: empty output. (The `sourcekit-bazel-bsp` submodule shows as modified across the whole repo; that's pre-existing and orthogonal.) If there are any other unstaged changes, commit or stash them before proceeding. - -- [ ] **Step 3: Confirm branch and HEAD** - -```bash -git branch --show-current -git log --oneline -3 -``` - -Expected: -- current branch: `refactor/postbox-to-engine-wave-6` -- top commit: the wave-6 spec commit. - ---- - -## Task 2: Speculative drop pass - -Mutates all candidate files. No commit yet. - -- [ ] **Step 1: Drop `import Postbox` from every candidate** - -```bash -while IFS= read -r f; do - /usr/bin/sed -i '' '/^import Postbox$/d' "$f" -done < /tmp/wave-6-candidates.txt -``` - -macOS `sed` requires the `''` after `-i` (BSD flavor). - -- [ ] **Step 2: Verify every candidate had exactly one line removed** - -```bash -git diff --stat | wc -l -``` - -Expected: `N_candidates + 1` (one line per file in `--stat` output, plus the summary line). - -```bash -git diff --stat | awk '{print $3}' | grep -v deletion | head -5 -``` - -Expected: each shown entry is `1` (one insertion, zero counted since all are single-line deletes). If any file shows more than 1 line changed, something went wrong — investigate. - -- [ ] **Step 3: Confirm no `@_exported` lines were accidentally touched** - -```bash -grep -r "@_exported import Postbox" submodules --include="*.swift" | head -5 -``` - -If this returns results, those lines must still be intact — verify. The regex used in Step 1 only matches bare `^import Postbox$`, so `@_exported import Postbox` is untouched. This step is a sanity check. - ---- - -## Task 3: Iteration 1 — first build, parse errors, restore failing files - -- [ ] **Step 1: Run the full project build (iteration 1)** - -Run the build command from the header. Expected: many errors — this is by design. Capture stderr to the build output file. - -Watch the tail of the output file for either `INFO: Build completed successfully` (rare: means zero imports were needed) or a cascade of compile errors (expected). - -- [ ] **Step 2: Extract failing files from the build output** - -```bash -BUILD_OUT=/private/tmp/claude-501/-Users-ali-build-telegram-telegram-ios/5d9b3268-5c9f-45fc-bd4e-87cac5361498/tasks/.output -grep -E "^submodules/.*\.swift:[0-9]+:[0-9]+: error:" "$BUILD_OUT" \ - | awk -F: '{print $1}' \ - | sort -u > /tmp/wave-6-failing.txt -wc -l /tmp/wave-6-failing.txt -``` - -The task-id comes from the background Bash tool's output file. Substitute the actual `/private/tmp/claude-501/.../.output` path. - -Sanity-check the content: - -```bash -head -3 /tmp/wave-6-failing.txt -``` - -Every line should be a path under `submodules/` that appears in `/tmp/wave-6-candidates.txt`. If any line is from `TelegramCore`, `Postbox`, or `TelegramApi`, the sweep has cascaded beyond the candidate set — halt and investigate. - -- [ ] **Step 3: Validate error types** - -```bash -grep -E "^submodules/.*\.swift:[0-9]+:[0-9]+: error:" "$BUILD_OUT" \ - | head -10 -``` - -Expected error patterns: -- `cannot find type 'X' in scope` -- `use of unresolved identifier 'X'` -- `cannot find 'X' in scope` -- `reference to invalid associated type 'X' of type 'Y'` (occasional) - -If you see `no such module 'Postbox'` or errors unrelated to missing Postbox symbols (e.g., codesign failures, Bazel graph errors), halt and investigate — those are not the sweep's signal. - -- [ ] **Step 4: Restore `import Postbox` on failing files** - -```bash -while IFS= read -r f; do - git checkout -- "$f" -done < /tmp/wave-6-failing.txt -``` - -- [ ] **Step 5: Verify restoration** - -```bash -git diff --stat | wc -l -``` - -Expected: `N_candidates - N_failing + 1` lines in `--stat` output (one per still-modified file plus summary). The count should be lower than Task 2 Step 2's count by exactly `N_failing`. - ---- - -## Task 4: Iteration 2 — rebuild, parse new errors, restore - -- [ ] **Step 1: Run the full project build (iteration 2)** - -Run the build command again. Expected: ideally clean success. If errors persist, it's because restoring some files in iteration 1 removed a symbol that another file (still in the candidate set with import dropped) needed transitively via that symbol's module-level re-export. - -Watch for `INFO: Build completed successfully`. If found, proceed to Task 6 (skipping Task 5). If errors persist, continue with Step 2. - -- [ ] **Step 2: Extract failing files** - -```bash -BUILD_OUT=/private/tmp/claude-501/-Users-ali-build-telegram-telegram-ios/5d9b3268-5c9f-45fc-bd4e-87cac5361498/tasks/.output -grep -E "^submodules/.*\.swift:[0-9]+:[0-9]+: error:" "$BUILD_OUT" \ - | awk -F: '{print $1}' \ - | sort -u > /tmp/wave-6-failing-2.txt -wc -l /tmp/wave-6-failing-2.txt -``` - -- [ ] **Step 3: Restore** - -```bash -while IFS= read -r f; do - git checkout -- "$f" -done < /tmp/wave-6-failing-2.txt -``` - -- [ ] **Step 4: Decision point** - -If `wc -l /tmp/wave-6-failing-2.txt` is 0, the iteration-2 rebuild actually succeeded — proceed to Task 6. If it's greater than 0, proceed to Task 5 for iteration 3. - ---- - -## Task 5: Iteration 3 — final rebuild - -- [ ] **Step 1: Run the full project build (iteration 3)** - -Run the build command again. If this iteration does not complete successfully, the sweep has failed the stability test. - -- [ ] **Step 2: Clean-success check** - -Expected: `INFO: Build completed successfully`. - -If successful, proceed to Task 6. - -If a third iteration of errors appears, **abandon the wave**: - -```bash -git checkout -- . -git status --short -``` - -Working tree should now be clean (modulo the pre-existing sourcekit-bazel-bsp submodule marker). Do not commit. Skip Task 6. Jump straight to an updated Task 7 that records the failed attempt in CLAUDE.md instead of a success outcome, and document what kind of errors surfaced so a future attempt can plan around them. - ---- - -## Task 6: Commit C1 — build-verified batch drop - -- [ ] **Step 1: Compute the final count** - -```bash -git diff --stat | tail -1 -``` - -Expected: something like ` N files changed, 0 insertions(+), N deletions(-)` where N is the number of files that survived the sweep. Record this count as `N_dropped`. - -- [ ] **Step 2: Spot-check a few diffs** - -```bash -git diff | grep -E "^-import Postbox$" | wc -l -``` - -Expected: `N_dropped` (every surviving diff is a single-line `-import Postbox` removal). - -```bash -git diff | grep -E "^\+" | grep -v "^+++" | head -``` - -Expected: no output. (The sweep only removes lines; it never adds any.) - -- [ ] **Step 3: Stage all changes** - -```bash -git add -u -``` - -`-u` stages only files that are already tracked and modified. No need to enumerate each file — the sweep touched many and they're all known to git. - -- [ ] **Step 4: Commit** - -```bash -N_DROPPED=$(git diff --staged --stat | tail -1 | awk '{print $1}') -git commit -m "$(cat < -EOF -)" -``` - -- [ ] **Step 5: Verify branch state** - -```bash -git log --oneline master..HEAD -``` - -Expected: -- ` Drop unused import Postbox from N consumer files` -- `816e7699ec docs(spec): wave-6 unused import Postbox batch sweep` - ---- - -## Task 7: CLAUDE.md — record outcome and add permanent sweep methodology - -- [ ] **Step 1: Add Wave 6 outcome subsection** - -Open `CLAUDE.md`. Find the "Wave 5 outcome (2026-04-19)" block. Insert a new "Wave 6 outcome (2026-04-19)" subsection immediately after Wave 5 and before "Modules currently free of `import Postbox`": - -```markdown -### Wave 6 outcome (2026-04-19) - -First unused-import sweep. Ran the speculative-drop + build-verify methodology (see "Unused-import sweeps" under Wave-selection guidance): dropped `import Postbox` from every consumer file where a plain `^import Postbox$` appeared (out of ~N_CANDIDATES candidates), rebuilt, restored the import on failures, iterated. N_DROPPED drops survived. - -No behavior change; zero facade migrations in this wave. Running tally updated for any modules whose last `import Postbox`-bearing file was swept (see the per-module list below). - -Plan: `docs/superpowers/plans/2026-04-19-postbox-to-telegramengine-wave-6.md` -``` - -Replace `N_CANDIDATES` and `N_DROPPED` with the actual numbers from Task 1 Step 1 and Task 6 Step 1. If the wave was abandoned (see Task 5 Step 2), replace the outcome text with a failed-attempt description instead: what iteration the sweep stalled at and what error category. - -- [ ] **Step 2: Add permanent "Unused-import sweeps" subsection under Wave-selection guidance** - -Still in `CLAUDE.md`, find the "Wave-selection guidance" block. Insert the following new subsection at the end of that block (immediately before "### Wave 1 outcome"): - -```markdown -**Unused-import sweeps are a valid wave shape.** After a round of facade migrations, consumer files accumulate `import Postbox` lines whose last semantic use was removed. Periodically sweep these: - -1. `grep -rl "^import Postbox$" submodules --include="*.swift" | grep -vE "/(TelegramCore|Postbox|TelegramApi)/"` generates the candidate list. -2. `sed -i '' '/^import Postbox$/d' ` (BSD sed) speculatively drops the import from every candidate. -3. Run the full project build. Swift compile errors (`::: error: cannot find type 'X'`) identify files that need the import restored via `git checkout -- `. -4. Rebuild. Iterate up to 3 times. Only restore files from the candidate set — if errors surface in `TelegramCore`, `Postbox`, or `TelegramApi`, halt and investigate (cascading breakage). -5. Commit the surviving drops as one atomic commit. - -Re-run this after every 2–3 facade-migration waves. First run: wave 6. -``` - -- [ ] **Step 3: Update "Modules currently free of `import Postbox`" tally** - -For each module in `submodules/` that has **no** remaining `import Postbox` after this wave, add a bullet under "Modules currently free of `import Postbox` (running tally)". Determine this list with: - -```bash -for d in submodules/*/; do - mod=$(basename "$d") - if [ -d "$d/Sources" ]; then - count=$(grep -rlE "^(@_exported )?import Postbox" "$d/Sources" --include="*.swift" 2>/dev/null | wc -l) - if [ "$count" -eq 0 ]; then - # Check this module isn't already in CLAUDE.md's tally - if ! grep -qF "\`$mod\`" CLAUDE.md; then - echo "$mod" - fi - fi - fi -done -``` - -Each printed module becomes a new bullet like `- \`\` (wave 6)` in the list. - -If the output is empty, no new module-level additions — individual file drops across multiple mixed modules aren't tally-eligible. That's fine, the Wave-6 outcome subsection still records the raw count. - -- [ ] **Step 4: Commit** - -```bash -git add CLAUDE.md -git commit -m "$(cat <<'EOF' -CLAUDE.md: record wave-6 outcome and unused-import-sweep methodology - -Adds the wave-6 outcome subsection with the candidate/drop counts, -documents the speculative-drop + build-verify methodology as -permanent guidance under wave-selection so future waves can re-run -the sweep directly, and updates the Postbox-free running tally for -any modules whose last import Postbox file was swept in this wave. - -Co-Authored-By: Claude Opus 4.7 (1M context) -EOF -)" -``` - -- [ ] **Step 5: Verify final branch state** - -```bash -git log --oneline master..HEAD -``` - -Expected (newest first): -- ` CLAUDE.md: record wave-6 outcome and unused-import-sweep methodology` -- ` Drop unused import Postbox from N consumer files` -- `816e7699ec docs(spec): wave-6 unused import Postbox batch sweep` - ---- - -## Success criteria - -- At least one `import Postbox` line has been removed from at least one consumer file, build-verified. -- Full build succeeds in `debug_sim_arm64`. -- `CLAUDE.md` has a "Wave 6 outcome (2026-04-19)" subsection with actual numeric results. -- `CLAUDE.md`'s "Wave-selection guidance" section has a new permanent "Unused-import sweeps" bullet list that describes the methodology for future re-runs. -- `CLAUDE.md`'s "Modules currently free of `import Postbox`" running tally includes any newly-fully-clean modules (if any). -- Branch `refactor/postbox-to-engine-wave-6` contains 3 commits above `master`: 1 doc (spec) + 1 code (C1 batch drop) + 1 tally (C2). diff --git a/docs/superpowers/plans/2026-04-20-decrypt-match-python-port.md b/docs/superpowers/plans/2026-04-20-decrypt-match-python-port.md deleted file mode 100644 index 702cbe807a..0000000000 --- a/docs/superpowers/plans/2026-04-20-decrypt-match-python-port.md +++ /dev/null @@ -1,539 +0,0 @@ -# Pure-Python port of fastlane match `decrypt.rb` — Implementation Plan - -> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. - -**Goal:** Replace the Ruby-based fastlane match decryption (`build-system/decrypt.rb` shelled from `BuildConfiguration.py:110`) with a self-contained Python 3 implementation using only the standard library. - -**Architecture:** Rewrite `build-system/Make/DecryptMatch.py` from scratch as a pure-Python AES-256 implementation. Covers V1 (CBC via `EVP_BytesToKey` with MD5→SHA256 fallback) and V2 (GCM with PBKDF2-derived key/iv/AAD + auth tag). `BuildConfiguration.py` calls the existing `decrypt_match_data(source, destination, password)` entry point directly instead of shelling out to Ruby. `decrypt.rb` is deleted. - -**Tech Stack:** Python 3 stdlib only — `hashlib` (MD5 / SHA256 / PBKDF2-HMAC), `base64`. - ---- - -## File structure - -- **Rewrite (not edit):** `build-system/Make/DecryptMatch.py` — new file replacing the broken placeholder. Single module containing: AES-256 primitives, `EVP_BytesToKey`, CBC decrypt, GCM decrypt (with GHASH + CTR), `MatchDataEncryption` dispatcher, `decrypt_match_data` public entry, `__main__` CLI. -- **Modify:** `build-system/Make/BuildConfiguration.py:103-118` — swap `os.system('ruby …')` for a direct Python call. -- **Delete:** `build-system/decrypt.rb`. - ---- - -## Task 1: Rewrite `build-system/Make/DecryptMatch.py` - -**Files:** -- Modify (rewrite): `build-system/Make/DecryptMatch.py` - -- [ ] **Step 1.1: Replace the file contents entirely** - -Overwrite `build-system/Make/DecryptMatch.py` with the following. This is the full file — no other changes to this module in later tasks. - -```python -import base64 -import hashlib - - -# FIPS-197 AES S-box and inverse S-box. -_SBOX = bytes.fromhex( - "637c777bf26b6fc53001672bfed7ab76" - "ca82c97dfa5947f0add4a2af9ca472c0" - "b7fd9326363ff7cc34a5e5f171d83115" - "04c723c31896059a071280e2eb27b275" - "09832c1a1b6e5aa0523bd6b329e32f84" - "53d100ed20fcb15b6acbbe394a4c58cf" - "d0efaafb434d338545f9027f503c9fa8" - "51a3408f929d38f5bcb6da2110fff3d2" - "cd0c13ec5f974417c4a77e3d645d1973" - "60814fdc222a908846eeb814de5e0bdb" - "e0323a0a4906245cc2d3ac629195e479" - "e7c8376d8dd54ea96c56f4ea657aae08" - "ba78252e1ca6b4c6e8dd741f4bbd8b8a" - "703eb5664803f60e613557b986c11d9e" - "e1f8981169d98e949b1e87e9ce5528df" - "8ca1890dbfe6426841992d0fb054bb16" -) - -_INV_SBOX = bytes.fromhex( - "52096ad53036a538bf40a39e81f3d7fb" - "7ce339829b2fff87348e4344c4dee9cb" - "547b9432a6c2233dee4c950b42fac34e" - "082ea16628d924b2765ba2496d8bd125" - "72f8f66486689816d4a45ccc5d65b692" - "6c704850fdedb9da5e154657a78d9d84" - "90d8ab008cbcd30af7e45805b8b34506" - "d02c1e8fca3f0f02c1afbd0301138a6b" - "3a9111414f67dcea97f2cfcef0b4e673" - "96ac7422e7ad3585e2f937e81c75df6e" - "47f11a711d29c5896fb7620eaa18be1b" - "fc563e4bc6d279209adbc0fe78cd5af4" - "1fdda8338807c731b11210592780ec5f" - "60517fa919b54a0d2de57a9f93c99cef" - "a0e03b4dae2af5b0c8ebbb3c83539961" - "172b047eba77d626e169146355210c7d" -) - -_RCON = bytes.fromhex("01020408102040801b36") - - -def _xtime(a): - return (((a << 1) ^ 0x1b) & 0xff) if (a & 0x80) else (a << 1) - - -def _gf_mul(a, b): - r = 0 - for _ in range(8): - if b & 1: - r ^= a - b >>= 1 - a = _xtime(a) - return r - - -def _key_expansion_256(key): - # AES-256: Nk=8, Nr=14, total 4 * (Nr + 1) = 60 words = 240 bytes. - assert len(key) == 32 - w = bytearray(240) - w[:32] = key - i = 32 - while i < 240: - t = bytearray(w[i - 4:i]) - if i % 32 == 0: - t = bytearray([t[1], t[2], t[3], t[0]]) - for j in range(4): - t[j] = _SBOX[t[j]] - t[0] ^= _RCON[i // 32 - 1] - elif i % 32 == 16: - for j in range(4): - t[j] = _SBOX[t[j]] - for j in range(4): - w[i + j] = w[i - 32 + j] ^ t[j] - i += 4 - return [bytes(w[r * 16:(r + 1) * 16]) for r in range(15)] - - -def _add_round_key(state, rk): - return bytes(s ^ k for s, k in zip(state, rk)) - - -def _sub_bytes(state): - return bytes(_SBOX[b] for b in state) - - -def _inv_sub_bytes(state): - return bytes(_INV_SBOX[b] for b in state) - - -# Column-major state: state[r + 4 * c], r = 0..3 (row), c = 0..3 (column). -def _shift_rows(state): - s = bytearray(state) - s[1], s[5], s[9], s[13] = s[5], s[9], s[13], s[1] - s[2], s[6], s[10], s[14] = s[10], s[14], s[2], s[6] - s[3], s[7], s[11], s[15] = s[15], s[3], s[7], s[11] - return bytes(s) - - -def _inv_shift_rows(state): - s = bytearray(state) - s[1], s[5], s[9], s[13] = s[13], s[1], s[5], s[9] - s[2], s[6], s[10], s[14] = s[10], s[14], s[2], s[6] - s[3], s[7], s[11], s[15] = s[7], s[11], s[15], s[3] - return bytes(s) - - -def _mix_columns(state): - s = bytearray(16) - for c in range(4): - a0, a1, a2, a3 = state[4 * c], state[4 * c + 1], state[4 * c + 2], state[4 * c + 3] - s[4 * c] = _xtime(a0) ^ (_xtime(a1) ^ a1) ^ a2 ^ a3 - s[4 * c + 1] = a0 ^ _xtime(a1) ^ (_xtime(a2) ^ a2) ^ a3 - s[4 * c + 2] = a0 ^ a1 ^ _xtime(a2) ^ (_xtime(a3) ^ a3) - s[4 * c + 3] = (_xtime(a0) ^ a0) ^ a1 ^ a2 ^ _xtime(a3) - return bytes(s) - - -def _inv_mix_columns(state): - s = bytearray(16) - for c in range(4): - a0, a1, a2, a3 = state[4 * c], state[4 * c + 1], state[4 * c + 2], state[4 * c + 3] - s[4 * c] = _gf_mul(a0, 0x0e) ^ _gf_mul(a1, 0x0b) ^ _gf_mul(a2, 0x0d) ^ _gf_mul(a3, 0x09) - s[4 * c + 1] = _gf_mul(a0, 0x09) ^ _gf_mul(a1, 0x0e) ^ _gf_mul(a2, 0x0b) ^ _gf_mul(a3, 0x0d) - s[4 * c + 2] = _gf_mul(a0, 0x0d) ^ _gf_mul(a1, 0x09) ^ _gf_mul(a2, 0x0e) ^ _gf_mul(a3, 0x0b) - s[4 * c + 3] = _gf_mul(a0, 0x0b) ^ _gf_mul(a1, 0x0d) ^ _gf_mul(a2, 0x09) ^ _gf_mul(a3, 0x0e) - return bytes(s) - - -def _aes_encrypt_block(block, round_keys): - state = _add_round_key(block, round_keys[0]) - for r in range(1, 14): - state = _sub_bytes(state) - state = _shift_rows(state) - state = _mix_columns(state) - state = _add_round_key(state, round_keys[r]) - state = _sub_bytes(state) - state = _shift_rows(state) - state = _add_round_key(state, round_keys[14]) - return state - - -def _aes_decrypt_block(block, round_keys): - state = _add_round_key(block, round_keys[14]) - for r in range(13, 0, -1): - state = _inv_shift_rows(state) - state = _inv_sub_bytes(state) - state = _add_round_key(state, round_keys[r]) - state = _inv_mix_columns(state) - state = _inv_shift_rows(state) - state = _inv_sub_bytes(state) - state = _add_round_key(state, round_keys[0]) - return state - - -def _evp_bytes_to_key(password, salt, hash_name, key_len=32, iv_len=16): - # OpenSSL EVP_BytesToKey with count=1, matching Ruby's - # Cipher#pkcs5_keyivgen(password, salt, 1, hash). - if isinstance(password, str): - password = password.encode('utf-8') - required = key_len + iv_len - material = b"" - prev = b"" - while len(material) < required: - h = hashlib.new(hash_name) - h.update(prev + password + salt) - prev = h.digest() - material += prev - return material[:key_len], material[key_len:key_len + iv_len] - - -def _aes_cbc_decrypt(ciphertext, key, iv): - if len(ciphertext) == 0 or len(ciphertext) % 16 != 0: - raise ValueError("V1 ciphertext length must be a non-zero multiple of 16") - round_keys = _key_expansion_256(key) - out = bytearray() - prev = iv - for i in range(0, len(ciphertext), 16): - block = ciphertext[i:i + 16] - decrypted = _aes_decrypt_block(block, round_keys) - out.extend(bytes(d ^ p for d, p in zip(decrypted, prev))) - prev = block - pad = out[-1] - if pad < 1 or pad > 16 or not all(b == pad for b in out[-pad:]): - raise ValueError("V1 PKCS#7 padding check failed") - return bytes(out[:-pad]) - - -def _ghash(h_bytes, data): - # GHASH over GF(2^128) with reduction polynomial x^128 + x^7 + x^2 + x + 1, - # using GCM's bit-reversed convention (top-bit-first when encoded as bytes). - h = int.from_bytes(h_bytes, 'big') - y = 0 - reduction = 0xe1 << 120 - for i in range(0, len(data), 16): - block = data[i:i + 16].ljust(16, b"\x00") - y ^= int.from_bytes(block, 'big') - z = 0 - v = y - for bit in range(127, -1, -1): - if (h >> bit) & 1: - z ^= v - if v & 1: - v = (v >> 1) ^ reduction - else: - v >>= 1 - y = z - return y.to_bytes(16, 'big') - - -def _aes_gcm_decrypt(ciphertext, key, iv, aad, auth_tag): - if len(iv) != 12: - raise ValueError("V2 requires a 96-bit IV") - round_keys = _key_expansion_256(key) - H = _aes_encrypt_block(b"\x00" * 16, round_keys) - j0 = iv + b"\x00\x00\x00\x01" - - plaintext = bytearray() - j0_int = int.from_bytes(j0, 'big') - mask32 = (1 << 32) - 1 - counter_high = j0_int & ~mask32 - counter_low = j0_int & mask32 - n_blocks = (len(ciphertext) + 15) // 16 - for i in range(n_blocks): - counter_low = (counter_low + 1) & mask32 - ctr_bytes = (counter_high | counter_low).to_bytes(16, 'big') - keystream = _aes_encrypt_block(ctr_bytes, round_keys) - block = ciphertext[i * 16:(i + 1) * 16] - plaintext.extend(bytes(c ^ k for c, k in zip(block, keystream[:len(block)]))) - - aad_pad = b"\x00" * ((16 - len(aad) % 16) % 16) - ct_pad = b"\x00" * ((16 - len(ciphertext) % 16) % 16) - length_block = (len(aad) * 8).to_bytes(8, 'big') + (len(ciphertext) * 8).to_bytes(8, 'big') - s = _ghash(H, aad + aad_pad + ciphertext + ct_pad + length_block) - e_j0 = _aes_encrypt_block(j0, round_keys) - computed_tag = bytes(a ^ b for a, b in zip(s, e_j0)) - if computed_tag != auth_tag: - raise ValueError("V2 GCM auth tag mismatch") - return bytes(plaintext) - - -_V1_PREFIX = b"Salted__" -_V2_PREFIX = b"match_encrypted_v2__" - - -def _decrypt_stored(stored_data, password): - if stored_data.startswith(_V2_PREFIX): - salt = stored_data[20:28] - auth_tag = stored_data[28:44] - ciphertext = stored_data[44:] - material = hashlib.pbkdf2_hmac( - 'sha256', - password.encode('utf-8'), - salt, - 10_000, - dklen=32 + 12 + 24, - ) - key = material[0:32] - iv = material[32:44] - aad = material[44:68] - return _aes_gcm_decrypt(ciphertext, key, iv, aad, auth_tag) - if stored_data.startswith(_V1_PREFIX): - salt = stored_data[8:16] - ciphertext = stored_data[16:] - try: - key, iv = _evp_bytes_to_key(password, salt, 'md5', 32, 16) - return _aes_cbc_decrypt(ciphertext, key, iv) - except Exception: - key, iv = _evp_bytes_to_key(password, salt, 'sha256', 32, 16) - return _aes_cbc_decrypt(ciphertext, key, iv) - raise ValueError("Unrecognized fastlane match payload (missing V1 'Salted__' or V2 'match_encrypted_v2__' prefix)") - - -def decrypt_match_data(source_path: str, destination_path: str, password: str): - with open(source_path, 'rb') as f: - raw = f.read() - stored_data = base64.b64decode(raw) - decrypted = _decrypt_stored(stored_data, password) - with open(destination_path, 'wb') as f: - f.write(decrypted) - - -if __name__ == '__main__': - import sys - if len(sys.argv) != 4: - print('Usage: DecryptMatch.py ') - sys.exit(1) - decrypt_match_data(source_path=sys.argv[2], destination_path=sys.argv[3], password=sys.argv[1]) -``` - ---- - -## Task 2: Smoke-test the AES-256 block primitive (FIPS-197 Appendix C.3) - -**Files:** -- No changes. One-liner shell command to validate the just-written primitive. - -- [ ] **Step 2.1: Run the FIPS-197 C.3 known-answer test** - -```bash -cd /Users/isaac/build/telegram/telegram-ios -python3 -c " -import sys -sys.path.insert(0, 'build-system/Make') -from DecryptMatch import _key_expansion_256, _aes_encrypt_block, _aes_decrypt_block -key = bytes.fromhex('000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f') -pt = bytes.fromhex('00112233445566778899aabbccddeeff') -expected = bytes.fromhex('8ea2b7ca516745bfeafc49904b496089') -rks = _key_expansion_256(key) -assert _aes_encrypt_block(pt, rks) == expected, 'encrypt failed' -assert _aes_decrypt_block(expected, rks) == pt, 'decrypt failed' -print('AES-256 FIPS-197 C.3 OK') -" -``` - -Expected output: `AES-256 FIPS-197 C.3 OK`. If this fails, the AES primitive is broken — re-read Task 1's code and fix before proceeding. - ---- - -## Task 3: Validate V2 decryption on real encrypted files - -**Files:** -- No changes. Decrypt real samples with the new Python and verify each output is a cryptographically-valid Apple-signed artifact. - -**Success criteria:** the decrypted `.mobileprovision` files verify under `openssl smime -verify` and parse as valid plists. A CMS signature covers every byte of the payload, so successful verification is equivalent to bit-exact decryption — any wrong byte anywhere would break the signature. This is a stronger check than diffing against another implementation, and it matches what `BuildConfiguration.copy_profiles_from_directory` does on every profile in the real build, so passing here means the port is production-ready. - -The encrypted repo is at `~/build/telegram/telegram-ios/build-input/configuration-repository-workdir/encrypted/profiles/development/`. Repo password: `sluchainost` (per the hard-coded value in the file Task 1 replaced). - -> NOTE: Do not attempt a byte-for-byte comparison against `ruby build-system/decrypt.rb`. Ruby's OpenSSL binding on macOS LibreSSL 3.3.6 fails on `cipher.auth_data=` with `couldn't set additional authenticated data`, so the legacy script cannot decrypt V2 at all on current macOS. (This is likely why the build accumulated a broken aspirational Python port in the first place.) Signature verification of the Python output is the authoritative check. - -- [ ] **Step 3.1: Decrypt one sample file** - -```bash -cd /Users/isaac/build/telegram/telegram-ios -SAMPLE=~/build/telegram/telegram-ios/build-input/configuration-repository-workdir/encrypted/profiles/development/Development_org.telegram.TelegramInternal.BroadcastUpload.mobileprovision -python3 build-system/Make/DecryptMatch.py sluchainost "$SAMPLE" /tmp/match-py.bin -shasum -a 256 /tmp/match-py.bin -``` - -Expected: `match-py.bin` is non-empty; a sha256 is printed. - -- [ ] **Step 3.2: Verify the output is a valid Apple-signed provisioning profile** - -```bash -openssl smime -inform der -verify -noverify -in /tmp/match-py.bin | plutil -lint - -``` - -Expected: `openssl smime` prints `Verification successful` (or similar; exit code 0 is what matters), and `plutil` reports `OK`. Either failure means the decryption is corrupt — STOP and report BLOCKED with the exact openssl/plutil output. - -- [ ] **Step 3.3: Spot-check remaining V2 files decrypt without error** - -```bash -cd /Users/isaac/build/telegram/telegram-ios -ENCRYPTED=~/build/telegram/telegram-ios/build-input/configuration-repository-workdir/encrypted/profiles/development -for f in "$ENCRYPTED"/*.mobileprovision; do - python3 build-system/Make/DecryptMatch.py sluchainost "$f" /tmp/match-check.bin \ - && openssl smime -inform der -verify -noverify -in /tmp/match-check.bin > /dev/null 2>&1 \ - && echo "OK $(basename "$f")" \ - || echo "FAIL $(basename "$f")" -done -``` - -Expected: every line starts with `OK`. Any `FAIL` line means that file's decryption is corrupt — STOP and report BLOCKED. - ---- - -## Task 4: Commit the rewrite - -**Files:** -- Commit `build-system/Make/DecryptMatch.py` only. - -- [ ] **Step 4.1: Stage and commit** - -```bash -cd /Users/isaac/build/telegram/telegram-ios -git add build-system/Make/DecryptMatch.py -git commit -m "$(cat <<'EOF' -DecryptMatch: pure-Python AES-256 port of decrypt.rb - -Implements fastlane match V1 (AES-256-CBC via EVP_BytesToKey with -MD5 default and SHA256 fallback) and V2 (AES-256-GCM with PBKDF2- -derived key/IV/AAD + auth tag) using only Python stdlib. Validated -by decrypting every V2 .mobileprovision in the repo and confirming -each output verifies under openssl smime + plutil -lint as a valid -Apple-signed artifact. - -Co-Authored-By: Claude Opus 4.7 (1M context) -EOF -)" -``` - -Expected: commit created cleanly. - ---- - -## Task 5: Switch `BuildConfiguration.py` to the Python implementation and remove `decrypt.rb` - -**Files:** -- Modify: `build-system/Make/BuildConfiguration.py:103-118` -- Delete: `build-system/decrypt.rb` - -- [ ] **Step 5.1: Swap the call site** - -Replace lines 103-118 of `build-system/Make/BuildConfiguration.py`: - -```python -def decrypt_codesigning_directory_recursively(source_base_path, destination_base_path, password): - for file_name in os.listdir(source_base_path): - source_path = source_base_path + '/' + file_name - destination_path = destination_base_path + '/' + file_name - allowed_file_extensions = ['.mobileprovision', '.cer', '.p12'] - if os.path.isfile(source_path) and any(source_path.endswith(ext) for ext in allowed_file_extensions): - #print('Decrypting {} to {} with {}'.format(source_path, destination_path, password)) - os.system('ruby build-system/decrypt.rb "{password}" "{source_path}" "{destination_path}"'.format( - password=password, - source_path=source_path, - destination_path=destination_path - )) - #decrypt_match_data(source_path, destination_path, password) - elif os.path.isdir(source_path): - os.makedirs(destination_path, exist_ok=True) - decrypt_codesigning_directory_recursively(source_path, destination_path, password) -``` - -with: - -```python -def decrypt_codesigning_directory_recursively(source_base_path, destination_base_path, password): - for file_name in os.listdir(source_base_path): - source_path = source_base_path + '/' + file_name - destination_path = destination_base_path + '/' + file_name - allowed_file_extensions = ['.mobileprovision', '.cer', '.p12'] - if os.path.isfile(source_path) and any(source_path.endswith(ext) for ext in allowed_file_extensions): - decrypt_match_data(source_path, destination_path, password) - elif os.path.isdir(source_path): - os.makedirs(destination_path, exist_ok=True) - decrypt_codesigning_directory_recursively(source_path, destination_path, password) -``` - -- [ ] **Step 5.2: Delete the Ruby script** - -```bash -cd /Users/isaac/build/telegram/telegram-ios -git rm build-system/decrypt.rb -``` - -- [ ] **Step 5.3: Commit** - -```bash -cd /Users/isaac/build/telegram/telegram-ios -git add build-system/Make/BuildConfiguration.py -git commit -m "$(cat <<'EOF' -BuildConfiguration: use Python DecryptMatch, drop Ruby decrypt.rb - -Swap the os.system('ruby build-system/decrypt.rb ...') shell-out for -a direct decrypt_match_data() call, and delete the now-unused Ruby -script. The iOS build no longer depends on a Ruby interpreter. - -Co-Authored-By: Claude Opus 4.7 (1M context) -EOF -)" -``` - -Expected: commit created cleanly; `git status` shows a clean tree. - ---- - -## Task 6: End-to-end verification with `generateProject` - -**Files:** -- No changes. - -- [ ] **Step 6.1: Wipe the previously-decrypted directory so the build re-decrypts fresh** - -```bash -cd /Users/isaac/build/telegram/telegram-ios -rm -rf ~/build/telegram/telegram-ios/build-input/configuration-repository-workdir/decrypted -``` - -Expected: directory removed. If it did not exist, that's also fine. - -- [ ] **Step 6.2: Run the user-supplied `generateProject` command** - -```bash -cd /Users/isaac/build/telegram/telegram-ios -source ~/.zshrc 2>/dev/null -python3 build-system/Make/Make.py --overrideXcodeVersion \ - --cacheDir ~/build/telegram/telegram-bazel-cache \ - generateProject \ - --configurationPath ~/build/telegram/telegram-internal-tools/PrivateData/build-configurations/enterprise-configuration.json \ - --gitCodesigningRepository git@gitlab.com:peter-iakovlev/fastlanematch.git \ - --gitCodesigningType development --gitCodesigningUseCurrent -``` - -Expected: the command runs through project generation. The decryption step is silent on success (per `BuildConfiguration.py:decrypt_codesigning_directory_recursively`). Any decryption failure would surface downstream in `copy_profiles_from_directory` when `openssl smime -verify` chokes on a corrupted `.mobileprovision`, so a clean run proves the port is working end-to-end. - -If the command fails with a decryption-related error, revert the two commits (`git revert HEAD~1..HEAD`) and debug; otherwise the migration is complete. - -- [ ] **Step 6.3: Spot-check the generated decrypted directory** - -```bash -ls ~/build/telegram/telegram-ios/build-input/configuration-repository-workdir/decrypted/profiles/development/ -``` - -Expected: a populated list of `.mobileprovision` files, matching the list in the encrypted sibling directory. diff --git a/docs/superpowers/plans/2026-04-20-postbox-to-telegramengine-wave-10.md b/docs/superpowers/plans/2026-04-20-postbox-to-telegramengine-wave-10.md deleted file mode 100644 index e13ee5a2d8..0000000000 --- a/docs/superpowers/plans/2026-04-20-postbox-to-telegramengine-wave-10.md +++ /dev/null @@ -1,194 +0,0 @@ -# Postbox → TelegramEngine Wave 10 Implementation Plan - -> **For agentic workers:** This plan was executed in a single session; steps below are a post-hoc record of the work landed, not a to-do list. - -**Goal:** Finish the `StorageUsageScreen` consumer-module de-Postbox work started in wave 8 and continued in wave 9 by eliminating the last `import Postbox` in the module: `StorageFileListPanelComponent.swift`'s `Icon.media(Media, TelegramMediaImageRepresentation)` enum case. - -**Architecture:** Replace the heterogeneous-protocol `Icon.media(Media, ...)` case with two concrete-type cases `.mediaFile(TelegramMediaFile, ...)` and `.mediaImage(TelegramMediaImage, ...)`. The split is lossless because the two construction sites already knew the concrete subtype (`imageIconValue = .media(file, representation)` vs `.media(image, representation)`), and the one consumer binding site immediately downcasted via `as? TelegramMediaFile` / `as? TelegramMediaImage` to pick which `setSignal(...)` to call. Auto-split the switch body over the two new cases; no downcast needed. Also replaces a placeholder `PeerId(namespace:..., id:...)` construction in the `measureItem` layout-measurement instance with `component.context.account.peerId` (a real, already-available `EnginePeer.Id`). - -**Tech Stack:** Swift / Bazel. No unit tests. - -**Build command:** - -```bash -source ~/.zshrc 2>/dev/null; PATH=/opt/homebrew/opt/ruby/bin:`gem environment gemdir`/bin:$PATH python3 build-system/Make/Make.py --overrideXcodeVersion --cacheDir ~/telegram-bazel-cache build --configurationPath build-system/appstore-configuration.json --gitCodesigningRepository git@gitlab.com:peter-iakovlev/fastlanematch.git --gitCodesigningType development --gitCodesigningUseCurrent --buildNumber 1 --configuration debug_sim_arm64 --continueOnError -``` - ---- - -## Scope - -**In scope:** -- `StorageFileListPanelComponent.swift`'s `Icon` enum: replace `case media(Media, TelegramMediaImageRepresentation)` with two concrete-type cases. -- Equatable rewrite: switch-over-tuple `(lhs, rhs)` pattern with id-based equality per concrete type (`lFile.fileId == rFile.fileId`, `lImage.imageId == rImage.imageId`). -- Binding rewrite at the `if case let .media(media, representation)` site (former line 448): lift `representation` via a compound `case let .mediaFile(_, representation), let .mediaImage(_, representation):` pattern, then inner switch-over-`component.icon` selects `setSignal` flavor. -- Construction rewrite at two `imageIconValue = .media(...)` sites: use the concrete case name (`.mediaFile`, `.mediaImage`). -- Placeholder `PeerId(namespace:..., id:...)` at former line 1062 (in the `measureItem` layout-measurement instance): replace with `component.context.account.peerId`. -- Remove `import Postbox` from `StorageFileListPanelComponent.swift`. - -**Out of scope:** -- None. This is the last file in the `StorageUsageScreen` module that imports Postbox; after this wave, the module is fully Postbox-free. - ---- - -## Tasks - -### Task 1: Split `Icon.media` into two concrete cases - -**Files:** -- Modify: `submodules/TelegramUI/Components/StorageUsageScreen/Sources/StorageFileListPanelComponent.swift` (former 103–135). - -Before: - -```swift -enum Icon: Equatable { - case fileExtension(String) - case media(Media, TelegramMediaImageRepresentation) - case audio - - static func ==(lhs: Icon, rhs: Icon) -> Bool { - switch lhs { - case let .fileExtension(value): - if case .fileExtension(value) = rhs { return true } else { return false } - case let .media(media, representation): - if case let .media(rhsMedia, rhsRepresentation) = rhs { - if media.id != rhsMedia.id { return false } - if representation != rhsRepresentation { return false } - return true - } else { return false } - case .audio: - if case .audio = rhs { return true } else { return false } - } - } -} -``` - -After: - -```swift -enum Icon: Equatable { - case fileExtension(String) - case mediaFile(TelegramMediaFile, TelegramMediaImageRepresentation) - case mediaImage(TelegramMediaImage, TelegramMediaImageRepresentation) - case audio - - static func ==(lhs: Icon, rhs: Icon) -> Bool { - switch (lhs, rhs) { - case let (.fileExtension(l), .fileExtension(r)): - return l == r - case let (.mediaFile(lFile, lRepresentation), .mediaFile(rFile, rRepresentation)): - return lFile.fileId == rFile.fileId && lRepresentation == rRepresentation - case let (.mediaImage(lImage, lRepresentation), .mediaImage(rImage, rRepresentation)): - return lImage.imageId == rImage.imageId && lRepresentation == rRepresentation - case (.audio, .audio): - return true - default: - return false - } - } -} -``` - -### Task 2: Rewrite the binding site - -**Files:** -- Modify: `submodules/TelegramUI/Components/StorageUsageScreen/Sources/StorageFileListPanelComponent.swift` (former 448–500). - -Before, the block started with `if case let .media(media, representation) = component.icon { ... }` then inside did `if let file = media as? TelegramMediaFile { ... } else if let image = media as? TelegramMediaImage { ... }`. - -After, use a compound case-binding pattern at the entry (both cases have the same `representation` type, so the pattern works) and an inner switch for the `setSignal` branch: - -```swift -let mediaRepresentation: TelegramMediaImageRepresentation? -switch component.icon { -case let .mediaFile(_, representation), let .mediaImage(_, representation): - mediaRepresentation = representation -default: - mediaRepresentation = nil -} - -if let representation = mediaRepresentation { - // ... setup iconImageNode as before ... - if resetImage { - switch component.icon { - case let .mediaFile(file, _): - iconImageNode.setSignal(chatWebpageSnippetFile( - account: component.context.account, - userLocation: .peer(component.messageId.peerId), - mediaReference: FileMediaReference.standalone(media: file).abstract, - representation: representation, - automaticFetch: false - )) - case let .mediaImage(image, _): - iconImageNode.setSignal(mediaGridMessagePhoto( - account: component.context.account, - userLocation: .peer(component.messageId.peerId), - photoReference: ImageMediaReference.standalone(media: image), - automaticFetch: false - )) - default: - break - } - } - // ... frame + asyncLayout + apply as before ... -} -``` - -### Task 3: Update the two construction sites - -**Files:** -- Modify: `submodules/TelegramUI/Components/StorageUsageScreen/Sources/StorageFileListPanelComponent.swift` (former 985 and 992). - -`imageIconValue = .media(file, representation)` → `.mediaFile(file, representation)` (for `TelegramMediaFile` branch). -`imageIconValue = .media(image, representation)` → `.mediaImage(image, representation)` (for `TelegramMediaImage` branch). - -### Task 4: Replace the placeholder `PeerId(...)` construction - -**Files:** -- Modify: `submodules/TelegramUI/Components/StorageUsageScreen/Sources/StorageFileListPanelComponent.swift` (former 1062). - -The `measureItem` layout-measurement instance uses a fully-zero placeholder peer id: - -```swift -messageId: EngineMessage.Id(peerId: PeerId(namespace: PeerId.Namespace._internalFromInt32Value(0), id: PeerId.Id._internalFromInt64Value(0)), namespace: 0, id: 0), -``` - -Naming `PeerId`, `PeerId.Namespace`, `PeerId.Id` all require `import Postbox` (these are raw Postbox types, not TelegramCore typealiases). Replace with `component.context.account.peerId`, a real `EnginePeer.Id` already in scope: - -```swift -messageId: EngineMessage.Id(peerId: component.context.account.peerId, namespace: 0, id: 0), -``` - -Semantically equivalent for the measurement use case — `messageId` is used downstream only for `.peerId` extraction in the image-fetch userLocation and for Equatable comparison; the measurement instance is standalone and not compared. The `id: 0, namespace: 0` part stays; those are plain `Int32`, nothing Postbox-specific. - -Caught by second-pass build failure `cannot find 'PeerId' in scope` after dropping `import Postbox`. - -### Task 5: Drop `import Postbox` - -**Files:** -- Modify: `submodules/TelegramUI/Components/StorageUsageScreen/Sources/StorageFileListPanelComponent.swift` (former line 14). - -Remove the `import Postbox` line. - -### Task 6: Full project build - -Expected green after Tasks 4 and 5. The first build attempt surfaced the `PeerId` issue; Task 4's fix addressed it. - -### Task 7: Commit - -Single wave-10 atomic commit. CLAUDE.md gets a wave-10 outcome section; the "Modules currently free of `import Postbox`" tally gains `StorageUsageScreen` (the module as a whole). Both files that previously imported Postbox in this module (`StorageUsageScreen.swift` from wave 9 and `StorageFileListPanelComponent.swift` from wave 10) are now Postbox-free. - ---- - -## Outcome (2026-04-20) - -Single atomic commit. Build verified green (27 actions, cached). - -**`StorageUsageScreen` consumer module is now fully Postbox-free** — last file (`StorageFileListPanelComponent.swift`) landed in this wave; the other file (`StorageUsageScreen.swift`) landed in wave 9. - -Net: 1 file changed, +22 / -29 lines (−7 simplification — the new switch-over-tuple Equatable is both terser and more idiomatic than the old three-way nested `switch` + `if case` pattern). - -**Lessons:** - -- **Heterogeneous-protocol enum cases are an easy de-Postbox win** when the protocol values already get downcast to a fixed small set of concrete subtypes. The compiler-enforced exhaustiveness of the split improves call-site safety (no silent `else` branch that forgot a subtype). -- **Placeholder `PeerId(...)` constructions in layout-measurement code are traps.** Common pattern in this codebase: a "dummy" component instance is constructed purely to run `.update(...)` and harvest the returned size. The dummy values (`messageId`, `peerId`) are not used for anything but type-filling, yet naming the types forces `import Postbox`. When de-Postboxing, look for `PeerId(namespace:...`/`MessageId(peerId:...` constructions with all-zero arguments and replace with any convenient real value already in scope (`context.account.peerId` works for peer-id placeholders). diff --git a/docs/superpowers/plans/2026-04-20-postbox-to-telegramengine-wave-7.md b/docs/superpowers/plans/2026-04-20-postbox-to-telegramengine-wave-7.md deleted file mode 100644 index b5bf1f0f57..0000000000 --- a/docs/superpowers/plans/2026-04-20-postbox-to-telegramengine-wave-7.md +++ /dev/null @@ -1,95 +0,0 @@ -# Postbox → TelegramEngine Wave 7 Implementation Plan - -> **For agentic workers:** This plan was executed in a single session; steps below are a post-hoc record of the work landed, not a to-do list. - -**Goal:** Close out the remaining raw-Postbox leaks in `TelegramEngine.*` public facades surfaced by the wave-6 post-sweep scouting pass (2026-04-20). Six facade-signature migrations + one dead-facade deletion + consumer call-site bridging, landed as a single wave commit. - -**Architecture:** Wave-2 shape scaled to seven facades at once: each facade signature changes in place from raw Postbox domain types (`Message`, `Peer`) to engine equivalents (`EngineMessage`, `EnginePeer`), with `_internal_*` implementations left raw per the standing "internal Postbox-facing stays raw" rule. Consumer call sites bridge at the facade boundary via `EngineMessage.init` / `._asMessage()` wrap/unwrap helpers or drop now-redundant wrapping. - -**Tech Stack:** Swift / Bazel. No unit tests by repo policy — verification is a full project build. - -**Build command:** - -```bash -source ~/.zshrc 2>/dev/null; PATH=/opt/homebrew/opt/ruby/bin:`gem environment gemdir`/bin:$PATH python3 build-system/Make/Make.py --overrideXcodeVersion --cacheDir ~/telegram-bazel-cache build --configurationPath build-system/appstore-configuration.json --gitCodesigningRepository git@gitlab.com:peter-iakovlev/fastlanematch.git --gitCodesigningType development --gitCodesigningUseCurrent --buildNumber 1 --configuration debug_sim_arm64 --continueOnError -``` - ---- - -## Scope — candidate list - -All seven items from the wave-6 post-sweep scouting pass: - -1. `TelegramEngine.Messages.downloadMessage(messageId: MessageId) -> Signal` → `(messageId: EngineMessage.Id) -> Signal`. Callers: 1 (`ChatListSearchListPaneNode`). -2. `TelegramEngine.Messages.topPeerActiveLiveLocationMessages(peerId: PeerId) -> Signal<(Peer?, [Message]), NoError>` → `(peerId: EnginePeer.Id) -> Signal<(EnginePeer?, [EngineMessage]), NoError>`. Callers: 2 (`LocationViewControllerNode`, `LiveLocationSummaryManager`). -3. `TelegramEngine.Messages.getSynchronizeAutosaveItemOperations()` — dead facade (sole caller `StoreDownloadedMedia.swift:298` uses `_internal_*` directly). Deleted. -4. `TelegramEngine.Peers.updatedRemotePeer(peer: PeerReference) -> Signal` → `Signal`. `PeerReference` param kept (no `EnginePeer.Reference` alias today). Callers: 1 (`ChannelAdminsController`, `ignoreValues` so no caller change needed). -5. `TelegramEngine.Resources.renderStorageUsageStatsMessages(…existingMessages: [EngineMessage.Id: Message]) -> Signal<[EngineMessage.Id: Message], NoError>` → `[EngineMessage.Id: EngineMessage]` on both sides. Callers: 1 (`StorageUsageScreen`). -6–8. `TelegramEngine.Resources.clearStorage(...)` overloads (three) — `[Message]` params → `[EngineMessage]`. Real external callers: 2 (`StorageUsageScreen`, two overloads). The third overload `clearStorage(messages:)` has no callers; migrated for overload-set consistency. - ---- - -## Tasks - -### Task 1: Migrate three `TelegramEngine.Messages` facades - -**Files:** -- Modify: `submodules/TelegramCore/Sources/TelegramEngine/Messages/TelegramEngineMessages.swift` (3 facades) -- Modify: `submodules/ChatListUI/Sources/ChatListSearchListPaneNode.swift` (drop redundant `.flatMap(EngineMessage.init)`) -- Modify: `submodules/LocationUI/Sources/LocationViewControllerNode.swift` (drop redundant `.map(EngineMessage.init)`) -- Modify: `submodules/LiveLocationManager/Sources/LiveLocationSummaryManager.swift` (drop redundant `EnginePeer(...)` / `EngineMessage(...)` wrappers) - -**Changes:** - -`downloadMessage` — wrap return `Message?` → `EngineMessage?` via `|> map { $0.flatMap(EngineMessage.init) }`. `_internal_downloadMessage` still takes `messageId: MessageId`, which is typealiased to `EngineMessage.Id`, so the param change is purely a rename at the public surface. - -`topPeerActiveLiveLocationMessages` — wrap tuple return via `|> map { peer, messages -> (EnginePeer?, [EngineMessage]) in (peer.flatMap(EnginePeer.init), messages.map(EngineMessage.init)) }`. - -`getSynchronizeAutosaveItemOperations` — deleted. The sole caller `StoreDownloadedMedia.swift:298` was already calling `_internal_getSynchronizeAutosaveItemOperations` directly (inside its own transaction block), so no caller update needed. - -### Task 2: Migrate `TelegramEngine.Peers.updatedRemotePeer` - -**Files:** -- Modify: `submodules/TelegramCore/Sources/TelegramEngine/Peers/TelegramEnginePeers.swift` - -Append `|> map(EnginePeer.init)` to wrap the `Peer` result. `PeerReference` param stays. Single call site in `ChannelAdminsController.swift` uses `ignoreValues`, so no caller-side change. - -### Task 3: Migrate four `TelegramEngine.Resources` facades - -**Files:** -- Modify: `submodules/TelegramCore/Sources/TelegramEngine/Resources/TelegramEngineResources.swift` (4 facades) -- Modify: `submodules/TelegramUI/Components/StorageUsageScreen/Sources/StorageUsageScreen.swift` (3 call sites) - -`renderStorageUsageStatsMessages` — unwrap `[EngineMessage.Id: EngineMessage]` input via `.mapValues { $0._asMessage() }`, wrap raw result via `.mapValues(EngineMessage.init)`. Caller bridges the other direction at its single call site (`.mapValues(EngineMessage.init)` on the input `existingMessages`, `.mapValues { $0._asMessage() }` on the mapped result). - -`clearStorage(peerId:categories:includeMessages:excludeMessages:)` / `clearStorage(peerIds:includeMessages:excludeMessages:)` / `clearStorage(messages:)` — unwrap `[EngineMessage]` params via `.map { $0._asMessage() }` before forwarding to `_internal_clearStorage`. Callers bridge `[Message]` locals with `.map(EngineMessage.init)` at the facade call site. - -Call-site changes in `StorageUsageScreen` are intentionally minimal: the file's `AggregatedData` type keeps `[MessageId: Message]` / `[Message]` internally, with bridging applied only at the four facade-call points. A full-consumer-module migration to `EngineMessage` is out of scope for this wave (would require changing ~30 sites plus the item types in `StorageFileListPanelComponent`; a future "StorageUsageScreen full de-Postbox" wave could land that). - -### Task 4: Full project build - -Run the build command above with `--continueOnError`. Expected: clean build (no errors or warnings introduced). One full build covers all facades since they're in TelegramCore and rebuilding TelegramCore re-verifies every consumer. - -### Task 5: Commit - -Single wave-7 atomic commit covering the 8 modified files and the CLAUDE.md outcome update. - ---- - -## Outcome (2026-04-20) - -All seven candidates landed. Single atomic commit. Build verified green (`bazel-bin/Telegram/Telegram.ipa` produced; 5854 total actions, 1009 executed). - -- 3 `TelegramEngine.Messages` facades migrated (1 rewrite, 1 rewrite, 1 deletion) -- 1 `TelegramEngine.Peers` facade migrated -- 4 `TelegramEngine.Resources` facades migrated (1 dict, 3 overloads) -- 5 consumer files updated: `ChatListSearchListPaneNode`, `LocationViewControllerNode`, `LiveLocationSummaryManager`, `StorageUsageScreen`, CLAUDE.md - -No modules became Postbox-free in this wave (all five touched consumers still import Postbox for unrelated reasons — `StorageUsageScreen` especially, which still has 43 raw `Message` / `MessageId` references outside the facade boundary). - -**Lesson recorded:** when a facade's consumer file uses the raw Postbox type extensively outside the facade boundary (e.g. `StorageUsageScreen` with its `[MessageId: Message]` dict stored in a helper class and threaded through ~30 sites), bridging at the facade call site is the correct scope. Full-consumer-module migration is its own separate wave, not a side-effect of facade migration. - -**Next-wave candidates.** The sum of the scouting pass's 8 candidates has been closed. No new `TelegramEngine.*` public facades with raw `Postbox`/`Account`/`MediaBox`/`Peer`/`Message`/`MediaResource` leaks remain. Future-wave focus shifts to: - -1. Full-consumer-module migrations (e.g. `StorageUsageScreen` — drop `AggregatedData`'s raw-Postbox storage types, drop `import Postbox`). -2. Another speculative unused-import sweep pass like wave 6, to catch imports that became unused after waves 4–7. diff --git a/docs/superpowers/plans/2026-04-20-postbox-to-telegramengine-wave-8.md b/docs/superpowers/plans/2026-04-20-postbox-to-telegramengine-wave-8.md deleted file mode 100644 index 85e3edd146..0000000000 --- a/docs/superpowers/plans/2026-04-20-postbox-to-telegramengine-wave-8.md +++ /dev/null @@ -1,103 +0,0 @@ -# Postbox → TelegramEngine Wave 8 Implementation Plan - -> **For agentic workers:** This plan was executed in a single session; steps below are a post-hoc record of the work landed, not a to-do list. - -**Goal:** `StorageUsageScreen` consumer-module migration — drop all raw `Message` domain types from the screen's internal storage and public peer-panel item types, and eliminate the wave-7 facade-boundary bridging. Scope is narrower than a full de-Postbox of the module: direct `postbox.combinedView` / `postbox.transaction` sites for `AccountSpecificCacheStorageSettings` observation are left for a future wave. - -**Architecture:** Two files modified. `StorageFileListPanelComponent.Item.message` and `StorageUsageScreen`'s `AggregatedData` + `RenderResult` + `SelectionState` internal types are migrated from raw `Message`/`[Message]`/`[MessageId: Message]` to `EngineMessage`/`[EngineMessage]`/`[EngineMessage.Id: EngineMessage]`. The two external APIs that still take raw `Message` (`OpenChatMessageParams.message`, `chatMediaListPreviewControllerData(message:)`) are called with `engineMessage._asMessage()` at the call site. - -**Tech Stack:** Swift / Bazel. No unit tests by repo policy — verification is a full project build. - -**Build command:** - -```bash -source ~/.zshrc 2>/dev/null; PATH=/opt/homebrew/opt/ruby/bin:`gem environment gemdir`/bin:$PATH python3 build-system/Make/Make.py --overrideXcodeVersion --cacheDir ~/telegram-bazel-cache build --configurationPath build-system/appstore-configuration.json --gitCodesigningRepository git@gitlab.com:peter-iakovlev/fastlanematch.git --gitCodesigningType development --gitCodesigningUseCurrent --buildNumber 1 --configuration debug_sim_arm64 --continueOnError -``` - ---- - -## Scope - -**In scope:** - -- `StorageFileListPanelComponent.Item.message: Message` → `EngineMessage` (the item type co-located with the panel component). -- `StorageUsageScreen.Component.SelectionState.togglePeer(id:availableMessages: [EngineMessage.Id: Message])` → `[EngineMessage.Id: EngineMessage]`. -- `StorageUsageScreen.Component.AggregatedData.messages: [MessageId: Message]` → `[EngineMessage.Id: EngineMessage]`. -- `AggregatedData.clearIncludeMessages: [Message]` / `.clearExcludeMessages: [Message]` → `[EngineMessage]` (plus the corresponding local vars in `AggregatedData.updateSelected...`). -- `AggregatedData.init(..., messages: [MessageId: Message])` → `[EngineMessage.Id: EngineMessage]`. -- `StorageUsageScreen.Component.RenderResult.messages: [MessageId: Message]` → `[EngineMessage.Id: EngineMessage]`. -- `openMessage(message: Message)` → `openMessage(message: EngineMessage)`. -- Drop the now-redundant wave-7 facade-boundary bridging (`.mapValues(EngineMessage.init)` on `existingMessages`, `.mapValues { $0._asMessage() }` on the facade's engineMessages output, `.map(EngineMessage.init)` on the two `clearStorage` call sites, `._asMessage()` on `item.message` inside the `AggregatedData.updateSelected...` loop, and `EngineMessage(message)` inside the `result.imageItems.append(...)` site). - -**Out of scope — left for a future wave:** - -- Direct postbox usage for `AccountSpecificCacheStorageSettings` observation: `StorageUsageScreen.swift:1047-1062` and `3131-3185`. Blocks `import Postbox` removal. Requires engine equivalents for `PostboxViewKey.preferences` / `PreferencesView` observation and for `transaction.getPeer` / `transaction.getPeerCachedData` — likely an `EngineData`-subscription based rewrite plus peer-category classification via already-existing engine APIs. -- `StorageFileListPanelComponent`'s `Icon.media(Media, TelegramMediaImageRepresentation)` enum case. Holds either `TelegramMediaFile` or `TelegramMediaImage` (always one of these two TelegramCore types per `imageIconValue = .media(file, ...)` and `.media(image, ...)` construction sites). Could be split into `.mediaFile(TelegramMediaFile, ...)` / `.mediaImage(TelegramMediaImage, ...)` to eliminate the raw `Media` protocol dependency; out of scope as it's unrelated to Message-type migration. - ---- - -## Tasks - -### Task 1: Migrate `StorageFileListPanelComponent.Item.message` - -**Files:** -- Modify: `submodules/TelegramUI/Components/StorageUsageScreen/Sources/StorageFileListPanelComponent.swift` — `Item.message` type and `init(message:)` param. - -No other changes inside the file. Internal usage (`item.message.id`, `item.message.timestamp`, `item.message.media`) already works on `EngineMessage` — `EngineMessage.media` returns `[Media]` (raw), so the `as? TelegramMediaFile` / `as? TelegramMediaImage` downcasts inside the `for media in item.message.media` loop still compile. - -### Task 2: Migrate `StorageUsageScreen` internal storage types - -**Files:** -- Modify: `submodules/TelegramUI/Components/StorageUsageScreen/Sources/StorageUsageScreen.swift` - -Change: -- `SelectionState.togglePeer(availableMessages: [EngineMessage.Id: Message])` → `[EngineMessage.Id: EngineMessage]`. Body only uses `messageId.peerId` so no body change required. -- `AggregatedData.messages` / `.clearIncludeMessages` / `.clearExcludeMessages` type declarations and the init param. -- The selected-messages accumulation loop inside `AggregatedData` (the block running from the photo/video/file/music category branches): drop `item.message._asMessage()` in the two photo/video branches (`imageItems` holds EngineMessage items, so `._asMessage()` was the EngineMessage→Message unwrap to fit the old `[Message]` local); `item.message` in the file/music branches now passes through since Item.message is EngineMessage. -- `RenderResult.messages` type. - -### Task 3: Drop wave-7 facade-boundary bridging - -At `StorageUsageScreen.swift:2397` the `renderStorageUsageStatsMessages` call previously wrapped input via `(self.aggregatedData?.messages ?? [:]).mapValues(EngineMessage.init)` and unwrapped output via `.mapValues { $0._asMessage() }`. With `AggregatedData.messages` and `RenderResult.messages` now EngineMessage-typed, both bridges vanish: the call just passes `self.aggregatedData?.messages ?? [:]` directly and assigns the result to `result.messages` unchanged. - -At the two `clearStorage` call sites in `StorageUsageScreen.swift` (inside `clearSelected(...)`): `aggregatedData.clearIncludeMessages.map(EngineMessage.init)` → `aggregatedData.clearIncludeMessages` (same for `excludeMessages`), plus the local `includeMessages: [Message]` / `excludeMessages: [Message]` vars become `[EngineMessage]`. - -At the `RenderResult`-building loop (post-`renderStorageUsageStatsMessages`), `StorageMediaGridPanelComponent.Item(message: EngineMessage(message), ...)` → `message: message` since `message` is already `EngineMessage`. - -### Task 4: Migrate `openMessage` + external-API unwraps - -`openMessage(message: Message)` → `openMessage(message: EngineMessage)`. Two external APIs receive raw `Message`: pass `message._asMessage()` to `OpenChatMessageParams(message:)` inside `openMessage`, and to `chatMediaListPreviewControllerData(message:)` inside `messageGaleryContextAction`. Also drop the one-line `let foundGalleryMessage: Message? = message` + `guard let galleryMessage = foundGalleryMessage` dance inside `openMessage` — it's a no-op wrap preserved from an older version. - -### Task 5: Full project build - -Expected clean (cached — 30 seconds on an incremental build; ~60s from a cold start since wave 7). - -### Task 6: Commit - -Single wave-8 atomic commit. - ---- - -## Outcome (2026-04-20) - -Single atomic commit landing the migration. Build verified green (59s incremental, 27 actions). Net -5 lines (simplification, as expected — most changes are type swaps and a handful of redundant wraps/unwraps removed). - -Two files modified: - -| File | Δ | -|---|---| -| `submodules/TelegramUI/Components/StorageUsageScreen/Sources/StorageUsageScreen.swift` | +33 / -44 | -| `submodules/TelegramUI/Components/StorageUsageScreen/Sources/StorageFileListPanelComponent.swift` | +3 / -3 | - -**Module did NOT become Postbox-free.** Both files retain `import Postbox` for the out-of-scope sites listed above. Drop-candidacy inventory in `StorageUsageScreen.swift`: - -- 1047–1062: preferences-view observation of `AccountSpecificCacheStorageSettings` via `postbox.combinedView` + `PreferencesView`. -- 3131–3185: second preferences-view observation + `postbox.transaction { transaction in ... transaction.getPeer / transaction.getPeerCachedData as? CachedGroupData / CachedChannelData ... }` for classifying peer-storage-timeout exceptions. - -And in `StorageFileListPanelComponent.swift`: - -- 105: `Icon.media(Media, TelegramMediaImageRepresentation)` enum case. - -Future wave targets either the preferences-view observation sites (substantial — `EngineData`-subscription rewrite + peer-category classification via engine APIs) or the `Icon.media` split (trivial — 3 sites to update). - -Plan / record: `docs/superpowers/plans/2026-04-20-postbox-to-telegramengine-wave-8.md`. diff --git a/docs/superpowers/plans/2026-04-20-postbox-to-telegramengine-wave-9.md b/docs/superpowers/plans/2026-04-20-postbox-to-telegramengine-wave-9.md deleted file mode 100644 index 28e5c85c9a..0000000000 --- a/docs/superpowers/plans/2026-04-20-postbox-to-telegramengine-wave-9.md +++ /dev/null @@ -1,162 +0,0 @@ -# Postbox → TelegramEngine Wave 9 Implementation Plan - -> **For agentic workers:** This plan was executed in a single session; steps below are a post-hoc record of the work landed, not a to-do list. - -**Goal:** Finish the `StorageUsageScreen` de-Postbox work started in wave 8 by rewriting the two remaining direct-postbox sites that observe `AccountSpecificCacheStorageSettings`, and drop `import Postbox` from `StorageUsageScreen.swift`. - -**Architecture:** Replace `postbox.combinedView(keys: [.preferences(...)]) + PreferencesView` observation with `context.engine.data.subscribe(TelegramEngine.EngineData.Item.Configuration.ApplicationSpecificPreference(key:))`, which returns `PreferencesEntry?` and is then decoded the same way (`.get(AccountSpecificCacheStorageSettings.self)`). Replace the transaction-based per-peer classification (`transaction.getPeer` + `transaction.getPeerCachedData as? CachedGroupData/CachedChannelData`) with an `EngineDataMap` of `TelegramEngine.EngineData.Item.Peer.Peer.init(id:)` lookups producing `EnginePeer?` values that pattern-match on `.user` / `.legacyGroup` / `.channel(channel)` / `.secretChat`. The `FoundPeer(peer:subscribers:)` wrapper in the signal's element type is dropped entirely since downstream consumers (`peerExceptions.isEmpty`, `.count`, `.prefix(3).map { EnginePeer($0.peer.peer) }`) never read `subscribers`. - -**Tech Stack:** Swift / Bazel. No unit tests. - -**Build command:** - -```bash -source ~/.zshrc 2>/dev/null; PATH=/opt/homebrew/opt/ruby/bin:`gem environment gemdir`/bin:$PATH python3 build-system/Make/Make.py --overrideXcodeVersion --cacheDir ~/telegram-bazel-cache build --configurationPath build-system/appstore-configuration.json --gitCodesigningRepository git@gitlab.com:peter-iakovlev/fastlanematch.git --gitCodesigningType development --gitCodesigningUseCurrent --buildNumber 1 --configuration debug_sim_arm64 --continueOnError -``` - ---- - -## Scope - -Two direct-postbox site clusters rewritten in `StorageUsageScreen.swift`: - -1. **Site 1 (former lines 1047–1087)** — `cacheSettingsExceptionCount` signal. Preserved its downstream `EngineDataMap` + `EnginePeer` per-category counting logic unchanged; only the preferences observation replaced. -2. **Site 2 (former lines 3131–3196)** — `peerExceptions` signal inside `openKeepMediaCategory`. Both the preferences observation AND the `postbox.transaction { transaction.getPeer / transaction.getPeerCachedData ... FoundPeer(...) }` block replaced. Signal element type changed from `[(peer: FoundPeer, value: Int32)]` to `[(peer: EnginePeer, value: Int32)]`; `FoundPeer` and the unread `subscribers` field dropped. - -One consumer-side edit: `peerExceptions.prefix(3).map { EnginePeer($0.peer.peer) }` → `peerExceptions.prefix(3).map { $0.peer }` (at the `MultiplePeerAvatarsContextItem` construction). - -One typealias fixup: `var mergedMedia: [MessageId: Int64]` → `[EngineMessage.Id: Int64]` (required once `import Postbox` is removed, since `MessageId` is the raw Postbox name, not a TelegramCore typealias). - -`import Postbox` removed from `StorageUsageScreen.swift`. - ---- - -## Tasks - -### Task 1: Rewrite site 1 — cacheSettingsExceptionCount - -**Files:** -- Modify: `submodules/TelegramUI/Components/StorageUsageScreen/Sources/StorageUsageScreen.swift` (former 1047–1058). - -Replace the preferences observation header. The downstream `mapToSignal { ... EngineDataMap ... EnginePeer ... }` body is already Engine-only and unchanged. - -Before: - -```swift -let viewKey: PostboxViewKey = .preferences(keys: Set([PreferencesKeys.accountSpecificCacheStorageSettings])) -let cacheSettingsExceptionCount: Signal<[CacheStorageSettings.PeerStorageCategory: Int32], NoError> = component.context.account.postbox.combinedView(keys: [viewKey]) -|> map { views -> AccountSpecificCacheStorageSettings in - let cacheSettings: AccountSpecificCacheStorageSettings - if let view = views.views[viewKey] as? PreferencesView, let value = view.values[PreferencesKeys.accountSpecificCacheStorageSettings]?.get(AccountSpecificCacheStorageSettings.self) { - cacheSettings = value - } else { - cacheSettings = AccountSpecificCacheStorageSettings.defaultSettings - } - return cacheSettings -} -|> distinctUntilChanged -|> mapToSignal { ... } -``` - -After: - -```swift -let cacheSettingsExceptionCount: Signal<[CacheStorageSettings.PeerStorageCategory: Int32], NoError> = context.engine.data.subscribe( - TelegramEngine.EngineData.Item.Configuration.ApplicationSpecificPreference(key: PreferencesKeys.accountSpecificCacheStorageSettings) -) -|> map { preferencesEntry -> AccountSpecificCacheStorageSettings in - return preferencesEntry?.get(AccountSpecificCacheStorageSettings.self) ?? AccountSpecificCacheStorageSettings.defaultSettings -} -|> distinctUntilChanged -|> mapToSignal { ... } -``` - -### Task 2: Rewrite site 2 — peerExceptions - -**Files:** -- Modify: `submodules/TelegramUI/Components/StorageUsageScreen/Sources/StorageUsageScreen.swift` (former 3131–3196). - -Replace both the preferences observation (as in Task 1) AND the subsequent `mapToSignal { context.account.postbox.transaction { ... } }` block. Signal element type changes from `[(peer: FoundPeer, value: Int32)]` to `[(peer: EnginePeer, value: Int32)]`. `subscriberCount` is not preserved — it's computed but never read by downstream consumers. - -After (showing the `peerExceptions` signal in full): - -```swift -let peerExceptions: Signal<[(peer: EnginePeer, value: Int32)], NoError> = accountSpecificSettings -|> mapToSignal { accountSpecificSettings -> Signal<[(peer: EnginePeer, value: Int32)], NoError> in - return context.engine.data.get( - EngineDataMap(accountSpecificSettings.peerStorageTimeoutExceptions.map(\.key).map(TelegramEngine.EngineData.Item.Peer.Peer.init(id:))) - ) - |> map { peers -> [(peer: EnginePeer, value: Int32)] in - var result: [(peer: EnginePeer, value: Int32)] = [] - for item in accountSpecificSettings.peerStorageTimeoutExceptions { - guard let peer = peers[item.key] ?? nil else { continue } - let peerCategory: CacheStorageSettings.PeerStorageCategory - switch peer { - case .user, .secretChat: - peerCategory = .privateChats - case .legacyGroup: - peerCategory = .groups - case let .channel(channel): - if case .group = channel.info { - peerCategory = .groups - } else { - peerCategory = .channels - } - } - if peerCategory != mappedCategory { continue } - result.append((peer: peer, value: item.value)) - } - return result.sorted(by: { lhs, rhs in - if lhs.value != rhs.value { - return lhs.value < rhs.value - } - return lhs.peer.debugDisplayTitle < rhs.peer.debugDisplayTitle - }) - } -} -``` - -### Task 3: Update consumer of `peerExceptions` - -**Files:** -- Modify: `submodules/TelegramUI/Components/StorageUsageScreen/Sources/StorageUsageScreen.swift` (former 3288). - -`peerExceptions.prefix(3).map { EnginePeer($0.peer.peer) }` → `peerExceptions.prefix(3).map { $0.peer }`. The `MultiplePeerAvatarsContextItem(context:, peers: [EnginePeer], totalCount:, action:)` signature is unchanged — we simply drop the redundant `EnginePeer(...)` wrap because `$0.peer` is now already an `EnginePeer`. - -### Task 4: Drop `import Postbox` - -**Files:** -- Modify: `submodules/TelegramUI/Components/StorageUsageScreen/Sources/StorageUsageScreen.swift` (line 12). - -Remove the `import Postbox` line. - -### Task 5: Typealias fixup for `MessageId` - -**Files:** -- Modify: `submodules/TelegramUI/Components/StorageUsageScreen/Sources/StorageUsageScreen.swift` (former 2397). - -`var mergedMedia: [MessageId: Int64]` → `[EngineMessage.Id: Int64]`. `MessageId` is the raw Postbox type name; with `import Postbox` removed, the type must be named through the `EngineMessage.Id` typealias. Discovered by first-pass build failure `cannot find type 'MessageId' in scope`. - -### Task 6: Full project build - -Expected green. Incremental build: ~60s (cached), 27 actions. - -### Task 7: Commit - -Single wave-9 atomic commit. CLAUDE.md updates the wave 8 outcome's "future-wave candidates" note since this wave closes both of them. `StorageUsageScreen` (the module as a whole) now has `StorageUsageScreen.swift` Postbox-free; the module's `StorageFileListPanelComponent.swift` still imports Postbox because of the `Icon.media(Media, TelegramMediaImageRepresentation)` enum case (trivial future wave, as previously noted). - ---- - -## Outcome (2026-04-20) - -Single atomic commit. Build verified green (27 actions, ~60s incremental). - -Net change: 1 file, +30 / -54 lines (-24 simplification). - -Lessons: - -- **`ApplicationSpecificPreference(key:)` is the general-purpose engine replacement** for any `postbox.combinedView(keys: [.preferences(keys: Set([key]))])` idiom. Takes a `ValueBoxKey`, returns `PreferencesEntry?`, decodes via `.get(T.self)`. Usable from any module that imports `TelegramCore` even without `import Postbox`, because the `ValueBoxKey`-typed input is obtained through a statically-named `PreferencesKeys.*` member (no `ValueBoxKey` identifier appears in the consumer). -- **`MessageId` is raw Postbox, not a TelegramCore typealias.** CLAUDE.md's "engine typealias cheat sheet" labels `PeerId`, `MessageId`, etc. as migration *targets*, not existing aliases. Files that drop `import Postbox` must rename these to `EngineMessage.Id` / `EnginePeer.Id`. Caught by the first-pass build failure. -- **Dead-code detection during rewrites.** The transaction block's `subscriberCount` computation and the `FoundPeer.subscribers` field it populated were never consumed downstream. The rewrite simply dropped them, shrinking the code further than a 1:1 rewrite would have. - -`StorageUsageScreen.swift` is now Postbox-free. The `StorageUsageScreen` consumer module as a whole is still not fully Postbox-free because `StorageFileListPanelComponent.swift` retains `import Postbox` for its `Icon.media(Media, TelegramMediaImageRepresentation)` enum case (3 construction sites; trivial future wave splits into `.mediaFile(TelegramMediaFile, ...)` / `.mediaImage(TelegramMediaImage, ...)`). diff --git a/docs/superpowers/plans/2026-04-21-swifttl-layered-schema-generation.md b/docs/superpowers/plans/2026-04-21-swifttl-layered-schema-generation.md deleted file mode 100644 index c5f5bc9549..0000000000 --- a/docs/superpowers/plans/2026-04-21-swifttl-layered-schema-generation.md +++ /dev/null @@ -1,1037 +0,0 @@ -# SwiftTL — Layered Schema Generation Implementation Plan - -> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. - -**Goal:** Extend `build-system/SwiftTL` to parse `.tl` schemas containing `===N===` layer markers and emit one cumulative-snapshot `{apiPrefix}Layer{N}.swift` file per layer, while leaving the flat schema pipeline byte-identical. - -**Architecture:** Approach 1 from the design spec (`docs/superpowers/specs/2026-04-21-swifttl-layered-schema-generation-design.md`). `DescriptionParser` returns a new `ParsedSchema` enum (`.flat` or `.layered`). `Resolver` gains `resolveLayeredTypes(layers:)` that snapshots a running constructor map per layer. `CodeGenerator` gains `generateLayered(apiPrefix:, layerNumber:, types:)` that emits a single-file-per-layer shape matching the existing hand-written `SecretApiLayer{N}.swift`. `main.swift` branches on `ParsedSchema`. - -**Tech Stack:** Swift 5.5 executable target (`build-system/SwiftTL/Package.swift`). Vendored `Parser` combinator library for parsing. Project itself uses Bazel (`Make.py build`) for the full iOS build — `swift build` and `swift run` work at the package level for SwiftTL itself. - -**Testing note:** per `CLAUDE.md`, no unit tests exist in this project. Verification is end-to-end: `swift run SwiftTL` on real schema files, diff against existing hand-written output, full Bazel build of the iOS app. No TDD steps in this plan — each task's verification is either (a) `swift build` (compiles), (b) `swift run SwiftTL` producing expected files, or (c) full Bazel build succeeds. - -**Baseline:** this plan is written against a pre-existing prep commit landed just before Task 1 begins, which threads `apiPrefix: String` through `CodeGenerator.generate` / `generateMainFile` / `generateImplFile` / `typeReferenceRepresentation`, removes dead `--stub-functions` and `--print-constructors` CLI flags from `main.swift`, and deletes the unused `LegacyOrderParser.swift`. All task-level edits below assume these changes are already committed — code snippets and line numbers reference the post-prep-commit state of the files. - ---- - -## File Structure - -All edits within `build-system/SwiftTL/Sources/SwiftTL/`: - -- `DescriptionParsing.swift` — add `ParsedSchema` enum, rework `parse(data:)` to detect `===N===` markers and route lines per layer. -- `Resolution.swift` — add `resolveLayeredTypes(layers:)` that walks sections and snapshots a running map. -- `CodeGeneration.swift` — add `generateLayered(apiPrefix:, layerNumber:, types:)` that emits one `{apiPrefix}Layer{N}.swift` string. -- `main.swift` — branch on `ParsedSchema`, loop for layered, unchanged for flat. - -Downstream changes in the repo: - -- `submodules/TelegramApi/Sources/SecretApiLayer{8,17,20,23,45,46,66,73,101,143,144}.swift` — replace existing 5 (of 11) with generator output; 6 new files added. BUILD uses `glob("Sources/**/*.swift")` so no BUILD update needed (confirmed — `submodules/TelegramApi/BUILD` line 9). - -Reference artifacts to consult during implementation: - -- Input schema: `/Users/isaac/build/telegram/telegram-ios-shared/tools/secret_scheme.tl` (112 lines). -- Legacy per-layer output to match: `submodules/TelegramApi/Sources/SecretApiLayer{8,46,73,101,144}.swift`. -- Flat reference: `submodules/TelegramApi/Sources/Api0.swift` and sharded `Api{1..5}.swift` — shows the `useStructPattern = true` shape to contrast against. -- Invocation script (not to be edited in this plan — spec calls it out as a follow-up in the sibling repo): `/Users/isaac/build/telegram/telegram-ios-shared/tools/generate_and_copy_scheme.sh`. - ---- - -### Task 1: `ParsedSchema` type + layered parsing in `DescriptionParser` - -**Files:** -- Modify: `build-system/SwiftTL/Sources/SwiftTL/DescriptionParsing.swift` - -**Goal:** Replace `DescriptionParser.parse(data:) -> (constructors, functions)` with `parse(data:) -> ParsedSchema`, where `ParsedSchema` is a new enum with `.flat` and `.layered` cases. Layered mode triggers on any line matching `^===\d+===\s*$`. Flat mode is byte-identical to today. - -- [ ] **Step 1: Add the `ParsedSchema` enum at the top of `DescriptionParser`** - -Insert immediately after the `enum DescriptionParser {` opening brace, before `enum TypeReferenceDescription`: - -```swift -enum ParsedSchema { - case flat(constructors: [ConstructorDescription], functions: [ConstructorDescription]) - case layered(layers: [(layerNumber: Int, constructors: [ConstructorDescription])]) -} - -struct SchemaParsingError: Error, CustomStringConvertible { - var text: String - var description: String { text } -} -``` - -- [ ] **Step 2: Rewrite `parse(data:)` signature and dispatch logic** - -Replace the current `static func parse(data: String) throws -> (constructors: [ConstructorDescription], functions: [ConstructorDescription])` (currently at lines 27–99) with: - -```swift -static func parse(data: String) throws -> ParsedSchema { - let lines = data.components(separatedBy: "\n") - - // Detect layered mode: any line of the form ===N=== - let layerMarker = try NSRegularExpression(pattern: "^===\\d+===\\s*$") - let hasLayerMarker = lines.contains { line in - let range = NSRange(line.startIndex..., in: line) - return layerMarker.firstMatch(in: line, range: range) != nil - } - - if hasLayerMarker { - return try parseLayered(lines: lines) - } else { - return try parseFlat(lines: lines) - } -} -``` - -- [ ] **Step 3: Extract the existing flat-parsing body into `parseFlat(lines:)`** - -Add directly below `parse(data:)`. This is the existing logic verbatim, just accepting pre-split lines and returning the new enum case: - -```swift -private static func parseFlat(lines: [String]) throws -> ParsedSchema { - var typeLines: [String] = [] - var functionLines: [String] = [] - - let skipPrefixes: [String] = [ - "true#3fedd339 = True;", - "vector#1cb5c415 {t:Type} # [ t ] = Vector t;", - "error#c4b9f9bb code:int text:string = Error;", - "null#56730bcc = Null;" - ] - let skipContains: [String] = ["{X:Type}"] - - var isParsingFunctions = false - loop: for line in lines { - if line.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).isEmpty { - continue - } else if line == "---functions---" { - isParsingFunctions = true - } else { - for string in skipPrefixes { - if line.hasPrefix(string) { continue loop } - } - for string in skipContains { - if line.contains(string) { continue loop } - } - if isParsingFunctions { - functionLines.append(line) - } else { - typeLines.append(line) - } - } - } - - var constructors: [ConstructorDescription] = [] - var functions: [ConstructorDescription] = [] - - for line in typeLines { - do { - constructors.append(try parseConstructor(string: line)) - } catch let e { - print("Error while parsing line:\n\(line)\n") - print("\(e)") - throw e - } - } - for line in functionLines { - do { - functions.append(try parseConstructor(string: line)) - } catch let e { - print("Error while parsing line:\n\(line)\n") - print("\(e)") - throw e - } - } - - return .flat(constructors: constructors, functions: functions) -} -``` - -- [ ] **Step 4: Add `parseLayered(lines:)`** - -Add directly below `parseFlat`: - -```swift -private static func parseLayered(lines: [String]) throws -> ParsedSchema { - let skipPrefixes: [String] = [ - "true#3fedd339 = True;", - "vector#1cb5c415 {t:Type} # [ t ] = Vector t;", - "error#c4b9f9bb code:int text:string = Error;", - "null#56730bcc = Null;" - ] - let skipContains: [String] = ["{X:Type}"] - let layerMarker = try NSRegularExpression(pattern: "^===(\\d+)===\\s*$") - - // Pre-marker constructor lines accumulate here and are attached to the first declared layer. - var preMarkerLines: [String] = [] - var sections: [(layerNumber: Int, lines: [String])] = [] - var lastLayerNumber: Int? = nil - - loop: for line in lines { - let trimmed = line.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) - if trimmed.isEmpty { continue } - - if line == "---functions---" { - throw SchemaParsingError(text: "Layered schemas may not declare ---functions---; secret/layered schemas are types-only.") - } - - let range = NSRange(line.startIndex..., in: line) - if let match = layerMarker.firstMatch(in: line, range: range), - let numberRange = Range(match.range(at: 1), in: line), - let layerNumber = Int(line[numberRange]) - { - if let previous = lastLayerNumber, layerNumber <= previous { - throw SchemaParsingError(text: "Layer markers must appear in strictly ascending order; found ===\(layerNumber)=== after ===\(previous)===.") - } - sections.append((layerNumber, [])) - lastLayerNumber = layerNumber - continue - } - - // Apply the same skip rules as flat mode. - for string in skipPrefixes { - if line.hasPrefix(string) { continue loop } - } - for string in skipContains { - if line.contains(string) { continue loop } - } - - if sections.isEmpty { - preMarkerLines.append(line) - } else { - sections[sections.count - 1].lines.append(line) - } - } - - if sections.isEmpty { - throw SchemaParsingError(text: "Layered schema has a layer marker regex match but no ===N=== sections were extracted; this indicates a parser bug.") - } - - // Attach pre-marker lines to the first (lowest) declared layer. - if !preMarkerLines.isEmpty { - sections[0].lines.insert(contentsOf: preMarkerLines, at: 0) - } - - var layers: [(layerNumber: Int, constructors: [ConstructorDescription])] = [] - for (layerNumber, sectionLines) in sections { - var constructors: [ConstructorDescription] = [] - for line in sectionLines { - do { - constructors.append(try parseConstructor(string: line)) - } catch let e { - print("Error while parsing line (layer \(layerNumber)):\n\(line)\n") - print("\(e)") - throw e - } - } - layers.append((layerNumber, constructors)) - } - - return .layered(layers: layers) -} -``` - -- [ ] **Step 5: Verify SwiftTL compiles** - -Run: `cd build-system/SwiftTL && swift build 2>&1` -Expected: build succeeds OR fails only at call sites in `main.swift` (the next task fixes main.swift). Errors inside `DescriptionParsing.swift` mean the rewrite has a syntax/type issue — fix before proceeding. - -Note: at this point `main.swift` still calls `parse(data:)` expecting the old tuple return type, so `swift build` from the package root will fail at the main-file callsite with a type-mismatch error. That's expected; Task 4 fixes it. - -- [ ] **Step 6: Commit** - -```bash -cd /Users/isaac/build/telegram/telegram-ios -git add build-system/SwiftTL/Sources/SwiftTL/DescriptionParsing.swift -git commit -m "$(cat <<'EOF' -SwiftTL: add ParsedSchema + layered schema parsing - -DescriptionParser.parse(data:) now returns ParsedSchema (.flat or -.layered) based on the presence of ===N=== markers. Layered schemas -split constructor lines per layer; pre-marker constructors attach to -the lowest-numbered layer; ---functions--- is rejected in layered -mode; non-ascending markers throw. - -Co-Authored-By: Claude Opus 4.7 (1M context) -EOF -)" -``` - ---- - -### Task 2: `Resolver.resolveLayeredTypes` for per-layer cumulative snapshots - -**Files:** -- Modify: `build-system/SwiftTL/Sources/SwiftTL/Resolution.swift` - -**Goal:** Add `Resolver.resolveLayeredTypes(layers:)` that walks per-layer constructor descriptions in order, threads a running name→constructor map with last-wins semantics, and snapshots `[SumType]` at the end of each layer. Shares argument-resolution logic with the existing `resolveTypes(constructors:)` (by factoring a shared helper closure/method). - -- [ ] **Step 1: Add `resolveLayeredTypes` to the `Resolver` enum** - -Insert this method immediately after `resolveTypes(constructors:)` (which ends at Resolution.swift:201, `return types.values.sorted(by: { $0.name < $1.name })`). The method threads mutable state (a running map of constructor name → resolved SumType.Constructor and target type) and snapshots at each layer boundary: - -```swift -static func resolveLayeredTypes( - layers: [(layerNumber: Int, constructors: [DescriptionParser.ConstructorDescription])] -) throws -> [(layerNumber: Int, types: [SumType])] { - // Running state: for each constructor name, the target type name and the raw description. - // We keep raw descriptions (not resolved forms) because a later-layer constructor may - // introduce new target-type names, and resolveTypeReference needs the final target-type set. - var liveConstructors: [QualifiedName: (typeName: QualifiedName, description: DescriptionParser.ConstructorDescription)] = [:] - var result: [(layerNumber: Int, types: [SumType])] = [] - - for (layerNumber, layerConstructors) in layers { - // Apply this layer's constructors to the running map with last-wins semantics. - for constructorDescription in layerConstructors { - switch constructorDescription.type { - case let .type(name): - if !name.value[name.value.startIndex].isUppercase { - throw ResolutionError(text: "Type constructor \(constructorDescription.name) -> \(name): the resulting type name should begin with a capital letter") - } - liveConstructors[constructorDescription.name] = (name, constructorDescription) - case let .generic(name, argumentType): - throw ResolutionError(text: "Type constructor \(constructorDescription.name) can not be used to construct a generic type \(name)<\(argumentType)>") - } - } - - // Snapshot: group by target type, resolve. - var constructedTypes: [QualifiedName: [DescriptionParser.ConstructorDescription]] = [:] - var constructorNameToType: [QualifiedName: QualifiedName] = [:] - for (ctorName, entry) in liveConstructors { - constructedTypes[entry.typeName, default: []].append(entry.description) - constructorNameToType[ctorName] = entry.typeName - } - - func resolveTypeReference(description: DescriptionParser.TypeReferenceDescription) throws -> TypeReference { - switch description { - case let .type(name): - if let resolvedBuiltinType = resolveBuiltinType(name: name) { - return resolvedBuiltinType - } - if name.value[name.value.startIndex].isUppercase { - if let _ = constructedTypes[name] { - return .boxedType(name) - } else { - throw ResolutionError(text: "Unresolved type \(name) in layer \(layerNumber)") - } - } else { - if let typeName = constructorNameToType[name] { - return .bareConstructor(typeName: typeName, name: name) - } else { - throw ResolutionError(text: "Unresolved type constructor \(name) in layer \(layerNumber)") - } - } - case let .generic(name, argumentType): - if name == "vector" { - return .bareVector(try resolveTypeReference(description: .type(name: argumentType))) - } else if name == "Vector" { - return .boxedVector(try resolveTypeReference(description: .type(name: argumentType))) - } else { - throw ResolutionError(text: "Unresolved generic type \(name) in layer \(layerNumber)") - } - } - } - - func resolveArgument(existingArguments: [Argument], description: DescriptionParser.ArgumentDescription) throws -> Argument { - return Argument( - name: description.name, - type: try resolveTypeReference(description: description.type), - condition: try description.condition.flatMap { condition -> Argument.Condition in - if !existingArguments.contains(where: { $0.name == condition.fieldName }) { - throw ResolutionError(text: "Unresolved conditional field reference to \(condition.fieldName) in layer \(layerNumber)") - } - return Argument.Condition(fieldName: condition.fieldName, bitIndex: condition.bitIndex) - } - ) - } - - var types: [QualifiedName: SumType] = [:] - for (typeName, constructorDescriptions) in constructedTypes { - let type = SumType(name: typeName) - for constructorDescription in constructorDescriptions { - var arguments: [Argument] = [] - for argumentDescription in constructorDescription.arguments { - arguments.append(try resolveArgument(existingArguments: arguments, description: argumentDescription)) - } - guard let id = constructorDescription.explicitId else { - throw ResolutionError(text: "Constructor \(constructorDescription.name) does not have an id") - } - type.constructors[constructorDescription.name] = SumType.Constructor( - name: constructorDescription.name, - id: id, - arguments: arguments - ) - } - types[type.name] = type - } - - let sortedTypes = types.values.sorted(by: { $0.name < $1.name }) - result.append((layerNumber, sortedTypes)) - } - - return result -} -``` - -- [ ] **Step 2: Verify SwiftTL package compiles (DescriptionParsing + Resolution)** - -Run: `cd build-system/SwiftTL && swift build 2>&1 | head -50` -Expected: the only remaining errors are in `main.swift` (unchanged in this task). If `Resolution.swift` itself has errors, fix before proceeding. - -- [ ] **Step 3: Commit** - -```bash -cd /Users/isaac/build/telegram/telegram-ios -git add build-system/SwiftTL/Sources/SwiftTL/Resolution.swift -git commit -m "$(cat <<'EOF' -SwiftTL: add Resolver.resolveLayeredTypes - -Walks layer sections in order, threads a running constructor-name map -with last-wins semantics, and snapshots [SumType] at each layer -boundary. Constructors appearing only in later layers do not leak into -earlier layers' snapshots. - -Co-Authored-By: Claude Opus 4.7 (1M context) -EOF -)" -``` - ---- - -### Task 3: `CodeGenerator.generateLayered` — one file per layer - -**Files:** -- Modify: `build-system/SwiftTL/Sources/SwiftTL/CodeGeneration.swift` - -**Goal:** Emit one `{apiPrefix}Layer{N}.swift` file per layer, matching the shape of the existing hand-written `SecretApiLayer8.swift` (nested `public struct`, inline enum case args, `fileprivate parse_*`). Reuses `typeReferenceRepresentation`, `generateFieldSerialization`, `generateFieldParsing`, and `SumType.hasDirectReference(to:typeMap:)` unchanged. - -Reference for the expected output shape: read `submodules/TelegramApi/Sources/SecretApiLayer8.swift` (the first 80 lines show the header + struct body; lines ~85+ show the nested enums). The generator output will not byte-match but must match this *shape*. - -- [ ] **Step 1: Add `generateLayered` entry point to `CodeGenerator`** - -Insert the following method after the existing `generate(...)` method (which ends at CodeGeneration.swift:200). Reads directly; uses the same `CodeWriter` helper and private type helpers already in the file: - -```swift -static func generateLayered( - apiPrefix: String, - layerNumber: Int, - types: [Resolver.SumType] -) throws -> (filename: String, source: String) { - let structName = "\(apiPrefix)\(layerNumber)" - let filename = "\(apiPrefix)Layer\(layerNumber).swift" - - var typeMap: [QualifiedName: Resolver.SumType] = [:] - for type in types { - typeMap[type.name] = type - } - - // Detect whether any constructor argument uses Int256; if so, we need the int256 parser entry. - var usesInt256 = false - for type in types { - for (_, constructor) in type.constructors { - for argument in constructor.arguments { - if containsInt256(argument.type) { usesInt256 = true; break } - } - if usesInt256 { break } - } - if usesInt256 { break } - } - - var writer = CodeWriter() - writer.line() - - // File-scope dispatch table - writer.line("fileprivate let parsers: [Int32 : (BufferReader) -> Any?] = {") - writer.indent() - writer.line("var dict: [Int32 : (BufferReader) -> Any?] = [:]") - writer.line("dict[-1471112230] = { return $0.readInt32() }") - writer.line("dict[570911930] = { return $0.readInt64() }") - writer.line("dict[571523412] = { return $0.readDouble() }") - writer.line("dict[-1255641564] = { return parseString($0) }") - if usesInt256 { - writer.line("dict[0x0929C32F] = { return parseInt256($0) }") - } - - let sortedTypes = types.sorted(by: { $0.name < $1.name }) - for type in sortedTypes { - let sortedConstructors = type.constructors.values.sorted(by: { $0.name < $1.name }) - for constructor in sortedConstructors { - writer.line("dict[\(Int32(bitPattern: constructor.id))] = { return \(structName).\(type.name).parse_\(constructor.name.value)($0) }") - } - } - writer.line("return dict") - writer.dedent() - writer.line("}()") - writer.line() - - // public struct {apiPrefix}{N} { - writer.line("public struct \(structName) {") - writer.indent() - - // public static func parse(_ buffer: Buffer) -> Any? - writer.line("public static func parse(_ buffer: Buffer) -> Any? {") - writer.indent() - writer.line("let reader = BufferReader(buffer)") - writer.line("if let signature = reader.readInt32() {") - writer.indent() - writer.line("return parse(reader, signature: signature)") - writer.dedent() - writer.line("}") - writer.line("return nil") - writer.dedent() - writer.line("}") - writer.line() - - // fileprivate static func parse(_ reader: BufferReader, signature: Int32) -> Any? - writer.line("fileprivate static func parse(_ reader: BufferReader, signature: Int32) -> Any? {") - writer.indent() - writer.line("if let parser = parsers[signature] {") - writer.indent() - writer.line("return parser(reader)") - writer.dedent() - writer.line("}") - writer.line("else {") - writer.indent() - writer.line("telegramApiLog(\"Type constructor \\(String(signature, radix: 16, uppercase: false)) not found\")") - writer.line("return nil") - writer.dedent() - writer.line("}") - writer.dedent() - writer.line("}") - writer.line() - - // fileprivate static func parseVector - writer.line("fileprivate static func parseVector(_ reader: BufferReader, elementSignature: Int32, elementType: T.Type) -> [T]? {") - writer.indent() - writer.line("if let count = reader.readInt32() {") - writer.indent() - writer.line("var array = [T]()") - writer.line("var i: Int32 = 0") - writer.line("while i < count {") - writer.indent() - writer.line("var signature = elementSignature") - writer.line("if elementSignature == 0 {") - writer.indent() - writer.line("if let unboxedSignature = reader.readInt32() {") - writer.indent() - writer.line("signature = unboxedSignature") - writer.dedent() - writer.line("}") - writer.line("else {") - writer.indent() - writer.line("return nil") - writer.dedent() - writer.line("}") - writer.dedent() - writer.line("}") - writer.line("if let item = \(structName).parse(reader, signature: signature) as? T {") - writer.indent() - writer.line("array.append(item)") - writer.dedent() - writer.line("}") - writer.line("else {") - writer.indent() - writer.line("return nil") - writer.dedent() - writer.line("}") - writer.line("i += 1") - writer.dedent() - writer.line("}") - writer.line("return array") - writer.dedent() - writer.line("}") - writer.line("return nil") - writer.dedent() - writer.line("}") - writer.line() - - // public static func serializeObject - writer.line("public static func serializeObject(_ object: Any, buffer: Buffer, boxed: Swift.Bool) {") - writer.indent() - writer.line("switch object {") - for type in sortedTypes { - writer.line("case let _1 as \(structName).\(type.name):") - writer.indent() - writer.line("_1.serialize(buffer, boxed)") - writer.dedent() - } - writer.line("default:") - writer.indent() - writer.line("break") - writer.dedent() - writer.line("}") - writer.dedent() - writer.line("}") - writer.line() - - // Nested public enum { ... } for each type - for type in sortedTypes { - try emitLayeredType(writer: &writer, apiPrefix: apiPrefix, structName: structName, type: type, typeMap: typeMap) - } - - writer.dedent() - writer.line("}") // close public struct - - return (filename, writer.output()) -} -``` - -- [ ] **Step 2: Add `containsInt256` helper** - -Insert directly below `generateLayered` (or above it, before `private static func generateFieldParsing`): - -```swift -private static func containsInt256(_ type: Resolver.TypeReference) -> Bool { - switch type { - case .int256: - return true - case .bareVector(let element), .boxedVector(let element): - return containsInt256(element) - case .int32, .int64, .double, .bytes, .string, .bool, .boolTrue, .bareConstructor, .boxedType: - return false - } -} -``` - -- [ ] **Step 3: Add `emitLayeredType` helper** - -Insert directly below `containsInt256`. This emits a single nested `public enum { ... }` with inline-args cases, a `serialize(_:_:)` method, and `fileprivate parse_*` methods. It mirrors the existing `generate`/`generateImplFile` logic for the type body but: -- renders with `useStructPattern = false` (no `Cons_*` wrapper) directly, -- drops `TypeConstructorDescription` conformance, -- drops the `descriptionFields()` method, -- uses `fileprivate` (not `public`) for `parse_*`, -- nests inside the outer struct writer's indent rather than using a `public extension`: - -```swift -private static func emitLayeredType( - writer: inout CodeWriter, - apiPrefix: String, - structName: String, - type: Resolver.SumType, - typeMap: [QualifiedName: Resolver.SumType] -) throws { - let sortedConstructors = type.constructors.values.sorted(by: { $0.name < $1.name }) - - let indirectPrefix = try type.hasDirectReference(to: [type], typeMap: typeMap) ? "indirect " : "" - writer.line("\(indirectPrefix)public enum \(type.name.value) {") - writer.indent() - - // case () -- inline-args shape - for constructor in sortedConstructors { - var argumentsString = "" - for argument in constructor.arguments { - if case .boolTrue = argument.type { continue } - if !argumentsString.isEmpty { argumentsString.append(", ") } - argumentsString.append(argument.name.camelCased) - argumentsString.append(": ") - // NOTE: layered generator uses structName (e.g. "SecretApi8") as the "apiPrefix" - // for nested-type references, because nested types live inside the struct. - argumentsString.append(typeReferenceRepresentation(structName, argument.type)) - if argument.condition != nil { argumentsString.append("?") } - } - writer.line("case \(constructor.name.value)\(argumentsString.isEmpty ? "" : "(\(argumentsString))")") - } - writer.line() - - // public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) - writer.line("public func serialize(_ buffer: Buffer, _ boxed: Swift.Bool) {") - writer.indent() - writer.line("switch self {") - for constructor in sortedConstructors { - var bindString = "" - for argument in constructor.arguments { - if case .boolTrue = argument.type { continue } - if !bindString.isEmpty { bindString.append(", ") } - bindString.append("let ") - bindString.append(argument.name.camelCasedAndEscaped) - } - writer.line("case .\(constructor.name.value)\(bindString.isEmpty ? "" : "(\(bindString))"):") - writer.indent() - writer.line("if boxed {") - writer.indent() - writer.line("buffer.appendInt32(\(Int32(bitPattern: constructor.id)))") - writer.dedent() - writer.line("}") - - for argument in constructor.arguments { - if case .boolTrue = argument.type { continue } - var argumentAccessor = "\(argument.name.camelCasedAndEscaped)" - if let condition = argument.condition { - writer.line("if Int(\(condition.fieldName)) & Int(1 << \(condition.bitIndex)) != 0 {") - writer.indent() - argumentAccessor.append("!") - generateFieldSerialization(writer: &writer, argument: argument, argumentAccessor: argumentAccessor) - writer.dedent() - writer.line("}") - } else { - generateFieldSerialization(writer: &writer, argument: argument, argumentAccessor: argumentAccessor) - } - } - writer.line("break") - writer.dedent() - } - writer.line("}") - writer.dedent() - writer.line("}") - writer.line() - - // fileprivate static func parse_(_ reader: BufferReader) -> ? - for constructor in sortedConstructors { - writer.line("fileprivate static func parse_\(constructor.name.value)(_ reader: BufferReader) -> \(type.name.value)? {") - writer.indent() - if constructor.arguments.contains(where: { if case .boolTrue = $0.type { return false } else { return true } }) { - var argumentIndex = 0 - var argumentCheckString = "" - var argumentCollectionString = "" - for argument in constructor.arguments { - if case .boolTrue = argument.type { continue } - - writer.line("var _\(argumentIndex + 1): \(typeReferenceRepresentation(structName, argument.type))?") - - if let condition = argument.condition { - guard let fieldIndex = constructor.arguments.filter({ if case .boolTrue = $0.type { return false } else { return true } }).firstIndex(where: { $0.name == condition.fieldName }) else { - throw CodeGenerationError(text: "Condition field \(condition.fieldName) not found") - } - writer.line("if Int(_\(fieldIndex + 1)!) & Int(1 << \(condition.bitIndex)) != 0 {") - writer.indent() - try generateFieldParsing(apiPrefix: structName, writer: &writer, typeMap: typeMap, argument: argument, argumentAccessor: "_\(argumentIndex + 1)") - writer.dedent() - writer.line("}") - } else { - try generateFieldParsing(apiPrefix: structName, writer: &writer, typeMap: typeMap, argument: argument, argumentAccessor: "_\(argumentIndex + 1)") - } - - if !argumentCheckString.isEmpty { argumentCheckString.append(" && ") } - argumentCheckString.append("_c\(argumentIndex + 1)") - - if !argumentCollectionString.isEmpty { argumentCollectionString.append(", ") } - argumentCollectionString.append("\(argument.name.camelCased): _\(argumentIndex + 1)") - if argument.condition == nil { argumentCollectionString.append("!") } - - argumentIndex += 1 - } - - var checkIndex = 0 - for argument in constructor.arguments { - if case .boolTrue = argument.type { continue } - if let condition = argument.condition { - guard let fieldIndex = constructor.arguments.filter({ if case .boolTrue = $0.type { return false } else { return true } }).firstIndex(where: { $0.name == condition.fieldName }) else { - throw CodeGenerationError(text: "Condition field \(condition.fieldName) not found") - } - writer.line("let _c\(checkIndex + 1) = (Int(_\(fieldIndex + 1)!) & Int(1 << \(condition.bitIndex)) == 0) || _\(checkIndex + 1) != nil") - } else { - writer.line("let _c\(checkIndex + 1) = _\(checkIndex + 1) != nil") - } - checkIndex += 1 - } - - writer.line("if \(argumentCheckString) {") - writer.indent() - writer.line("return \(structName).\(type.name).\(constructor.name.value)\(argumentCollectionString.isEmpty ? "" : "(\(argumentCollectionString))")") - writer.dedent() - writer.line("}") - writer.line("else {") - writer.indent() - writer.line("return nil") - writer.dedent() - writer.line("}") - } else { - writer.line("return \(structName).\(type.name).\(constructor.name.value)") - } - writer.dedent() - writer.line("}") - } - - writer.dedent() - writer.line("}") - writer.line() -} -``` - -**IMPORTANT:** `typeReferenceRepresentation`, `generateFieldSerialization`, and `generateFieldParsing` take an `apiPrefix` parameter that they inject as a prefix on type names (e.g. `"Api.ChatFull"`). For layered output, the prefix becomes the per-layer struct name (`"SecretApi8"`), so inline-args like `media: SecretApi8.DecryptedMessageMedia` render correctly. We pass `structName` (not `apiPrefix`) to these helpers inside the layered emitter. - -Also: `camelCasedAndEscaped` is a private String extension at the top of `CodeGeneration.swift`. The layered emitter uses it as-is — no duplication. - -- [ ] **Step 4: Verify CodeGeneration.swift compiles** - -Run: `cd build-system/SwiftTL && swift build 2>&1 | head -50` -Expected: only `main.swift` errors (unchanged in this task). Any error inside `CodeGeneration.swift` itself means the emitter has a syntax/type issue — fix before proceeding. - -- [ ] **Step 5: Commit** - -```bash -cd /Users/isaac/build/telegram/telegram-ios -git add build-system/SwiftTL/Sources/SwiftTL/CodeGeneration.swift -git commit -m "$(cat <<'EOF' -SwiftTL: add CodeGenerator.generateLayered for per-layer output - -Emits one {apiPrefix}Layer{N}.swift file per layer: file-scope -dispatch table, public struct {apiPrefix}{N} with parse/parseVector/ -serializeObject, nested public enums for each sum type using the -inline-args shape. Int256 dispatch entry emitted only when a layer's -constructors reference it. Reuses typeReferenceRepresentation / -generateFieldSerialization / generateFieldParsing unchanged, passing -the struct name as the apiPrefix so nested type refs render correctly. - -Co-Authored-By: Claude Opus 4.7 (1M context) -EOF -)" -``` - ---- - -### Task 4: Wire `main.swift` to branch on `ParsedSchema` - -**Files:** -- Modify: `build-system/SwiftTL/Sources/SwiftTL/main.swift:47-98` - -**Goal:** Update the top-level `do { ... }` block to pattern-match on `ParsedSchema`. Flat path uses today's body unchanged; layered path iterates `resolveLayeredTypes` output and calls `generateLayered` once per layer. - -- [ ] **Step 1: Replace the `do { ... } catch let e { ... }` block** - -Replace the existing block from line 47 (`do {`) to line 98 (the closing `}` of the catch) with: - -```swift -do { - let parsedSchema = try DescriptionParser.parse(data: data) - - try FileManager.default.createDirectory(at: URL(fileURLWithPath: outputDirectoryPath), withIntermediateDirectories: true, attributes: nil) - - switch parsedSchema { - case let .flat(constructors, functions): - let resolvedTypes = try Resolver.resolveTypes(constructors: constructors) - var resolvedFunctions = try Resolver.resolveFunctions(types: resolvedTypes, functionDescriptions: functions) - - resolvedFunctions.append(Resolver.Function(name: QualifiedName(namespace: "help", value: "test"), id: 0xc0e202f7, arguments: [], result: .boxedType(QualifiedName(namespace: nil, value: "Bool")))) - - var constructorOrder: [(typeName: QualifiedName, constructorName: String)] = [] - var typeOrder: [(types: [(typeName: QualifiedName, constructorNames: [String])], functions: [QualifiedName])] = [] - - let sortedTypes = resolvedTypes.sorted(by: { $0.name < $1.name }) - - for type in sortedTypes { - for constructor in type.constructors.values.sorted(by: { $0.name < $1.name }) { - constructorOrder.append((type.name, constructor.name.value)) - } - } - - var totalConstructorCount = 0 - var currentConstructorCount = 0 - for type in sortedTypes { - if typeOrder.isEmpty || currentConstructorCount >= 32 { - typeOrder.append(([], [])) - currentConstructorCount = 0 - } - typeOrder[typeOrder.count - 1].types.append((type.name, type.constructors.values.sorted(by: { $0.name < $1.name }).map(\.name.value))) - currentConstructorCount += type.constructors.count - totalConstructorCount += type.constructors.count - if totalConstructorCount > 40 { } - } - - typeOrder.append(([], [])) - for function in resolvedFunctions.sorted(by: { $0.name < $1.name }) { - typeOrder[typeOrder.count - 1].functions.append(function.name) - } - - let generatedFiles = try CodeGenerator.generate(apiPrefix: apiPrefix, types: resolvedTypes, functions: resolvedFunctions, constructorOrder: constructorOrder, typeOrder: typeOrder) - - for (name, fileData) in generatedFiles { - let filePath = URL(fileURLWithPath: outputDirectoryPath).appendingPathComponent(name).path - let _ = try? FileManager.default.removeItem(atPath: filePath) - try fileData.write(toFile: filePath, atomically: true, encoding: .utf8) - } - - case let .layered(layers): - let resolvedLayers = try Resolver.resolveLayeredTypes(layers: layers) - for (layerNumber, types) in resolvedLayers { - let (filename, source) = try CodeGenerator.generateLayered(apiPrefix: apiPrefix, layerNumber: layerNumber, types: types) - let filePath = URL(fileURLWithPath: outputDirectoryPath).appendingPathComponent(filename).path - let _ = try? FileManager.default.removeItem(atPath: filePath) - try source.write(toFile: filePath, atomically: true, encoding: .utf8) - } - } -} catch let e { - print("\(e)") -} -``` - -Note the flat branch body is the same 40-odd lines that were in the original `do`, lightly reindented. The `createDirectory` call is hoisted above the switch since both branches need it. - -- [ ] **Step 2: Verify SwiftTL builds** - -Run: `cd build-system/SwiftTL && swift build 2>&1` -Expected: `Build complete!` with no errors. - -- [ ] **Step 3: Dry-run layered generation on secret_scheme.tl** - -```bash -cd /Users/isaac/build/telegram/telegram-ios/build-system/SwiftTL -rm -rf /tmp/swifttl-layered-out -swift run SwiftTL /Users/isaac/build/telegram/telegram-ios-shared/tools/secret_scheme.tl /tmp/swifttl-layered-out --api-prefix=SecretApi -ls /tmp/swifttl-layered-out/ -``` - -Expected output: 11 files named `SecretApiLayer{8,17,20,23,45,46,66,73,101,143,144}.swift`. If any are missing or extra, inspect the parser's layer-marker handling. If the tool errors, the error message should point at the offending layer or constructor. - -- [ ] **Step 4: Dry-run flat generation on swift_scheme.tl (regression check)** - -```bash -cd /Users/isaac/build/telegram/telegram-ios/build-system/SwiftTL -rm -rf /tmp/swifttl-flat-out -swift run SwiftTL /Users/isaac/build/telegram/telegram-ios-shared/tools/swift_scheme.tl /tmp/swifttl-flat-out -ls /tmp/swifttl-flat-out/ -diff -q /tmp/swifttl-flat-out /Users/isaac/build/telegram/telegram-ios/submodules/TelegramApi/Sources/ 2>&1 | grep -E "^(Only in|Files)" | head -``` - -Expected: 6 files (`Api0.swift` through `Api5.swift`). The diff against `submodules/TelegramApi/Sources/` should show only "Only in submodules" entries for non-`Api*.swift` files (e.g. `SecretApiLayer*.swift`, `Api+*.swift` helpers). `Api0.swift`-`Api5.swift` must either be identical or show only trivially-different content — any structural diff would indicate a regression in the flat pipeline that must be fixed before proceeding. - -- [ ] **Step 5: Commit** - -```bash -cd /Users/isaac/build/telegram/telegram-ios -git add build-system/SwiftTL/Sources/SwiftTL/main.swift -git commit -m "$(cat <<'EOF' -SwiftTL: main.swift branches on ParsedSchema - -Flat schemas keep the existing generate(...) pipeline. Layered -schemas iterate resolveLayeredTypes and write one -{apiPrefix}Layer{N}.swift per layer via generateLayered. - -Co-Authored-By: Claude Opus 4.7 (1M context) -EOF -)" -``` - ---- - -### Task 5: Regenerate `SecretApiLayer*.swift` and verify full project build - -**Files:** -- Overwrite: `submodules/TelegramApi/Sources/SecretApiLayer{8,46,73,101,144}.swift` (existing, hand-written) -- Create: `submodules/TelegramApi/Sources/SecretApiLayer{17,20,23,45,66,143}.swift` (new) - -**Goal:** Regenerate all 11 layer files using the new SwiftTL and confirm the entire iOS project still compiles. Downstream consumers (`ManagedSecretChatOutgoingOperations.swift`, `ProcessSecretChatIncomingDecryptedOperations.swift`) already reference `SecretApi{8,46,73,101,144}..` symbols; they must continue to resolve. - -- [ ] **Step 1: Pre-flight — snapshot current state of `submodules/TelegramApi/Sources/SecretApiLayer*.swift`** - -```bash -cd /Users/isaac/build/telegram/telegram-ios -ls submodules/TelegramApi/Sources/SecretApiLayer*.swift -git log --oneline -5 -- submodules/TelegramApi/Sources/SecretApiLayer*.swift -``` - -Expected: 5 files (`SecretApiLayer{8,46,73,101,144}.swift`), each tracked by git. If there are uncommitted modifications to any of these files, stop and investigate — they should be clean before regeneration. - -- [ ] **Step 2: Regenerate into a staging directory** - -```bash -cd /Users/isaac/build/telegram/telegram-ios/build-system/SwiftTL -rm -rf /tmp/secretapi-staging -swift run SwiftTL /Users/isaac/build/telegram/telegram-ios-shared/tools/secret_scheme.tl /tmp/secretapi-staging --api-prefix=SecretApi -ls /tmp/secretapi-staging/ -``` - -Expected: 11 files, one per layer. - -- [ ] **Step 3: Spot-check layer 8 output against the hand-written file** - -```bash -diff /tmp/secretapi-staging/SecretApiLayer8.swift /Users/isaac/build/telegram/telegram-ios/submodules/TelegramApi/Sources/SecretApiLayer8.swift | head -80 -``` - -Expected: cosmetic differences (whitespace, maybe case ordering) but each enum case name must appear in both; each `buffer.appendInt32()` must have the same ID in both files for the same constructor; the `parsers` dict must contain the same set of `dict[]` entries. If the generator added a `Bool` type (from the pre-marker `boolFalse`/`boolTrue`), that's an expected addition per the spec — not a failure. - -If any *constructor ID* or *enum case name* differs for an existing constructor, STOP. That means either the schema's legacy hand-written content drifted from the `.tl` source (spec risk section covers this — schema wins) or the generator has a bug. Decide on the fly: if the legacy hand-written file has a typo'd ID, the regenerated file is correct and should land as-is. If the generator has a bug, fix before proceeding. - -- [ ] **Step 4: Copy staging output into place** - -```bash -cd /Users/isaac/build/telegram/telegram-ios -rm -f submodules/TelegramApi/Sources/SecretApiLayer*.swift -cp /tmp/secretapi-staging/SecretApiLayer*.swift submodules/TelegramApi/Sources/ -ls submodules/TelegramApi/Sources/SecretApiLayer*.swift -``` - -Expected: 11 files, one per layer (5 overwrites + 6 new). - -- [ ] **Step 5: Full Bazel build** - -```bash -cd /Users/isaac/build/telegram/telegram-ios -source ~/.zshrc 2>/dev/null -python3 build-system/Make/Make.py build --continueOnError 2>&1 | tee /tmp/swifttl-wave-build.log | tail -40 -``` - -Expected: build completes with no errors. The `Telegram.ipa` target builds successfully. If compile errors surface, they will most likely be in `ManagedSecretChatOutgoingOperations.swift` or `ProcessSecretChatIncomingDecryptedOperations.swift` — cases where a specific `SecretApi{N}..` symbol the consumer expects doesn't appear in the regenerated file. Triage: - -- If the missing symbol is a constructor present in `secret_scheme.tl` under some layer: verify the resolver captured it correctly in the snapshot for that layer. Likely a bug in `resolveLayeredTypes` (e.g. pre-marker handling) or in the emitter (e.g. case-name mis-generation). Fix in SwiftTL and regenerate. -- If the missing symbol names a constructor NOT in `secret_scheme.tl` under that layer's cumulative set: the hand-written file and the consumer code drifted from the schema. Not a generator bug. Escalate with the user before modifying consumer code. - -- [ ] **Step 6: Commit regenerated files** - -```bash -cd /Users/isaac/build/telegram/telegram-ios -git add submodules/TelegramApi/Sources/SecretApiLayer*.swift -git status --short submodules/TelegramApi/Sources/ -git commit -m "$(cat <<'EOF' -TelegramApi: regenerate SecretApiLayer*.swift via SwiftTL - -Replaces the hand-written layer 8/46/73/101/144 files with SwiftTL -output and adds the previously-unpublished layers 17/20/23/45/66/143. -Per-layer struct names (SecretApi8, SecretApi46, ...) and public -enum case signatures are unchanged; downstream consumers -(ManagedSecretChatOutgoingOperations, ProcessSecretChatIncomingDecryptedOperations) -compile unchanged. - -BUILD uses glob("Sources/**/*.swift") so no BUILD update required. - -Co-Authored-By: Claude Opus 4.7 (1M context) -EOF -)" -``` - ---- - -### Task 6: Final flat-path regression check - -**Files:** none modified — this is a verification-only task. - -**Goal:** Confirm the flat pipeline is structurally unchanged — `Api*.swift` files regenerated from `swift_scheme.tl` match what's currently committed in `submodules/TelegramApi/Sources/`. - -- [ ] **Step 1: Regenerate `Api*.swift` into staging** - -```bash -cd /Users/isaac/build/telegram/telegram-ios/build-system/SwiftTL -rm -rf /tmp/api-flat-staging -swift run SwiftTL /Users/isaac/build/telegram/telegram-ios-shared/tools/swift_scheme.tl /tmp/api-flat-staging -ls /tmp/api-flat-staging/ -``` - -Expected: `Api0.swift` through `Api5.swift` (exact count depends on the schema's constructor count; 6 files is the current count). - -- [ ] **Step 2: Diff against committed flat output** - -```bash -for f in /tmp/api-flat-staging/Api*.swift; do - base=$(basename "$f") - diff -q "$f" "/Users/isaac/build/telegram/telegram-ios/submodules/TelegramApi/Sources/$base" || echo "DIFFERS: $base" -done -``` - -Expected: every file identical to the committed version, or at most whitespace differences. Any structural diff (different enum cases, different IDs, different method signatures) is a regression in the flat pipeline introduced by this wave's edits — must be fixed. - -- [ ] **Step 3: (If no diff) confirm in conversation** - -If step 2 reports all files identical, the wave is complete — note in the PR description / commit log that the flat pipeline is verified unchanged. No further commit. - -- [ ] **Step 4: (If diff found) investigate and fix** - -If diffs exist: most likely cause is that a shared helper in `CodeGeneration.swift` was touched with an effect that cascades into `generate(...)`. Revisit Task 3 and ensure all edits added new methods only, with no modifications to `generate`, `generateMainFile`, `generateImplFile`, or the top-level `CodeGenerator` API. Fix and re-run step 2. - ---- - -## Out-of-scope follow-ups (do not execute in this plan) - -Documented in the spec; not part of this plan's delivered scope. - -- Update `/Users/isaac/build/telegram/telegram-ios-shared/tools/generate_and_copy_scheme.sh` to `rm -f` and `cp` the `SecretApiLayer*.swift` output alongside the existing `Api*.swift` copy step. Lives in a sibling repo; the user handles when ready. -- Delete `build-system/SwiftTL/Sources/SwiftTL/LegacyOrderParser.swift` was ALREADY deleted in the uncommitted working tree (per `git status` at plan writing time — `D Sources/SwiftTL/LegacyOrderParser.swift`). Not in this plan; the deletion can land with Task 1 if still convenient or as a separate cleanup. diff --git a/docs/superpowers/plans/2026-04-21-textstyleeditscreen-caret-tracking.md b/docs/superpowers/plans/2026-04-21-textstyleeditscreen-caret-tracking.md deleted file mode 100644 index d404d91583..0000000000 --- a/docs/superpowers/plans/2026-04-21-textstyleeditscreen-caret-tracking.md +++ /dev/null @@ -1,351 +0,0 @@ -# TextStyleEditScreen caret-tracking Implementation Plan - -> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. - -**Goal:** On every text change inside `TextStyleEditScreen`, scroll the enclosing `ResizableSheetComponent` scroll view so the caret in the active `ListMultilineTextFieldItemComponent` stays visible ~24pt above the keyboard/bottom button area. - -**Architecture:** Single-file change in `submodules/TelegramUI/Components/TextProcessingScreen/Sources/TextStyleEditScreen.swift`. Give each text field a `ListMultilineTextFieldItemComponent.Tag`; at the end of `TextStyleEditContentComponent.View.update(...)`, read `TextFieldComponent.AnimationHint` off the transition's userData; on a `.textChanged` hint, resolve the editing field, compute the caret rect via `UITextInput.caretRect(for:)`, walk `superview` to the enclosing `UIScrollView`, and adjust its `bounds.origin.y` using the direct-assign + additive-animate pattern from `ComposePollScreen.swift:2873-2895`. - -**Tech Stack:** Swift, UIKit, Telegram's ComponentFlow (`ComponentView`, `ComponentTransition`, `TextFieldComponent.AnimationHint`), Bazel via `Make.py`. No unit tests exist in this project — verification is a full build + manual smoke test per `CLAUDE.md`. - -**Reference spec:** `docs/superpowers/specs/2026-04-21-textstyleeditscreen-caret-tracking-design.md`. - -**Reference precedent:** `submodules/TelegramUI/Components/ComposePollScreen/Sources/ComposePollScreen.swift:2733-2895` (field-bounds variant of this same pattern). - ---- - -## File Structure - -Only one file is touched: - -- **Modify:** `submodules/TelegramUI/Components/TextProcessingScreen/Sources/TextStyleEditScreen.swift` - - Add two stored `ListMultilineTextFieldItemComponent.Tag` properties on `TextStyleEditContentComponent.View`. - - Thread those tags into the two existing `ListMultilineTextFieldItemComponent(...)` constructions inside `update(...)`. - - Add a private `recenterCaret(hintView:transition:)` method on `TextStyleEditContentComponent.View`. - - Call `recenterCaret` from the tail of `update(...)` when the transition carries a `.textChanged` `TextFieldComponent.AnimationHint`. - -No other files are modified. Public API of `ResizableSheetComponent`, `ListMultilineTextFieldItemComponent`, and `TextFieldComponent` is used as-is. - ---- - -## Task 1: Add field tags and wire them into the two text field constructors - -**Files:** -- Modify: `submodules/TelegramUI/Components/TextProcessingScreen/Sources/TextStyleEditScreen.swift` (around lines 64-77, 277, 322) - -- [ ] **Step 1: Add the two `Tag` stored properties to `TextStyleEditContentComponent.View`** - -In `TextStyleEditScreen.swift`, locate the stored-property block at the top of `final class View: UIView` (lines 64-77). Below `private let linkOption = ComponentView()` (line 76) add: - -```swift - private let titleFieldTag = ListMultilineTextFieldItemComponent.Tag() - private let textFieldTag = ListMultilineTextFieldItemComponent.Tag() -``` - -Keep them above the `override init(frame: CGRect)` at line 78. - -- [ ] **Step 2: Pass `self.titleFieldTag` into the title field constructor** - -Locate the `ListMultilineTextFieldItemComponent(...)` construction for the title section (starts at line 260). Its last argument currently reads `tag: nil` (line 277). Change it to: - -```swift - tag: self.titleFieldTag -``` - -- [ ] **Step 3: Pass `self.textFieldTag` into the prompt field constructor** - -Locate the second `ListMultilineTextFieldItemComponent(...)` construction for the text section (starts at line 304). Its last argument currently reads `tag: nil` (line 322). Change it to: - -```swift - tag: self.textFieldTag -``` - -- [ ] **Step 4: Verify the change compiles** - -Run: - -```bash -source ~/.zshrc 2>/dev/null; python3 build-system/Make/Make.py --overrideXcodeVersion \ - --cacheDir ~/telegram-bazel-cache \ - build \ - --configurationPath build-system/appstore-configuration.json \ - --gitCodesigningRepository git@gitlab.com:peter-iakovlev/fastlanematch.git \ - --gitCodesigningType development --gitCodesigningUseCurrent --buildNumber=1 --configuration=debug_sim_arm64 \ - --continueOnError -``` - -Expected: build succeeds (or the same pre-existing failures unrelated to `TextStyleEditScreen.swift`). A failure in `TextStyleEditScreen.swift` means the tag types or property names are wrong — fix before moving on. - -- [ ] **Step 5: Do not commit yet** — tag wiring is inert without the recenter logic. Defer commit to Task 4. - ---- - -## Task 2: Add the `recenterCaret` helper - -**Files:** -- Modify: `submodules/TelegramUI/Components/TextProcessingScreen/Sources/TextStyleEditScreen.swift` - -- [ ] **Step 1: Add the method on `TextStyleEditContentComponent.View`** - -Inside `final class View: UIView` (the class that starts at line 64), directly **before** the `func update(component:availableSize:state:environment:transition:)` method (line 86), add this private method. It covers steps 1–6 from the design spec (locate field view → caret rect → scroll view → scroll view coordinates → visible region → adjust bounds). - -```swift - private func recenterCaret(hintView: UIView, transition: ComponentTransition) { - var fieldView: ListMultilineTextFieldItemComponent.View? - var ancestor: UIView? = hintView - while let current = ancestor { - if let candidate = current as? ListMultilineTextFieldItemComponent.View { - fieldView = candidate - break - } - ancestor = current.superview - } - guard let fieldView else { - return - } - if !(fieldView.matches(tag: self.titleFieldTag) || fieldView.matches(tag: self.textFieldTag)) { - return - } - guard let inputTextView = fieldView.textFieldView?.inputTextView else { - return - } - let caretPosition = inputTextView.selectedTextRange?.end ?? inputTextView.endOfDocument - let caretRect = inputTextView.caretRect(for: caretPosition) - if caretRect.isNull || caretRect.isInfinite { - return - } - - var scrollAncestor: UIView? = self.superview - var scrollView: UIScrollView? - while let current = scrollAncestor { - if let candidate = current as? UIScrollView { - scrollView = candidate - break - } - scrollAncestor = current.superview - } - guard let scrollView, let environment = self.environment else { - return - } - - let caretInScroll = inputTextView.convert(caretRect, to: scrollView) - - let bottomActionAreaHeight: CGFloat = 60.0 - let caretTopInset: CGFloat = 24.0 - let caretBottomInset: CGFloat = 24.0 - let visibleTop = scrollView.bounds.minY + caretTopInset - let visibleBottom = scrollView.bounds.maxY - environment.inputHeight - bottomActionAreaHeight - caretBottomInset - - let previousBounds = scrollView.bounds - var newBounds = previousBounds - if caretInScroll.maxY > visibleBottom { - newBounds.origin.y += (caretInScroll.maxY - visibleBottom) - } else if caretInScroll.minY < visibleTop { - newBounds.origin.y -= (visibleTop - caretInScroll.minY) - } - let maxOriginY = max(0.0, scrollView.contentSize.height - scrollView.bounds.height) - newBounds.origin.y = min(max(0.0, newBounds.origin.y), maxOriginY) - - if newBounds != previousBounds { - scrollView.bounds = newBounds - if !transition.animation.isImmediate { - let offsetY = previousBounds.origin.y - newBounds.origin.y - transition.animateBoundsOrigin(view: scrollView, from: CGPoint(x: 0.0, y: offsetY), to: CGPoint(), additive: true) - } - } - } -``` - -Notes on key choices: - -- `bottomActionAreaHeight: 60.0` = `52.0` (bottom item height — see `ResizableSheetComponent.swift:750`) + `8.0` gap above the button (matches `ResizableSheetComponent.swift:732`). -- `caretTopInset` / `caretBottomInset` (both `24.0`) provide the "small inset" biased positioning the user confirmed. -- The hint's view ancestor walk is used (rather than `self.titleFieldTag`'s / `self.textFieldTag`'s views directly) because the hint already carries the `TextFieldComponent.View` that actually fired the change — this is safer than guessing which of our two fields is editing when both may have briefly claimed focus. -- `transition.animateBoundsOrigin` is the proven pattern from `ComposePollScreen.swift:2891-2894`; `transition.animation.isImmediate` gating avoids an unnecessary animation when the transition is immediate. -- Silent bails on missing scroll view or text view keep the code robust against host refactors (they should never happen in normal operation). - -- [ ] **Step 2: Verify compilation** - -Re-run the build command from Task 1 Step 4. Expected: the method compiles cleanly. Common failure modes to watch for: - -- `cannot find 'ListMultilineTextFieldItemComponent.View' in scope` → wrong type path; check the import and the class name in `ListMultilineTextFieldItemComponent.swift:196` (it is the nested `View` class of `ListMultilineTextFieldItemComponent`). -- `value of type 'TextFieldComponent.View' has no member 'inputTextView'` → the property is defined at `TextFieldComponent.swift:359`; ensure you're reading `fieldView.textFieldView?.inputTextView`, not reaching into private internals. -- `'ComponentTransition' has no member 'animateBoundsOrigin'` → this is a ComponentFlow method; grep confirms it exists and is used at `ComposePollScreen.swift:2893`. If missing, the import line (`import ComponentFlow`) at file top is the place to check. - -- [ ] **Step 3: Do not commit yet** — the helper is unreferenced and unused. Defer commit to Task 4. - ---- - -## Task 3: Hook up the `.textChanged` trigger in `update(...)` - -**Files:** -- Modify: `submodules/TelegramUI/Components/TextProcessingScreen/Sources/TextStyleEditScreen.swift` - -- [ ] **Step 1: Add the trigger at the tail of `update(...)`** - -At the end of `func update(component:availableSize:state:environment:transition:)` on `TextStyleEditContentComponent.View`, locate lines 455-460: - -```swift - contentHeight += 104.0 - - let _ = alphaTransition - - return CGSize(width: availableSize.width, height: contentHeight) -``` - -Insert the trigger block **before** `return`: - -```swift - contentHeight += 104.0 - - let _ = alphaTransition - - if let hint = transition.userData(TextFieldComponent.AnimationHint.self), case .textChanged = hint.kind, let hintView = hint.view { - self.recenterCaret(hintView: hintView, transition: transition) - } - - return CGSize(width: availableSize.width, height: contentHeight) -``` - -Do NOT match on `.textFocusChanged` — per the user's requirement, scrolling fires only on text edits. - -- [ ] **Step 2: Ensure `TextFieldComponent` is importable** - -`TextFieldComponent.AnimationHint` is vended from the `TextFieldComponent` module. Check the file's import list at the top (lines 1-25). `TextFieldComponent` is used transitively today via `ListMultilineTextFieldItemComponent`, but the type is only re-exposed if we explicitly import it. - -Locate the import block (around lines 1-25). If `import TextFieldComponent` is not present, add it alphabetically — for example, between `import ResizableSheetComponent` and `import TelegramCore`: - -```swift -import TextFieldComponent -``` - -If it is already present, skip this sub-step. - -- [ ] **Step 3: Ensure the BUILD dep is present** - -Locate the sibling `BUILD` file: - -```bash -cat submodules/TelegramUI/Components/TextProcessingScreen/BUILD -``` - -Look for `//submodules/TelegramUI/Components/TextFieldComponent:TextFieldComponent` in the `deps` list. If present, skip to the next step. If absent, add it to the `deps` array (preserving alphabetical order where the BUILD file follows that convention). For example: - -``` - "//submodules/TelegramUI/Components/TextFieldComponent:TextFieldComponent", -``` - -- [ ] **Step 4: Verify compilation** - -Re-run the build command from Task 1 Step 4. - -Expected: clean build for `TextStyleEditScreen.swift` and its host module (`TextProcessingScreen`). Common failure modes: - -- `cannot find 'TextFieldComponent' in scope` → missing `import TextFieldComponent` (fix in Step 2). -- Bazel link error naming `TextFieldComponent` → missing BUILD dep (fix in Step 3). -- `instance method requires the types 'X' and 'Y' to be equivalent` on the `case .textChanged = hint.kind` line → the `case let` pattern binding; verify with `grep -n 'case \\.textChanged' submodules/TelegramUI/Components/TextFieldComponent/Sources/TextFieldComponent.swift` that the case is payload-less (it is, per `TextFieldComponent.swift:95-103` where `Kind` declares `case textChanged` without associated values and `case textFocusChanged(isFocused: Bool)` with one). - -- [ ] **Step 5: Do not commit yet** — verify end-to-end behavior in Task 4 first. - ---- - -## Task 4: Manual smoke test and commit - -**Files:** -- Modify (commit): `submodules/TelegramUI/Components/TextProcessingScreen/Sources/TextStyleEditScreen.swift` -- Possibly modify (commit): `submodules/TelegramUI/Components/TextProcessingScreen/BUILD` - -- [ ] **Step 1: Launch the app on the simulator** - -Run: - -```bash -source ~/.zshrc 2>/dev/null; python3 build-system/Make/Make.py --overrideXcodeVersion \ - --cacheDir ~/telegram-bazel-cache \ - build \ - --configurationPath build-system/appstore-configuration.json \ - --gitCodesigningRepository git@gitlab.com:peter-iakovlev/fastlanematch.git \ - --gitCodesigningType development --gitCodesigningUseCurrent --buildNumber=1 --configuration=debug_sim_arm64 -``` - -Expected: `Telegram.ipa` target built successfully, 0 errors. - -Note: this project has no unit tests; feature correctness for UI changes requires a manual check on device or simulator. Install the built app on the iOS simulator (`xcrun simctl install booted ...` if not done by the build script) and navigate to the AI style-edit sheet — this is typically reached from a chat's AI compose-mode style selector or from Settings, depending on build flavour. If the entry point is unclear, grep for `TextStyleEditScreen(` to find a test harness or the production call site: - -```bash -grep -rn "TextStyleEditScreen(" submodules --include="*.swift" -``` - -- [ ] **Step 2: Smoke test — short content path** - -1. Tap the "Style Name" field. Confirm the keyboard slides up and the "Create" button rides above the keyboard (pre-existing behavior from the earlier `inputHeight` work). -2. Type one character. With short content no scroll should occur; the scroll view should remain at origin zero (visual check: the emoji icon at the top stays visible). - -Pass criterion: no visual regression; the title field is visible and typable. - -- [ ] **Step 3: Smoke test — long prompt path** - -1. Tap the "Instructions" field. -2. Type enough text (or paste a paragraph) to make the prompt field taller than the viewport with the keyboard up. -3. Continue typing so new characters appear at the caret. - -Pass criterion: as each newline is added, the caret stays approximately 24pt above the keyboard/button area. The field's top may scroll out of view — that's expected. - -- [ ] **Step 4: Smoke test — manual-scroll-then-type** - -1. Still in the "Instructions" field with enough content that scroll is possible. -2. Manually drag the sheet content up so the caret is pushed above the visible area. -3. Type one character. - -Pass criterion: the scroll view snaps downward so the caret is visible again, above the keyboard with the configured inset. - -- [ ] **Step 5: Smoke test — edit-mode mid-field tap (non-goal regression check)** - -1. Trigger the screen in edit mode on a style with a long pre-populated prompt (enough text to exceed the viewport). -2. Tap **in the middle** of the prompt so the caret lands off-screen-top (no text change). - -Pass criterion: **no** scroll occurs (this is per the non-goal — we only scroll on text change). A follow-up text edit is expected to trigger a scroll; that is covered by Step 3. - -- [ ] **Step 6: Check for regressions in adjacent flows** - -Briefly exercise: - -1. The emoji-selection sheet (tap the big round emoji area at the top) — must still open, select, and dismiss without issue. -2. The "Add a link to my account" checkbox — toggling still flips the check. -3. The "Delete Style" row (edit mode) — still pushes the confirm alert. - -Pass criterion: all three work as before. - -- [ ] **Step 7: Commit** - -```bash -git add submodules/TelegramUI/Components/TextProcessingScreen/Sources/TextStyleEditScreen.swift -# Only stage the BUILD file if it was modified in Task 3 Step 3: -git status --short submodules/TelegramUI/Components/TextProcessingScreen/BUILD -# If the BUILD file shows up modified, stage it too: -git add submodules/TelegramUI/Components/TextProcessingScreen/BUILD -git commit -m "$(cat <<'EOF' -TextStyleEditScreen: scroll caret into view on text change - -Tag both ListMultilineTextFieldItemComponents and, at the tail of -TextStyleEditContentComponent.View.update(...), read TextFieldComponent. -AnimationHint off the transition userData. On a .textChanged hint, locate -the editing field, compute the caret rect, walk up to the enclosing -ResizableSheetComponent scroll view, and adjust bounds.origin.y so the -caret sits ~24pt above the keyboard/bottom action area. - -Scroll runs only on text edits (not on focus/selection changes) per spec. -Uses the direct-assign + additive-animate pattern from ComposePollScreen. -EOF -)" -``` - -Expected: commit succeeds. The diff is ~50 lines added across one .swift file (and possibly one line added to BUILD). - ---- - -## Out-of-scope / follow-ups - -None planned. The non-goals called out in the spec (scroll on focus change, scroll on selection change, scroll on keyboard show/hide independently of a text edit) are intentional omissions, not deferred work. - -If manual smoke testing reveals that focus-gain keyboard appearance creates a bad UX (user taps a field near the bottom and the keyboard covers it until they type), consider adding back the `.textFocusChanged(isFocused: true)` case in the trigger block. That is a one-line change to the conditional in Task 3 Step 1 and does not require any design iteration. diff --git a/docs/superpowers/plans/2026-04-24-contactlistpeer-engine-peer-migration.md b/docs/superpowers/plans/2026-04-24-contactlistpeer-engine-peer-migration.md deleted file mode 100644 index 8732b7a790..0000000000 --- a/docs/superpowers/plans/2026-04-24-contactlistpeer-engine-peer-migration.md +++ /dev/null @@ -1,944 +0,0 @@ -# Wave 36: `ContactListPeer.peer: Peer → EnginePeer` Implementation Plan - -> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. - -**Goal:** Migrate the public enum case `ContactListPeer.peer(peer: Peer, isGlobal: Bool, participantCount: Int32?)` from the Postbox `Peer` protocol to the TelegramCore `EnginePeer` enum in a single atomic commit. Cascading changes: change `ContactListPeer.indexName` return type from `PeerIndexNameRepresentation` to `EnginePeer.IndexName` (drops 2 `EnginePeer.IndexName(...)` wraps at one call site); rewrite the enum's custom `==` to use `EnginePeer`'s synthesized Equatable; drop 20 outflow `._asPeer()` bridges, 16 inflow `EnginePeer(peer)` wraps; rewrite 2 Postbox-concrete cast chains to EnginePeer case patterns. - -**Architecture:** One atomic commit. The enum-case payload change is necessarily atomic. `ContactListPeer` lives in `submodules/AccountContext/Sources/ContactSelectionController.swift`; 7 consumer files touched in addition. 2 consumer files verified untouched (`ComposeController.swift`, `ChatSendAudioMessageContextPreview.swift`). No new wrappers, no new typealiases. `import Postbox` stays in every touched consumer (follow-up unused-import sweep handles it). - -**Tech Stack:** Swift, Bazel build via Make.py wrapper. No tests — verification is build success + targeted grep checks. - -**Spec:** `docs/superpowers/specs/2026-04-24-contactlistpeer-engine-peer-migration-design.md` - ---- - -## File Structure - -**Modified files (8 expected — 1 definition + 7 consumer. Plus 2 verify-only.)** - -| File | Edits | Categories | -|---|---|---| -| `submodules/AccountContext/Sources/ContactSelectionController.swift` | 3 (case type + indexName return type + `==` body) | α | -| `submodules/ContactListUI/Sources/ContactListNode.swift` | ~21 (12 outflow + 4 inflow + 2 cast rewrites [L182-186, L1968] + 2 IndexName wraps [L517]) | β + δ + φ + ε′ | -| `submodules/ContactListUI/Sources/ContactsController.swift` | 1 (inflow wrap at L294) | δ | -| `submodules/ContactListUI/Sources/ContactsSearchContainerNode.swift` | 7 (3 outflow + 4 inflow) | β + δ | -| `submodules/TelegramUI/Sources/ContactMultiselectionController.swift` | 6 (2 outflow + 4 inflow) | β + δ | -| `submodules/TelegramUI/Sources/ContactMultiselectionControllerNode.swift` | 2 (1 outflow + 1 inflow) | β + δ | -| `submodules/TelegramUI/Sources/ContactSelectionController.swift` | 2 (inflow wraps L517/527) | δ | -| `submodules/TelegramUI/Sources/ContactSelectionControllerNode.swift` | 2 (outflow bridges L160/230) | β | - -**Verify-only (no edits expected):** - -| File | Reason | -|---|---| -| `submodules/TelegramUI/Sources/ComposeController.swift` | Destructures at L120/160 access `.id` only. Same-type access works on EnginePeer. | -| `submodules/TelegramUI/Components/Chat/ChatSendAudioMessageContextPreview/Sources/ChatSendAudioMessageContextPreview.swift` | Only holds `[ContactListPeer]` at collection level; no `.peer` destructures. | - -**EnginePeer enum case mapping (used in cast rewrites):** - -| Postbox concrete | EnginePeer case | -|---|---| -| `TelegramUser` | `.user(TelegramUser)` | -| `TelegramGroup` | `.legacyGroup(TelegramGroup)` | -| `TelegramChannel` | `.channel(TelegramChannel)` | - -**Sites that stay as `._asPeer()` bridges (NOT in wave scope):** - -- `submodules/ContactListUI/Sources/ContactsSearchContainerNode.swift:488, 528, 562` — `canSendMessagesToPeer(peer._asPeer())` / `canSendMessagesToPeer(peer.peer._asPeer())`. `canSendMessagesToPeer(_: Peer)` migration is a deferred future wave. -- `submodules/TelegramUI/Sources/ContactMultiselectionController.swift:171, 201, 748` — `peerTokenTitle(accountPeerId:..., peer: peer._asPeer(), strings:...)`. `peerTokenTitle(peer: Peer)` migration is out of scope. - ---- - -## Task 1: Edit `AccountContext/Sources/ContactSelectionController.swift` — definition - -**Files:** -- Modify: `submodules/AccountContext/Sources/ContactSelectionController.swift` - -Foundational change. Without it, none of the consumer edits compile. - -- [ ] **Step 1.1: Update the case payload type, `indexName` return type, and `==` operator body** - -Edit using the Edit tool: - -```swift -// OLD (lines 61-99) -public enum ContactListPeer: Equatable { - case peer(peer: Peer, isGlobal: Bool, participantCount: Int32?) - case deviceContact(DeviceContactStableId, DeviceContactBasicData) - - public var id: ContactListPeerId { - switch self { - case let .peer(peer, _, _): - return .peer(peer.id) - case let .deviceContact(id, _): - return .deviceContact(id) - } - } - - public var indexName: PeerIndexNameRepresentation { - switch self { - case let .peer(peer, _, _): - return peer.indexName - case let .deviceContact(_, contact): - return .personName(first: contact.firstName, last: contact.lastName, addressNames: [], phoneNumber: "") - } - } - - public static func ==(lhs: ContactListPeer, rhs: ContactListPeer) -> Bool { - switch lhs { - case let .peer(lhsPeer, lhsIsGlobal, lhsParticipantCount): - if case let .peer(rhsPeer, rhsIsGlobal, rhsParticipantCount) = rhs, lhsPeer.isEqual(rhsPeer), lhsIsGlobal == rhsIsGlobal, lhsParticipantCount == rhsParticipantCount { - return true - } else { - return false - } - case let .deviceContact(id, contact): - if case .deviceContact(id, contact) = rhs { - return true - } else { - return false - } - } - } -} -``` - -```swift -// NEW -public enum ContactListPeer: Equatable { - case peer(peer: EnginePeer, isGlobal: Bool, participantCount: Int32?) - case deviceContact(DeviceContactStableId, DeviceContactBasicData) - - public var id: ContactListPeerId { - switch self { - case let .peer(peer, _, _): - return .peer(peer.id) - case let .deviceContact(id, _): - return .deviceContact(id) - } - } - - public var indexName: EnginePeer.IndexName { - switch self { - case let .peer(peer, _, _): - return peer.indexName - case let .deviceContact(_, contact): - return .personName(first: contact.firstName, last: contact.lastName, addressNames: [], phoneNumber: "") - } - } - - public static func ==(lhs: ContactListPeer, rhs: ContactListPeer) -> Bool { - switch lhs { - case let .peer(lhsPeer, lhsIsGlobal, lhsParticipantCount): - if case let .peer(rhsPeer, rhsIsGlobal, rhsParticipantCount) = rhs, lhsPeer == rhsPeer, lhsIsGlobal == rhsIsGlobal, lhsParticipantCount == rhsParticipantCount { - return true - } else { - return false - } - case let .deviceContact(id, contact): - if case .deviceContact(id, contact) = rhs { - return true - } else { - return false - } - } - } -} -``` - -Three changes in this edit: -1. Line 62: `peer: Peer` → `peer: EnginePeer` -2. Line 74: return type `PeerIndexNameRepresentation` → `EnginePeer.IndexName` -3. Line 86 (inside the `==` operator): `lhsPeer.isEqual(rhsPeer)` → `lhsPeer == rhsPeer` - -`EnginePeer.IndexName.personName(first:last:addressNames:phoneNumber:)` has the same labels/types as `PeerIndexNameRepresentation.personName`, so line 79 body is untouched — only its return target enum changes. - -- [ ] **Step 1.2: Verify** - -Run: - -```bash -grep -nE "case peer\(peer:|public var indexName:|\.isEqual\(" submodules/AccountContext/Sources/ContactSelectionController.swift -``` - -Expected output: -- Line 62: `case peer(peer: EnginePeer, ...)` -- Line 74: `public var indexName: EnginePeer.IndexName {` -- No `isEqual(` match on the `==` path (the only remaining occurrences would be unrelated). - -Do not commit yet. - ---- - -## Task 2: Edit `ContactListNode.swift` — largest consumer, multi-category - -**Files:** -- Modify: `submodules/ContactListUI/Sources/ContactListNode.swift` - -Most changes happen here: 12 outflow bridges + 4 inflow wraps + 2 cast chain rewrites + 2 IndexName wrap drops. - -- [ ] **Step 2.1: Drop the 12 outflow `._asPeer()` bridges via `replace_all`** - -All 12 `._asPeer()` bridges at ContactListPeer.peer construction sites follow the shape `._asPeer(), isGlobal:`. Non-construction `._asPeer()` uses in this file (if any) feed other functions and do NOT use this exact substring. - -Pre-flight verify: - -```bash -grep -cE "\._asPeer\(\), isGlobal:" submodules/ContactListUI/Sources/ContactListNode.swift -``` - -Expected: `12`. - -If the count is 12, apply the Edit tool with `replace_all=true`: -- `old_string`: `._asPeer(), isGlobal:` -- `new_string`: `, isGlobal:` - -If the count is not 12, fall back to per-site Edits at lines 632, 690, 701, 747, 765, 1365, 1647, 1656, 1693, 1731, 1942, 1944 using enough surrounding context to make each `old_string` unique. - -- [ ] **Step 2.2: Verify the 12 outflow drops** - -Run: - -```bash -grep -nE "\._asPeer\(\), isGlobal:" submodules/ContactListUI/Sources/ContactListNode.swift -``` - -Expected: zero matches. - -- [ ] **Step 2.3: Drop 2 inflow wraps at L204** - -Read lines 200–210 first to confirm the line text. - -Edit: - -```swift -// OLD (line 204) - itemPeer = .peer(peer: EnginePeer(peer), chatPeer: EnginePeer(peer)) -``` - -```swift -// NEW - itemPeer = .peer(peer: peer, chatPeer: peer) -``` - -- [ ] **Step 2.4: Drop 1 inflow wrap at L252** - -Read lines 248–256 first to confirm. - -Edit: - -```swift -// OLD (line 252) - interaction.openDisabledPeer(EnginePeer(peer), requiresPremiumForMessaging ? .premiumRequired : .generic) -``` - -```swift -// NEW - interaction.openDisabledPeer(peer, requiresPremiumForMessaging ? .premiumRequired : .generic) -``` - -- [ ] **Step 2.5: Drop 1 inflow wrap at L844** - -Read lines 840–848 first to confirm. - -Edit: - -```swift -// OLD (line 844) - if let isPeerEnabled, !isPeerEnabled(EnginePeer(peer)) { -``` - -```swift -// NEW - if let isPeerEnabled, !isPeerEnabled(peer) { -``` - -- [ ] **Step 2.6: Rewrite the L182-186 cast chain to EnginePeer case patterns** - -Read lines 176–200 first. The cast chain is inside the ContactListPeer.peer destructure at line 177. - -Edit: - -```swift -// OLD (lines 182-186) - } else { - if let _ = peer as? TelegramUser { - status = .presence(presence ?? EnginePeer.Presence(status: .longTimeAgo, lastActivity: 0), dateTimeFormat) - } else if let group = peer as? TelegramGroup { - status = .custom(string: NSAttributedString(string: strings.Conversation_StatusMembers(Int32(group.participantCount))), multiline: false, isActive: false, icon: nil) - } else if let channel = peer as? TelegramChannel { -``` - -```swift -// NEW - } else { - if case .user = peer { - status = .presence(presence ?? EnginePeer.Presence(status: .longTimeAgo, lastActivity: 0), dateTimeFormat) - } else if case let .legacyGroup(group) = peer { - status = .custom(string: NSAttributedString(string: strings.Conversation_StatusMembers(Int32(group.participantCount))), multiline: false, isActive: false, icon: nil) - } else if case let .channel(channel) = peer { -``` - -`channel.info` access inside the surviving inner block continues to compile unchanged (`EnginePeer.channel` wraps `TelegramChannel`). `group.participantCount` inside the `legacyGroup` branch works identically. The first branch doesn't bind the user — the `case .user = peer` form preserves that. - -- [ ] **Step 2.7: Rewrite the L1968 cast to an EnginePeer case pattern** - -Read lines 1964–1976 first. The cast is inside the ContactListPeer.peer destructure at line 1966. - -Edit: - -```swift -// OLD (lines 1967-1968) - if requirePhoneNumbers, - let user = peer as? TelegramUser { -``` - -```swift -// NEW - if requirePhoneNumbers, - case let .user(user) = peer { -``` - -`user.phone` on the following line continues to compile (`EnginePeer.user` wraps `TelegramUser`). - -- [ ] **Step 2.8: Drop 2 IndexName wraps at L517** - -Read lines 515–522 first. - -Edit: - -```swift -// OLD (line 517) - let result = EnginePeer.IndexName(lhs.indexName).isLessThan(other: EnginePeer.IndexName(rhs.indexName), ordering: sortOrder) -``` - -```swift -// NEW - let result = lhs.indexName.isLessThan(other: rhs.indexName, ordering: sortOrder) -``` - -`ContactListPeer.indexName` now returns `EnginePeer.IndexName` (from Task 1), and `isLessThan(other:ordering:)` is defined on `EnginePeer.IndexName` at `submodules/LocalizedPeerData/Sources/PeerTitle.swift:64`, so the wrap idiom is no longer required. - -- [ ] **Step 2.9: Verify ContactListNode.swift changes** - -Run: - -```bash -grep -nE "\._asPeer\(\), isGlobal:|EnginePeer\(peer\)|peer as\? Telegram(User|Group|Channel)\b|EnginePeer\.IndexName\(lhs\.indexName\)|EnginePeer\.IndexName\(rhs\.indexName\)" submodules/ContactListUI/Sources/ContactListNode.swift -``` - -Expected output: only `EnginePeer(peer)` matches at lines 1819 and 1825 (out-of-scope; `peer` there is from `entryData.renderedPeer.peer`, raw `Peer`, wraps stay). Similarly, `peer as? TelegramChannel` at 1802/1820 and `peer is TelegramGroup` at 1818 stay. - -If any other match appears, re-examine that site and apply the matching fix. - ---- - -## Task 3: Edit `ContactsController.swift` — 1 inflow wrap drop - -**Files:** -- Modify: `submodules/ContactListUI/Sources/ContactsController.swift` - -- [ ] **Step 3.1: Drop inflow wrap at L294** - -Read lines 285–300 first. - -Edit: - -```swift -// OLD (line 294) - strongSelf.context.sharedContext.navigateToChatController(NavigateToChatControllerParams(navigationController: navigationController, context: strongSelf.context, chatLocation: .peer(EnginePeer(peer)), purposefulAction: { [weak self] in -``` - -```swift -// NEW - strongSelf.context.sharedContext.navigateToChatController(NavigateToChatControllerParams(navigationController: navigationController, context: strongSelf.context, chatLocation: .peer(peer), purposefulAction: { [weak self] in -``` - -`peer` here is destructured from the ContactListPeer.peer case at line 287; post-migration it is already `EnginePeer`. `chatLocation: .peer(EnginePeer)` case takes `EnginePeer`. - -- [ ] **Step 3.2: Verify** - -Run: - -```bash -grep -nE "chatLocation: \.peer\(EnginePeer\(peer\)\)" submodules/ContactListUI/Sources/ContactsController.swift -``` - -Expected: zero matches. - ---- - -## Task 4: Edit `ContactsSearchContainerNode.swift` — 3 outflow + 4 inflow - -**Files:** -- Modify: `submodules/ContactListUI/Sources/ContactsSearchContainerNode.swift` - -- [ ] **Step 4.1: Drop the 3 outflow `._asPeer()` bridges at L494/535/569** - -Use the same `._asPeer(), isGlobal:` pattern as Task 2.1. The 3 bridges at `ContactListPeer.peer(...)` constructions all match this substring; the 3 unrelated bridges at L488/528/562 (`canSendMessagesToPeer(...)` sites) do NOT match (they lack the `, isGlobal:` suffix). - -Pre-flight verify: - -```bash -grep -cE "\._asPeer\(\), isGlobal:" submodules/ContactListUI/Sources/ContactsSearchContainerNode.swift -``` - -Expected: `3`. - -Apply Edit with `replace_all=true`: -- `old_string`: `._asPeer(), isGlobal:` -- `new_string`: `, isGlobal:` - -- [ ] **Step 4.2: Drop 4 inflow wraps at L164/165/181** - -Read lines 160–185 first. - -Three edits, each targeting one source line. - -Edit (line 164 — 2 wraps in one expression): - -```swift -// OLD - peerItem = .peer(peer: EnginePeer(peer), chatPeer: EnginePeer(peer)) -``` - -```swift -// NEW - peerItem = .peer(peer: peer, chatPeer: peer) -``` - -Edit (line 165): - -```swift -// OLD - nativePeer = EnginePeer(peer) -``` - -```swift -// NEW - nativePeer = peer -``` - -Edit (line 181): - -```swift -// OLD - openDisabledPeer(EnginePeer(peer), requiresPremiumForMessaging ? .premiumRequired : .generic) -``` - -```swift -// NEW - openDisabledPeer(peer, requiresPremiumForMessaging ? .premiumRequired : .generic) -``` - -- [ ] **Step 4.3: Verify** - -Run: - -```bash -grep -nE "\._asPeer\(\), isGlobal:|EnginePeer\(peer\)" submodules/ContactListUI/Sources/ContactsSearchContainerNode.swift -``` - -Expected: zero matches. - -The `._asPeer()` calls at L488/528/562 (feeding `canSendMessagesToPeer`) should remain. Verify: - -```bash -grep -nE "canSendMessagesToPeer\(.*\._asPeer\(\)\)" submodules/ContactListUI/Sources/ContactsSearchContainerNode.swift -``` - -Expected: 3 matches (L488, L528, L562). - ---- - -## Task 5: Edit `TelegramUI/Sources/ContactMultiselectionController.swift` — 2 outflow + 4 inflow - -**Files:** -- Modify: `submodules/TelegramUI/Sources/ContactMultiselectionController.swift` - -- [ ] **Step 5.1: Drop 2 outflow bridges at L451/459 via `replace_all`** - -Pre-flight verify: - -```bash -grep -cE "\._asPeer\(\), isGlobal:" submodules/TelegramUI/Sources/ContactMultiselectionController.swift -``` - -Expected: `2`. - -Apply Edit with `replace_all=true`: -- `old_string`: `._asPeer(), isGlobal:` -- `new_string`: `, isGlobal:` - -Unrelated `._asPeer()` calls at L171/201/748 (feeding `peerTokenTitle(peer: Peer, ...)`) do NOT use this substring and stay. - -- [ ] **Step 5.2: Drop 4 inflow wraps at L386/403/481/491** - -Read the file around each site to confirm exact text. Two wraps (L386, L403) have identical text; the other two (L481, L491) have distinct tails. - -Edit for L386 and L403 — `replace_all=true` on the substring: - -Pre-flight verify: - -```bash -grep -cE "subject: \.peer\(EnginePeer\(peer\)\)" submodules/TelegramUI/Sources/ContactMultiselectionController.swift -``` - -Expected: `2`. - -Apply Edit with `replace_all=true`: -- `old_string`: `subject: .peer(EnginePeer(peer))` -- `new_string`: `subject: .peer(peer)` - -Edit for L481: - -```swift -// OLD - self.params.sendMessage?(EnginePeer(peer)) -``` - -```swift -// NEW - self.params.sendMessage?(peer) -``` - -Edit for L491: - -```swift -// OLD - self.params.openProfile?(EnginePeer(peer)) -``` - -```swift -// NEW - self.params.openProfile?(peer) -``` - -- [ ] **Step 5.3: Verify** - -Run: - -```bash -grep -nE "\._asPeer\(\), isGlobal:|subject: \.peer\(EnginePeer\(peer\)\)|sendMessage\?\(EnginePeer\(peer\)\)|openProfile\?\(EnginePeer\(peer\)\)" submodules/TelegramUI/Sources/ContactMultiselectionController.swift -``` - -Expected: zero matches. - -Preserved bridge sites (sanity check): - -```bash -grep -nE "peerTokenTitle\(.*\._asPeer\(\)" submodules/TelegramUI/Sources/ContactMultiselectionController.swift -``` - -Expected: 3 matches (L171, L201, L748). - ---- - -## Task 6: Edit `TelegramUI/Sources/ContactMultiselectionControllerNode.swift` — 1 outflow + 1 inflow - -**Files:** -- Modify: `submodules/TelegramUI/Sources/ContactMultiselectionControllerNode.swift` - -- [ ] **Step 6.1: Drop 1 outflow bridge at L317** - -Read lines 315–320 first. - -Edit: - -```swift -// OLD (line 317) - self?.openPeer?(.peer(peer: peer._asPeer(), isGlobal: false, participantCount: nil)) -``` - -```swift -// NEW - self?.openPeer?(.peer(peer: peer, isGlobal: false, participantCount: nil)) -``` - -- [ ] **Step 6.2: Drop 1 inflow wrap at L492** - -Read lines 488–495 first. - -Edit: - -```swift -// OLD (line 492) - callTitle = self.presentationData.strings.NewCall_ActionCallSingle(EnginePeer(peer).compactDisplayTitle).string -``` - -```swift -// NEW - callTitle = self.presentationData.strings.NewCall_ActionCallSingle(peer.compactDisplayTitle).string -``` - -- [ ] **Step 6.3: Verify** - -Run: - -```bash -grep -nE "\._asPeer\(\), isGlobal:|EnginePeer\(peer\)\.compactDisplayTitle" submodules/TelegramUI/Sources/ContactMultiselectionControllerNode.swift -``` - -Expected: zero matches. - ---- - -## Task 7: Edit `TelegramUI/Sources/ContactSelectionController.swift` — 2 inflow wraps - -**Files:** -- Modify: `submodules/TelegramUI/Sources/ContactSelectionController.swift` - -- [ ] **Step 7.1: Drop 2 inflow wraps at L517/527** - -Read lines 510–535 first. Both sites are inside the destructure at L504. - -Edit for L517: - -```swift -// OLD - self.sendMessage?(EnginePeer(peer)) -``` - -```swift -// NEW - self.sendMessage?(peer) -``` - -Edit for L527: - -```swift -// OLD - self.openProfile?(EnginePeer(peer)) -``` - -```swift -// NEW - self.openProfile?(peer) -``` - -- [ ] **Step 7.2: Verify** - -Run: - -```bash -grep -nE "sendMessage\?\(EnginePeer\(peer\)\)|openProfile\?\(EnginePeer\(peer\)\)" submodules/TelegramUI/Sources/ContactSelectionController.swift -``` - -Expected: zero matches. - ---- - -## Task 8: Edit `TelegramUI/Sources/ContactSelectionControllerNode.swift` — 2 outflow bridges - -**Files:** -- Modify: `submodules/TelegramUI/Sources/ContactSelectionControllerNode.swift` - -- [ ] **Step 8.1: Drop 2 outflow bridges at L160/230 via `replace_all`** - -Pre-flight verify: - -```bash -grep -cE "\._asPeer\(\), isGlobal:" submodules/TelegramUI/Sources/ContactSelectionControllerNode.swift -``` - -Expected: `2`. - -Apply Edit with `replace_all=true`: -- `old_string`: `._asPeer(), isGlobal:` -- `new_string`: `, isGlobal:` - -- [ ] **Step 8.2: Verify** - -Run: - -```bash -grep -nE "\._asPeer\(\), isGlobal:" submodules/TelegramUI/Sources/ContactSelectionControllerNode.swift -``` - -Expected: zero matches. - ---- - -## Task 9: Verify no-edit consumer files - -**Files (read only):** -- Read: `submodules/TelegramUI/Sources/ComposeController.swift` -- Read: `submodules/TelegramUI/Components/Chat/ChatSendAudioMessageContextPreview/Sources/ChatSendAudioMessageContextPreview.swift` - -- [ ] **Step 9.1: Confirm ComposeController.swift has no inflow wraps, casts, or outflow bridges** - -Run: - -```bash -grep -nE "\.peer\(peer:|EnginePeer\(peer\)|peer as\? Telegram|\._asPeer\(\)" submodules/TelegramUI/Sources/ComposeController.swift -``` - -Expected: zero matches (destructures at L120/160 only access `.id`). - -If any match appears, add the appropriate fix step here and re-run Task 9.1 before proceeding. - -- [ ] **Step 9.2: Confirm ChatSendAudioMessageContextPreview.swift has no ContactListPeer.peer destructures** - -Run: - -```bash -grep -nE "case let \.peer\(peer, _, _\)|case \.peer\(let peer|EnginePeer\(peer\)|\.peer\(peer: " submodules/TelegramUI/Components/Chat/ChatSendAudioMessageContextPreview/Sources/ChatSendAudioMessageContextPreview.swift -``` - -Expected: zero matches. The file only references `[ContactListPeer]` at the collection level. - ---- - -## Task 10: Build verification (first pass) - -- [ ] **Step 10.1: Run the full build with `--continueOnError`** - -Run: - -```bash -source ~/.zshrc 2>/dev/null && python3 build-system/Make/Make.py --overrideXcodeVersion --cacheDir ~/telegram-bazel-cache build --configurationPath build-system/appstore-configuration.json --gitCodesigningRepository git@gitlab.com:peter-iakovlev/fastlanematch.git --gitCodesigningType development --gitCodesigningUseCurrent --buildNumber=1 --configuration=debug_sim_arm64 --continueOnError 2>&1 | tee /tmp/wave36-build.log -``` - -Expected outcome: ideally clean. Realistic: 0–3 inventory-missed sites (wave 35 trend was 14% miss rate on a 7-file wave; this 8-file wave has a larger surface area, so budget for up to 3 misses). - -- [ ] **Step 10.2: Triage build errors** - -Likely patterns and fixes: - -| Error | Fix | -|---|---| -| `cannot convert value of type 'EnginePeer' to expected argument type 'Peer'` at a call site | Add `._asPeer()` bridge. The callee takes raw `Peer` and is out of wave scope. | -| `cannot convert value of type 'Peer' to expected argument type 'EnginePeer'` at a `.peer(peer:, ...)` construction | Wrap raw peer with `EnginePeer(...)`. The raw-Peer source is probably from `transaction.getPeer(...)` or similar. | -| `value of type 'EnginePeer' has no member 'isEqual'` | Replace with `==`. | -| `type 'EnginePeer' cannot be cast to 'TelegramUser'` / `TelegramGroup` / `TelegramChannel` | Missed φ-category cast — rewrite to `case .user = peer` / `case let .legacyGroup(x) = peer` / `case let .channel(x) = peer`. | -| `cannot invoke initializer for type 'EnginePeer' with an argument list of type '(EnginePeer)'` | Missed inflow drop — strip `EnginePeer(...)` wrap. | -| `cannot convert value of type 'EnginePeer.IndexName' to expected argument type 'PeerIndexNameRepresentation'` | Either wrap the call site's expected-type change or adjust the consumer to accept `EnginePeer.IndexName`. Probably rare — ContactListPeer.indexName consumers were grepped in pre-flight and found only in ContactListNode. | -| `value of type 'EnginePeer' has no member ''` | That method is only on the Postbox `Peer` protocol. Bridge via `._asPeer()` OR find the EnginePeer-native equivalent. | - -For each error: identify file:line, apply the fix, re-run the build until clean. - -- [ ] **Step 10.3: Iterate to clean build** - -Re-run the build after each batch of fixes. The wave is complete when the build returns 0 errors for the targeted configuration. - -If 10+ unexpected errors surface, halt and reassess: the inventory may have significantly undercounted and the wave may need to be split. Discuss with the user before continuing. - ---- - -## Task 11: Post-build grep validations - -- [ ] **Step 11.1: Outflow-bridge-drop validation** - -Run: - -```bash -grep -rnE "\.peer\(peer: \w+\._asPeer\(\), isGlobal:" submodules/ --include="*.swift" -``` - -Expected: zero hits. Any remaining site is a missed outflow-bridge drop. - -- [ ] **Step 11.2: Inflow-wrap-drop validation** - -Run: - -```bash -for f in submodules/ContactListUI/Sources/ContactListNode.swift \ - submodules/ContactListUI/Sources/ContactsController.swift \ - submodules/ContactListUI/Sources/ContactsSearchContainerNode.swift \ - submodules/TelegramUI/Sources/ContactMultiselectionController.swift \ - submodules/TelegramUI/Sources/ContactMultiselectionControllerNode.swift \ - submodules/TelegramUI/Sources/ContactSelectionController.swift; do - echo "=== $f ===" - grep -nE "EnginePeer\(peer\)" "$f" -done -``` - -Expected hits: -- ContactListNode.swift L1819, L1825 (raw `renderedPeer.peer`, out-of-scope wraps stay) -- Any other hit in the 6 listed files is a missed inflow drop — inspect and fix. - -- [ ] **Step 11.3: Cast-rewrite validation** - -Run: - -```bash -grep -nE "\bpeer (as\?|as!|is) Telegram(User|Group|Channel)\b" submodules/ContactListUI/Sources/ContactListNode.swift -``` - -Expected: only L1802, L1818, L1820 remain (out-of-scope, `peer` is raw from `renderedPeer.peer`). - -If L182, L184, L186, or L1968 appear, those are missed φ rewrites. - -- [ ] **Step 11.4: IndexName wrap validation** - -Run: - -```bash -grep -nE "EnginePeer\.IndexName\(lhs\.indexName\)|EnginePeer\.IndexName\(rhs\.indexName\)" submodules/ContactListUI/Sources/ContactListNode.swift -``` - -Expected: zero matches. - -- [ ] **Step 11.5: isEqual-in-==-operator validation** - -Run: - -```bash -grep -nE "lhsPeer\.isEqual\(rhsPeer\)" submodules/AccountContext/Sources/ContactSelectionController.swift -``` - -Expected: zero matches. - -- [ ] **Step 11.6: Construction-site sanity sweep** - -Run: - -```bash -grep -rnE "ContactListPeer\.peer\(peer: |\.peer\(peer: \w+, isGlobal:" submodules/ --include="*.swift" | head -40 -``` - -Inspect each hit. Expected forms: -- `.peer(peer: , isGlobal: …)` where `` is either a local already typed `EnginePeer` or `EnginePeer()`. -- Anything of the form `.peer(peer: , isGlobal: …)` where `` is a Postbox `Peer` value is a miss (would surface as a build error — this is a belt-and-suspenders check). - -If any validation fails, return to Task 10. - ---- - -## Task 12: Atomic commit + memory + log update - -- [ ] **Step 12.1: Stage and review** - -Run: - -```bash -git status --short -git diff --stat -``` - -Confirm exactly 8 modified Swift files: -- `submodules/AccountContext/Sources/ContactSelectionController.swift` -- `submodules/ContactListUI/Sources/ContactListNode.swift` -- `submodules/ContactListUI/Sources/ContactsController.swift` -- `submodules/ContactListUI/Sources/ContactsSearchContainerNode.swift` -- `submodules/TelegramUI/Sources/ContactMultiselectionController.swift` -- `submodules/TelegramUI/Sources/ContactMultiselectionControllerNode.swift` -- `submodules/TelegramUI/Sources/ContactSelectionController.swift` -- `submodules/TelegramUI/Sources/ContactSelectionControllerNode.swift` - -Pre-existing WIP (`build-system/bazel-rules/sourcekit-bazel-bsp`, `ChatListFilterPresetController.swift`, `ChatListFilterPresetListController.swift`, untracked `build-system/tulsi/` / `submodules/TgVoip/` / `third-party/libx264/` / `docs/superpowers/plans/2026-04-22-claude-md-reorganization.md`) should NOT be staged. - -- [ ] **Step 12.2: Stage only the wave-36 files** - -Run: - -```bash -git add submodules/AccountContext/Sources/ContactSelectionController.swift \ - submodules/ContactListUI/Sources/ContactListNode.swift \ - submodules/ContactListUI/Sources/ContactsController.swift \ - submodules/ContactListUI/Sources/ContactsSearchContainerNode.swift \ - submodules/TelegramUI/Sources/ContactMultiselectionController.swift \ - submodules/TelegramUI/Sources/ContactMultiselectionControllerNode.swift \ - submodules/TelegramUI/Sources/ContactSelectionController.swift \ - submodules/TelegramUI/Sources/ContactSelectionControllerNode.swift -``` - -If Task 10 introduced additional files (inventory-miss fixes), append them. - -- [ ] **Step 12.3: Commit** - -Run: - -```bash -git commit -m "$(cat <<'EOF' -Postbox -> TelegramEngine wave 36: ContactListPeer.peer Peer -> EnginePeer - -Migrates the public enum case `ContactListPeer.peer(peer: Peer, isGlobal:, -participantCount:)` from the Postbox `Peer` protocol to the TelegramCore -`EnginePeer` enum. Also cascades `ContactListPeer.indexName` return type -from `PeerIndexNameRepresentation` to `EnginePeer.IndexName` and rewrites -the enum's custom `==` operator to use EnginePeer's synthesized Equatable. - -Consumer-side cascade in 7 files: - - 20 `._asPeer()` outflow bridge-drops at ContactListPeer.peer - construction sites (the payload is now EnginePeer) - - 16 `EnginePeer(peer)` inflow wrap-drops at destructure sites (the - destructured `peer` is already EnginePeer) - - 2 `EnginePeer.IndexName(...)` wrap-drops at a sort-comparator (the - indexName property now returns EnginePeer.IndexName directly) - - 2 Postbox-concrete cast chains rewritten to EnginePeer case patterns - (`peer as? TelegramUser` → `case .user = peer`, etc.) - - `lhsPeer.isEqual(rhsPeer)` → `lhsPeer == rhsPeer` in the ==operator - -Files modified: - submodules/AccountContext/Sources/ContactSelectionController.swift - submodules/ContactListUI/Sources/ContactListNode.swift - submodules/ContactListUI/Sources/ContactsController.swift - submodules/ContactListUI/Sources/ContactsSearchContainerNode.swift - submodules/TelegramUI/Sources/ContactMultiselectionController.swift - submodules/TelegramUI/Sources/ContactMultiselectionControllerNode.swift - submodules/TelegramUI/Sources/ContactSelectionController.swift - submodules/TelegramUI/Sources/ContactSelectionControllerNode.swift - -Bridges intentionally retained (out-of-wave scope): - - `canSendMessagesToPeer(peer._asPeer())` — callee takes Peer, deferred - - `peerTokenTitle(peer: peer._asPeer(), ...)` — callee takes Peer, - deferred - -Plan: docs/superpowers/plans/2026-04-24-contactlistpeer-engine-peer-migration.md -Spec: docs/superpowers/specs/2026-04-24-contactlistpeer-engine-peer-migration-design.md - -Co-Authored-By: Claude Opus 4.7 (1M context) -EOF -)" -``` - -- [ ] **Step 12.4: Update CLAUDE.md wave counter** - -Edit `CLAUDE.md` to bump the "Waves landed so far" line from "35 waves" to "36 waves" and update the "as of" date if the commit lands after 2026-04-24. - -- [ ] **Step 12.5: Append wave outcome to the postbox-refactor-log** - -Append a "Wave 36 outcome" section to `docs/superpowers/postbox-refactor-log.md` documenting: -- Actual files touched + edit counts vs. plan -- Any inventory undercounts surfaced by Task 10 (file:line + missed-category) -- Any lessons learned (e.g., whether the γ category really had zero sites; how the φ cast-rewrites behaved; post-migration undercount percentage vs wave 35's 14%) -- Ratio of bridge-drops to bridge-additions (wave theme: removal-dominated) - -Keep concise. - -- [ ] **Step 12.6: Commit the docs update** - -Run: - -```bash -git add CLAUDE.md docs/superpowers/postbox-refactor-log.md -git commit -m "$(cat <<'EOF' -docs: add wave 36 outcome (ContactListPeer.peer Peer→EnginePeer) - -Co-Authored-By: Claude Opus 4.7 (1M context) -EOF -)" -``` - -- [ ] **Step 12.7: Update the next-wave memory** - -Edit `/Users/isaac/.claude/projects/-Users-isaac-build-telegram-telegram-ios/memory/project_postbox_refactor_next_wave.md`: -- Add wave 36 to the "Latest commits" section. -- Move ContactListPeer migration from "Recommended wave 36 candidates" to landed. -- Record the inventory undercount ratio (actual-files-touched ÷ pre-flight-file-count) for calibration. -- Update the "Recommended wave 37" section. Promote candidates: `canSendMessagesToPeer(_:)` parameter (the ContactsSearchContainerNode `._asPeer()` bridges at L488/528/562 plus others elsewhere drop when this lands); `peerTokenTitle(peer:)` parameter (drops 3 bridges in ContactMultiselectionController); `makePeerInfoController` / `makeChatQrCodeScreen` / `makeChatRecentActionsController` AccountContext protocol methods (largest remaining Peer-typed-API); accountManager engine path; Shape-C `resourceData` module. - -Use the Edit tool on the memory file. No git commit needed. - ---- - -## Risks and notes - -- **Inventory undercount.** Pre-flight caught several sites the Explore agent missed (inflow wraps at L481/491/517/527/492/844, cast rewrites at L182-186 and L1968). Budget for 1–3 additional misses surfacing in Task 10. If the build surfaces 5+ misses in new categories, stop and reassess. -- **`replace_all` usage.** Every `replace_all=true` Edit in this plan is gated by a pre-flight `grep -c` count check. If the count is wrong, fall back to per-site Edits with surrounding context. -- **Cast rewrite at L182-186.** The original cast chain binds `group` and `channel` (but not `user`). The EnginePeer case-pattern form preserves this: `case .user = peer` is a binding-free match, mirroring `if let _ = peer as? TelegramUser`. -- **`._asPeer()` sites that stay.** Tasks 4.3 and 5.3 explicitly verify that the 3 `canSendMessagesToPeer(peer._asPeer())` bridges and 3 `peerTokenTitle(peer: peer._asPeer(), ...)` bridges remain intact. Dropping these would be out-of-scope migration. -- **WIP isolation.** Pre-existing `ChatListFilterPresetController.swift` / `ChatListFilterPresetListController.swift` edits and untracked `build-system/tulsi/`, `submodules/TgVoip/`, `third-party/libx264/` paths are user WIP — do NOT stage them. Use the explicit `git add ` form in Step 12.2. -- **Scope boundary.** Task 10 errors surfacing in `TelegramCore`, `Postbox`, or `TelegramApi` mean the migration cascaded beyond its intended consumer scope. Halt and investigate — do NOT edit TelegramCore in this wave. -- **No new typealiases/wrappers.** Rule 2 and 3 of the Postbox refactor guidance apply — this wave stays inside. diff --git a/docs/superpowers/plans/2026-04-24-foundpeer-engine-peer-migration.md b/docs/superpowers/plans/2026-04-24-foundpeer-engine-peer-migration.md deleted file mode 100644 index f596e3270e..0000000000 --- a/docs/superpowers/plans/2026-04-24-foundpeer-engine-peer-migration.md +++ /dev/null @@ -1,1287 +0,0 @@ -# Wave 34: `FoundPeer.peer: Peer → EnginePeer` Implementation Plan - -> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. - -**Goal:** Migrate the public field `FoundPeer.peer` from the Postbox `Peer` protocol to the TelegramCore `EnginePeer` enum in a single atomic commit. Drops 5 `._asPeer()` bridges (most added in wave 33), eliminates 22 `EnginePeer(peer.peer)` redundant wraps, rewrites 30 Postbox-concrete-type downcasts to enum patterns, and adds bridges where `peer.peer` flows out to APIs that still take raw `Peer`. - -**Architecture:** One atomic commit. The field-type change is necessarily atomic (half-migrated FoundPeer doesn't compile), so all edits land together. TelegramCore's `_internal_searchPeers` keeps `import Postbox` — only `FoundPeer`'s public surface changes. No new wrappers, no new typealiases beyond what already exists. - -**Tech Stack:** Swift, Bazel build via Make.py wrapper. No tests — verification is build success + targeted grep checks. - -**Spec:** `docs/superpowers/specs/2026-04-24-foundpeer-engine-peer-migration-design.md` - ---- - -## File Structure - -**Modified files (8 total — 1 TelegramCore + 7 consumer):** - -| File | Edit count | -|---|---| -| `submodules/TelegramCore/Sources/TelegramEngine/Peers/SearchPeers.swift` | ~13 spot edits (struct change + 6 filter rewrites + 4 constructor wraps + manual `==` body) | -| `submodules/TelegramCallsUI/Sources/VideoChatScreen.swift` | 1 (bridge-drop at line 1833) | -| `submodules/TelegramCallsUI/Sources/VideoChatScreenMoreMenu.swift` | 7 (3 C2 downcasts + 4 C3 wraps) | -| `submodules/ContactListUI/Sources/ContactListNode.swift` | ~21 (3 C4 + 13 C2 + 0 C3 + 3 outflow bridges; some lines have multiple edits) | -| `submodules/ChatListUI/Sources/ChatListSearchListPaneNode.swift` | ~17 (8 C2 + ~9 C3) | -| `submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoScreenCallActions.swift` | ~10 (2 C4 + 3 C2 + 4 C3 + 1 outflow bridge at line 161 — verify) | -| `submodules/TelegramBaseController/Sources/TelegramBaseController.swift` | 6 (1 C4 + 3 C2 + 2 C3) | -| `submodules/SettingsUI/Sources/Data and Storage/StorageUsageExceptionsScreen.swift` | 3 (1 C4 + 2 C3) | - -Note: line counts above are approximations from spec — execution may surface additional outflow-bridge sites caught by the build pass (Task 10). - -**EnginePeer enum case mapping (used throughout):** - -| Postbox concrete | EnginePeer case | -|---|---| -| `TelegramUser` | `.user(TelegramUser)` | -| `TelegramSecretChat` | `.secretChat(TelegramSecretChat)` | -| `TelegramGroup` | `.legacyGroup(TelegramGroup)` | -| `TelegramChannel` | `.channel(TelegramChannel)` | - ---- - -## Task 1: Edit `SearchPeers.swift` — struct definition + body rewrites - -**Files:** -- Modify: `submodules/TelegramCore/Sources/TelegramEngine/Peers/SearchPeers.swift` - -This is the foundational change. Without it, none of the consumer edits compile in the right direction. - -- [ ] **Step 1.1: Update the FoundPeer struct field, init parameter, and `==` body** - -Edit: - -```swift -// OLD -public struct FoundPeer: Equatable { - public let peer: Peer - public let subscribers: Int32? - - public init(peer: Peer, subscribers: Int32?) { - self.peer = peer - self.subscribers = subscribers - } - - public static func ==(lhs: FoundPeer, rhs: FoundPeer) -> Bool { - return lhs.peer.isEqual(rhs.peer) && lhs.subscribers == rhs.subscribers - } -} -``` - -```swift -// NEW -public struct FoundPeer: Equatable { - public let peer: EnginePeer - public let subscribers: Int32? - - public init(peer: EnginePeer, subscribers: Int32?) { - self.peer = peer - self.subscribers = subscribers - } - - public static func ==(lhs: FoundPeer, rhs: FoundPeer) -> Bool { - return lhs.peer == rhs.peer && lhs.subscribers == rhs.subscribers - } -} -``` - -Use the Edit tool with the OLD block as `old_string` and the NEW block as `new_string`. - -- [ ] **Step 1.2: Wrap raw peer values in the four constructor sites inside `_internal_searchPeers`** - -There are four `FoundPeer(peer: peer, subscribers: …)` calls inside `_internal_searchPeers` at lines 70, 72, 85, 87. Each wraps `peer` (a raw `Peer` from `parsedPeers.get(peerId)`) with `EnginePeer(peer)`. - -Edit (replace_all=false because there are 4 distinct contexts; use enough surrounding context per edit to make each unique): - -For lines 70 and 72 (inside the `myResults` loop): - -```swift -// OLD - if let user = peer as? TelegramUser { - renderedMyPeers.append(FoundPeer(peer: peer, subscribers: user.subscriberCount)) - } else { - renderedMyPeers.append(FoundPeer(peer: peer, subscribers: subscribers[peerId])) - } -``` - -```swift -// NEW - if let user = peer as? TelegramUser { - renderedMyPeers.append(FoundPeer(peer: EnginePeer(peer), subscribers: user.subscriberCount)) - } else { - renderedMyPeers.append(FoundPeer(peer: EnginePeer(peer), subscribers: subscribers[peerId])) - } -``` - -For lines 85 and 87 (inside the `results` loop): - -```swift -// OLD - if let user = peer as? TelegramUser { - renderedPeers.append(FoundPeer(peer: peer, subscribers: user.subscriberCount)) - } else { - renderedPeers.append(FoundPeer(peer: peer, subscribers: subscribers[peerId])) - } -``` - -```swift -// NEW - if let user = peer as? TelegramUser { - renderedPeers.append(FoundPeer(peer: EnginePeer(peer), subscribers: user.subscriberCount)) - } else { - renderedPeers.append(FoundPeer(peer: EnginePeer(peer), subscribers: subscribers[peerId])) - } -``` - -- [ ] **Step 1.3: Rewrite the six scope-filter expressions to enum-pattern form** - -For `.channels` scope (two filter blocks; identical bodies — use one Edit per block, NOT replace_all, since the surrounding `renderedMyPeers =` vs `renderedPeers =` differs): - -```swift -// OLD (renderedMyPeers, lines ~96-102) - case .channels: - renderedMyPeers = renderedMyPeers.filter { item in - if let channel = item.peer as? TelegramChannel, case .broadcast = channel.info { - return true - } else { - return false - } - } - renderedPeers = renderedPeers.filter { item in - if let channel = item.peer as? TelegramChannel, case .broadcast = channel.info { - return true - } else { - return false - } - } -``` - -```swift -// NEW - case .channels: - renderedMyPeers = renderedMyPeers.filter { item in - if case let .channel(channel) = item.peer, case .broadcast = channel.info { - return true - } else { - return false - } - } - renderedPeers = renderedPeers.filter { item in - if case let .channel(channel) = item.peer, case .broadcast = channel.info { - return true - } else { - return false - } - } -``` - -For `.groups` scope (two filter blocks): - -```swift -// OLD - case .groups: - renderedMyPeers = renderedMyPeers.filter { item in - if let channel = item.peer as? TelegramChannel, case .group = channel.info { - return true - } else if item.peer is TelegramGroup { - return true - } else { - return false - } - } - renderedPeers = renderedPeers.filter { item in - if let channel = item.peer as? TelegramChannel, case .group = channel.info { - return true - } else if item.peer is TelegramGroup { - return true - } else { - return false - } - } -``` - -```swift -// NEW - case .groups: - renderedMyPeers = renderedMyPeers.filter { item in - if case let .channel(channel) = item.peer, case .group = channel.info { - return true - } else if case .legacyGroup = item.peer { - return true - } else { - return false - } - } - renderedPeers = renderedPeers.filter { item in - if case let .channel(channel) = item.peer, case .group = channel.info { - return true - } else if case .legacyGroup = item.peer { - return true - } else { - return false - } - } -``` - -For `.privateChats` scope: - -```swift -// OLD - case .privateChats: - renderedMyPeers = renderedMyPeers.filter { item in - if item.peer is TelegramUser { - return true - } else { - return false - } - } - renderedPeers = renderedPeers.filter { item in - if item.peer is TelegramUser { - return true - } else { - return false - } - } -``` - -```swift -// NEW - case .privateChats: - renderedMyPeers = renderedMyPeers.filter { item in - if case .user = item.peer { - return true - } else { - return false - } - } - renderedPeers = renderedPeers.filter { item in - if case .user = item.peer { - return true - } else { - return false - } - } -``` - -- [ ] **Step 1.4: Verify** — read the updated file from line 1 to ~155 and confirm there are no remaining `item.peer as? Telegram*` or `item.peer is Telegram*` patterns and the four `FoundPeer(peer: peer, ...)` constructions are now `FoundPeer(peer: EnginePeer(peer), ...)`. Do not commit yet. - ---- - -## Task 2: Edit `VideoChatScreen.swift` - -**Files:** -- Modify: `submodules/TelegramCallsUI/Sources/VideoChatScreen.swift` - -- [ ] **Step 2.1: Drop `._asPeer()` bridge in the FoundPeer constructor at line 1833** - -Edit: - -```swift -// OLD - |> map { peer in - return [FoundPeer(peer: peer._asPeer(), subscribers: nil)] - } -``` - -```swift -// NEW - |> map { peer in - return [FoundPeer(peer: peer, subscribers: nil)] - } -``` - -The surrounding context (`|> mapToSignal { peer -> Signal` two lines earlier) confirms `peer` is `EnginePeer`. The `._asPeer()` bridge becomes unnecessary. - ---- - -## Task 3: Edit `VideoChatScreenMoreMenu.swift` - -**Files:** -- Modify: `submodules/TelegramCallsUI/Sources/VideoChatScreenMoreMenu.swift` - -7 edits in this file: 4 C3 wrap-drops + 3 C2 downcast rewrites. - -- [ ] **Step 3.1: Drop the two `EnginePeer(peer.peer)` wraps on line 171** - -Edit: - -```swift -// OLD - items.append(.action(ContextMenuActionItem(text: environment.strings.VoiceChat_DisplayAs, textLayout: .secondLineWithValue(EnginePeer(peer.peer).displayTitle(strings: environment.strings, displayOrder: currentCall.accountContext.sharedContext.currentPresentationData.with({ $0 }).nameDisplayOrder)), icon: { _ in nil }, iconSource: ContextMenuActionItemIconSource(size: avatarSize, signal: peerAvatarCompleteImage(account: currentCall.accountContext.account, peer: EnginePeer(peer.peer), size: avatarSize)), action: { [weak self] c, _ in -``` - -```swift -// NEW - items.append(.action(ContextMenuActionItem(text: environment.strings.VoiceChat_DisplayAs, textLayout: .secondLineWithValue(peer.peer.displayTitle(strings: environment.strings, displayOrder: currentCall.accountContext.sharedContext.currentPresentationData.with({ $0 }).nameDisplayOrder)), icon: { _ in nil }, iconSource: ContextMenuActionItemIconSource(size: avatarSize, signal: peerAvatarCompleteImage(account: currentCall.accountContext.account, peer: peer.peer, size: avatarSize)), action: { [weak self] c, _ in -``` - -- [ ] **Step 3.2: Rewrite the C2 downcasts at lines 628–648** - -Edit: - -```swift -// OLD (around lines 627-635) - for peer in displayAsPeers { - if peer.peer is TelegramGroup { - isGroup = true - break - } else if let peer = peer.peer as? TelegramChannel, case .group = peer.info { - isGroup = true - break - } - } -``` - -```swift -// NEW - for peer in displayAsPeers { - if case .legacyGroup = peer.peer { - isGroup = true - break - } else if case let .channel(channel) = peer.peer, case .group = channel.info { - isGroup = true - break - } - } -``` - -(Note the `else if let peer = peer.peer as? TelegramChannel` shadowed the outer loop `peer` with a new `peer: TelegramChannel`. The rewrite uses `channel` to avoid further shadowing the EnginePeer loop variable.) - -Edit (around line 648): - -```swift -// OLD - } else if let subscribers = peer.subscribers { - if let peer = peer.peer as? TelegramChannel, case .broadcast = peer.info { - subtitle = environment.strings.Conversation_StatusSubscribers(subscribers) - } else { - subtitle = environment.strings.Conversation_StatusMembers(subscribers) - } - } -``` - -```swift -// NEW - } else if let subscribers = peer.subscribers { - if case let .channel(channel) = peer.peer, case .broadcast = channel.info { - subtitle = environment.strings.Conversation_StatusSubscribers(subscribers) - } else { - subtitle = environment.strings.Conversation_StatusMembers(subscribers) - } - } -``` - -- [ ] **Step 3.3: Drop the `EnginePeer(peer.peer)` wrap at line 658** - -Edit: - -```swift -// OLD - let avatarSignal = peerAvatarCompleteImage(account: groupCall.accountContext.account, peer: EnginePeer(peer.peer), size: avatarSize) -``` - -```swift -// NEW - let avatarSignal = peerAvatarCompleteImage(account: groupCall.accountContext.account, peer: peer.peer, size: avatarSize) -``` - -- [ ] **Step 3.4: Drop the `EnginePeer(peer.peer)` wrap at line 679** - -Edit: - -```swift -// OLD - items.append(.action(ContextMenuActionItem(text: EnginePeer(peer.peer).displayTitle(strings: environment.strings, displayOrder: groupCall.accountContext.sharedContext.currentPresentationData.with({ $0 }).nameDisplayOrder), textLayout: subtitle.flatMap { .secondLineWithValue($0) } ?? .singleLine, icon: { _ in nil }, iconSource: ContextMenuActionItemIconSource(size: isSelected ? extendedAvatarSize : avatarSize, signal: avatarSignal), action: { [weak self] _, f in -``` - -```swift -// NEW - items.append(.action(ContextMenuActionItem(text: peer.peer.displayTitle(strings: environment.strings, displayOrder: groupCall.accountContext.sharedContext.currentPresentationData.with({ $0 }).nameDisplayOrder), textLayout: subtitle.flatMap { .secondLineWithValue($0) } ?? .singleLine, icon: { _ in nil }, iconSource: ContextMenuActionItemIconSource(size: isSelected ? extendedAvatarSize : avatarSize, signal: avatarSignal), action: { [weak self] _, f in -``` - ---- - -## Task 4: Edit `ContactListNode.swift` - -**Files:** -- Modify: `submodules/ContactListUI/Sources/ContactListNode.swift` - -The largest file: 3 C4 (constructor) edits, 13 C2 (downcast) rewrites, and 3 outflow bridges where `peer.peer` is passed to `.peer(peer:)` (raw-Peer-taking enum case). - -- [ ] **Step 4.1: Bridge-drop at constructor lines 1485 and 1517** - -Edit: - -```swift -// OLD (line 1485) - resultPeers.append(FoundPeer(peer: mainPeer._asPeer(), subscribers: nil)) -``` - -```swift -// NEW - resultPeers.append(FoundPeer(peer: mainPeer, subscribers: nil)) -``` - -(Verification: `mainPeer` is bound from `peer.chatMainPeer` at line 1479. `chatMainPeer` returns `EnginePeer?` on `EngineRenderedPeer`. After migration this needs no bridge.) - -Edit: - -```swift -// OLD (line 1517) - return (peers.map({ FoundPeer(peer: $0._asPeer(), subscribers: nil) }), presences) -``` - -```swift -// NEW - return (peers.map({ FoundPeer(peer: $0, subscribers: nil) }), presences) -``` - -(Verification: `peers` comes from `context.engine.contacts.searchContacts(query:)` whose return type's first element is `[EnginePeer]`. Confirmed by inspection.) - -- [ ] **Step 4.2: Rewrite the C2 downcast at line 1501** - -Edit: - -```swift -// OLD - if let _ = peer.peer as? TelegramChannel { -``` - -```swift -// NEW - if case .channel = peer.peer { -``` - -- [ ] **Step 4.3: Rewrite the three identical C2 sites at lines 1563, 1569, 1574** - -These three lines have the SAME pattern (`if let user = peer.peer as? TelegramUser, user.flags.contains(.requirePremium) {`). Use `replace_all=true` since the line is identical (verify uniqueness by grepping first). - -Edit (`replace_all=true`): - -```swift -// OLD - if let user = peer.peer as? TelegramUser, user.flags.contains(.requirePremium) { -``` - -```swift -// NEW - if case let .user(user) = peer.peer, user.flags.contains(.requirePremium) { -``` - -Verify `replace_all` actually replaced exactly 3 sites (count occurrences before and after; if not 3, something else uses the same pattern and you must split into individual edits). - -- [ ] **Step 4.4: Add `._asPeer()` outflow bridges at lines 1656, 1693, 1731** - -These are `peers.append(.peer(peer: peer.peer, ...))` where `.peer(peer:)` is `ContactListPeer.peer(peer:isGlobal:participantCount:)` taking raw `Peer`. Add bridge. - -Edit (line 1656): - -```swift -// OLD - peers.append(.peer(peer: peer.peer, isGlobal: false, participantCount: peer.subscribers)) -``` - -```swift -// NEW - peers.append(.peer(peer: peer.peer._asPeer(), isGlobal: false, participantCount: peer.subscribers)) -``` - -Edit (line 1693): - -```swift -// OLD - peers.append(.peer(peer: peer.peer, isGlobal: true, participantCount: peer.subscribers)) -``` - -```swift -// NEW - peers.append(.peer(peer: peer.peer._asPeer(), isGlobal: true, participantCount: peer.subscribers)) -``` - -The same pattern appears at line 1731 — apply the same edit. Use `replace_all` if and only if the second occurrence is identical (it is, but verify). - -- [ ] **Step 4.5: Rewrite the C2 sites at lines 1658, 1665, 1673, 1675, 1695, 1703, 1711, 1713, 1733** - -These are scattered through three nearly-identical loop bodies (`localPeersAndStatuses.0`, `remotePeers.0`, `remotePeers.1`). The patterns: - -For lines 1658, 1695, 1733 (`if searchDeviceContacts, let user = peer.peer as? TelegramUser, let phone = user.phone`): - -Edit (`replace_all=true` if the 3 occurrences are textually identical — verify): - -```swift -// OLD - if searchDeviceContacts, - let user = peer.peer as? TelegramUser, - let phone = user.phone { -``` - -```swift -// NEW - if searchDeviceContacts, - case let .user(user) = peer.peer, - let phone = user.phone { -``` - -For line 1665 and 1703 (single-condition `if let user = peer.peer as? TelegramUser {`): - -Edit (`replace_all=true` if textually identical): - -```swift -// OLD - if let user = peer.peer as? TelegramUser { -``` - -```swift -// NEW - if case let .user(user) = peer.peer { -``` - -For line 1673 (`if peer.peer is TelegramGroup && searchGroups`): - -Edit: - -```swift -// OLD - if peer.peer is TelegramGroup && searchGroups { - matches = true - } else if let channel = peer.peer as? TelegramChannel { -``` - -```swift -// NEW - if case .legacyGroup = peer.peer, searchGroups { - matches = true - } else if case let .channel(channel) = peer.peer { -``` - -For line 1711 (`if peer.peer is TelegramGroup`): - -Edit: - -```swift -// OLD - if peer.peer is TelegramGroup { - matches = searchGroups - } else if let channel = peer.peer as? TelegramChannel { -``` - -```swift -// NEW - if case .legacyGroup = peer.peer { - matches = searchGroups - } else if case let .channel(channel) = peer.peer { -``` - -(Note that line 1675 and 1713 carry the same `else if let channel = peer.peer as? TelegramChannel` pattern that is folded into the edits above. Confirm both got rewritten.) - -- [ ] **Step 4.6: Verify** — grep for remaining FoundPeer-relevant Postbox patterns in the file: - -Run: `grep -nE "peer\.peer\s+(as\?|is)\s+Telegram|EnginePeer\(peer\.peer\)|FoundPeer\(peer:\s+\w+\._asPeer\(\)" submodules/ContactListUI/Sources/ContactListNode.swift` - -Expected: zero matches if the C2/C3/C4 edits are complete. - ---- - -## Task 5: Edit `ChatListSearchListPaneNode.swift` - -**Files:** -- Modify: `submodules/ChatListUI/Sources/ChatListSearchListPaneNode.swift` - -8 C2 downcasts + 9 C3 wrap drops. - -- [ ] **Step 5.1a: Add outflow bridge at line 1018** - -Edit: - -```swift -// OLD - enabled = canSendMessagesToPeer(peer.peer) -``` - -```swift -// NEW - enabled = canSendMessagesToPeer(peer.peer._asPeer()) -``` - -(`canSendMessagesToPeer(_ peer: Peer, ...)` in `submodules/TelegramCore/Sources/Utils/CanSendMessagesToPeer.swift` takes raw `Peer`, so the bridge is required.) - -- [ ] **Step 5.1b: Rewrite the disjunction at line 1024 using `switch`** - -Edit: - -```swift -// OLD - if filter.contains(.onlyPrivateChats) { - if !(peer.peer is TelegramUser || peer.peer is TelegramSecretChat) { - enabled = false - } - } -``` - -```swift -// NEW - if filter.contains(.onlyPrivateChats) { - switch peer.peer { - case .user, .secretChat: - break - default: - enabled = false - } - } -``` - -The `switch ... case .user, .secretChat: break / default: enabled = false` form preserves the negation semantics of the original `if !(... || ...)` and reads cleanly. - -- [ ] **Step 5.1c: Rewrite C2 downcasts at lines 1029-1030** - -Edit (lines 1029-1030): - -```swift -// OLD - if let _ = peer.peer as? TelegramGroup { - } else if let peer = peer.peer as? TelegramChannel, case .group = peer.info { -``` - -```swift -// NEW - if case .legacyGroup = peer.peer { - } else if case let .channel(channel) = peer.peer, case .group = channel.info { -``` - -Edit (lines 1038-1040): - -```swift -// OLD - if peer.peer is TelegramUser { -``` - -(continues `} else if let channel = peer.peer as? TelegramChannel, case .broadcast = channel.info {` at line 1040) - -```swift -// NEW - if case .user = peer.peer { -``` - -```swift -// OLD - } else if let channel = peer.peer as? TelegramChannel, case .broadcast = channel.info { -``` - -```swift -// NEW - } else if case let .channel(channel) = peer.peer, case .broadcast = channel.info { -``` - -(If line 1040's old form is used elsewhere in the file, scope the Edit by including more surrounding context.) - -- [ ] **Step 5.2: Drop C3 wraps on line 1075** - -Edit: - -```swift -// OLD - return ContactsPeerItem(presentationData: ItemListPresentationData(presentationData), sortOrder: nameSortOrder, displayOrder: nameDisplayOrder, context: context, peerMode: .generalSearch(isSavedMessages: isSavedMessages), peer: .peer(peer: EnginePeer(peer.peer), chatPeer: EnginePeer(peer.peer)), status: .addressName(suffixString), badge: badge, requiresPremiumForMessaging: requiresPremiumForMessaging, enabled: enabled, selection: .none, editing: ContactsPeerItemEditing(editable: false, editing: false, revealed: false), index: nil, header: header, searchQuery: query, isAd: false, action: { _ in -``` - -```swift -// NEW - return ContactsPeerItem(presentationData: ItemListPresentationData(presentationData), sortOrder: nameSortOrder, displayOrder: nameDisplayOrder, context: context, peerMode: .generalSearch(isSavedMessages: isSavedMessages), peer: .peer(peer: peer.peer, chatPeer: peer.peer), status: .addressName(suffixString), badge: badge, requiresPremiumForMessaging: requiresPremiumForMessaging, enabled: enabled, selection: .none, editing: ContactsPeerItemEditing(editable: false, editing: false, revealed: false), index: nil, header: header, searchQuery: query, isAd: false, action: { _ in -``` - -- [ ] **Step 5.3: Drop C3 wraps on lines 1076, 1078, 1081** - -Edit (line 1076): - -```swift -// OLD - interaction.peerSelected(EnginePeer(peer.peer), nil, nil, nil, false) -``` - -```swift -// NEW - interaction.peerSelected(peer.peer, nil, nil, nil, false) -``` - -Edit (line 1078): - -```swift -// OLD - interaction.disabledPeerSelected(EnginePeer(peer.peer), nil, requiresPremiumForMessaging ? .premiumRequired : .generic) -``` - -```swift -// NEW - interaction.disabledPeerSelected(peer.peer, nil, requiresPremiumForMessaging ? .premiumRequired : .generic) -``` - -Edit (line 1081): - -```swift -// OLD - peerContextAction(EnginePeer(peer.peer), .search(nil), node, gesture, location) -``` - -```swift -// NEW - peerContextAction(peer.peer, .search(nil), node, gesture, location) -``` - -- [ ] **Step 5.4: Rewrite the C2 downcasts at lines 1500 and 1507 (inside `filteredPeerSearchQueryResults`)** - -Edit (line 1500, inside `value.0.filter`): - -```swift -// OLD - value.0.filter { peer in - if let channel = peer.peer as? TelegramChannel, case .broadcast = channel.info { - return true - } else { - return false - } - }, -``` - -```swift -// NEW - value.0.filter { peer in - if case let .channel(channel) = peer.peer, case .broadcast = channel.info { - return true - } else { - return false - } - }, -``` - -Edit (line 1507, inside `value.1.filter`): - -```swift -// OLD - value.1.filter { peer in - if let channel = peer.peer as? TelegramChannel, case .broadcast = channel.info { - return true - } else { - return false - } - } -``` - -```swift -// NEW - value.1.filter { peer in - if case let .channel(channel) = peer.peer, case .broadcast = channel.info { - return true - } else { - return false - } - } -``` - -- [ ] **Step 5.5: Drop C3 wraps in `foundRemotePeers` loops (lines 3088, 3096, 3214, 3216, 3241)** - -Edit (`replace_all=true` for the lines that match exactly the same pattern, otherwise individual Edits): - -```swift -// OLD (occurs at 3088, 3096, 3214, 3241 — the FoundPeer wrap; the EnginePeer(accountPeer) wrap stays since `accountPeer` is raw Peer) - if !existingPeerIds.contains(peer.peer.id), filteredPeer(EnginePeer(peer.peer), EnginePeer(accountPeer)) { -``` - -```swift -// NEW - if !existingPeerIds.contains(peer.peer.id), filteredPeer(peer.peer, EnginePeer(accountPeer)) { -``` - -If `replace_all=true`, verify the count is exactly 4 by grep before and after. - -Edit (line 3216 separately — different pattern): - -```swift -// OLD - entries.append(.localPeer(EnginePeer(peer.peer), nil, nil, index, presentationData.theme, presentationData.strings, presentationData.nameSortOrder, presentationData.nameDisplayOrder, localExpandType, nil, false, false)) -``` - -```swift -// NEW - entries.append(.localPeer(peer.peer, nil, nil, index, presentationData.theme, presentationData.strings, presentationData.nameSortOrder, presentationData.nameDisplayOrder, localExpandType, nil, false, false)) -``` - -(Note: this assumes `.localPeer(EnginePeer, ...)` accepts EnginePeer directly. If the build fails saying it expected raw `Peer`, add `._asPeer()` instead. Verify in build pass.) - -- [ ] **Step 5.6: Verify** — grep: - -Run: `grep -nE "peer\.peer\s+(as\?|is)\s+Telegram|EnginePeer\(peer\.peer\)" submodules/ChatListUI/Sources/ChatListSearchListPaneNode.swift` - -Expected: zero matches. - ---- - -## Task 6: Edit `PeerInfoScreenCallActions.swift` - -**Files:** -- Modify: `submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoScreenCallActions.swift` - -2 C4 bridge-drops + 3 C2 downcasts + 4 C3 wraps. The function is duplicated almost verbatim at the second site (line 156 vs 265). - -- [ ] **Step 6.1: Bridge-drops at lines 156 and 265** - -Edit (`replace_all=true` if the line is literally identical at both sites): - -```swift -// OLD - return [FoundPeer(peer: peer._asPeer(), subscribers: nil)] -``` - -```swift -// NEW - return [FoundPeer(peer: peer, subscribers: nil)] -``` - -Verify `replace_all` got exactly 2 sites. - -- [ ] **Step 6.2: Rewrite C2 downcasts at lines 175, 178, 193** - -Edit (lines 175 and 178 form one if-else chain): - -```swift -// OLD - for peer in peers { - if peer.peer is TelegramGroup { - isGroup = true - break - } else if let peer = peer.peer as? TelegramChannel, case .group = peer.info { - isGroup = true - break - } - } -``` - -```swift -// NEW - for peer in peers { - if case .legacyGroup = peer.peer { - isGroup = true - break - } else if case let .channel(channel) = peer.peer, case .group = channel.info { - isGroup = true - break - } - } -``` - -Edit (line 193 — inside the second `for peer in peers` loop): - -```swift -// OLD - } else if let subscribers = peer.subscribers { - if let peer = peer.peer as? TelegramChannel, case .broadcast = peer.info { - subtitle = strongSelf.presentationData.strings.Conversation_StatusSubscribers(subscribers) - } else { - subtitle = strongSelf.presentationData.strings.Conversation_StatusMembers(subscribers) - } - } -``` - -```swift -// NEW - } else if let subscribers = peer.subscribers { - if case let .channel(channel) = peer.peer, case .broadcast = channel.info { - subtitle = strongSelf.presentationData.strings.Conversation_StatusSubscribers(subscribers) - } else { - subtitle = strongSelf.presentationData.strings.Conversation_StatusMembers(subscribers) - } - } -``` - -- [ ] **Step 6.3: Drop C3 wraps at lines 201, 202** - -Edit: - -```swift -// OLD - let avatarSignal = peerAvatarCompleteImage(account: strongSelf.context.account, peer: EnginePeer(peer.peer), size: avatarSize) - items.append(.action(ContextMenuActionItem(text: EnginePeer(peer.peer).displayTitle(strings: strongSelf.presentationData.strings, displayOrder: strongSelf.presentationData.nameDisplayOrder), textLayout: subtitle.flatMap { .secondLineWithValue($0) } ?? .singleLine, icon: { _ in nil }, iconSource: ContextMenuActionItemIconSource(size: avatarSize, signal: avatarSignal), action: { _, f in -``` - -```swift -// NEW - let avatarSignal = peerAvatarCompleteImage(account: strongSelf.context.account, peer: peer.peer, size: avatarSize) - items.append(.action(ContextMenuActionItem(text: peer.peer.displayTitle(strings: strongSelf.presentationData.strings, displayOrder: strongSelf.presentationData.nameDisplayOrder), textLayout: subtitle.flatMap { .secondLineWithValue($0) } ?? .singleLine, icon: { _ in nil }, iconSource: ContextMenuActionItemIconSource(size: avatarSize, signal: avatarSignal), action: { _, f in -``` - -- [ ] **Step 6.4: Drop two C3 wraps on line 288** - -Edit: - -```swift -// OLD - items.append(.action(ContextMenuActionItem(text: strongSelf.presentationData.strings.VoiceChat_DisplayAs, textLayout: .secondLineWithValue(EnginePeer(peer.peer).displayTitle(strings: strongSelf.presentationData.strings, displayOrder: strongSelf.presentationData.nameDisplayOrder)), icon: { _ in nil }, iconSource: ContextMenuActionItemIconSource(size: avatarSize, signal: peerAvatarCompleteImage(account: strongSelf.context.account, peer: EnginePeer(peer.peer), size: avatarSize)), action: { c, f in -``` - -```swift -// NEW - items.append(.action(ContextMenuActionItem(text: strongSelf.presentationData.strings.VoiceChat_DisplayAs, textLayout: .secondLineWithValue(peer.peer.displayTitle(strings: strongSelf.presentationData.strings, displayOrder: strongSelf.presentationData.nameDisplayOrder)), icon: { _ in nil }, iconSource: ContextMenuActionItemIconSource(size: avatarSize, signal: peerAvatarCompleteImage(account: strongSelf.context.account, peer: peer.peer, size: avatarSize)), action: { c, f in -``` - -- [ ] **Step 6.5: Verify** — grep: - -Run: `grep -nE "peer\.peer\s+(as\?|is)\s+Telegram|EnginePeer\(peer\.peer\)" submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoScreenCallActions.swift` - -Expected: zero matches. - ---- - -## Task 7: Edit `TelegramBaseController.swift` - -**Files:** -- Modify: `submodules/TelegramBaseController/Sources/TelegramBaseController.swift` - -1 C4 bridge-drop + 3 C2 downcasts + 2 C3 wraps. - -- [ ] **Step 7.1: Bridge-drop at line 208** - -Edit: - -```swift -// OLD - |> map { peer in - return [FoundPeer(peer: peer._asPeer(), subscribers: nil)] - } -``` - -```swift -// NEW - |> map { peer in - return [FoundPeer(peer: peer, subscribers: nil)] - } -``` - -- [ ] **Step 7.2: Rewrite C2 downcasts at lines 243, 246, 258** - -Edit (lines 243 and 246 form one if-else chain): - -```swift -// OLD - for peer in peers { - if peer.peer is TelegramGroup { - isGroup = true - break - } else if let peer = peer.peer as? TelegramChannel, case .group = peer.info { - isGroup = true - break - } - } -``` - -```swift -// NEW - for peer in peers { - if case .legacyGroup = peer.peer { - isGroup = true - break - } else if case let .channel(channel) = peer.peer, case .group = channel.info { - isGroup = true - break - } - } -``` - -Edit (line 258): - -```swift -// OLD - } else if let subscribers = peer.subscribers { - if let peer = peer.peer as? TelegramChannel, case .broadcast = peer.info { - subtitle = strongSelf.presentationData.strings.Conversation_StatusSubscribers(subscribers) - } else { - subtitle = strongSelf.presentationData.strings.Conversation_StatusMembers(subscribers) - } - } -``` - -```swift -// NEW - } else if let subscribers = peer.subscribers { - if case let .channel(channel) = peer.peer, case .broadcast = channel.info { - subtitle = strongSelf.presentationData.strings.Conversation_StatusSubscribers(subscribers) - } else { - subtitle = strongSelf.presentationData.strings.Conversation_StatusMembers(subscribers) - } - } -``` - -- [ ] **Step 7.3: Drop two C3 wraps on line 265** - -Edit: - -```swift -// OLD - items.append(VoiceChatPeerActionSheetItem(context: context, peer: EnginePeer(peer.peer), title: EnginePeer(peer.peer).displayTitle(strings: presentationData.strings, displayOrder: presentationData.nameDisplayOrder), subtitle: subtitle ?? "", action: { -``` - -```swift -// NEW - items.append(VoiceChatPeerActionSheetItem(context: context, peer: peer.peer, title: peer.peer.displayTitle(strings: presentationData.strings, displayOrder: presentationData.nameDisplayOrder), subtitle: subtitle ?? "", action: { -``` - -- [ ] **Step 7.4: Verify** — grep: - -Run: `grep -nE "peer\.peer\s+(as\?|is)\s+Telegram|EnginePeer\(peer\.peer\)" submodules/TelegramBaseController/Sources/TelegramBaseController.swift` - -Expected: zero matches. - ---- - -## Task 8: Edit `StorageUsageExceptionsScreen.swift` - -**Files:** -- Modify: `submodules/SettingsUI/Sources/Data and Storage/StorageUsageExceptionsScreen.swift` - -1 C4 wrap-needed + 2 C3 wrap-drops. - -- [ ] **Step 8.1: Drop C3 wrap at line 173** - -Edit: - -```swift -// OLD - title = EnginePeer(peer.peer).displayTitle(strings: presentationData.strings, displayOrder: .firstLast) -``` - -```swift -// NEW - title = peer.peer.displayTitle(strings: presentationData.strings, displayOrder: .firstLast) -``` - -- [ ] **Step 8.2: Drop C3 wrap at line 176** - -Edit: - -```swift -// OLD - return ItemListDisclosureItem(presentationData: presentationData, icon: nil, context: arguments.context, iconPeer: EnginePeer(peer.peer), title: title, enabled: true, titleFont: .bold, label: optionText, labelStyle: .text, additionalDetailLabel: additionalDetailLabel, sectionId: self.section, style: .blocks, disclosureStyle: .optionArrows, action: { -``` - -```swift -// NEW - return ItemListDisclosureItem(presentationData: presentationData, icon: nil, context: arguments.context, iconPeer: peer.peer, title: title, enabled: true, titleFont: .bold, label: optionText, labelStyle: .text, additionalDetailLabel: additionalDetailLabel, sectionId: self.section, style: .blocks, disclosureStyle: .optionArrows, action: { -``` - -- [ ] **Step 8.3: Add EnginePeer wrap at constructor line 288** - -Edit: - -```swift -// OLD - result.append((peer: FoundPeer(peer: peer, subscribers: subscriberCount), value: value)) -``` - -```swift -// NEW - result.append((peer: FoundPeer(peer: EnginePeer(peer), subscribers: subscriberCount), value: value)) -``` - -(Verification: `peer` here is bound from a Postbox transaction higher up — it is a raw `Peer`. The wrap is required.) - -- [ ] **Step 8.4: Verify** — grep: - -Run: `grep -nE "EnginePeer\(peer\.peer\)" "submodules/SettingsUI/Sources/Data and Storage/StorageUsageExceptionsScreen.swift"` - -Expected: zero matches. - ---- - -## Task 9: Build verification (first pass) - -- [ ] **Step 9.1: Run the full build with `--continueOnError`** - -Run: - -```bash -source ~/.zshrc 2>/dev/null && python3 build-system/Make/Make.py --overrideXcodeVersion --cacheDir ~/telegram-bazel-cache build --configurationPath build-system/appstore-configuration.json --gitCodesigningRepository git@gitlab.com:peter-iakovlev/fastlanematch.git --gitCodesigningType development --gitCodesigningUseCurrent --buildNumber=1 --configuration=debug_sim_arm64 --continueOnError 2>&1 | tee /tmp/wave34-build.log -``` - -Expected outcome: ideally clean. Realistic outcome: a small number of errors at sites the inventory missed. - -- [ ] **Step 9.2: Triage build errors** - -Likely error patterns and their fixes: - -| Error | Fix | -|---|---| -| `cannot convert value of type 'EnginePeer' to expected argument type 'Peer'` at site `(peer.peer, ...)` | Add `._asPeer()` bridge: `(peer.peer._asPeer(), ...)` | -| `value of type 'EnginePeer' has no member 'isEqual'` | Replace with `==`: `peer.peer == otherPeer` | -| `cannot convert value of type 'EnginePeer' to expected argument type 'Peer?'` | Same as above: `._asPeer()` bridge | -| `pattern of type 'TelegramX' cannot match values of type 'EnginePeer'` | Missed C2 site — rewrite to `if case .X = peer.peer` form | -| `extraneous argument 'EnginePeer'` (when `.localPeer` etc. expected raw Peer) | Add `._asPeer()` bridge | - -For each error, identify the file:line, apply the appropriate fix, and re-run the build (Step 9.1) until clean. - -- [ ] **Step 9.3: Iterate to clean build** - -Re-run the build after each batch of fixes. The wave is complete when the build returns 0 errors. - -If 10+ unexpected errors surface, halt and reassess: the inventory was significantly incomplete and the wave may need to be split into pre-cleanup commits. Discuss with user. - ---- - -## Task 10: Post-build grep validations - -- [ ] **Step 10.1: Bridge-drop validation** - -Run: - -```bash -grep -rn "FoundPeer(peer:.*\._asPeer()" submodules/ --include="*.swift" | grep -v "^submodules/TelegramCore/" | grep -v "^submodules/Postbox/" -``` - -Expected: zero hits. If any remain, they are missed bridge-drops — fix and re-build. - -- [ ] **Step 10.2: C3 wrap validation** - -Run for each touched consumer file: - -```bash -for f in submodules/TelegramCallsUI/Sources/VideoChatScreen.swift \ - submodules/TelegramCallsUI/Sources/VideoChatScreenMoreMenu.swift \ - submodules/ContactListUI/Sources/ContactListNode.swift \ - submodules/ChatListUI/Sources/ChatListSearchListPaneNode.swift \ - submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoScreenCallActions.swift \ - submodules/TelegramBaseController/Sources/TelegramBaseController.swift \ - "submodules/SettingsUI/Sources/Data and Storage/StorageUsageExceptionsScreen.swift"; do - echo "=== $f ===" - grep -n "EnginePeer(peer\.peer)" "$f" -done -``` - -Expected: zero hits in each touched file. - -- [ ] **Step 10.3: C2 downcast validation** - -Run: - -```bash -for f in submodules/TelegramCallsUI/Sources/VideoChatScreenMoreMenu.swift \ - submodules/ContactListUI/Sources/ContactListNode.swift \ - submodules/ChatListUI/Sources/ChatListSearchListPaneNode.swift \ - submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoScreenCallActions.swift \ - submodules/TelegramBaseController/Sources/TelegramBaseController.swift; do - echo "=== $f ===" - grep -nE "peer\.peer\s+(as\?|is)\s+Telegram" "$f" -done -``` - -Expected: zero hits. - -If any of the validations fail, return to Task 9 to fix. - ---- - -## Task 11: Single atomic commit + memory + log update - -- [ ] **Step 11.1: Stage and review** - -Run: - -```bash -git status --short -git diff --stat -``` - -Confirm exactly 8 modified files (1 TelegramCore + 7 consumer) and no other unintended changes. WIP from earlier (`build-system/bazel-rules/sourcekit-bazel-bsp`, `ChatListFilterPresetController.swift`, `ChatListFilterPresetListController.swift`, untracked `build-system/tulsi/`, `submodules/TgVoip/`, `third-party/libx264/`) should NOT be staged. - -- [ ] **Step 11.2: Stage only the wave-34 files** - -Run: - -```bash -git add submodules/TelegramCore/Sources/TelegramEngine/Peers/SearchPeers.swift \ - submodules/TelegramCallsUI/Sources/VideoChatScreen.swift \ - submodules/TelegramCallsUI/Sources/VideoChatScreenMoreMenu.swift \ - submodules/ContactListUI/Sources/ContactListNode.swift \ - submodules/ChatListUI/Sources/ChatListSearchListPaneNode.swift \ - submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoScreenCallActions.swift \ - submodules/TelegramBaseController/Sources/TelegramBaseController.swift \ - "submodules/SettingsUI/Sources/Data and Storage/StorageUsageExceptionsScreen.swift" -``` - -- [ ] **Step 11.3: Commit** - -Run: - -```bash -git commit -m "$(cat <<'EOF' -Postbox -> TelegramEngine wave 34: FoundPeer.peer Peer -> EnginePeer - -Migrates the public field `FoundPeer.peer` from the Postbox `Peer` protocol -to the TelegramCore `EnginePeer` enum. The `_internal_searchPeers` body -keeps `import Postbox` (it still calls `postbox.transaction`) and wraps raw -peer values with `EnginePeer(peer)` at the FoundPeer constructor sites. - -Consumer-side cascade in 7 files: - - 5 `._asPeer()` bridge-drops at FoundPeer constructor sites - - 22 redundant `EnginePeer(peer.peer)` wrap drops (the field is now - EnginePeer, so the wrap fails to compile) - - 30 `peer.peer as? TelegramX` / `is TelegramX` Postbox-concrete - downcasts rewritten to `if case .X = peer.peer` enum-pattern form - - 3 `._asPeer()` bridges added where `peer.peer` flows into - `ContactListPeer.peer(peer:)` (downstream API still takes raw Peer) - - Manual `==` body updated from `lhs.peer.isEqual(rhs.peer)` to - `lhs.peer == rhs.peer` (EnginePeer is Equatable) - -Files modified: - submodules/TelegramCore/Sources/TelegramEngine/Peers/SearchPeers.swift - submodules/TelegramCallsUI/Sources/VideoChatScreen.swift - submodules/TelegramCallsUI/Sources/VideoChatScreenMoreMenu.swift - submodules/ContactListUI/Sources/ContactListNode.swift - submodules/ChatListUI/Sources/ChatListSearchListPaneNode.swift - submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoScreenCallActions.swift - submodules/TelegramBaseController/Sources/TelegramBaseController.swift - submodules/SettingsUI/Sources/Data and Storage/StorageUsageExceptionsScreen.swift - -Plan: docs/superpowers/plans/2026-04-24-foundpeer-engine-peer-migration.md -Spec: docs/superpowers/specs/2026-04-24-foundpeer-engine-peer-migration-design.md - -Co-Authored-By: Claude Opus 4.7 (1M context) -EOF -)" -``` - -- [ ] **Step 11.4: Update CLAUDE.md wave counter** - -Edit `CLAUDE.md` to bump the "Waves landed so far" line from "33 waves" to "34 waves" and update the "as of" date if changed. - -- [ ] **Step 11.5: Append wave outcome to the postbox-refactor-log** - -Append a new "Wave 34 outcome" section to `docs/superpowers/postbox-refactor-log.md` documenting the migration, the actual edit count (in case it differed from the planned ~70), and any lessons learned. Keep concise. - -- [ ] **Step 11.6: Commit the docs update** - -Run: - -```bash -git add CLAUDE.md docs/superpowers/postbox-refactor-log.md -git commit -m "$(cat <<'EOF' -docs: add wave 34 outcome (FoundPeer.peer Peer→EnginePeer) - -Co-Authored-By: Claude Opus 4.7 (1M context) -EOF -)" -``` - -- [ ] **Step 11.7: Update the next-wave memory** - -Update `/Users/isaac/.claude/projects/-Users-isaac-build-telegram-telegram-ios/memory/project_postbox_refactor_next_wave.md`: -- Add wave 34 to the "Latest commits" section -- Move FoundPeer migration from "Wave 34+ candidates" to landed -- Reframe remaining work: SendAsPeer, makePeerInfoController, etc., are now the next ring of Peer-typed-API waves -- Note any newly-surfaced bridge-add sites (the 3 `._asPeer()` bridges in ContactListNode point to `ContactListPeer.peer(peer:)` as the next downstream-API migration target) - -Use the Edit tool on the memory file. No git commit needed for the memory file (it's outside the repo). - ---- - -## Risks and notes - -- **Inner `peer` shadowing.** Several rewrites collapse `else if let peer = peer.peer as? TelegramChannel` patterns where the inner `peer` shadows the loop variable. The rewrites use `channel` as the new binding name to avoid double shadowing of the EnginePeer loop variable. Confirm subsequent uses of the bound name within the if-let scope are updated (e.g., `peer.info` becomes `channel.info`). -- **`replace_all` correctness.** Whenever the plan suggests `replace_all=true`, verify the count first via grep. If the count is unexpected, revert to per-site Edits with surrounding context. -- **Outflow-bridge surprises.** The plan enumerates 3 `._asPeer()` outflow bridges in ContactListNode. The build pass (Task 9) may surface 1–3 more in other touched files (e.g., ChatListSearchListPaneNode's `.localPeer` case). Apply the bridge pattern to each and iterate. -- **WIP isolation.** Pre-existing modifications to `ChatListFilterPresetController.swift`, `ChatListFilterPresetListController.swift`, the `sourcekit-bazel-bsp` submodule marker, and untracked `build-system/tulsi/` / `submodules/TgVoip/` / `third-party/libx264/` are user WIP — do NOT stage them. Use the explicit `git add ` form in Step 11.2. diff --git a/docs/superpowers/plans/2026-04-24-makeChatQrCodeScreen-recentActions-engine-peer-migration.md b/docs/superpowers/plans/2026-04-24-makeChatQrCodeScreen-recentActions-engine-peer-migration.md deleted file mode 100644 index f22b33ca5e..0000000000 --- a/docs/superpowers/plans/2026-04-24-makeChatQrCodeScreen-recentActions-engine-peer-migration.md +++ /dev/null @@ -1,411 +0,0 @@ -# Wave 40 — `makeChatQrCodeScreen` + `makeChatRecentActionsController` Peer → EnginePeer Implementation Plan - -> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. - -**Goal:** Bundle migrate two sibling `AccountContext` methods deferred from wave 39 — `makeChatQrCodeScreen` (4 consumer sites) and `makeChatRecentActionsController` (3 consumer sites) — from raw `peer: Peer` to `peer: EnginePeer`, applying the body-shadow pattern. - -**Architecture:** Body-shadow pattern (wave-38/39 style). Protocol + impl signatures change to `peer: EnginePeer`; each impl body gets a `let peer = peer._asPeer()` shadow so the downstream constructors (`ChatQrCodeScreenImpl`, `ChatRecentActionsController`) remain raw-`Peer` consumers (out of scope). - -**Tech Stack:** Swift, Bazel, iOS; TelegramCore / AccountContext / TelegramUI / PeerInfoUI / StatisticsUI / SettingsUI / ContactListUI / PeerInfoScreen submodules. - -**Reference:** Wave-39 "Out of scope" section in `docs/superpowers/specs/2026-04-24-makePeerInfoController-engine-peer-migration-design.md`. - ---- - -## Pre-flight classification - -**`makeChatQrCodeScreen` (4 consumer sites):** - -| # | Site | Shape | Edit | -|---|---|---|---| -| 1 | `SettingsSearchableItems.swift:974` | **Shape-A-variant** | Rewrite upstream `guard let peer = peer?._asPeer() else { return }` (line 971) → `guard let peer = peer else { return }`. Call stays `peer: peer`. | -| 2 | `SettingsSearchableItems.swift:992` | **Shape-A-variant** | Same pattern as #1 (upstream guard at line 989). | -| 3 | `ContactsController.swift:478` | **Shape-A** | Drop `._asPeer()` from `peer: peer._asPeer()` → `peer: peer`. Source: `Signal`. | -| 4 | `PeerInfoScreen.swift:4623` | **Shape-C** | Wrap: `peer: peer` → `peer: EnginePeer(peer)`. Source: `data.peer: Peer?`. | - -**`makeChatRecentActionsController` (3 consumer sites):** - -| # | Site | Shape | Edit | -|---|---|---|---| -| 5 | `ChannelAdminsController.swift:734` | **Shape-A** | Drop `._asPeer()`. Source: `engine.data.get(Peer.Peer(id:))` — `peer` is `EnginePeer` in the `guard let peer` on line 729. | -| 6 | `GroupStatsController.swift:915` | **Shape-A** | Drop `._asPeer()`. Source: `Signal` (mapToSignal at 906). | -| 7 | `PeerInfoScreenOpenChat.swift:115` | **Shape-C** | Wrap: `peer: peer` → `peer: EnginePeer(peer)`. Source: `self.data?.peer: Peer?`. | - -**Net bridge delta:** −5 `_asPeer()` drops (sites 1, 2, 3, 5, 6) + 2 `EnginePeer(...)` wraps (sites 4, 7) = **−3 net**. Sites 4 and 7 become ratchet markers for a future `PeerInfoScreenData.peer Peer → EnginePeer` wave. - ---- - -## File touch summary - -8 files: - -1. `submodules/AccountContext/Sources/AccountContext.swift` — protocol decls (2 lines). -2. `submodules/TelegramUI/Sources/SharedAccountContext.swift` — impl signatures + body shadows (2 sites). -3. `submodules/SettingsUI/Sources/Search/SettingsSearchableItems.swift` — 2 Shape-A-variant upstream guard rewrites. -4. `submodules/ContactListUI/Sources/ContactsController.swift` — 1 Shape-A drop. -5. `submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoScreen.swift` — 1 Shape-C wrap. -6. `submodules/PeerInfoUI/Sources/ChannelAdminsController.swift` — 1 Shape-A drop. -7. `submodules/StatisticsUI/Sources/GroupStatsController.swift` — 1 Shape-A drop. -8. `submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoScreenOpenChat.swift` — 1 Shape-C wrap. - ---- - -### Task 1: Update `AccountContext` protocol signatures - -**Files:** -- Modify: `submodules/AccountContext/Sources/AccountContext.swift:1401` and `:1461` - -- [ ] **Step 1: Update `makeChatRecentActionsController` decl** - -```swift -// old_string - func makeChatRecentActionsController(context: AccountContext, peer: Peer, adminPeerId: PeerId?, starsState: StarsRevenueStats?) -> ViewController - -// new_string - func makeChatRecentActionsController(context: AccountContext, peer: EnginePeer, adminPeerId: PeerId?, starsState: StarsRevenueStats?) -> ViewController -``` - -- [ ] **Step 2: Update `makeChatQrCodeScreen` decl** - -```swift -// old_string - func makeChatQrCodeScreen(context: AccountContext, peer: Peer, threadId: Int64?, temporary: Bool) -> ViewController - -// new_string - func makeChatQrCodeScreen(context: AccountContext, peer: EnginePeer, threadId: Int64?, temporary: Bool) -> ViewController -``` - ---- - -### Task 2: Update `SharedAccountContext` impls with body-shadow - -**Files:** -- Modify: `submodules/TelegramUI/Sources/SharedAccountContext.swift:2302` (makeChatRecentActionsController) -- Modify: `submodules/TelegramUI/Sources/SharedAccountContext.swift:2730` (makeChatQrCodeScreen) - -- [ ] **Step 1: Update `makeChatRecentActionsController` impl** - -```swift -// old_string - public func makeChatRecentActionsController(context: AccountContext, peer: Peer, adminPeerId: PeerId?, starsState: StarsRevenueStats?) -> ViewController { - return ChatRecentActionsController(context: context, peer: peer, adminPeerId: adminPeerId, starsState: starsState) - } - -// new_string - public func makeChatRecentActionsController(context: AccountContext, peer: EnginePeer, adminPeerId: PeerId?, starsState: StarsRevenueStats?) -> ViewController { - let peer = peer._asPeer() - return ChatRecentActionsController(context: context, peer: peer, adminPeerId: adminPeerId, starsState: starsState) - } -``` - -- [ ] **Step 2: Update `makeChatQrCodeScreen` impl** - -```swift -// old_string - public func makeChatQrCodeScreen(context: AccountContext, peer: Peer, threadId: Int64?, temporary: Bool) -> ViewController { - return ChatQrCodeScreenImpl(context: context, subject: .peer(peer: peer, threadId: threadId, temporary: temporary)) - } - -// new_string - public func makeChatQrCodeScreen(context: AccountContext, peer: EnginePeer, threadId: Int64?, temporary: Bool) -> ViewController { - let peer = peer._asPeer() - return ChatQrCodeScreenImpl(context: context, subject: .peer(peer: peer, threadId: threadId, temporary: temporary)) - } -``` - ---- - -### Task 3: `SettingsSearchableItems.swift` — two Shape-A-variant guard rewrites - -**Files:** -- Modify: `submodules/SettingsUI/Sources/Search/SettingsSearchableItems.swift:971` and `:989` - -Both sites share the same structure: an upstream `guard let peer = peer?._asPeer() else { return }` unwraps `EnginePeer?` to `Peer`. Rewrite the guard to keep the local as `EnginePeer`; the call site below stays unchanged. - -- [ ] **Step 1: Rewrite guard at line 971 (qr-code item)** - -```swift -// old_string - present: { context, _, present in - let _ = (context.engine.data.get(TelegramEngine.EngineData.Item.Peer.Peer(id: context.account.peerId)) - |> deliverOnMainQueue).start(next: { peer in - guard let peer = peer?._asPeer() else { - return - } - let controller = context.sharedContext.makeChatQrCodeScreen(context: context, peer: peer, threadId: nil, temporary: false) - present(.push, controller) - }) - } - ) - ) - - //TODO:fix - items.append( - SettingsSearchableItem( - id: "qr-code/share", - -// new_string - present: { context, _, present in - let _ = (context.engine.data.get(TelegramEngine.EngineData.Item.Peer.Peer(id: context.account.peerId)) - |> deliverOnMainQueue).start(next: { peer in - guard let peer = peer else { - return - } - let controller = context.sharedContext.makeChatQrCodeScreen(context: context, peer: peer, threadId: nil, temporary: false) - present(.push, controller) - }) - } - ) - ) - - //TODO:fix - items.append( - SettingsSearchableItem( - id: "qr-code/share", -``` - -- [ ] **Step 2: Rewrite guard at line 989 (qr-code/share item)** - -```swift -// old_string - id: "qr-code/share", - isVisible: false, - present: { context, _, present in - let _ = (context.engine.data.get(TelegramEngine.EngineData.Item.Peer.Peer(id: context.account.peerId)) - |> deliverOnMainQueue).start(next: { peer in - guard let peer = peer?._asPeer() else { - return - } - let controller = context.sharedContext.makeChatQrCodeScreen(context: context, peer: peer, threadId: nil, temporary: false) - present(.push, controller) - }) - } - -// new_string - id: "qr-code/share", - isVisible: false, - present: { context, _, present in - let _ = (context.engine.data.get(TelegramEngine.EngineData.Item.Peer.Peer(id: context.account.peerId)) - |> deliverOnMainQueue).start(next: { peer in - guard let peer = peer else { - return - } - let controller = context.sharedContext.makeChatQrCodeScreen(context: context, peer: peer, threadId: nil, temporary: false) - present(.push, controller) - }) - } -``` - ---- - -### Task 4: `ContactsController.swift` — Shape-A drop - -**Files:** -- Modify: `submodules/ContactListUI/Sources/ContactsController.swift:478` - -- [ ] **Step 1: Drop `._asPeer()` at the call site** - -```swift -// old_string - controller.present(strongSelf.context.sharedContext.makeChatQrCodeScreen(context: strongSelf.context, peer: peer._asPeer(), threadId: nil, temporary: false), in: .window(.root)) - -// new_string - controller.present(strongSelf.context.sharedContext.makeChatQrCodeScreen(context: strongSelf.context, peer: peer, threadId: nil, temporary: false), in: .window(.root)) -``` - ---- - -### Task 5: `PeerInfoScreen.swift` — Shape-C wrap - -**Files:** -- Modify: `submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoScreen.swift:4623` - -Local `peer` comes from `data.peer` (type `Peer`). Wrap at the call site. - -- [ ] **Step 1: Wrap with `EnginePeer(...)`** - -```swift -// old_string - let qrController = self.context.sharedContext.makeChatQrCodeScreen(context: self.context, peer: peer, threadId: threadId, temporary: temporary) - -// new_string - let qrController = self.context.sharedContext.makeChatQrCodeScreen(context: self.context, peer: EnginePeer(peer), threadId: threadId, temporary: temporary) -``` - ---- - -### Task 6: `ChannelAdminsController.swift` — Shape-A drop - -**Files:** -- Modify: `submodules/PeerInfoUI/Sources/ChannelAdminsController.swift:734` - -Local `peer` is `EnginePeer` (from `guard let peer` on :729 unwrapping `EnginePeer?` from `engine.data.get(Peer.Peer(id:))`). - -- [ ] **Step 1: Drop `._asPeer()`** - -```swift -// old_string - pushControllerImpl?(context.sharedContext.makeChatRecentActionsController(context: context, peer: peer._asPeer(), adminPeerId: nil, starsState: nil)) - -// new_string - pushControllerImpl?(context.sharedContext.makeChatRecentActionsController(context: context, peer: peer, adminPeerId: nil, starsState: nil)) -``` - ---- - -### Task 7: `GroupStatsController.swift` — Shape-A drop - -**Files:** -- Modify: `submodules/StatisticsUI/Sources/GroupStatsController.swift:915` - -Local `peer` is `EnginePeer` (from `Signal` via the `mapToSignal` at :906). - -- [ ] **Step 1: Drop `._asPeer()`** - -```swift -// old_string - let controller = context.sharedContext.makeChatRecentActionsController(context: context, peer: peer._asPeer(), adminPeerId: participantPeerId, starsState: nil) - -// new_string - let controller = context.sharedContext.makeChatRecentActionsController(context: context, peer: peer, adminPeerId: participantPeerId, starsState: nil) -``` - ---- - -### Task 8: `PeerInfoScreenOpenChat.swift` — Shape-C wrap - -**Files:** -- Modify: `submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoScreenOpenChat.swift:115` - -Local `peer` comes from `self.data?.peer` (type `Peer`). Wrap at the call site. - -- [ ] **Step 1: Wrap with `EnginePeer(...)`** - -```swift -// old_string - let controller = self.context.sharedContext.makeChatRecentActionsController(context: self.context, peer: peer, adminPeerId: nil, starsState: self.data?.starsRevenueStatsState) - -// new_string - let controller = self.context.sharedContext.makeChatRecentActionsController(context: self.context, peer: EnginePeer(peer), adminPeerId: nil, starsState: self.data?.starsRevenueStatsState) -``` - ---- - -### Task 9: Build + iterate - -- [ ] **Step 1: Run full build** - -```bash -source ~/.zshrc 2>/dev/null; python3 build-system/Make/Make.py --overrideXcodeVersion \ - --cacheDir ~/telegram-bazel-cache \ - build \ - --configurationPath build-system/appstore-configuration.json \ - --gitCodesigningRepository git@gitlab.com:peter-iakovlev/fastlanematch.git \ - --gitCodesigningType development --gitCodesigningUseCurrent --buildNumber=1 --configuration=debug_sim_arm64 \ - --continueOnError -``` - -Expected: first-pass-clean (wave 39's 50-file wave landed first-pass-clean; this 8-file wave should too). - -- [ ] **Step 2: If errors, iterate** - -Each error should point at a call site the plan missed. Fix, re-run. Do not widen the scope — if a call site not in the classification table above appears as an error, investigate whether the memory/inventory was stale. - ---- - -### Task 10: Verify no residue - -- [ ] **Step 1: Grep for raw-`Peer` sites** - -```bash -grep -rn "makeChatQrCodeScreen\|makeChatRecentActionsController" --include="*.swift" submodules/ -``` - -Expected output: 2 protocol-decl lines (AccountContext.swift), 2 impl-decl lines (SharedAccountContext.swift), and exactly 7 consumer sites — all with `peer: peer`, `peer: EnginePeer(peer)`, or similar (no `peer: x._asPeer()` remaining for these two methods). - ---- - -### Task 11: Commit + update refactor log - -**Files:** -- Modify: `docs/superpowers/postbox-refactor-log.md` — append wave-40 outcome section. - -- [ ] **Step 1: Stage exactly these 8 files (enumerate, do not use `git add -u`)** - -```bash -git add \ - submodules/AccountContext/Sources/AccountContext.swift \ - submodules/TelegramUI/Sources/SharedAccountContext.swift \ - submodules/SettingsUI/Sources/Search/SettingsSearchableItems.swift \ - submodules/ContactListUI/Sources/ContactsController.swift \ - submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoScreen.swift \ - submodules/PeerInfoUI/Sources/ChannelAdminsController.swift \ - submodules/StatisticsUI/Sources/GroupStatsController.swift \ - submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoScreenOpenChat.swift \ - docs/superpowers/plans/2026-04-24-makeChatQrCodeScreen-recentActions-engine-peer-migration.md -``` - -- [ ] **Step 2: Verify staging with `git status --short`** - -Verify only the 9 files above are staged. If other files appear (e.g. `ChatMessageTransitionNode.swift` WIP, `sourcekit-bazel-bsp` submodule marker) — reset them out of the index with `git restore --staged ` and re-check. - -- [ ] **Step 3: Commit (wave 40)** - -```bash -git commit -m "$(cat <<'EOF' -Postbox -> TelegramEngine wave 40 - -makeChatQrCodeScreen + makeChatRecentActionsController peer Peer->EnginePeer. - -- AccountContext protocol: 2 decls updated -- SharedAccountContext impls: 2 signatures + 2 body-shadow `let peer = peer._asPeer()` -- 5 Shape-A `._asPeer()` drops (SettingsSearchableItems x2 guard-variant, ContactsController, ChannelAdminsController, GroupStatsController) -- 2 Shape-C `EnginePeer(peer)` wraps (PeerInfoScreen, PeerInfoScreenOpenChat) -- Net: -3 bridges - -Sibling follow-up to wave 39 (makePeerInfoController). Pre-flight classification -completed in wave-39 design doc's "Out of scope" section. - -Co-Authored-By: Claude Opus 4.7 (1M context) -EOF -)" -``` - -- [ ] **Step 4: Log wave 40 outcome** - -Append a new section to `docs/superpowers/postbox-refactor-log.md`: - -```markdown -## Wave 40 outcome - -Commit: ``. Bundle of `AccountContext.makeChatQrCodeScreen` + `makeChatRecentActionsController` peer `Peer → EnginePeer`. 8 files / ~12 lines changed. Pre-flight classification from wave-39 design doc held: 5 Shape-A drops + 2 Shape-C wraps + 2 impl body-shadows + 2 protocol decls. Net −3 bridges. Build outcome: . - -Sibling follow-up to wave 39 — completes the "Option 1 cluster" (makePeerInfoController family from wave-38 memory). Ratchet markers installed at PeerInfoScreen:4623 and PeerInfoScreenOpenChat:115 for a future `PeerInfoScreenData.peer Peer → EnginePeer` wave. -``` - -Then commit the log update: - -```bash -git add docs/superpowers/postbox-refactor-log.md -git commit -m "$(cat <<'EOF' -docs: log wave 40 outcome - -Co-Authored-By: Claude Opus 4.7 (1M context) -EOF -)" -``` - -- [ ] **Step 5: Update memory** - -Update `/Users/isaac/.claude/projects/-Users-isaac-build-telegram-telegram-ios/memory/project_postbox_refactor_next_wave.md`: -- Move wave-40 (this bundle) from "candidates" to "Latest commits". -- Bump wave-41 recommendation to RenderedChannelParticipant.peer (Option 3) or RenderedPeer (Option 2). -- Add wave-40 lesson if any (e.g. "bundled sibling migration with shared pre-flight is cheap" or similar). - ---- - -## Self-review checklist (writing-plans skill) - -- **Spec coverage:** Every site from the memory/wave-39-doc pre-flight is a task. Sites 1+2 → Task 3; Site 3 → Task 4; Site 4 → Task 5; Site 5 → Task 6; Site 6 → Task 7; Site 7 → Task 8. Impl bodies → Task 2. Protocol → Task 1. Build → Task 9. Verify → Task 10. Commit+log → Task 11. ✓ -- **Placeholders:** None. Every Edit step has exact `old_string` / `new_string`. Commit message and log-update text are spelled out. ✓ -- **Type consistency:** Both methods take `peer: EnginePeer` everywhere — protocol decl, impl decl, and call sites' parameter passes. ✓ diff --git a/docs/superpowers/plans/2026-04-24-makePeerInfoController-engine-peer-migration.md b/docs/superpowers/plans/2026-04-24-makePeerInfoController-engine-peer-migration.md deleted file mode 100644 index 16e9a16adb..0000000000 --- a/docs/superpowers/plans/2026-04-24-makePeerInfoController-engine-peer-migration.md +++ /dev/null @@ -1,1037 +0,0 @@ -# Wave 39 — `makePeerInfoController` Peer → EnginePeer Implementation Plan - -> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. - -**Goal:** Migrate the `peer:` parameter of `AccountContext.makePeerInfoController` from raw `Peer` to `EnginePeer`, dropping 61 `_asPeer()` bridges and adding 12 `EnginePeer(...)` wraps. - -**Architecture:** Body-shadow pattern (wave-38 style). The protocol and impl signatures change to `peer: EnginePeer`. Inside the impl body, a `let peer = peer._asPeer()` shadow preserves the downstream `peerInfoControllerImpl` (private, same file) as a raw-`Peer` consumer — out of scope for this wave. - -**Tech Stack:** Swift, Bazel, iOS; TelegramCore / AccountContext / TelegramUI submodules. - -**Spec:** `docs/superpowers/specs/2026-04-24-makePeerInfoController-engine-peer-migration-design.md` - ---- - -## File touch summary - -- **Signature** (2 files): `submodules/AccountContext/Sources/AccountContext.swift`, `submodules/TelegramUI/Sources/SharedAccountContext.swift`. -- **Shape-A-variant** (1 file): `submodules/SettingsUI/Sources/Search/SettingsSearchableItems.swift` (3 sites). -- **Shape-C** (8 files, 12 sites): BlockedPeersController, ChannelMembersController, ChannelBlacklistController, ChatRecentActionsControllerNode, PeerInfoScreen, ChatControllerNavigationButtonAction (4), ChatControllerOpenPeer (2), ChatControllerLoadDisplayNode. -- **Shape-A** (~42 files, 58 sites): inline `peer: x._asPeer()` → `peer: x` drops. - -Total: ~50 files. - ---- - -### Task 1: Update `AccountContext` protocol signature - -**Files:** -- Modify: `submodules/AccountContext/Sources/AccountContext.swift:1371` - -- [ ] **Step 1: Apply edit** - -Change the protocol declaration to take `peer: EnginePeer` instead of `peer: Peer`. - -```swift -// old_string - func makePeerInfoController(context: AccountContext, updatedPresentationData: (initial: PresentationData, signal: Signal)?, peer: Peer, mode: PeerInfoControllerMode, avatarInitiallyExpanded: Bool, fromChat: Bool, requestsContext: PeerInvitationImportersContext?) -> ViewController? - -// new_string - func makePeerInfoController(context: AccountContext, updatedPresentationData: (initial: PresentationData, signal: Signal)?, peer: EnginePeer, mode: PeerInfoControllerMode, avatarInitiallyExpanded: Bool, fromChat: Bool, requestsContext: PeerInvitationImportersContext?) -> ViewController? -``` - ---- - -### Task 2: Update `SharedAccountContext` implementation + body-shadow + 3 self-call Shape-A drops - -**Files:** -- Modify: `submodules/TelegramUI/Sources/SharedAccountContext.swift:1937` (signature + body) -- Modify: `submodules/TelegramUI/Sources/SharedAccountContext.swift:3335, 3483, 4016` (Shape-A drops — 3 sites where `self.makePeerInfoController(...)` or `context.sharedContext.makePeerInfoController(...)` is called with `peer: peer._asPeer()`) - -- [ ] **Step 1: Update the impl signature and add body-shadow** - -```swift -// old_string - public func makePeerInfoController(context: AccountContext, updatedPresentationData: (initial: PresentationData, signal: Signal)?, peer: Peer, mode: PeerInfoControllerMode, avatarInitiallyExpanded: Bool, fromChat: Bool, requestsContext: PeerInvitationImportersContext?) -> ViewController? { - let controller = peerInfoControllerImpl(context: context, updatedPresentationData: updatedPresentationData, peer: peer, mode: mode, avatarInitiallyExpanded: avatarInitiallyExpanded, isOpenedFromChat: fromChat) - controller?.navigationPresentation = .modalInLargeLayout - return controller - } - -// new_string - public func makePeerInfoController(context: AccountContext, updatedPresentationData: (initial: PresentationData, signal: Signal)?, peer: EnginePeer, mode: PeerInfoControllerMode, avatarInitiallyExpanded: Bool, fromChat: Bool, requestsContext: PeerInvitationImportersContext?) -> ViewController? { - let peer = peer._asPeer() - let controller = peerInfoControllerImpl(context: context, updatedPresentationData: updatedPresentationData, peer: peer, mode: mode, avatarInitiallyExpanded: avatarInitiallyExpanded, isOpenedFromChat: fromChat) - controller?.navigationPresentation = .modalInLargeLayout - return controller - } -``` - -- [ ] **Step 2: Drop `._asPeer()` at line 3335** (inside `openProfileImpl = { [weak self, weak controller] peer in ...`) - -```swift -// old_string - peer: peer._asPeer(), - mode: .generic, - avatarInitiallyExpanded: peer.smallProfileImage != nil, - fromChat: false, - requestsContext: nil - ) { - controller.replace(with: infoController) - -// new_string - peer: peer, - mode: .generic, - avatarInitiallyExpanded: peer.smallProfileImage != nil, - fromChat: false, - requestsContext: nil - ) { - controller.replace(with: infoController) -``` - -- [ ] **Step 3: Drop `._asPeer()` at line 3483** - -Read 10 lines of context around 3483 to select a unique `old_string` and replace the `peer: peer._asPeer(),` line with `peer: peer,`. The surrounding arguments vary from the line-3335 site, so use a larger surrounding context (6+ lines) to make `old_string` unique. - -- [ ] **Step 4: Drop `._asPeer()` at line 4016** (inside `navigateToPeer: { [weak self] peer in ...` in `makeStarsTransferScreen`) - -```swift -// old_string - peer: peer._asPeer(), - mode: .generic, - avatarInitiallyExpanded: peer.smallProfileImage != nil, - fromChat: false, - requestsContext: nil - ) { - if let navigationController = self.mainWindow?.viewController as? NavigationController { - navigationController.pushViewController(infoController) - -// new_string - peer: peer, - mode: .generic, - avatarInitiallyExpanded: peer.smallProfileImage != nil, - fromChat: false, - requestsContext: nil - ) { - if let navigationController = self.mainWindow?.viewController as? NavigationController { - navigationController.pushViewController(infoController) -``` - ---- - -### Task 3: Shape-A-variant drops in `SettingsSearchableItems.swift` - -**Files:** -- Modify: `submodules/SettingsUI/Sources/Search/SettingsSearchableItems.swift` (lines 1020, 1046, 1080 — the guard statements upstream of the makePeerInfoController calls at 1023, 1049, 1083) - -The call-site line (`peer: peer,`) does not change — the upstream `guard let peer = peer?._asPeer() else` changes to `guard let peer = peer else`, making the local `peer` stay as `EnginePeer` instead of being unwrapped to raw `Peer`. - -- [ ] **Step 1: Line 1020** (inside the `id: "my-profile"` item) - -```swift -// old_string - |> deliverOnMainQueue).start(next: { peer in - guard let peer = peer?._asPeer() else { - return - } - let controller = context.sharedContext.makePeerInfoController( - context: context, - updatedPresentationData: nil, - peer: peer, - mode: .myProfile, - -// new_string - |> deliverOnMainQueue).start(next: { peer in - guard let peer = peer else { - return - } - let controller = context.sharedContext.makePeerInfoController( - context: context, - updatedPresentationData: nil, - peer: peer, - mode: .myProfile, -``` - -- [ ] **Step 2: Line 1046** (inside the `id: "my-profile/edit"` item) - -The `old_string` is nearly identical to Step 1. Since Edit tool requires uniqueness, use a broader context including the distinguishing `controller.activateEdit()` suffix (at line ~1062) or use `replace_all=false` with a larger context block. Recommended: include the `Queue.mainQueue().justDispatch { if let controller = controller as? PeerInfoScreen { controller.activateEdit() } }` block below the `present(.push, controller)` line to disambiguate. - -```swift -// old_string - |> deliverOnMainQueue).start(next: { peer in - guard let peer = peer?._asPeer() else { - return - } - let controller = context.sharedContext.makePeerInfoController( - context: context, - updatedPresentationData: nil, - peer: peer, - mode: .myProfile, - avatarInitiallyExpanded: false, - fromChat: false, - requestsContext: nil - ) - present(.push, controller) - - Queue.mainQueue().justDispatch { - if let controller = controller as? PeerInfoScreen { - controller.activateEdit() - } - } - }) - -// new_string - |> deliverOnMainQueue).start(next: { peer in - guard let peer = peer else { - return - } - let controller = context.sharedContext.makePeerInfoController( - context: context, - updatedPresentationData: nil, - peer: peer, - mode: .myProfile, - avatarInitiallyExpanded: false, - fromChat: false, - requestsContext: nil - ) - present(.push, controller) - - Queue.mainQueue().justDispatch { - if let controller = controller as? PeerInfoScreen { - controller.activateEdit() - } - } - }) -``` - -- [ ] **Step 3: Line 1080** (inside the `id: "my-profile/gifts"` item — distinguished by `mode: .myProfileGifts`) - -```swift -// old_string - |> deliverOnMainQueue).start(next: { peer in - guard let peer = peer?._asPeer() else { - return - } - let controller = context.sharedContext.makePeerInfoController( - context: context, - updatedPresentationData: nil, - peer: peer, - mode: .myProfileGifts, - -// new_string - |> deliverOnMainQueue).start(next: { peer in - guard let peer = peer else { - return - } - let controller = context.sharedContext.makePeerInfoController( - context: context, - updatedPresentationData: nil, - peer: peer, - mode: .myProfileGifts, -``` - ---- - -### Task 4: Shape-C wraps (12 sites across 8 files) - -**Files:** -- Modify: `submodules/SettingsUI/Sources/Privacy and Security/BlockedPeersController.swift:270` -- Modify: `submodules/PeerInfoUI/Sources/ChannelMembersController.swift:707` -- Modify: `submodules/PeerInfoUI/Sources/ChannelBlacklistController.swift:381` -- Modify: `submodules/TelegramUI/Components/Chat/ChatRecentActionsController/Sources/ChatRecentActionsControllerNode.swift:1011` -- Modify: `submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoScreen.swift:4306` -- Modify: `submodules/TelegramUI/Sources/Chat/ChatControllerNavigationButtonAction.swift:441, 461, 471, 492` -- Modify: `submodules/TelegramUI/Sources/Chat/ChatControllerOpenPeer.swift:218, 359` -- Modify: `submodules/TelegramUI/Sources/Chat/ChatControllerLoadDisplayNode.swift:4362` - -- [ ] **Step 1: BlockedPeersController.swift:270** - -```swift -// old_string - }, openPeer: { peer in - if let controller = context.sharedContext.makePeerInfoController(context: context, updatedPresentationData: nil, peer: peer, mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { - -// new_string - }, openPeer: { peer in - if let controller = context.sharedContext.makePeerInfoController(context: context, updatedPresentationData: nil, peer: EnginePeer(peer), mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { -``` - -- [ ] **Step 2: ChannelMembersController.swift:707** - -```swift -// old_string - if let infoController = context.sharedContext.makePeerInfoController(context: context, updatedPresentationData: nil, peer: participant.peer, mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { - pushControllerImpl?(infoController) - } - } - }, inviteViaLink: { - -// new_string - if let infoController = context.sharedContext.makePeerInfoController(context: context, updatedPresentationData: nil, peer: EnginePeer(participant.peer), mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { - pushControllerImpl?(infoController) - } - } - }, inviteViaLink: { -``` - -- [ ] **Step 3: ChannelBlacklistController.swift:381** - -```swift -// old_string - } else if let infoController = context.sharedContext.makePeerInfoController(context: context, updatedPresentationData: nil, peer: participant.peer, mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { - pushControllerImpl?(infoController) - } - })) - -// new_string - } else if let infoController = context.sharedContext.makePeerInfoController(context: context, updatedPresentationData: nil, peer: EnginePeer(participant.peer), mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { - pushControllerImpl?(infoController) - } - })) -``` - -- [ ] **Step 4: ChatRecentActionsControllerNode.swift:1011** - -```swift -// old_string - } else { - if let infoController = strongSelf.context.sharedContext.makePeerInfoController(context: strongSelf.context, updatedPresentationData: nil, peer: peer, mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { - strongSelf.pushController(infoController) - } - } - -// new_string - } else { - if let infoController = strongSelf.context.sharedContext.makePeerInfoController(context: strongSelf.context, updatedPresentationData: nil, peer: EnginePeer(peer), mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { - strongSelf.pushController(infoController) - } - } -``` - -- [ ] **Step 5: PeerInfoScreen.swift:4306** (inside `openPeerInfo(peer: Peer, isMember: Bool)`) - -```swift -// old_string - private func openPeerInfo(peer: Peer, isMember: Bool) { - let mode: PeerInfoControllerMode = .generic - if let infoController = self.context.sharedContext.makePeerInfoController(context: self.context, updatedPresentationData: nil, peer: peer, mode: mode, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { - -// new_string - private func openPeerInfo(peer: Peer, isMember: Bool) { - let mode: PeerInfoControllerMode = .generic - if let infoController = self.context.sharedContext.makePeerInfoController(context: self.context, updatedPresentationData: nil, peer: EnginePeer(peer), mode: mode, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { -``` - -- [ ] **Step 6: ChatControllerNavigationButtonAction.swift:441** - -Context: the outer `if let peer = self.presentationInterfaceState.renderedPeer?.chatMainPeer` binds `peer` to raw `Peer` (from `RenderedPeer.chatMainPeer` in `TelegramCore/Sources/Utils/PeerUtils.swift:512`). Wrap at the call site. - -```swift -// old_string - if let peer = self.presentationInterfaceState.renderedPeer?.chatMainPeer, let infoController = self.context.sharedContext.makePeerInfoController(context: self.context, updatedPresentationData: self.updatedPresentationData, peer: peer, mode: .generic, avatarInitiallyExpanded: false, fromChat: true, requestsContext: nil) { - self.effectiveNavigationController?.pushViewController(infoController) - } - -// new_string - if let peer = self.presentationInterfaceState.renderedPeer?.chatMainPeer, let infoController = self.context.sharedContext.makePeerInfoController(context: self.context, updatedPresentationData: self.updatedPresentationData, peer: EnginePeer(peer), mode: .generic, avatarInitiallyExpanded: false, fromChat: true, requestsContext: nil) { - self.effectiveNavigationController?.pushViewController(infoController) - } -``` - -- [ ] **Step 7: ChatControllerNavigationButtonAction.swift:461** - -Context: `peer` here is the outer `peer` bound from `peerView.peers[peerView.peerId]` (raw Peer) at line 418. Wrap at call site. - -```swift -// old_string - if let infoController = self.context.sharedContext.makePeerInfoController(context: self.context, updatedPresentationData: self.updatedPresentationData, peer: peer, mode: mode, avatarInitiallyExpanded: expandAvatar, fromChat: true, requestsContext: self.contentData?.inviteRequestsContext) { - self.effectiveNavigationController?.pushViewController(infoController) - } - } - - let _ = self.dismissPreviewing?(false) - -// new_string - if let infoController = self.context.sharedContext.makePeerInfoController(context: self.context, updatedPresentationData: self.updatedPresentationData, peer: EnginePeer(peer), mode: mode, avatarInitiallyExpanded: expandAvatar, fromChat: true, requestsContext: self.contentData?.inviteRequestsContext) { - self.effectiveNavigationController?.pushViewController(infoController) - } - } - - let _ = self.dismissPreviewing?(false) -``` - -- [ ] **Step 8: ChatControllerNavigationButtonAction.swift:471** - -Context: `if let peer = self.presentationInterfaceState.renderedPeer?.peer` — raw Peer from Postbox RenderedPeer. Wrap at call site. - -```swift -// old_string - if let peer = self.presentationInterfaceState.renderedPeer?.peer, case let .replyThread(replyThreadMessage) = self.chatLocation, replyThreadMessage.peerId == self.context.account.peerId { - if let infoController = self.context.sharedContext.makePeerInfoController(context: self.context, updatedPresentationData: self.updatedPresentationData, peer: peer, mode: .forumTopic(thread: replyThreadMessage), avatarInitiallyExpanded: false, fromChat: true, requestsContext: nil) { - self.effectiveNavigationController?.pushViewController(infoController) - } - -// new_string - if let peer = self.presentationInterfaceState.renderedPeer?.peer, case let .replyThread(replyThreadMessage) = self.chatLocation, replyThreadMessage.peerId == self.context.account.peerId { - if let infoController = self.context.sharedContext.makePeerInfoController(context: self.context, updatedPresentationData: self.updatedPresentationData, peer: EnginePeer(peer), mode: .forumTopic(thread: replyThreadMessage), avatarInitiallyExpanded: false, fromChat: true, requestsContext: nil) { - self.effectiveNavigationController?.pushViewController(infoController) - } -``` - -- [ ] **Step 9: ChatControllerNavigationButtonAction.swift:492** - -Context: `channel` is bound from `self.presentationInterfaceState.renderedPeer?.peer as? TelegramChannel` — raw `TelegramChannel`/`Peer`. Wrap at call site. - -```swift -// old_string - } else if let channel = self.presentationInterfaceState.renderedPeer?.peer as? TelegramChannel, channel.isForumOrMonoForum, case let .replyThread(message) = self.chatLocation { - if let infoController = self.context.sharedContext.makePeerInfoController(context: self.context, updatedPresentationData: self.updatedPresentationData, peer: channel, mode: .forumTopic(thread: message), avatarInitiallyExpanded: false, fromChat: true, requestsContext: self.contentData?.inviteRequestsContext) { - -// new_string - } else if let channel = self.presentationInterfaceState.renderedPeer?.peer as? TelegramChannel, channel.isForumOrMonoForum, case let .replyThread(message) = self.chatLocation { - if let infoController = self.context.sharedContext.makePeerInfoController(context: self.context, updatedPresentationData: self.updatedPresentationData, peer: EnginePeer(channel), mode: .forumTopic(thread: message), avatarInitiallyExpanded: false, fromChat: true, requestsContext: self.contentData?.inviteRequestsContext) { -``` - -- [ ] **Step 10: ChatControllerOpenPeer.swift:218** - -Context: `peer` is raw Peer from the outer closure parameter. - -```swift -// old_string - if let infoController = strongSelf.context.sharedContext.makePeerInfoController(context: strongSelf.context, updatedPresentationData: strongSelf.updatedPresentationData, peer: peer, mode: mode, avatarInitiallyExpanded: expandAvatar, fromChat: false, requestsContext: nil) { - strongSelf.effectiveNavigationController?.pushViewController(infoController) - } - -// new_string - if let infoController = strongSelf.context.sharedContext.makePeerInfoController(context: strongSelf.context, updatedPresentationData: strongSelf.updatedPresentationData, peer: EnginePeer(peer), mode: mode, avatarInitiallyExpanded: expandAvatar, fromChat: false, requestsContext: nil) { - strongSelf.effectiveNavigationController?.pushViewController(infoController) - } -``` - -- [ ] **Step 11: ChatControllerOpenPeer.swift:359** - -Context: `let peer = self.presentationInterfaceState.renderedPeer?.chatMainPeer` — raw Peer. - -```swift -// old_string - guard let self, let peer = self.presentationInterfaceState.renderedPeer?.chatMainPeer else { - return - } - - guard let controller = self.context.sharedContext.makePeerInfoController(context: self.context, updatedPresentationData: nil, peer: peer, mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) else { - -// new_string - guard let self, let peer = self.presentationInterfaceState.renderedPeer?.chatMainPeer else { - return - } - - guard let controller = self.context.sharedContext.makePeerInfoController(context: self.context, updatedPresentationData: nil, peer: EnginePeer(peer), mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) else { -``` - -- [ ] **Step 12: ChatControllerLoadDisplayNode.swift:4362** - -Context: `let peer = self.presentationInterfaceState.renderedPeer?.peer` — raw Peer. - -```swift -// old_string - guard let self, let peer = self.presentationInterfaceState.renderedPeer?.peer else { - return - } - if let controller = self.context.sharedContext.makePeerInfoController( - context: self.context, - updatedPresentationData: nil, - peer: peer, - mode: .gifts, - -// new_string - guard let self, let peer = self.presentationInterfaceState.renderedPeer?.peer else { - return - } - if let controller = self.context.sharedContext.makePeerInfoController( - context: self.context, - updatedPresentationData: nil, - peer: EnginePeer(peer), - mode: .gifts, -``` - ---- - -### Task 5: Shape-A drops across 42 files (55 remaining sites) - -Each Shape-A site swaps `peer: ._asPeer()` for `peer: ` at the listed line. Edits are mechanical; bundle into a single implementer dispatch if using subagent-driven development (wave-38 lesson). - -**Files with single sites (replace `peer: ._asPeer(),` or `peer: ._asPeer()` with the `_asPeer()` dropped):** - -Most sites have the pattern `peer: peer._asPeer()`. Use the full single-line `makePeerInfoController(...)` call as `old_string` when replacing to guarantee uniqueness. Two sites use different receivers: - -- `submodules/TelegramUI/Components/PeerInfo/AffiliateProgramSetupScreen/Sources/JoinAffiliateProgramScreen.swift:878` uses `peer: component.sourcePeer._asPeer(),` — drop to `peer: component.sourcePeer,`. -- `submodules/TelegramUI/Sources/Chat/ChatControllerNavigationButtonAction.swift:486` uses `peer: peer._asPeer()` where `peer` is `EnginePeer` (local name shadowed earlier inside `Task {}`). Drop to `peer: peer,`. - -- [ ] **Step 1: SelectivePrivacySettingsPeersController.swift:509** - -```swift -// old_string - guard let controller = context.sharedContext.makePeerInfoController(context: context, updatedPresentationData: nil, peer: peer._asPeer(), mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) else { - -// new_string - guard let controller = context.sharedContext.makePeerInfoController(context: context, updatedPresentationData: nil, peer: peer, mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) else { -``` - -- [ ] **Step 2: InstantPageControllerNode.swift:1766** - -```swift -// old_string - if let controller = strongSelf.context.sharedContext.makePeerInfoController(context: strongSelf.context, updatedPresentationData: nil, peer: peer._asPeer(), mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { - -// new_string - if let controller = strongSelf.context.sharedContext.makePeerInfoController(context: strongSelf.context, updatedPresentationData: nil, peer: peer, mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { -``` - -- [ ] **Step 3: CallListController.swift:375** - -```swift -// old_string - if let strongSelf = self, let peer = peer, let controller = strongSelf.context.sharedContext.makePeerInfoController(context: strongSelf.context, updatedPresentationData: nil, peer: peer._asPeer(), mode: .calls(messages: messages.map({ $0._asMessage() })), avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { - -// new_string - if let strongSelf = self, let peer = peer, let controller = strongSelf.context.sharedContext.makePeerInfoController(context: strongSelf.context, updatedPresentationData: nil, peer: peer, mode: .calls(messages: messages.map({ $0._asMessage() })), avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { -``` - -- [ ] **Step 4: ContactsController.swift:777** - -```swift -// old_string - if let infoController = strongSelf.context.sharedContext.makePeerInfoController(context: strongSelf.context, updatedPresentationData: nil, peer: peer._asPeer(), mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { - -// new_string - if let infoController = strongSelf.context.sharedContext.makePeerInfoController(context: strongSelf.context, updatedPresentationData: nil, peer: peer, mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { -``` - -- [ ] **Step 5: ContactContextMenus.swift:42** - -```swift -// old_string - guard let peer = peer, let controller = context.sharedContext.makePeerInfoController(context: context, updatedPresentationData: nil, peer: peer._asPeer(), mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) else { - -// new_string - guard let peer = peer, let controller = context.sharedContext.makePeerInfoController(context: context, updatedPresentationData: nil, peer: peer, mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) else { -``` - -- [ ] **Step 6: SecureIdAuthController.swift:343** - -```swift -// old_string - if let infoController = strongSelf.context.sharedContext.makePeerInfoController(context: strongSelf.context, updatedPresentationData: nil, peer: peer._asPeer(), mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { - -// new_string - if let infoController = strongSelf.context.sharedContext.makePeerInfoController(context: strongSelf.context, updatedPresentationData: nil, peer: peer, mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { -``` - -- [ ] **Step 7: ChannelAdminController.swift:1233** - -```swift -// old_string - if let controller = context.sharedContext.makePeerInfoController(context: context, updatedPresentationData: updatedPresentationData, peer: peer._asPeer(), mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { - -// new_string - if let controller = context.sharedContext.makePeerInfoController(context: context, updatedPresentationData: updatedPresentationData, peer: peer, mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { -``` - -- [ ] **Step 8: ChannelMembersController.swift:785** - -```swift -// old_string - if let infoController = context.sharedContext.makePeerInfoController(context: context, updatedPresentationData: nil, peer: peer._asPeer(), mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { - -// new_string - if let infoController = context.sharedContext.makePeerInfoController(context: context, updatedPresentationData: nil, peer: peer, mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { -``` - -- [ ] **Step 9: ChannelBannedMemberController.swift:785** - -```swift -// old_string - if let controller = context.sharedContext.makePeerInfoController(context: context, updatedPresentationData: updatedPresentationData, peer: peer._asPeer(), mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { - -// new_string - if let controller = context.sharedContext.makePeerInfoController(context: context, updatedPresentationData: updatedPresentationData, peer: peer, mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { -``` - -- [ ] **Step 10: ChannelPermissionsController.swift:1111** - -```swift -// old_string - if let controller = context.sharedContext.makePeerInfoController(context: context, updatedPresentationData: nil, peer: peer._asPeer(), mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { - -// new_string - if let controller = context.sharedContext.makePeerInfoController(context: context, updatedPresentationData: nil, peer: peer, mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { -``` - -- [ ] **Step 11: GroupStatsController.swift:883** - -```swift -// old_string - if let controller = context.sharedContext.makePeerInfoController(context: context, updatedPresentationData: nil, peer: peer._asPeer(), mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { - -// new_string - if let controller = context.sharedContext.makePeerInfoController(context: context, updatedPresentationData: nil, peer: peer, mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { -``` - -- [ ] **Step 12: MessageStatsController.swift:604** - -```swift -// old_string - if let controller = context.sharedContext.makePeerInfoController(context: context, updatedPresentationData: nil, peer: peer._asPeer(), mode: .generic, avatarInitiallyExpanded: peer.largeProfileImage != nil, fromChat: false, requestsContext: nil) { - -// new_string - if let controller = context.sharedContext.makePeerInfoController(context: context, updatedPresentationData: nil, peer: peer, mode: .generic, avatarInitiallyExpanded: peer.largeProfileImage != nil, fromChat: false, requestsContext: nil) { -``` - -- [ ] **Step 13: InviteRequestsController.swift:379** - -```swift -// old_string - if let navigationController = controller?.navigationController as? NavigationController, let controller = context.sharedContext.makePeerInfoController(context: context, updatedPresentationData: nil, peer: peer._asPeer(), mode: .generic, avatarInitiallyExpanded: peer.largeProfileImage != nil, fromChat: false, requestsContext: nil) { - -// new_string - if let navigationController = controller?.navigationController as? NavigationController, let controller = context.sharedContext.makePeerInfoController(context: context, updatedPresentationData: nil, peer: peer, mode: .generic, avatarInitiallyExpanded: peer.largeProfileImage != nil, fromChat: false, requestsContext: nil) { -``` - -- [ ] **Step 14: BrowserInstantPageContent.swift:1501** - -```swift -// old_string - if let controller = strongSelf.context.sharedContext.makePeerInfoController(context: strongSelf.context, updatedPresentationData: nil, peer: peer._asPeer(), mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { - -// new_string - if let controller = strongSelf.context.sharedContext.makePeerInfoController(context: strongSelf.context, updatedPresentationData: nil, peer: peer, mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { -``` - -- [ ] **Step 15: WebAppController.swift:3375** - -```swift -// old_string - if let infoController = self.context.sharedContext.makePeerInfoController(context: self.context, updatedPresentationData: nil, peer: peer._asPeer(), mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { - -// new_string - if let infoController = self.context.sharedContext.makePeerInfoController(context: self.context, updatedPresentationData: nil, peer: peer, mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { -``` - -- [ ] **Step 16: PeersNearbyController.swift:629** - -```swift -// old_string - if let navigationController = controller?.navigationController as? NavigationController, let controller = context.sharedContext.makePeerInfoController(context: context, updatedPresentationData: nil, peer: peer._asPeer(), mode: .nearbyPeer(distance: distance), avatarInitiallyExpanded: peer.largeProfileImage != nil, fromChat: false, requestsContext: nil) { - -// new_string - if let navigationController = controller?.navigationController as? NavigationController, let controller = context.sharedContext.makePeerInfoController(context: context, updatedPresentationData: nil, peer: peer, mode: .nearbyPeer(distance: distance), avatarInitiallyExpanded: peer.largeProfileImage != nil, fromChat: false, requestsContext: nil) { -``` - -- [ ] **Step 17: ChatSendStarsScreen.swift:2296** (multi-line call; edit the `peer: peer._asPeer(),` line only; include surrounding lines for uniqueness) - -Read the 5-line context around line 2296, then edit: - -```swift -// old_string (substring) - peer: peer._asPeer(), - -// new_string - peer: peer, -``` - -For uniqueness, include at least one neighboring argument line (e.g., the `mode:` line above or below) in the `old_string`. If truly unique (no other `peer: peer._asPeer(),` lines in this file), `replace_all=false` with this substring works. - -- [ ] **Step 18: ChatRecentActionsControllerNode.swift:1031** - -```swift -// old_string - if let infoController = strongSelf.context.sharedContext.makePeerInfoController(context: strongSelf.context, updatedPresentationData: nil, peer: peer._asPeer(), mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { - -// new_string - if let infoController = strongSelf.context.sharedContext.makePeerInfoController(context: strongSelf.context, updatedPresentationData: nil, peer: peer, mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { -``` - -- [ ] **Step 19: MiniAppListScreen.swift:230** - -```swift -// old_string - if let peerInfoScreen = component.context.sharedContext.makePeerInfoController(context: component.context, updatedPresentationData: nil, peer: peer._asPeer(), mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { - -// new_string - if let peerInfoScreen = component.context.sharedContext.makePeerInfoController(context: component.context, updatedPresentationData: nil, peer: peer, mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { -``` - -- [ ] **Step 20: JoinSubjectScreen.swift:320** (multi-line) - -Same pattern as Step 17. The `peer: peer._asPeer(),` line at 320 is the only such substring in the file; include the surrounding `mode:` line for safety. - -- [ ] **Step 21: NewContactScreen.swift:586** - -```swift -// old_string - if let infoController = component.context.sharedContext.makePeerInfoController(context: component.context, updatedPresentationData: nil, peer: peer._asPeer(), mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { - -// new_string - if let infoController = component.context.sharedContext.makePeerInfoController(context: component.context, updatedPresentationData: nil, peer: peer, mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { -``` - -- [ ] **Step 22: StarsTransactionScreen.swift:1958** - -```swift -// old_string - if let controller = context.sharedContext.makePeerInfoController(context: context, updatedPresentationData: nil, peer: peer._asPeer(), mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { - -// new_string - if let controller = context.sharedContext.makePeerInfoController(context: context, updatedPresentationData: nil, peer: peer, mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { -``` - -- [ ] **Step 23: StoryItemSetContainerComponent.swift:5629** - -```swift -// old_string - guard let chatController = component.context.sharedContext.makePeerInfoController(context: component.context, updatedPresentationData: nil, peer: peer._asPeer(), mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) else { - -// new_string - guard let chatController = component.context.sharedContext.makePeerInfoController(context: component.context, updatedPresentationData: nil, peer: peer, mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) else { -``` - -- [ ] **Step 24: StoryItemSetContainerComponent.swift:7619** (multi-line; same pattern as Step 17) - -- [ ] **Step 25: StoryItemSetContainerViewSendMessage.swift:3132** - -```swift -// old_string - if let infoController = context.sharedContext.makePeerInfoController(context: context, updatedPresentationData: nil, peer: peer._asPeer(), mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { - -// new_string - if let infoController = context.sharedContext.makePeerInfoController(context: context, updatedPresentationData: nil, peer: peer, mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { -``` - -- [ ] **Step 26: StoryItemSetContainerViewSendMessage.swift:3387** - -```swift -// old_string - if let infoController = component.context.sharedContext.makePeerInfoController(context: component.context, updatedPresentationData: nil, peer: peer._asPeer(), mode: mode, avatarInitiallyExpanded: expandAvatar, fromChat: false, requestsContext: nil) { - -// new_string - if let infoController = component.context.sharedContext.makePeerInfoController(context: component.context, updatedPresentationData: nil, peer: peer, mode: mode, avatarInitiallyExpanded: expandAvatar, fromChat: false, requestsContext: nil) { -``` - -- [ ] **Step 27: GiftViewScreen.swift:413, 561, 2252** (three multi-line sites in the same file; use `replace_all=false` with per-site surrounding context for uniqueness) - -Each site has `peer: peer._asPeer(),`. Read 4-line contexts around each line number to construct unique `old_string` blocks. Replace `peer: peer._asPeer(),` with `peer: peer,` in each. - -- [ ] **Step 28: GiftOptionsScreen.swift:930** (multi-line; same pattern as Step 17) - -- [ ] **Step 29: StorageUsageScreen.swift:2078** (multi-line; same pattern as Step 17) - -- [ ] **Step 30: TextProcessingScreen.swift:795** - -```swift -// old_string - if let peerInfoController = context.sharedContext.makePeerInfoController(context: context, updatedPresentationData: nil, peer: peer._asPeer(), mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { - -// new_string - if let peerInfoController = context.sharedContext.makePeerInfoController(context: context, updatedPresentationData: nil, peer: peer, mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { -``` - -- [ ] **Step 31: PeerInfoScreen.swift:6915, 7218** (two sites — the `old_string`s look identical; use `replace_all=true` or larger per-site context) - -Both lines are identical: `if let infoController = context.sharedContext.makePeerInfoController(context: context, updatedPresentationData: nil, peer: peer._asPeer(), mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) {`. If identical in full, `replace_all=true` with this `old_string` handles both. Verify by reading the two surrounding blocks first — if surrounding context differs, use two focused Edit calls instead. - -```swift -// old_string (both occurrences) - if let infoController = context.sharedContext.makePeerInfoController(context: context, updatedPresentationData: nil, peer: peer._asPeer(), mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { - -// new_string - if let infoController = context.sharedContext.makePeerInfoController(context: context, updatedPresentationData: nil, peer: peer, mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { -``` - -- [ ] **Step 32: PeerInfoScreenOpenURL.swift:28** - -```swift -// old_string - if let infoController = strongSelf.context.sharedContext.makePeerInfoController(context: strongSelf.context, updatedPresentationData: nil, peer: peer._asPeer(), mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { - -// new_string - if let infoController = strongSelf.context.sharedContext.makePeerInfoController(context: strongSelf.context, updatedPresentationData: nil, peer: peer, mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { -``` - -- [ ] **Step 33: JoinAffiliateProgramScreen.swift:878** (multi-line; `peer: component.sourcePeer._asPeer(),` → `peer: component.sourcePeer,`) - -- [ ] **Step 34: ChatControllerScrollToPointInHistory.swift:162** (multi-line; `peer: peer._asPeer(),` → `peer: peer,`) - -- [ ] **Step 35: OpenUrl.swift:175** - -```swift -// old_string - if let infoController = context.sharedContext.makePeerInfoController(context: context, updatedPresentationData: nil, peer: peer._asPeer(), mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { - -// new_string - if let infoController = context.sharedContext.makePeerInfoController(context: context, updatedPresentationData: nil, peer: peer, mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { -``` - -- [ ] **Step 36: OpenUrl.swift:535** (multi-line; `peer: peer._asPeer(),` → `peer: peer,`) - -- [ ] **Step 37: OpenResolvedUrl.swift:1810, 1831** (two multi-line sites; `peer: peer._asPeer(),` → `peer: peer,`; use per-site surrounding context for uniqueness) - -- [ ] **Step 38: TextLinkHandling.swift:45** - -```swift -// old_string - if let infoController = context.sharedContext.makePeerInfoController(context: context, updatedPresentationData: nil, peer: peer._asPeer(), mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { - -// new_string - if let infoController = context.sharedContext.makePeerInfoController(context: context, updatedPresentationData: nil, peer: peer, mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { -``` - -- [ ] **Step 39: ChatController.swift:9437** - -```swift -// old_string - if let infoController = strongSelf.context.sharedContext.makePeerInfoController(context: strongSelf.context, updatedPresentationData: strongSelf.updatedPresentationData, peer: peer._asPeer(), mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { - -// new_string - if let infoController = strongSelf.context.sharedContext.makePeerInfoController(context: strongSelf.context, updatedPresentationData: strongSelf.updatedPresentationData, peer: peer, mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { -``` - -- [ ] **Step 40: ChatManagingBotTitlePanelNode.swift:356** - -```swift -// old_string - if let controller = self.context.sharedContext.makePeerInfoController(context: self.context, updatedPresentationData: nil, peer: peer._asPeer(), mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { - -// new_string - if let controller = self.context.sharedContext.makePeerInfoController(context: self.context, updatedPresentationData: nil, peer: peer, mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { -``` - -- [ ] **Step 41: NavigateToChatController.swift:143** - -```swift -// old_string - if let controller = params.context.sharedContext.makePeerInfoController(context: params.context, updatedPresentationData: nil, peer: peer._asPeer(), mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { - -// new_string - if let controller = params.context.sharedContext.makePeerInfoController(context: params.context, updatedPresentationData: nil, peer: peer, mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { -``` - -- [ ] **Step 42: OverlayAudioPlayerControllerNode.swift:739** (multi-line) - -- [ ] **Step 43: OpenAddContact.swift:28** - -```swift -// old_string - if let infoController = context.sharedContext.makePeerInfoController(context: context, updatedPresentationData: nil, peer: peer._asPeer(), mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { - -// new_string - if let infoController = context.sharedContext.makePeerInfoController(context: context, updatedPresentationData: nil, peer: peer, mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { -``` - -- [ ] **Step 44: PollResultsController.swift:451** - -```swift -// old_string - if let controller = context.sharedContext.makePeerInfoController(context: context, updatedPresentationData: nil, peer: peer._asPeer(), mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { - -// new_string - if let controller = context.sharedContext.makePeerInfoController(context: context, updatedPresentationData: nil, peer: peer, mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { -``` - -- [ ] **Step 45: ChatControllerOpenWebApp.swift:485** - -```swift -// old_string - if let infoController = context.sharedContext.makePeerInfoController(context: context, updatedPresentationData: nil, peer: peer._asPeer(), mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { - -// new_string - if let infoController = context.sharedContext.makePeerInfoController(context: context, updatedPresentationData: nil, peer: peer, mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { -``` - -- [ ] **Step 46: ChatControllerNavigationButtonAction.swift:486** - -Context: inside `Task { @MainActor [weak self] in ...` — local `peer` was bound from `context.engine.data.get(...).get()` (returns `EnginePeer?`), and `_asPeer()` is called to pass to the current Peer-typed API. - -```swift -// old_string - if let infoController = self.context.sharedContext.makePeerInfoController(context: self.context, updatedPresentationData: self.updatedPresentationData, peer: peer._asPeer(), mode: .monoforum(monoforumPeer.id), avatarInitiallyExpanded: false, fromChat: true, requestsContext: nil) { - -// new_string - if let infoController = self.context.sharedContext.makePeerInfoController(context: self.context, updatedPresentationData: self.updatedPresentationData, peer: peer, mode: .monoforum(monoforumPeer.id), avatarInitiallyExpanded: false, fromChat: true, requestsContext: nil) { -``` - -- [ ] **Step 47: ChatListController.swift:1913** - -```swift -// old_string - if let peerInfoController = strongSelf.context.sharedContext.makePeerInfoController(context: strongSelf.context, updatedPresentationData: nil, peer: peer._asPeer(), mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { - -// new_string - if let peerInfoController = strongSelf.context.sharedContext.makePeerInfoController(context: strongSelf.context, updatedPresentationData: nil, peer: peer, mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { -``` - -- [ ] **Step 48: ChatListController.swift:3309** - -```swift -// old_string - guard let peer = peer, let controller = self.context.sharedContext.makePeerInfoController(context: self.context, updatedPresentationData: nil, peer: peer._asPeer(), mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) else { - -// new_string - guard let peer = peer, let controller = self.context.sharedContext.makePeerInfoController(context: self.context, updatedPresentationData: nil, peer: peer, mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) else { -``` - -- [ ] **Step 49: ChatListController.swift:3795** - -```swift -// old_string - guard let sourceController = sourceController, let peer = peer, let controller = context.sharedContext.makePeerInfoController(context: context, updatedPresentationData: nil, peer: peer._asPeer(), mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) else { - -// new_string - guard let sourceController = sourceController, let peer = peer, let controller = context.sharedContext.makePeerInfoController(context: context, updatedPresentationData: nil, peer: peer, mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) else { -``` - -- [ ] **Step 50: ChatListController.swift:7301** - -```swift -// old_string - guard let self, let peer = peer, let controller = self.context.sharedContext.makePeerInfoController(context: self.context, updatedPresentationData: nil, peer: peer._asPeer(), mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) else { - -// new_string - guard let self, let peer = peer, let controller = self.context.sharedContext.makePeerInfoController(context: self.context, updatedPresentationData: nil, peer: peer, mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) else { -``` - -- [ ] **Step 51: ChatListSearchListPaneNode.swift:4464** - -```swift -// old_string - if let peerInfoScreen = self.context.sharedContext.makePeerInfoController(context: self.context, updatedPresentationData: nil, peer: peer._asPeer(), mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { - -// new_string - if let peerInfoScreen = self.context.sharedContext.makePeerInfoController(context: self.context, updatedPresentationData: nil, peer: peer, mode: .generic, avatarInitiallyExpanded: false, fromChat: false, requestsContext: nil) { -``` - -**Site count check:** 51 steps listed. Multi-line sites (Steps 17, 20, 24, 27, 28, 29, 33, 34, 36, 37, 42) contain 1–3 sub-sites each; Step 27 covers 3 GiftViewScreen sites, Step 31 covers 2 PeerInfoScreen sites, Step 37 covers 2 OpenResolvedUrl sites. Running total: 51 + 2 (step 27 extras) + 1 (step 31 extra) + 1 (step 37 extra) = 55 sites. Adding 3 self-call sites in Task 2 = 58 Shape-A total. Correct. - ---- - -### Task 6: Full project build verification - -- [ ] **Step 1: Run build with `--continueOnError`** - -```bash -source ~/.zshrc 2>/dev/null; python3 build-system/Make/Make.py --overrideXcodeVersion \ - --cacheDir ~/telegram-bazel-cache \ - build \ - --configurationPath build-system/appstore-configuration.json \ - --gitCodesigningRepository git@gitlab.com:peter-iakovlev/fastlanematch.git \ - --gitCodesigningType development --gitCodesigningUseCurrent --buildNumber=1 \ - --configuration=debug_sim_arm64 --continueOnError -``` - -Expected: build succeeds. If errors, collect the error output for Task 7. - -Budget: 2–4 iterations. Expected runtime: 200–600 seconds per full build. - ---- - -### Task 7: Fix iteration-surfaced errors (if any) - -- [ ] **Step 1: Classify errors** - -Common expected categories: -- **Stored-field type mismatches:** a call site passes `peer` declared as raw `Peer` where the migrated API now wants `EnginePeer`. Fix with `EnginePeer(peer)` wrap at the call site (new Shape-C). -- **Closure-parameter type mismatches:** an outer closure types `peer` as `Peer`, fixed by wrapping at the call site with `EnginePeer(peer)`. -- **Downstream inference cascades:** transient errors in Peer-typed helpers not directly calling `makePeerInfoController`. Verify the helper is not `peerInfoControllerImpl` — if it is, investigate whether the body-shadow boundary was violated (abandonment criterion). - -- [ ] **Step 2: Apply fixes** - -For each unique error site, apply the minimum wrap/drop/shadow change. Do not edit `peerInfoControllerImpl` or any file outside the consumer set. If an error surfaces in `TelegramCore`/`Postbox`/`TelegramApi`, abandon. - -- [ ] **Step 3: Rerun the build** - -Loop back to Task 6 Step 1. Halt at iteration 5 per abandonment criterion. - ---- - -### Task 8: Commit atomically - -- [ ] **Step 1: Review staged diff** - -```bash -git status --short -git diff --stat -``` - -Expected: ~50 files touched. No unexpected files (e.g., `TelegramCore` or `Postbox` edits). - -- [ ] **Step 2: Stage and commit** - -```bash -git add \ - submodules/AccountContext/Sources/AccountContext.swift \ - submodules/TelegramUI/Sources/SharedAccountContext.swift \ - # ... (all touched files) - -git commit -m "$(cat <<'EOF' -Postbox -> TelegramEngine wave 39 - -Migrate AccountContext.makePeerInfoController's peer: parameter from -raw Peer to EnginePeer. Body-shadow pattern preserves downstream -peerInfoControllerImpl as a raw-Peer consumer (out of scope). - -73 consumer call sites across ~50 files: 58 Shape-A _asPeer() drops, -3 Shape-A-variant guard-statement drops, 12 Shape-C EnginePeer(...) -wraps. Net -49 bridges. - -Co-Authored-By: Claude Opus 4.7 (1M context) -EOF -)" -``` - -- [ ] **Step 3: Verify commit** - -```bash -git log --oneline -n 3 -git show --stat HEAD -``` - ---- - -### Task 9: Update memory + log + CLAUDE.md - -- [ ] **Step 1: Append outcome entry to `docs/superpowers/postbox-refactor-log.md`** - -Append a "Wave 39 outcome" section with: commit SHA, file count, line-change count, Shape-A/Shape-A-variant/Shape-C tallies, build iteration count, any surprises, any lesson worth adding to wave-selection guidance. - -- [ ] **Step 2: Update `project_postbox_refactor_next_wave.md` memory** - -Rewrite "Latest commits" and "Wave 39/40 candidates" sections. Promote `makeChatQrCodeScreen` + `makeChatRecentActionsController` to wave 40 (the trivial follow-up). Keep `RenderedPeer → EngineRenderedPeer`, accountManager-side engine path, Shape-C resourceData, and cached-rep triple on the shortlist. - -- [ ] **Step 3: Update `CLAUDE.md` wave tally** - -The "Waves landed so far" line on CLAUDE.md:44 currently says "36 waves plus standalone cleanups" (stale — waves 37 and 38 landed 2026-04-24 but CLAUDE.md wasn't updated). Bump the tally to "39 waves plus standalone cleanups". - -- [ ] **Step 4: Commit the docs update** - -```bash -git add docs/superpowers/postbox-refactor-log.md CLAUDE.md -git commit -m "$(cat <<'EOF' -docs: log wave 39 outcome - -Co-Authored-By: Claude Opus 4.7 (1M context) -EOF -)" -``` - -Memory file is in `~/.claude/projects/.../memory/` — saved via Write, not git-committed. - ---- - -## Self-review checklist (run before handoff) - -- [x] Every numbered Shape-A site in the spec has a corresponding Step in Task 5 (or Task 2/3 for in-signature-file sites). -- [x] Every Shape-C site in the spec table has a corresponding Step in Task 4. -- [x] Protocol + impl signatures shown verbatim. -- [x] Build command includes `source ~/.zshrc 2>/dev/null;` prefix and `--continueOnError`. -- [x] Abandonment criteria inherited from spec. -- [x] No placeholders, TBD, or "implement later". -- [x] Commit message matches the project's wave-NN style (see `git log` output for prior waves). diff --git a/docs/superpowers/plans/2026-04-24-peerinfoscreen-helpers-engine-peer-migration.md b/docs/superpowers/plans/2026-04-24-peerinfoscreen-helpers-engine-peer-migration.md deleted file mode 100644 index 560e79b10c..0000000000 --- a/docs/superpowers/plans/2026-04-24-peerinfoscreen-helpers-engine-peer-migration.md +++ /dev/null @@ -1,658 +0,0 @@ -# Wave 43 plan: PeerInfoScreen helpers `peer: Peer?` → `peer: EnginePeer?` - -> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. - -**Goal:** Migrate six PeerInfoScreen module helpers (`canEditPeerInfo`, `availableActionsForMemberOfPeer`, `peerInfoHeaderActionButtons`, `peerInfoHeaderButtons`, `peerInfoCanEdit`, `peerInfoIsChatMuted`) from `peer: Peer?` to `peer: EnginePeer?`, rewriting internal `as?`/`is` against concrete `TelegramX` subclasses to `case let .x` / `case .x` enum patterns on `EnginePeer`, and updating all 21 call sites to drop wave-42-installed `._asPeer()` / `?._asPeer()` bridges or add `.flatMap(EnginePeer.init)` / `EnginePeer(...)` wraps as appropriate. - -**Architecture:** In-place signature migration following wave-42 precedent — no new typealiases, no engine wrapper structs, no TelegramCore changes. All edits within `submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/` (10 files). Single atomic commit. - -**Tech Stack:** Swift, Bazel build, `EnginePeer` enum cases (`.user(TelegramUser)`, `.legacyGroup(TelegramGroup)`, `.channel(TelegramChannel)`, `.secretChat(TelegramSecretChat)`). - -**Preceding waves:** 42 (`PeerInfoScreenData.peer: Peer? → EnginePeer?`) on 2026-04-24. This wave drops ~7 `?._asPeer()` / `._asPeer()` bridges installed then. - -**Expected net wrap change:** ~7 DROPs vs ~12 ADDs → net roughly 0. The headline win is helper-signature migration, not wrap count. Follow-up waves migrating `PeerInfoHeaderEditingContentNode.update`, `PeerInfoEditingAvatarNode.update`, `PeerInfoEditingAvatarOverlayNode.update`, `PeerInfoHeaderNode.update`, `PeerInfoScreenMemberItem.enclosingPeer`, `PeerInfoMembersPane` enclosingPeer param will drop the ADDs introduced here. - -**Build expectation:** 2 iterations likely (per wave-41 lesson — foundational-type migrations rarely first-pass-clean). Hedge for iteration-3 if unexpected property accesses surface. - ---- - -## Pre-flight facts (verified from repo 2026-04-24) - -### EnginePeer cases (from `submodules/TelegramCore/Sources/TelegramEngine/Peers/Peer.swift:177`) - -``` -case user(TelegramUser) -case legacyGroup(TelegramGroup) -case channel(TelegramChannel) -case secretChat(TelegramSecretChat) -``` - -Forwarded property subset on `EnginePeer` includes `id`, `addressName`, `usernames`, `indexName`, `debugDisplayTitle`, `displayLetters`, `profileImageRepresentations`, `smallProfileImage`, `largeProfileImage`, `isDeleted`, `isScam`, `isFake`, `isVerified`, `isPremium`, `isSubscription`, `isService`, `nameColor`, `verificationIconFileId`, `profileColor`, `effectiveProfileColor`, `emojiStatus`, `backgroundEmojiId`, `profileBackgroundEmojiId`, and (via `LocalizedPeerData/Sources/PeerTitle.swift`) `compactDisplayTitle`, `displayTitle(strings:displayOrder:)`. **Not** forwarded: Peer-specific members like `isCopyProtectionEnabled`, `hasPermission(_:)`, `hasBannedPermission(_:)`, `isDeleted` on user (WAIT: yes forwarded). **Internal helper bodies do not access any non-forwarded Peer members** — all their concrete-type work happens via `as? TelegramX`, which is enum-rewrite territory. Confirmed by reading helper bodies (PeerInfoData.swift:2255–2670). - -### Helper call sites inventory (21 sites across 10 files) - -Running command: - -```bash -grep -rn "\bcanEditPeerInfo\b\|\bavailableActionsForMemberOfPeer\b\|\bpeerInfoHeaderActionButtons\b\|\bpeerInfoHeaderButtons\b\|\bpeerInfoCanEdit\b\|\bpeerInfoIsChatMuted\b" submodules/ --include="*.swift" | grep -v PeerInfoData.swift -``` - -All 21 call sites: - -| # | File | Line | Current arg | Peer var origin | Action | -|---|------|------|-------------|-----------------|--------| -| 1 | `PeerInfoHeaderNode.swift` | 548 | `peer: peer` | method param `peer: Peer?` | ADD-WRAP: `peer: peer.flatMap(EnginePeer.init)` | -| 2 | `PeerInfoHeaderNode.swift` | 549 | `peer: peer` | same | ADD-WRAP | -| 3 | `PeerInfoHeaderNode.swift` | 2361 | `peer: peer` | same | ADD-WRAP | -| 4 | `PeerInfoEditingAvatarNode.swift` | 66 | `peer: peer` | method param `peer: Peer?` (unwrapped via `guard let peer = peer`) | ADD-WRAP: `peer: EnginePeer(peer)` (peer is non-optional `Peer` here) | -| 5 | `PeerInfoEditingAvatarOverlayNode.swift` | 85 | `peer: peer` | method param `peer: Peer?` (unwrapped via `guard let peer = peer`) | ADD-WRAP: `peer: EnginePeer(peer)` | -| 6 | `PeerInfoHeaderEditingContentNode.swift` | 59 | `peer: peer` | method param `peer: Peer?` | ADD-WRAP: `peer: peer.flatMap(EnginePeer.init)` | -| 7 | `PeerInfoHeaderEditingContentNode.swift` | 88 | `peer: peer` | same | ADD-WRAP | -| 8 | `PeerInfoHeaderEditingContentNode.swift` | 93 | `peer: peer` | same | ADD-WRAP | -| 9 | `PeerInfoHeaderEditingContentNode.swift` | 159 | `peer: peer` | same | ADD-WRAP | -| 10 | `PeerInfoHeaderEditingContentNode.swift` | 162 | `peer: peer` | same | ADD-WRAP | -| 11 | `PeerInfoScreenAvatarSetup.swift` | 435 | `peer: peer._asPeer()` | `peer = data.peer` (EnginePeer unwrapped) | DROP: `peer: peer` | -| 12 | `PeerInfoScreenPerformButtonAction.swift` | 62 | `peer: self.data?.peer?._asPeer()` | `self.data?.peer` is `EnginePeer?` | DROP: `peer: self.data?.peer` | -| 13 | `PeerInfoScreenPerformButtonAction.swift` | 397 | `peer: peer._asPeer()` | `peer = data.peer` unwrapped at line 381 | DROP: `peer: peer` | -| 14 | `PeerInfoScreenPerformButtonAction.swift` | 398 | `peer: peer._asPeer()` | same | DROP: `peer: peer` | -| 15 | `PeerInfoScreenOpenMember.swift` | 19 | `peer: enclosingPeer._asPeer()` | `enclosingPeer = self.data?.peer` unwrapped at line 14 | DROP: `peer: enclosingPeer` | -| 16 | `PeerInfoScreen.swift` | 1905 | `peer: group` | `group: TelegramGroup` from `if case let .legacyGroup(group) = data.peer` | CONVERT: `peer: data.peer` | -| 17 | `PeerInfoScreen.swift` | 1961 | `peer: channel` | `channel: TelegramChannel` from `if case let .channel(channel) = data.peer` | CONVERT: `peer: data.peer` | -| 18 | `PeerInfoScreen.swift` | 5857 | `peer: self.data?.peer?._asPeer()` | `self.data?.peer` is `EnginePeer?` | DROP: `peer: self.data?.peer` | -| 19 | `PeerInfoProfileItems.swift` | 853 | `peer: peer._asPeer()` | `peer = data.peer` unwrapped at line 821 | DROP: `peer: peer` | -| 20 | `PeerInfoScreenMemberItem.swift` | 178 | `peer: item.enclosingPeer` | `item.enclosingPeer: Peer` (stored raw) | ADD-WRAP: `peer: EnginePeer(item.enclosingPeer)` | -| 21 | `PeerInfoMembersPane.swift` | 139 | `peer: enclosingPeer` | `enclosingPeer: Peer` (local raw) | ADD-WRAP: `peer: EnginePeer(enclosingPeer)` | - -**Summary:** 7 DROPs (sites 11–15, 18, 19), 10 ADD-WRAPs (1–10, 20, 21 = 12 total ADDs), 2 CONVERTs (16, 17 — from concrete-type arg to whole-EnginePeer; no wrap delta but simpler/safer). - -### `is TelegramX` scan on helper bodies - -Only `peerInfoIsChatMuted` has them (PeerInfoData.swift:2641, 2643). Rewrite pattern: `if peer is TelegramUser` → `if case .user = peer`, `else if peer is TelegramGroup` → `else if case .legacyGroup = peer`. - -No `is TelegramX` checks exist at call sites for these specific helpers (wave-42 would have caught them since call-site `data.peer` is already `EnginePeer?`). - ---- - -## File Structure - -All edits within `submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/`: - -**Modify (helper definitions):** -- `PeerInfoData.swift:2265–2670` — 6 helper signatures + bodies - -**Modify (call sites):** -- `PeerInfoScreen.swift` (3 sites: 1905, 1961, 5857) -- `PeerInfoHeaderNode.swift` (3 sites: 548, 549, 2361) -- `PeerInfoEditingAvatarNode.swift` (1 site: 66) -- `PeerInfoEditingAvatarOverlayNode.swift` (1 site: 85) -- `PeerInfoHeaderEditingContentNode.swift` (5 sites: 59, 88, 93, 159, 162) -- `PeerInfoScreenAvatarSetup.swift` (1 site: 435) -- `PeerInfoScreenPerformButtonAction.swift` (3 sites: 62, 397, 398) -- `PeerInfoScreenOpenMember.swift` (1 site: 19) -- `PeerInfoProfileItems.swift` (1 site: 853) -- `ListItems/PeerInfoScreenMemberItem.swift` (1 site: 178) -- `Panes/PeerInfoMembersPane.swift` (1 site: 139) - -Total: 10 files modified (PeerInfoData.swift counts once). - ---- - -### Task 1: Migrate the six helper signatures and bodies in `PeerInfoData.swift` - -**Files:** -- Modify: `submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoData.swift:2265–2670` - -- [ ] **Step 1: Migrate `canEditPeerInfo` (line 2265).** Signature: `peer: Peer?` → `peer: EnginePeer?`. Body rewrites: - -```swift -// before (line 2269-2287) -if let user = peer as? TelegramUser, let botInfo = user.botInfo { - return botInfo.flags.contains(.canEdit) -} else if let channel = peer as? TelegramChannel { - if let threadData = threadData { - if chatLocation.threadId == 1 { - return false - } - if channel.hasPermission(.manageTopics) { - return true - } - if threadData.author == context.account.peerId { - return true - } - } else { - if channel.hasPermission(.changeInfo) { - return true - } - } -} else if let group = peer as? TelegramGroup { - switch group.role { - case .admin, .creator: - return true - case .member: - break - } - if !group.hasBannedPermission(.banChangeInfo) { - return true - } -} - -// after -if case let .user(user) = peer, let botInfo = user.botInfo { - return botInfo.flags.contains(.canEdit) -} else if case let .channel(channel) = peer { - if let threadData = threadData { - if chatLocation.threadId == 1 { - return false - } - if channel.hasPermission(.manageTopics) { - return true - } - if threadData.author == context.account.peerId { - return true - } - } else { - if channel.hasPermission(.changeInfo) { - return true - } - } -} else if case let .legacyGroup(group) = peer { - switch group.role { - case .admin, .creator: - return true - case .member: - break - } - if !group.hasBannedPermission(.banChangeInfo) { - return true - } -} -``` - -The `if context.account.peerId == peer?.id` line (2266) stays identical (`.id` is forwarded by `EnginePeer`). - -- [ ] **Step 2: Migrate `availableActionsForMemberOfPeer` (line 2314).** Signature: `peer: Peer?` → `peer: EnginePeer?`. Body rewrites — four `peer as? TelegramChannel/TelegramGroup` sites become `case let .channel/.legacyGroup` patterns: - -```swift -// Line 2320: if let channel = peer as? TelegramChannel -// → : if case let .channel(channel) = peer - -// Line 2324: } else if let group = peer as? TelegramGroup { -// → : } else if case let .legacyGroup(group) = peer { - -// Line 2330: if let channel = peer as? TelegramChannel -// → : if case let .channel(channel) = peer - -// Line 2374: } else if let group = peer as? TelegramGroup { -// → : } else if case let .legacyGroup(group) = peer { -``` - -The `if peer == nil` check (line 2317) stays identical (Optional == nil works on EnginePeer? too). - -- [ ] **Step 3: Migrate `peerInfoHeaderActionButtons` (line 2434).** Signature: `peer: Peer?` → `peer: EnginePeer?`. Single body rewrite at line 2436: - -```swift -// before -if !isContact && !isSecretChat, let user = peer as? TelegramUser, user.botInfo == nil { - -// after -if !isContact && !isSecretChat, case let .user(user) = peer, user.botInfo == nil { -``` - -- [ ] **Step 4: Migrate `peerInfoHeaderButtons` (line 2447).** Signature: `peer: Peer?` → `peer: EnginePeer?`. Three body rewrites: - -```swift -// Line 2449: if let user = peer as? TelegramUser { -// → : if case let .user(user) = peer { - -// Line 2483: } else if let channel = peer as? TelegramChannel { -// → : } else if case let .channel(channel) = peer { - -// Line 2558: } else if let group = peer as? TelegramGroup { -// → : } else if case let .legacyGroup(group) = peer { -``` - -- [ ] **Step 5: Migrate `peerInfoCanEdit` (line 2585).** Signature: `peer: Peer?` → `peer: EnginePeer?`. Three body rewrites. Note: original shadows `peer` inside each branch (`let peer = peer as? TelegramX`). Rewrite preserves the shadowing via `case let`: - -```swift -// Line 2586: if let user = peer as? TelegramUser { -// → : if case let .user(user) = peer { - -// Line 2597: } else if let peer = peer as? TelegramChannel { -// → : } else if case let .channel(peer) = peer { -// (intentional shadow of outer `peer` with inner `peer: TelegramChannel` — preserved) - -// Line 2618: } else if let peer = peer as? TelegramGroup { -// → : } else if case let .legacyGroup(peer) = peer { -``` - -- [ ] **Step 6: Migrate `peerInfoIsChatMuted` (line 2633).** Outer signature: `peer: Peer?` → `peer: EnginePeer?`. Inner function signature (line 2634) also migrates: `func isPeerMuted(peer: Peer?, ...)` → `func isPeerMuted(peer: EnginePeer?, ...)`. Body rewrites inside the inner function (line 2641–2651): - -```swift -// before (line 2641) -if peer is TelegramUser { - peerIsMuted = !globalNotificationSettings.privateChats.enabled -} else if peer is TelegramGroup { - peerIsMuted = !globalNotificationSettings.groupChats.enabled -} else if let channel = peer as? TelegramChannel { - switch channel.info { - case .group: - peerIsMuted = !globalNotificationSettings.groupChats.enabled - case .broadcast: - peerIsMuted = !globalNotificationSettings.channels.enabled - } -} - -// after -if case .user = peer { - peerIsMuted = !globalNotificationSettings.privateChats.enabled -} else if case .legacyGroup = peer { - peerIsMuted = !globalNotificationSettings.groupChats.enabled -} else if case let .channel(channel) = peer { - switch channel.info { - case .group: - peerIsMuted = !globalNotificationSettings.groupChats.enabled - case .broadcast: - peerIsMuted = !globalNotificationSettings.channels.enabled - } -} -``` - -The outer `if let peer = peer` (line 2640) stays unchanged (Optional binding works on EnginePeer?). - -The inner `peerInfoIsChatMuted` body (line 2659–2669) calls `isPeerMuted(peer: peer, ...)` with the outer `peer` (now EnginePeer?) — works without change because inner signature now matches. - -- [ ] **Step 7: Re-read PeerInfoData.swift lines 2265–2670 and visually verify no `as? TelegramX` or `is TelegramX` patterns remain.** - -Run: `grep -n "as? TelegramUser\|as? TelegramChannel\|as? TelegramGroup\|is TelegramUser\|is TelegramChannel\|is TelegramGroup" submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoData.swift | awk -F: '$2 >= 2265 && $2 <= 2670'` -Expected: empty output. - ---- - -### Task 2: Update call sites — DROPs (7 sites) - -**Files:** -- Modify: `submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoScreenAvatarSetup.swift:435` -- Modify: `submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoScreenPerformButtonAction.swift:62,397,398` -- Modify: `submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoScreenOpenMember.swift:19` -- Modify: `submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoScreen.swift:5857` -- Modify: `submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoProfileItems.swift:853` - -- [ ] **Step 1: DROP at `PeerInfoScreenAvatarSetup.swift:435`.** - -```swift -// before -guard let data = self.controllerNode.data, let peer = data.peer, mode != .generic || canEditPeerInfo(context: self.context, peer: peer._asPeer(), chatLocation: self.chatLocation, threadData: data.threadData) else { - -// after -guard let data = self.controllerNode.data, let peer = data.peer, mode != .generic || canEditPeerInfo(context: self.context, peer: peer, chatLocation: self.chatLocation, threadData: data.threadData) else { -``` - -- [ ] **Step 2: DROP at `PeerInfoScreenPerformButtonAction.swift:62`.** - -```swift -// before -let chatIsMuted = peerInfoIsChatMuted(peer: self.data?.peer?._asPeer(), peerNotificationSettings: self.data?.peerNotificationSettings, threadNotificationSettings: self.data?.threadNotificationSettings, globalNotificationSettings: self.data?.globalNotificationSettings) - -// after -let chatIsMuted = peerInfoIsChatMuted(peer: self.data?.peer, peerNotificationSettings: self.data?.peerNotificationSettings, threadNotificationSettings: self.data?.threadNotificationSettings, globalNotificationSettings: self.data?.globalNotificationSettings) -``` - -- [ ] **Step 3: DROP at `PeerInfoScreenPerformButtonAction.swift:397 and :398` (peerInfoHeaderButtons, two lines, same pattern `peer: peer._asPeer()` → `peer: peer`).** - -Use Edit with `replace_all=true` on the substring `peer: peer._asPeer(), cachedData: data.cachedData` — this exact form appears exactly twice in the file (lines 397, 398), both targets. - -```swift -// before (at both 397 and 398) -peerInfoHeaderButtons(peer: peer._asPeer(), cachedData: data.cachedData, isOpenedFromChat: ... - -// after -peerInfoHeaderButtons(peer: peer, cachedData: data.cachedData, isOpenedFromChat: ... -``` - -Verification after edit: - -```bash -grep -n "_asPeer()" submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoScreenPerformButtonAction.swift -``` -Expected: empty (all three DROPs done). - -- [ ] **Step 4: DROP at `PeerInfoScreenOpenMember.swift:19`.** - -```swift -// before -let actions = availableActionsForMemberOfPeer(accountPeerId: self.context.account.peerId, peer: enclosingPeer._asPeer(), member: member) - -// after -let actions = availableActionsForMemberOfPeer(accountPeerId: self.context.account.peerId, peer: enclosingPeer, member: member) -``` - -- [ ] **Step 5: DROP at `PeerInfoScreen.swift:5857`.** - -```swift -// before -} else if peerInfoCanEdit(peer: self.data?.peer?._asPeer(), chatLocation: self.chatLocation, threadData: self.data?.threadData, cachedData: self.data?.cachedData, isContact: self.data?.isContact) { - -// after -} else if peerInfoCanEdit(peer: self.data?.peer, chatLocation: self.chatLocation, threadData: self.data?.threadData, cachedData: self.data?.cachedData, isContact: self.data?.isContact) { -``` - -- [ ] **Step 6: DROP at `PeerInfoProfileItems.swift:853`.** - -Only the `availableActionsForMemberOfPeer` call — the sibling `enclosingPeer: peer._asPeer()` at line 852 is NOT a helper-migration target (it's `PeerInfoScreenMemberItem.enclosingPeer: Peer`, unchanged in this wave). - -```swift -// before (line 853) -let actions = availableActionsForMemberOfPeer(accountPeerId: context.account.peerId, peer: peer._asPeer(), member: member) - -// after -let actions = availableActionsForMemberOfPeer(accountPeerId: context.account.peerId, peer: peer, member: member) -``` - ---- - -### Task 3: Update call sites — CONVERTs (2 sites in PeerInfoScreen.swift) - -**Files:** -- Modify: `submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoScreen.swift:1905,1961` - -At these sites the helper arg is currently a concrete `TelegramGroup` / `TelegramChannel` extracted via case pattern. After migration the helper takes `EnginePeer?`, so pass `data.peer` directly — the helper re-does the pattern match internally, semantics preserved. - -- [ ] **Step 1: CONVERT at `PeerInfoScreen.swift:1905`.** - -```swift -// before -} else if case let .legacyGroup(group) = data.peer, canEditPeerInfo(context: strongSelf.context, peer: group, chatLocation: chatLocation, threadData: data.threadData) { - -// after -} else if case let .legacyGroup(group) = data.peer, canEditPeerInfo(context: strongSelf.context, peer: data.peer, chatLocation: chatLocation, threadData: data.threadData) { -``` - -`group` stays bound because the body below still uses it. Only the helper arg changes. - -- [ ] **Step 2: CONVERT at `PeerInfoScreen.swift:1961`.** - -```swift -// before -} else if case let .channel(channel) = data.peer, canEditPeerInfo(context: strongSelf.context, peer: channel, chatLocation: strongSelf.chatLocation, threadData: data.threadData) { - -// after -} else if case let .channel(channel) = data.peer, canEditPeerInfo(context: strongSelf.context, peer: data.peer, chatLocation: strongSelf.chatLocation, threadData: data.threadData) { -``` - ---- - -### Task 4: Update call sites — ADD-WRAPs in internal-update methods (10 sites in 4 files) - -These files' internal `.update(peer: Peer?, ...)` methods are NOT migrated in this wave (scope: helpers only). Each helper call inside bridges `peer` (raw `Peer?`) to `EnginePeer?` via `.flatMap(EnginePeer.init)`, or — where `peer` has already been unwrapped to non-optional `Peer` — via `EnginePeer(peer)`. - -**Files:** -- Modify: `submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoHeaderNode.swift:548,549,2361` -- Modify: `submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoEditingAvatarNode.swift:66` -- Modify: `submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoEditingAvatarOverlayNode.swift:85` -- Modify: `submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoHeaderEditingContentNode.swift:59,88,93,159,162` - -- [ ] **Step 1: ADD-WRAPs at `PeerInfoHeaderNode.swift:548,549,2361`.** At lines 548, 549, the local `peer` is the raw `Peer?` method parameter (line 496). At line 2361 likewise. - -```swift -// before (line 548) -let actionButtonKeys: [PeerInfoHeaderButtonKey] = (self.isSettings || self.isMyProfile) ? [] : peerInfoHeaderActionButtons(peer: peer, isSecretChat: isSecretChat, isContact: isContact) - -// after -let actionButtonKeys: [PeerInfoHeaderButtonKey] = (self.isSettings || self.isMyProfile) ? [] : peerInfoHeaderActionButtons(peer: peer.flatMap(EnginePeer.init), isSecretChat: isSecretChat, isContact: isContact) -``` - -```swift -// before (line 549) -let buttonKeys: [PeerInfoHeaderButtonKey] = (self.isSettings || self.isMyProfile) ? [] : peerInfoHeaderButtons(peer: peer, cachedData: cachedData, ...) - -// after -let buttonKeys: [PeerInfoHeaderButtonKey] = (self.isSettings || self.isMyProfile) ? [] : peerInfoHeaderButtons(peer: peer.flatMap(EnginePeer.init), cachedData: cachedData, ...) -``` - -```swift -// before (line 2361) -let chatIsMuted = peerInfoIsChatMuted(peer: peer, peerNotificationSettings: peerNotificationSettings, threadNotificationSettings: threadNotificationSettings, globalNotificationSettings: globalNotificationSettings) - -// after -let chatIsMuted = peerInfoIsChatMuted(peer: peer.flatMap(EnginePeer.init), peerNotificationSettings: peerNotificationSettings, threadNotificationSettings: threadNotificationSettings, globalNotificationSettings: globalNotificationSettings) -``` - -- [ ] **Step 2: ADD-WRAP at `PeerInfoEditingAvatarNode.swift:66`.** Here `peer` is non-optional `Peer` (unwrapped at line 62: `guard let peer = peer else { return }`). Use `EnginePeer(peer)`. - -```swift -// before -let canEdit = canEditPeerInfo(context: self.context, peer: peer, chatLocation: chatLocation, threadData: threadData) - -// after -let canEdit = canEditPeerInfo(context: self.context, peer: EnginePeer(peer), chatLocation: chatLocation, threadData: threadData) -``` - -- [ ] **Step 3: ADD-WRAP at `PeerInfoEditingAvatarOverlayNode.swift:85`.** Same shape — `peer` is non-optional `Peer` (unwrapped at line 64). - -```swift -// before -if canEditPeerInfo(context: self.context, peer: peer, chatLocation: chatLocation, threadData: threadData) - -// after -if canEditPeerInfo(context: self.context, peer: EnginePeer(peer), chatLocation: chatLocation, threadData: threadData) -``` - -- [ ] **Step 4: ADD-WRAPs at `PeerInfoHeaderEditingContentNode.swift:59,88,93,159,162`.** Here `peer` is the method's `peer: Peer?` parameter (line 52). Five identical bridge forms. - -For each of lines 59, 88, 93, 159, 162, replace `peer: peer` (inside `canEditPeerInfo(... peer: peer, ...)`) with `peer: peer.flatMap(EnginePeer.init)`. - -The simplest approach: issue five separate Edit calls, each scoped to a unique surrounding substring. Example: - -```swift -// before (line 59) -if canEditPeerInfo(context: self.context, peer: peer, chatLocation: chatLocation, threadData: threadData) { - -// after -if canEditPeerInfo(context: self.context, peer: peer.flatMap(EnginePeer.init), chatLocation: chatLocation, threadData: threadData) { -``` - -Note line 59's trailing double-space before `{` in the original — preserve it. - -Lines 88, 93, 159 share an identical surrounding substring `if canEditPeerInfo(context: self.context, peer: peer, chatLocation: chatLocation, threadData: threadData) {` (no trailing double-space, no `|| isEditableBot`). To avoid collision with line 59, use `replace_all=true` on THIS exact string (matches 88, 93 — wait, 159 uses `isEnabled = canEditPeerInfo(...)`, different prefix). Safer plan: one Edit per line, each with enough surrounding context to be unique. Verify uniqueness after each edit with grep. - -Line 88's surrounding context: inside `if let _ = peer as? TelegramGroup {` branch — preceded by `fieldKeys.append(.title)`. - -Line 93's surrounding context: inside `if let _ = peer as? TelegramChannel {` branch — preceded by `fieldKeys.append(.title)`. Same inner phrase as 88 — so `fieldKeys.append(.title)\n if canEditPeerInfo...` appears twice. Use line-specific context (preceding `else if let _ = peer as?` token). - -Line 159: `isEnabled = canEditPeerInfo(context: self.context, peer: peer, chatLocation: chatLocation, threadData: threadData)` (no trailing text). - -Line 162: `isEnabled = canEditPeerInfo(context: self.context, peer: peer, chatLocation: chatLocation, threadData: threadData) || isEditableBot`. Unique — contains ` || isEditableBot`. - -Recommended: five sequential Edits with explicit line disambiguation via surrounding context. Do not bulk-replace-all — the identical `peer: peer, chatLocation: chatLocation, threadData: threadData)` substring appears at all five sites but their line-specific surroundings differ. - -Verification after all five edits: - -```bash -grep -c "peer: peer," submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoHeaderEditingContentNode.swift -``` -Expected: 0 (no unmigrated call sites remain; other `peer:` occurrences in the file are either type annotations or at the method signature, which uses `peer: Peer?` not `peer: peer`). - ---- - -### Task 5: Update call sites — ADD-WRAPs at raw-`Peer` member-item sites (2 sites) - -**Files:** -- Modify: `submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/ListItems/PeerInfoScreenMemberItem.swift:178` -- Modify: `submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/Panes/PeerInfoMembersPane.swift:139` - -At these sites `enclosingPeer` is non-optional `Peer` (raw, stored on the item / local). Wrap with `EnginePeer(...)`. - -- [ ] **Step 1: ADD-WRAP at `PeerInfoScreenMemberItem.swift:178`.** - -```swift -// before -let actions = availableActionsForMemberOfPeer(accountPeerId: item.context.accountPeerId, peer: item.enclosingPeer, member: item.member) - -// after -let actions = availableActionsForMemberOfPeer(accountPeerId: item.context.accountPeerId, peer: EnginePeer(item.enclosingPeer), member: item.member) -``` - -- [ ] **Step 2: ADD-WRAP at `PeerInfoMembersPane.swift:139`.** - -```swift -// before -let actions = availableActionsForMemberOfPeer(accountPeerId: context.account.peerId, peer: enclosingPeer, member: member) - -// after -let actions = availableActionsForMemberOfPeer(accountPeerId: context.account.peerId, peer: EnginePeer(enclosingPeer), member: member) -``` - ---- - -### Task 6: Build and iterate - -- [ ] **Step 1: Full project build with `--continueOnError` to surface all errors at once.** - -```bash -source ~/.zshrc 2>/dev/null; python3 build-system/Make/Make.py --overrideXcodeVersion \ - --cacheDir ~/telegram-bazel-cache \ - build \ - --configurationPath build-system/appstore-configuration.json \ - --gitCodesigningRepository git@gitlab.com:peter-iakovlev/fastlanematch.git \ - --gitCodesigningType development --gitCodesigningUseCurrent --buildNumber=1 \ - --configuration=debug_sim_arm64 --continueOnError -``` - -Expected: likely 2-iteration convergence. Budget up to iteration 3. - -Likely categories of residual errors: - -1. **Missed call sites** — grep-miss from planning. Remediate by adding `.flatMap(EnginePeer.init)` or `EnginePeer(...)` as appropriate. -2. **Missed `as? TelegramX` / `is TelegramX` inside helper bodies** — Swift compiler error "cannot convert value of type 'EnginePeer?' to expected argument type 'Peer?'" or warning "'is' test is always false". Fix with `case` pattern. -3. **Optional-lifting edge cases** — `if case let .user(user) = peer` may fail if Swift interprets `peer` as non-optional. If so, rewrite as `if let peer, case let .user(user) = peer`. -4. **Unused binding warnings** — e.g. `if case let .user(user) = peer` where `user` isn't used inside that branch. Swift's `-warnings-as-errors` (658/665 submodule BUILDs) promotes these. Rewrite as `if case .user = peer`. -5. **Unused variable `peer` or `group`/`channel` at CONVERT sites 16, 17** — lines 1905/1961 bind `group`/`channel` in the `case let` pattern; if the body body doesn't use it, Swift emits "value 'group' was never used" which `-warnings-as-errors` promotes to error. Since the body below DOES use them (updatePeerTitle(peerId: group.id, ...)` etc.), this should not trigger — but verify. - -- [ ] **Step 2: For each error category above, apply the correct fix in-place and rebuild. Iterate until green.** - -- [ ] **Step 3: After build is green, run the post-migration grep audit:** - -```bash -# Should be empty — no _asPeer() bridges at helper call sites -grep -rn "canEditPeerInfo(.*_asPeer\|peerInfoIsChatMuted(.*_asPeer\|peerInfoHeaderButtons(.*_asPeer\|peerInfoHeaderActionButtons(.*_asPeer\|peerInfoCanEdit(.*_asPeer\|availableActionsForMemberOfPeer(.*_asPeer" submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/ - -# Should be empty — no concrete-type casts against peer param in helper bodies -grep -nE "as\?\s+TelegramUser|as\?\s+TelegramChannel|as\?\s+TelegramGroup|\bis\s+TelegramUser\b|\bis\s+TelegramChannel\b|\bis\s+TelegramGroup\b" submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoData.swift | awk -F: '$2 >= 2265 && $2 <= 2670' -``` - -Expected: both empty. - ---- - -### Task 7: Commit - -- [ ] **Step 1: Verify working tree only contains wave-43 edits + pre-existing WIP.** - -```bash -git status --short -``` - -Expected (pre-existing WIP, NOT to be staged): - -``` - m build-system/bazel-rules/sourcekit-bazel-bsp - M submodules/TelegramUI/Sources/ChatMessageTransitionNode.swift -?? build-system/tulsi/ -?? submodules/TgVoip/ -?? third-party/libx264/ -``` - -Plus wave-43 edits (all under `submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/`): - -``` - M submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoData.swift - M submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoScreen.swift - M submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoHeaderNode.swift - M submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoEditingAvatarNode.swift - M submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoEditingAvatarOverlayNode.swift - M submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoHeaderEditingContentNode.swift - M submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoScreenAvatarSetup.swift - M submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoScreenPerformButtonAction.swift - M submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoScreenOpenMember.swift - M submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoProfileItems.swift - M submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/ListItems/PeerInfoScreenMemberItem.swift - M submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/Panes/PeerInfoMembersPane.swift -``` - -- [ ] **Step 2: Explicitly stage only the wave-43 files (not the WIP).** - -```bash -git add \ - submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoData.swift \ - submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoScreen.swift \ - submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoHeaderNode.swift \ - submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoEditingAvatarNode.swift \ - submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoEditingAvatarOverlayNode.swift \ - submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoHeaderEditingContentNode.swift \ - submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoScreenAvatarSetup.swift \ - submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoScreenPerformButtonAction.swift \ - submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoScreenOpenMember.swift \ - submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoProfileItems.swift \ - submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/ListItems/PeerInfoScreenMemberItem.swift \ - submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/Panes/PeerInfoMembersPane.swift \ - docs/superpowers/plans/2026-04-24-peerinfoscreen-helpers-engine-peer-migration.md -``` - -- [ ] **Step 3: Commit.** - -Use a HEREDOC for the message: - -```bash -git commit -m "$(cat <<'EOF' -Postbox -> TelegramEngine wave 43 - -Migrate six PeerInfoScreen helpers (canEditPeerInfo, -availableActionsForMemberOfPeer, peerInfoHeaderActionButtons, -peerInfoHeaderButtons, peerInfoCanEdit, peerInfoIsChatMuted) from -`peer: Peer?` to `peer: EnginePeer?`. Internal `as? TelegramX` / -`is TelegramX` patterns rewritten to `case let .x` / `case .x` on -EnginePeer enum. All 21 call sites updated in the same commit: 7 -`._asPeer()` bridges installed by wave 42 dropped; 12 -`.flatMap(EnginePeer.init)` / `EnginePeer(...)` wraps added at sites -whose enclosing methods still take raw Peer?; 2 concrete-type args -converted to pass the whole EnginePeer value. - -All edits within submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/. -No new engine typealiases. No TelegramCore changes. - -Co-Authored-By: Claude Opus 4.7 (1M context) -EOF -)" -``` - -- [ ] **Step 4: Verify commit.** - -```bash -git log --oneline -1 -git show --stat HEAD -``` - -Expected: one commit, ~10 files changed, clean diff. - ---- - -## Self-review checklist (run before handoff) - -**Spec coverage:** -- All 6 helper signatures migrated (Task 1 steps 1–6). ✓ -- All 21 call sites touched (Tasks 2–5). ✓ -- Build iteration explicit (Task 6). ✓ -- Commit explicit (Task 7). ✓ - -**Type consistency:** -- Helper signatures all `peer: EnginePeer?` (consistent). ✓ -- Call-site transforms: DROP/ADD/CONVERT actions match the inventory table. ✓ -- `EnginePeer.init` constructor used both as `.flatMap(EnginePeer.init)` (Peer? → EnginePeer?) and `EnginePeer(...)` (Peer → EnginePeer) — both are valid (construction overloaded on EnginePeer extension at `TelegramCore/TelegramEngine/Peers/Peer.swift:564`). ✓ - -**Placeholder scan:** -- No "TBD" / "handle appropriately" / "similar to Task N" language — every step has its concrete code. ✓ - -**Risks flagged:** -- Wave-41 lesson: foundational-type migrations rarely first-pass-clean. Budget 2 iterations. ✓ -- Wave-41 lesson: `-warnings-as-errors` promotes always-false `is` checks and unused bindings to build errors. Task 6 step 1 calls these out explicitly. ✓ -- Wave-42 lesson: `EnginePeer` doesn't forward every Peer property. Helper bodies were verified to access only `.id`, which IS forwarded; other property accesses were on concrete types (`TelegramChannel.hasPermission(...)` etc.) which remain on concrete types post-migration. No forwarding-gap remediation expected in helpers. ✓ diff --git a/docs/superpowers/plans/2026-04-24-peerinfoscreendata-peer-engine-peer-migration.md b/docs/superpowers/plans/2026-04-24-peerinfoscreendata-peer-engine-peer-migration.md deleted file mode 100644 index a3fc76f355..0000000000 --- a/docs/superpowers/plans/2026-04-24-peerinfoscreendata-peer-engine-peer-migration.md +++ /dev/null @@ -1,164 +0,0 @@ -# Wave 42 plan: `PeerInfoScreenData.peer: Peer? → EnginePeer?` - -Date: 2026-04-24 -Preceding waves: 41 (`RenderedChannelParticipant.peer`), 40 (`makeChatQrCodeScreen`/`makeChatRecentActionsController`), 39 (`makePeerInfoController`) -Scope (confirmed with user): only `PeerInfoScreenData.peer`. Sibling fields (`chatPeer`, `savedMessagesPeer`, `linkedDiscussionPeer`, `linkedMonoforumPeer`) are follow-up-wave candidates. - -## Change target - -File: `submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoData.swift` - -- L386: `let peer: Peer?` → `let peer: EnginePeer?` -- L442: `peer: Peer?,` → `peer: EnginePeer?,` -- Store unchanged (`self.peer = peer`) - -## Construction sites (5, all in PeerInfoData.swift) - -| Line | Current `peer:` arg | Rewrite | -|------|---------------------|---------| -| 1027 | `peer: peer` (local, `Peer?` from `peerView.peers[peerId]`) | `peer: peer.flatMap(EnginePeer.init)` | -| 1100 | `peer: nil` | unchanged | -| 1620 | `peer: peer` (local, `Peer?` from `peerView.peers[userPeerId]`) | `peer: peer.flatMap(EnginePeer.init)` | -| 1867 | `peer: peerView.peers[peerId]` | `peer: peerView.peers[peerId].flatMap(EnginePeer.init)` | -| 2205 | `peer: peerView.peers[groupId]` | `peer: peerView.peers[groupId].flatMap(EnginePeer.init)` | - -## Consumer migration patterns (across 18 files, ~114 `data.peer` accesses) - -### Pattern A — as-cast → enum pattern match (~20 sites) - -```swift -// before -if let user = data.peer as? TelegramUser, user.botInfo == nil { ... } - -// after -if case let .user(user) = data.peer, user.botInfo == nil { ... } -``` - -Scope both sides consistently. A cast inside a larger `guard let ..., let user = ... as? TelegramUser else { return }` becomes `guard ..., case let .user(user) = data.peer else { return }`. - -### Pattern B — `is TelegramXxx` check → enum case pattern (~5 sites) - -The wave-41 lesson: `-warnings-as-errors` catches always-false `is` checks. - -```swift -// before -if let peer = self.data?.peer, peer is TelegramChannel { ... } -if peer is TelegramGroup { ... } - -// after -if case .channel = self.data?.peer { ... } -if case .legacyGroup = peer { ... } -``` - -`TelegramGroup` maps to `.legacyGroup`. `TelegramChannel` maps to `.channel`. `TelegramUser` maps to `.user`. `TelegramSecretChat` maps to `.secretChat`. - -Known sites in PeerInfoScreen.swift (inventory): L3981, L4133, L4192, L4194 (and L7421 for `chatPeer`-bound — chatPeer stays raw, so L7421 is out of scope). Use repo grep on `PeerInfoScreen/Sources` with token `is Telegram(Channel|User|Group|SecretChat)` to catch other sites. - -### Pattern C — existing `EnginePeer(peer)` wraps where `peer` was bound from `data.peer` — DROP (15+ sites) - -```swift -// before -if let peer = self.data?.peer { - self.joinChannel(peer: EnginePeer(peer)) // wave-40 wrap -} - -// after -if let peer = self.data?.peer { - self.joinChannel(peer: peer) // peer is now EnginePeer already -} -``` - -Care needed: only drop the wrap where the bound `peer` variable comes from `data.peer`. Wraps on `chatPeer`, `currentPeer`, `user` (bound via `as? TelegramUser`), `groupPeer`, or PeerView lookups stay. The lexical scope makes this judgeable. - -Known drop sites (PeerInfoScreen.swift): 1331, 1339, 1346, 1561, 2353, 2405, 3409, 3459, 3624, 3747, 4306, 4573 (inner — review scope), 4623. PeerInfoHeaderNode.swift: 571, 1218, 2054 (if bound from data.peer). PeerInfoScreenOpenChat.swift: 25, 40, 51, 57, 80, 89, 115. Verify each by backtracking the `if let peer = ...` binding. - -### Pattern D — helper call sites still taking `Peer?` (ADD-WRAP, ~10 sites) - -`canEditPeerInfo`, `peerInfoIsChatMuted`, `peerInfoHeaderButtons`, `peerInfoHeaderActionButtons`, `peerInfoCanEdit`, `availableActionsForMemberOfPeer` all keep `peer: Peer?` in this wave. Call sites must bridge: - -```swift -// before -peerInfoIsChatMuted(peer: self.data?.peer, ...) - -// after -peerInfoIsChatMuted(peer: self.data?.peer?._asPeer(), ...) -``` - -Site count (from grep): PeerInfoHeaderNode.swift:548/549/2361, PeerInfoScreenAvatarSetup.swift:435, PeerInfoScreenPerformButtonAction.swift:62/397/398, PeerInfoEditingAvatarNode.swift:66, PeerInfoScreen.swift:1905/1961/5857, PeerInfoHeaderEditingContentNode.swift:59/88/93/159/162, PeerInfoEditingAvatarOverlayNode.swift:85. But the local `peer` at some of these is already narrowed via `as? TelegramUser` (now `case let .user(user)`); in that case the helper gets `user` (still `Peer`-conforming), no bridge needed. Bridge only where the raw `data.peer` flows into the helper. - -These ADD-WRAP markers become ratchet-drops for a follow-up wave that migrates the helper signatures. - -### Pattern E — `EnginePeer?` passed as `EnginePeer?` directly (DROP wraps on callback args) - -Where `data.peer` feeds `makePeerInfoController(peer: EnginePeer)` / `chatInterfaceInteraction.openPeer(_ peer: EnginePeer, ...)` / `.peer(EnginePeer)` ChatLocation / `AvatarGalleryController(peer: EnginePeer)` / `makeChatQrCodeScreen(peer: EnginePeer)` / `makeChatRecentActionsController(peer: EnginePeer)` — drop the `EnginePeer(...)` wrap; pass directly. - -### Pattern F — `EnginePeer(peer).displayTitle(...)` / `.compactDisplayTitle` usage (DROP wrap) - -```swift -// before -EnginePeer(peer).displayTitle(strings: ..., displayOrder: ...) - -// after (peer is now EnginePeer already) -peer.displayTitle(strings: ..., displayOrder: ...) -``` - -### Pattern G — `.isPremium` on `peer?` inside construction site (L1060, L1626, L1902, L2242) - -`peerView.peers[peerId]?.isPremium` — `Peer` protocol exposes `isPremium`. But the construction site receives raw `Peer?` and then we wrap via `flatMap(EnginePeer.init)`. The `peer?.isPremium` in the same construction scope still refers to the *local* raw peer variable (type unchanged), not `self.peer`. **No change needed at construction sites for `.isPremium` accesses on the local raw `peer`.** Only change `.isPremium` accesses on `data.peer` (which is now `EnginePeer?`) — `EnginePeer.isPremium` exists. - -## File-by-file plan - -1. **PeerInfoData.swift** — declaration + init + 5 constructions. Also review L1529 (`peerView.peers[peerView.peerId] is TelegramUser`) — OUT OF SCOPE (not `data.peer`); don't touch. Helper functions L2265/2314/2434/2447/2585/2633 stay `peer: Peer?` — DO NOT TOUCH. - -2. **PeerInfoScreen.swift** — largest consumer, ~70+ sites. Walk every `data.peer` / `data?.peer` / `self.data?.peer` / `self.data.peer`. Apply A/B/C/E/F patterns. For `if let peer = data.peer` bindings, subsequent uses of `peer` now have type `EnginePeer` — drop wraps on those uses. - -3. **PeerInfoScreenOpenChat.swift, PeerInfoScreenOpenBio.swift, PeerInfoScreenOpenMember.swift, PeerInfoScreenOpenPeerInfoContextMenu.swift, PeerInfoScreenOpenUsername.swift, PeerInfoScreenCallActions.swift, PeerInfoScreenMessageActions.swift, PeerInfoScreenPerformButtonAction.swift, PeerInfoScreenAvatarSetup.swift, PeerInfoScreenSettingsActions.swift, PeerInfoScreenDisplayGiftsContextMenu.swift, PeerInfoScreenDisplayMediaGalleryContextMenu.swift** — various `data?.peer as? TelegramXxx` (A), helper bridges (D), wrap drops (C/E). - -4. **PeerInfoPaneContainerNode.swift** — L1252 `as? TelegramChannel` (A). - -5. **PeerInfoProfileItems.swift, PeerInfoSettingsItems.swift, ListItems/PeerInfoScreenPersonalChannelItem.swift** — `data.peer as? TelegramUser` style consumers (A). - -6. **PeerInfoHeaderNode.swift, PeerInfoEditingAvatarNode.swift, PeerInfoEditingAvatarOverlayNode.swift, PeerInfoHeaderEditingContentNode.swift** — these files receive `peer` as a parameter (not directly `data.peer`). Only touch if a parameter type declared as `Peer?` is the field from `data.peer` being passed in; otherwise leave. - -## Replace_all guidance (wave-41 lesson) - -Several wraps repeat identically. Where a file has multiple identical `EnginePeer(peer)` expressions in scopes where `peer` is now `EnginePeer`, use `replace_all=true` on the unique full expression. BUT verify each such file has no same-pattern wrap where `peer` is still raw (chatPeer-bound, currentPeer-bound, etc.) — such wraps must survive. - -Safer alternative: edit each site individually. - -## Out of scope (enumerated) - -- `PeerInfoScreenData.chatPeer`, `.savedMessagesPeer`, `.linkedDiscussionPeer`, `.linkedMonoforumPeer` — stay `Peer?`. -- Internal helpers `canEditPeerInfo` / `peerInfoIsChatMuted` / etc. — stay `peer: Peer?`. -- `peerView.peers[...]` access inside PeerInfoData.swift — stays raw `Peer?`. -- Any `is TelegramXxx` check on a non-`data.peer`-derived variable. - -## Build methodology - -1. Apply declaration + init + construction edits. -2. Apply consumer edits file by file. -3. `source ~/.zshrc 2>/dev/null; python3 build-system/Make/Make.py --overrideXcodeVersion --cacheDir ~/telegram-bazel-cache build --configurationPath build-system/appstore-configuration.json --gitCodesigningRepository git@gitlab.com:peter-iakovlev/fastlanematch.git --gitCodesigningType development --gitCodesigningUseCurrent --buildNumber=1 --configuration=debug_sim_arm64 --continueOnError` -4. Iterate on errors. Budget: 2–4 iterations (wave-41 lesson: foundational-type property-access migrations are not first-pass-clean). - -## Expected ratchet math - -- Drops: 15+ wave-40 wraps, ~20 as-cast patterns collapsed, ~5 is-checks rewritten, several `EnginePeer(peer).displayTitle` wraps dropped. -- Adds: ~10 `?._asPeer()` helper bridges, 4 `flatMap(EnginePeer.init)` at construction. -- Net: ~15–25 bridges dropped. - -## WIP interference check - -Pre-existing WIP in tree (per memory): -- `submodules/TelegramUI/Sources/ChatMessageTransitionNode.swift` — modified, unrelated animation WIP. DO NOT TOUCH. -- `submodules/TgVoip/`, `third-party/libx264/`, `build-system/tulsi/` — untracked, unrelated. -- `build-system/bazel-rules/sourcekit-bazel-bsp` — submodule marker, unrelated. - -Wave-42 files are all in `submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/` — no overlap with WIP. Commit with explicit file list (wave-39/41 lesson). - -## Post-commit followups - -- Update `docs/superpowers/postbox-refactor-log.md` with "Wave 42 outcome". -- Update `memory/project_postbox_refactor_next_wave.md` with wave 43 candidates: - - Wave 42.x sibling: `PeerInfoScreenData.chatPeer` / `.savedMessagesPeer` / `.linkedDiscussionPeer` / `.linkedMonoforumPeer` as a bundle (same file, narrow blast radius). - - Wave 42.y: PeerInfo-internal helper signatures (drops the ~10 ADD-WRAP markers). - - Option 2 from wave-42 shortlist: `RenderedChannelParticipant.peers` dict. diff --git a/docs/superpowers/plans/2026-04-24-peertokentitle-engine-peer-migration.md b/docs/superpowers/plans/2026-04-24-peertokentitle-engine-peer-migration.md deleted file mode 100644 index d8386bf99d..0000000000 --- a/docs/superpowers/plans/2026-04-24-peertokentitle-engine-peer-migration.md +++ /dev/null @@ -1,395 +0,0 @@ -# Postbox → TelegramEngine wave 37: `peerTokenTitle` peer parameter Peer → EnginePeer - -> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. - -**Goal:** Migrate the private free function `peerTokenTitle(accountPeerId: PeerId, peer: Peer, strings:, nameDisplayOrder:)` in `submodules/TelegramUI/Sources/ContactMultiselectionController.swift` so `peer` is `EnginePeer`, dropping 5 `._asPeer()` bridges at call sites in the same file. - -**Architecture:** Single-file, atomic, private-function refactor. No public API change, no BUILD-file touch, no cross-module effects. Function body simplifies `EnginePeer(peer).displayTitle(...)` → `peer.displayTitle(...)`. - -**Tech Stack:** Swift, Bazel via `Make.py` wrapper, Telegram-iOS project conventions (see CLAUDE.md). - -**Reference:** Spec `docs/superpowers/specs/2026-04-24-peertokentitle-engine-peer-migration-design.md`. - ---- - -## File Structure - -Only one file is touched: - -- **Modify:** `submodules/TelegramUI/Sources/ContactMultiselectionController.swift` - - L21 — signature change (`peer: Peer` → `peer: EnginePeer`) - - L27 — body simplification (drop redundant `EnginePeer(...)` wrap) - - L171, L201, L386, L403, L748 — call-site bridge drops (`peer: peer._asPeer()` → `peer: peer`) - -No files created. No files deleted. No BUILD files touched. - ---- - -## Task 1: Pre-flight inventory verification - -**Files:** None (grep-only). - -- [ ] **Step 1: Confirm the function is private and single-file** - -Run: - -```bash -grep -rn "peerTokenTitle" submodules/ Telegram/ third-party/ --include="*.swift" -``` - -Expected: exactly 6 matches, all in `submodules/TelegramUI/Sources/ContactMultiselectionController.swift` — 1 definition at L21 and 5 call sites at L171, L201, L386, L403, L748. - -If any match appears outside this file, **stop and re-evaluate scope**: the function may not actually be private or another file has copy-pasted the name. - -- [ ] **Step 2: Confirm all 5 call sites currently use `._asPeer()`** - -Run: - -```bash -grep -n "peerTokenTitle(.*_asPeer())" submodules/TelegramUI/Sources/ContactMultiselectionController.swift -``` - -Expected: 5 matches, line numbers 171, 201, 386, 403, 748. - -If the count is not 5, **stop and re-inventory** — a prior change may have shifted line numbers or altered a call site. - -- [ ] **Step 3: Confirm no other `peerTokenTitle` overload exists** - -Run: - -```bash -grep -n "func peerTokenTitle" submodules/TelegramUI/Sources/ContactMultiselectionController.swift -``` - -Expected: exactly 1 match at line 21 (`private func peerTokenTitle(...)`). - -- [ ] **Step 4: Confirm `EnginePeer.displayTitle(strings:displayOrder:)` exists** - -Run: - -```bash -grep -rn "func displayTitle(strings:" submodules/TelegramCore/Sources/TelegramEngine/ submodules/TelegramCore/Sources/SyncCore/ -``` - -Expected: a match on `EnginePeer` extension exposing `displayTitle(strings: PresentationStrings, displayOrder: PresentationPersonNameOrder)`. (This is the method already called as `EnginePeer(peer).displayTitle(...)` at L27, so its existence is certain — this step just makes the dependency explicit.) - ---- - -## Task 2: Edit the function signature and body - -**Files:** -- Modify: `submodules/TelegramUI/Sources/ContactMultiselectionController.swift:21-29` - -- [ ] **Step 1: Read the current function definition** - -Read the file, lines 21–29. Current state: - -```swift -private func peerTokenTitle(accountPeerId: PeerId, peer: Peer, strings: PresentationStrings, nameDisplayOrder: PresentationPersonNameOrder) -> String { - if peer.id == accountPeerId { - return strings.DialogList_SavedMessages - } else if peer.id.isReplies { - return strings.DialogList_Replies - } else { - return EnginePeer(peer).displayTitle(strings: strings, displayOrder: nameDisplayOrder) - } -} -``` - -- [ ] **Step 2: Apply the signature change** - -Use Edit with: - -- `old_string`: - ``` - private func peerTokenTitle(accountPeerId: PeerId, peer: Peer, strings: PresentationStrings, nameDisplayOrder: PresentationPersonNameOrder) -> String { - if peer.id == accountPeerId { - return strings.DialogList_SavedMessages - } else if peer.id.isReplies { - return strings.DialogList_Replies - } else { - return EnginePeer(peer).displayTitle(strings: strings, displayOrder: nameDisplayOrder) - } - } - ``` -- `new_string`: - ``` - private func peerTokenTitle(accountPeerId: PeerId, peer: EnginePeer, strings: PresentationStrings, nameDisplayOrder: PresentationPersonNameOrder) -> String { - if peer.id == accountPeerId { - return strings.DialogList_SavedMessages - } else if peer.id.isReplies { - return strings.DialogList_Replies - } else { - return peer.displayTitle(strings: strings, displayOrder: nameDisplayOrder) - } - } - ``` - -Note: `accountPeerId: PeerId` stays as-is — `PeerId` is already the typealias for `EnginePeer.Id`. `peer.id.isReplies` works unchanged because `EnginePeer.Id` exposes `isReplies`. - ---- - -## Task 3: Drop `._asPeer()` bridges at all 5 call sites - -**Files:** -- Modify: `submodules/TelegramUI/Sources/ContactMultiselectionController.swift` (L171, L201, L386, L403, L748) - -All 5 call sites have an identical argument fragment: - -``` -peer: peer._asPeer(), -``` - -…which must become: - -``` -peer: peer, -``` - -The surrounding context differs per site (two distinct `strings/nameDisplayOrder` chains, see below), so we handle the substitution in two batches. - -- [ ] **Step 1: Replace sites L171, L201, L748 (use `strongSelf.presentationData.strings` / `strongSelf.presentationData.nameDisplayOrder` or `self.presentationData.strings` / `self.presentationData.nameDisplayOrder`)** - -Three call sites share identical code but with different leading `accountPeerId` expressions. Apply them individually. - -**L171 and L201 are identical** — both read: - -```swift -return EditableTokenListToken(id: peer.id, title: peerTokenTitle(accountPeerId: params.context.account.peerId, peer: peer._asPeer(), strings: strongSelf.presentationData.strings, nameDisplayOrder: strongSelf.presentationData.nameDisplayOrder), fixedPosition: nil, subject: .peer(peer)) -``` - -Use Edit with `replace_all=true`: - -- `old_string`: - ``` - return EditableTokenListToken(id: peer.id, title: peerTokenTitle(accountPeerId: params.context.account.peerId, peer: peer._asPeer(), strings: strongSelf.presentationData.strings, nameDisplayOrder: strongSelf.presentationData.nameDisplayOrder), fixedPosition: nil, subject: .peer(peer)) - ``` -- `new_string`: - ``` - return EditableTokenListToken(id: peer.id, title: peerTokenTitle(accountPeerId: params.context.account.peerId, peer: peer, strings: strongSelf.presentationData.strings, nameDisplayOrder: strongSelf.presentationData.nameDisplayOrder), fixedPosition: nil, subject: .peer(peer)) - ``` - -**L748** reads: - -```swift -tokens.append(EditableTokenListToken(id: peer.id, title: peerTokenTitle(accountPeerId: self.context.account.peerId, peer: peer._asPeer(), strings: self.presentationData.strings, nameDisplayOrder: self.presentationData.nameDisplayOrder), fixedPosition: nil, subject: .peer(peer))) -``` - -Use Edit (no `replace_all` — this line is unique): - -- `old_string`: - ``` - tokens.append(EditableTokenListToken(id: peer.id, title: peerTokenTitle(accountPeerId: self.context.account.peerId, peer: peer._asPeer(), strings: self.presentationData.strings, nameDisplayOrder: self.presentationData.nameDisplayOrder), fixedPosition: nil, subject: .peer(peer))) - ``` -- `new_string`: - ``` - tokens.append(EditableTokenListToken(id: peer.id, title: peerTokenTitle(accountPeerId: self.context.account.peerId, peer: peer, strings: self.presentationData.strings, nameDisplayOrder: self.presentationData.nameDisplayOrder), fixedPosition: nil, subject: .peer(peer))) - ``` - -- [ ] **Step 2: Replace sites L386 and L403 (use `accountPeerId` local)** - -**L386 and L403 are identical** — both read: - -```swift -addedToken = EditableTokenListToken(id: peer.id, title: peerTokenTitle(accountPeerId: accountPeerId, peer: peer._asPeer(), strings: strongSelf.presentationData.strings, nameDisplayOrder: strongSelf.presentationData.nameDisplayOrder), fixedPosition: nil, subject: .peer(peer)) -``` - -Use Edit with `replace_all=true`: - -- `old_string`: - ``` - addedToken = EditableTokenListToken(id: peer.id, title: peerTokenTitle(accountPeerId: accountPeerId, peer: peer._asPeer(), strings: strongSelf.presentationData.strings, nameDisplayOrder: strongSelf.presentationData.nameDisplayOrder), fixedPosition: nil, subject: .peer(peer)) - ``` -- `new_string`: - ``` - addedToken = EditableTokenListToken(id: peer.id, title: peerTokenTitle(accountPeerId: accountPeerId, peer: peer, strings: strongSelf.presentationData.strings, nameDisplayOrder: strongSelf.presentationData.nameDisplayOrder), fixedPosition: nil, subject: .peer(peer)) - ``` - -- [ ] **Step 3: Grep to confirm zero remaining bridge sites** - -Run: - -```bash -grep -n "peerTokenTitle(.*_asPeer())" submodules/TelegramUI/Sources/ContactMultiselectionController.swift -``` - -Expected: **0 matches**. - -If any match remains, the previous edits missed a line variant — re-read the file around each missed line and apply a targeted Edit for that variant. - -- [ ] **Step 4: Confirm the 5 expected `peer: peer,` call sites now appear** - -Run: - -```bash -grep -n "peerTokenTitle(.*peer: peer," submodules/TelegramUI/Sources/ContactMultiselectionController.swift -``` - -Expected: 5 matches, line numbers approximately 171, 201, 386, 403, 748 (exact numbers unchanged — the edits don't shift line counts). - ---- - -## Task 4: Build verification - -**Files:** None edited in this task. - -- [ ] **Step 1: Run the full project build with --continueOnError** - -Run: - -```bash -source ~/.zshrc 2>/dev/null; python3 build-system/Make/Make.py --overrideXcodeVersion \ - --cacheDir ~/telegram-bazel-cache \ - build \ - --configurationPath build-system/appstore-configuration.json \ - --gitCodesigningRepository git@gitlab.com:peter-iakovlev/fastlanematch.git \ - --gitCodesigningType development --gitCodesigningUseCurrent --buildNumber=1 --configuration=debug_sim_arm64 \ - --continueOnError -``` - -Expected: build succeeds with exit code 0 and no compilation errors. - -**If the build fails:** - -1. Inspect the error output. Three failure modes are anticipated (all should be rare given the scope): - - **Missing `displayTitle` on `EnginePeer`:** unlikely, since L27 was calling it pre-migration. If it happens, verify the `EnginePeer` import chain — but do not add new imports; this file already imports `TelegramCore`. - - **A 6th call site exists** that the pre-flight grep missed (e.g., one using a different string pattern like `peer:peer` with no space, or a multi-line call). Locate it with `grep -n "peerTokenTitle" submodules/TelegramUI/Sources/ContactMultiselectionController.swift` and apply the bridge drop manually. - - **Unrelated type-inference cascade**, e.g., some `peer` local was previously inferred as `Peer` via the callback chain and now can't be. Read the error line and assess: if it's inside the function body or call site, adjust; if it's elsewhere in the file, it was pre-existing and unrelated — still, don't touch it mid-wave. Abandon per wave-rule 5 if scope creep is required. -2. Re-run the build after the fix. - -- [ ] **Step 2: Confirm the post-migration grep is clean** - -Run (after successful build): - -```bash -grep -n "peerTokenTitle(.*_asPeer())" submodules/TelegramUI/Sources/ContactMultiselectionController.swift -``` - -Expected: **0 matches**. - ---- - -## Task 5: Commit - -**Files:** -- `submodules/TelegramUI/Sources/ContactMultiselectionController.swift` - -- [ ] **Step 1: Stage the one file** - -Run: - -```bash -git add submodules/TelegramUI/Sources/ContactMultiselectionController.swift -``` - -- [ ] **Step 2: Verify the staged diff** - -Run: - -```bash -git diff --cached --stat -``` - -Expected: `1 file changed, 6 insertions(+), 6 deletions(-)` (or thereabouts — 1 line's worth of signature change, 1 body-line change, 5 identical call-site changes; each is a 1-line replacement, net zero line-count delta). - -Also run: - -```bash -git diff --cached -``` - -Inspect manually to confirm: (a) the function signature changed `peer: Peer` → `peer: EnginePeer`; (b) the body `EnginePeer(peer).displayTitle(...)` → `peer.displayTitle(...)`; (c) 5 call sites lost `._asPeer()`. No other edits. - -- [ ] **Step 3: Commit** - -Run: - -```bash -git commit -m "$(cat <<'EOF' -Postbox -> TelegramEngine wave 37 - -peerTokenTitle: peer parameter Peer -> EnginePeer. - -Drops 5 _asPeer() bridges in ContactMultiselectionController.swift -(L171, L201, L386, L403, L748) - bridges installed by prior waves. - -Private free function, single-file change. - -Co-Authored-By: Claude Opus 4.7 (1M context) -EOF -)" -``` - -- [ ] **Step 4: Confirm commit** - -Run: - -```bash -git log --oneline -3 -``` - -Expected: the new wave-37 commit at the top. - ---- - -## Task 6: Update memory / log - -**Files:** -- Modify: `/Users/isaac/.claude/projects/-Users-isaac-build-telegram-telegram-ios/memory/project_postbox_refactor_next_wave.md` -- Modify: `docs/superpowers/postbox-refactor-log.md` - -- [ ] **Step 1: Read the current memory file for the refactor** - -Read `/Users/isaac/.claude/projects/-Users-isaac-build-telegram-telegram-ios/memory/project_postbox_refactor_next_wave.md`. - -- [ ] **Step 2: Update frontmatter + add wave-37 entry** - -Update the `description:` frontmatter field to reference wave 37 outcome (number of bridges dropped, build-iteration count, first-pass-clean-or-not). Add a bullet to "Latest commits" section with the new SHA and a one-line summary. Remove the "peerTokenTitle parameter migration" bullet from the "Wave 37 candidates" section (it's now landed). Update "Recommended wave 37" section to "Recommended wave 38" with a fresh recommendation from the remaining candidates. - -- [ ] **Step 3: Read the refactor log** - -Read `docs/superpowers/postbox-refactor-log.md`, locate the "Wave 36 outcome" section. - -- [ ] **Step 4: Append wave-37 outcome** - -Under the "Wave N outcomes" section, append a "Wave 37 outcome" subsection with: - -- Commit SHA (from `git log --oneline -1`) -- File touched (1: ContactMultiselectionController.swift) -- Lines changed (6 deletions, 6 insertions) -- Bridges dropped (5) -- Build iterations to converge (should be 1) -- Any lessons observed (likely none — this wave is mechanical) - -- [ ] **Step 5: Commit memory + log update** - -Run: - -```bash -git add docs/superpowers/postbox-refactor-log.md -git commit -m "$(cat <<'EOF' -docs: log wave 37 outcome - -Co-Authored-By: Claude Opus 4.7 (1M context) -EOF -)" -``` - -(Memory file under `~/.claude/` is not in the repo — save it separately via the Write tool; do not try to `git add` it.) - ---- - -## Self-review results - -**Spec coverage:** Every scope item in the spec maps to a task: -- Spec L21 signature change → Task 2 Step 2 -- Spec L27 body simplification → Task 2 Step 2 -- Spec L171/201/386/403/748 bridge drops → Task 3 Steps 1–2 -- Spec verification (grep + build + post-grep) → Task 1 + Task 4 -- Spec commit message → Task 5 Step 3 - -Out-of-scope items (L459, `import Postbox`, `accountPeerId: PeerId`) remain explicitly untouched — no task edits them. - -**Placeholder scan:** No TBD, TODO, placeholder phrases, or "handle edge cases"-style hand-waves. Every step has a concrete command or code block. - -**Type consistency:** `peer: EnginePeer`, `EnginePeer.Id` (= `PeerId` typealias), and `EnginePeer.displayTitle(strings:displayOrder:)` are all consistent across tasks. diff --git a/docs/superpowers/plans/2026-04-24-rcp-peers-engine-migration.md b/docs/superpowers/plans/2026-04-24-rcp-peers-engine-migration.md deleted file mode 100644 index 9e29acda0c..0000000000 --- a/docs/superpowers/plans/2026-04-24-rcp-peers-engine-migration.md +++ /dev/null @@ -1,666 +0,0 @@ -# Wave 44 — RenderedChannelParticipant.peers Engine-Peer Migration Implementation Plan - -> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. - -**Goal:** Migrate `RenderedChannelParticipant.peers: [PeerId: Peer]` to `[EnginePeer.Id: EnginePeer]`. Closes the wave-41 ratchet — the public struct no longer leaks raw Postbox `Peer` in any field. - -**Architecture:** Single atomic commit. Declaration in TelegramCore changes; 8 TelegramCore producer functions wrap raw `Peer` values at their local-dict insertion points (inside transactions that already read from Postbox); 11 consumer-surface bridges drop (6 `EnginePeer(peer)` read-wraps + 5 `.mapValues({ $0._asPeer() })` constructor-unwrap transforms); 1 consumer-surface unwrap is added where an extracted `EnginePeer` value flows into a `SimpleDictionary`. - -**Tech Stack:** Swift, Bazel (via `python3 build-system/Make/Make.py`), Postbox, TelegramCore, TelegramEngine. No unit tests — full-build verification only. - -**Spec:** `docs/superpowers/specs/2026-04-24-rcp-peers-engine-migration-design.md` - ---- - -## File Structure - -All edits happen in existing files — no new files created. Touched files: - -**TelegramCore (declaration + producers, 9 files):** -- `submodules/TelegramCore/Sources/TelegramEngine/Peers/ChannelParticipants.swift` (declaration) -- `submodules/TelegramCore/Sources/TelegramEngine/Messages/RequestStartBot.swift` -- `submodules/TelegramCore/Sources/TelegramEngine/Peers/ChannelOwnershipTransfer.swift` -- `submodules/TelegramCore/Sources/TelegramEngine/Peers/JoinChannel.swift` -- `submodules/TelegramCore/Sources/TelegramEngine/Peers/AddPeerMember.swift` -- `submodules/TelegramCore/Sources/TelegramEngine/Peers/PeerAdmins.swift` -- `submodules/TelegramCore/Sources/TelegramEngine/Peers/ChannelBlacklist.swift` -- `submodules/TelegramCore/Sources/TelegramEngine/Peers/Ranks.swift` -- `submodules/TelegramCore/Sources/TelegramEngine/Peers/ChannelMembers.swift` - -**Consumers (drops + 1 add, 5 files):** -- `submodules/PeerInfoUI/Sources/ChannelAdminsController.swift` -- `submodules/PeerInfoUI/Sources/ChannelMembersSearchContainerNode.swift` -- `submodules/PeerInfoUI/Sources/ChannelMembersSearchControllerNode.swift` -- `submodules/PeerInfoUI/Sources/ChannelBlacklistController.swift` -- `submodules/TelegramUI/Components/Chat/ChatRecentActionsController/Sources/ChatRecentActionsHistoryTransition.swift` - -**Total:** 14 files, ~30 edits, one atomic commit. - ---- - -## Task 1: Pre-flight re-verification - -**Purpose:** Confirm the grep surface matches the spec before editing anything. If any site count diverges, stop and update the spec. - -**Files:** None modified. - -- [ ] **Step 1.1: Verify 7 `participant.peers[...]` consumer read sites** - -Run: -```bash -grep -rnE "participant\.peers\[|rcp\.peers\[|renderedParticipant\.peers\[" --include="*.swift" submodules/ 2>/dev/null -``` - -Expected output — exactly 6 bracketed-indexing sites (the 7th site, iteration without bracket-indexing, is checked in Step 1.2): -- `submodules/PeerInfoUI/Sources/ChannelAdminsController.swift:293` -- `submodules/PeerInfoUI/Sources/ChannelMembersSearchContainerNode.swift:835` -- `submodules/PeerInfoUI/Sources/ChannelMembersSearchContainerNode.swift:869` -- `submodules/PeerInfoUI/Sources/ChannelMembersSearchContainerNode.swift:1087` -- `submodules/PeerInfoUI/Sources/ChannelMembersSearchContainerNode.swift:1121` -- `submodules/PeerInfoUI/Sources/ChannelBlacklistController.swift:164` - -If any line numbers differ by more than ±3 lines, re-read surrounding context to confirm identity. If a NEW site appears that isn't in the spec, STOP and update the spec before proceeding. - -- [ ] **Step 1.2: Verify the iteration site is still at the expected line** - -Run: -```bash -grep -nE "for \(.*,.* peer\) in participant\.peers" submodules/TelegramUI/Components/Chat/ChatRecentActionsController/Sources/ChatRecentActionsHistoryTransition.swift -``` - -Expected: `672: for (_, peer) in participant.peers {` - -- [ ] **Step 1.3: Verify all 8 TelegramCore producers still build `var peers: [PeerId: Peer] = [:]` locally** - -Run: -```bash -grep -rnE "^[[:space:]]+var peers: \[PeerId: Peer\] = \[:\]" submodules/TelegramCore/Sources/TelegramEngine/ 2>/dev/null -``` - -Expected 8 matches, one per producer file: -- `Messages/RequestStartBot.swift:61` -- `Peers/ChannelOwnershipTransfer.swift:170` -- `Peers/JoinChannel.swift:59` -- `Peers/AddPeerMember.swift:242` -- `Peers/PeerAdmins.swift:251` -- `Peers/ChannelBlacklist.swift:128` -- `Peers/Ranks.swift:60` -- `Peers/ChannelMembers.swift:102` - -If a producer is missing from this grep, check whether it now receives `peers` as a parameter rather than building locally — if so, STOP and update the spec (chain-migration needed). - -- [ ] **Step 1.4: Verify no `as?` / `is TelegramX` casts exist on extracted dict values** - -Run: -```bash -grep -rnE "peer = participant\.peers" --include="*.swift" -A 4 submodules/ 2>/dev/null | grep -E "as\?|is Telegram" -``` - -Expected output: empty. If this returns non-empty, STOP and update the spec. - -- [ ] **Step 1.5: Verify no one is assigning into `participant.peers` (writes would break the migration)** - -Run: -```bash -grep -rnE "participant\.peers\[[^]]+\][[:space:]]*=" --include="*.swift" submodules/ 2>/dev/null -``` - -Expected output: empty (`.peers` is a `let`; no writes possible anyway, but double-check). - ---- - -## Task 2: Migrate declaration in ChannelParticipants.swift - -**Purpose:** Change the struct field type and init default. - -**Files:** -- Modify: `submodules/TelegramCore/Sources/TelegramEngine/Peers/ChannelParticipants.swift:11, 14` - -- [ ] **Step 2.1: Change field declaration** - -In `submodules/TelegramCore/Sources/TelegramEngine/Peers/ChannelParticipants.swift`, line 11: - -```swift -// before - public let peers: [PeerId: Peer] - -// after - public let peers: [EnginePeer.Id: EnginePeer] -``` - -- [ ] **Step 2.2: Change init default** - -Same file, line 14: - -```swift -// before - public init(participant: ChannelParticipant, peer: EnginePeer, peers: [PeerId: Peer] = [:], presences: [PeerId: PeerPresence] = [:]) { - -// after - public init(participant: ChannelParticipant, peer: EnginePeer, peers: [EnginePeer.Id: EnginePeer] = [:], presences: [PeerId: PeerPresence] = [:]) { -``` - -Do NOT commit yet — this leaves the repo in a broken state until producers and consumers are updated. - ---- - -## Task 3: Migrate TelegramCore producers (8 files) - -**Purpose:** Each of the 8 TelegramCore producers builds a local `peers: [PeerId: Peer] = [:]` dict from raw Postbox peers inside a transaction. Migrate each local dict to `[EnginePeer.Id: EnginePeer] = [:]` and wrap every insertion value with `EnginePeer(...)`. - -**Pattern (applies to every sub-step):** -```swift -// before -var peers: [PeerId: Peer] = [:] -peers[X.id] = X - -// after -var peers: [EnginePeer.Id: EnginePeer] = [:] -peers[X.id] = EnginePeer(X) -``` - -The surrounding `presences: [PeerId: PeerPresence]` dict and the `RCP(..., peer: EnginePeer(X), ...)` wrap on the primary `peer` field both stay unchanged. - -- [ ] **Step 3.1: Migrate `RequestStartBot.swift`** - -File: `submodules/TelegramCore/Sources/TelegramEngine/Messages/RequestStartBot.swift` - -Line 61: `var peers: [PeerId: Peer] = [:]` → `var peers: [EnginePeer.Id: EnginePeer] = [:]` -Line 64: `peers[peer.id] = peer` → `peers[peer.id] = EnginePeer(peer)` - -- [ ] **Step 3.2: Migrate `ChannelOwnershipTransfer.swift`** - -File: `submodules/TelegramCore/Sources/TelegramEngine/Peers/ChannelOwnershipTransfer.swift` - -Line 170: `var peers: [PeerId: Peer] = [:]` → `var peers: [EnginePeer.Id: EnginePeer] = [:]` -Line 172: `peers[accountUser.id] = accountUser` → `peers[accountUser.id] = EnginePeer(accountUser)` -Line 176: `peers[user.id] = user` → `peers[user.id] = EnginePeer(user)` - -Line 180 is a double-RCP-construction; `peers:` reuses the same local — no change at line 180. - -- [ ] **Step 3.3: Migrate `JoinChannel.swift`** - -File: `submodules/TelegramCore/Sources/TelegramEngine/Peers/JoinChannel.swift` - -Line 59: `var peers: [PeerId: Peer] = [:]` → `var peers: [EnginePeer.Id: EnginePeer] = [:]` -Line 64: `peers[account.peerId] = peer` → `peers[account.peerId] = EnginePeer(peer)` -Line 77: `peers[peer.id] = peer` → `peers[peer.id] = EnginePeer(peer)` - -- [ ] **Step 3.4: Migrate `AddPeerMember.swift`** - -File: `submodules/TelegramCore/Sources/TelegramEngine/Peers/AddPeerMember.swift` - -Line 242: `var peers: [PeerId: Peer] = [:]` → `var peers: [EnginePeer.Id: EnginePeer] = [:]` -Line 244: `peers[memberPeer.id] = memberPeer` → `peers[memberPeer.id] = EnginePeer(memberPeer)` -Line 251: `peers[peer.id] = peer` → `peers[peer.id] = EnginePeer(peer)` - -- [ ] **Step 3.5: Migrate `PeerAdmins.swift`** - -File: `submodules/TelegramCore/Sources/TelegramEngine/Peers/PeerAdmins.swift` - -Line 251: `var peers: [PeerId: Peer] = [:]` → `var peers: [EnginePeer.Id: EnginePeer] = [:]` -Line 253: `peers[adminPeer.id] = adminPeer` → `peers[adminPeer.id] = EnginePeer(adminPeer)` -Line 259: `peers[peer.id] = peer` → `peers[peer.id] = EnginePeer(peer)` - -- [ ] **Step 3.6: Migrate `ChannelBlacklist.swift`** - -File: `submodules/TelegramCore/Sources/TelegramEngine/Peers/ChannelBlacklist.swift` - -Line 128: `var peers: [PeerId: Peer] = [:]` → `var peers: [EnginePeer.Id: EnginePeer] = [:]` -Line 130: `peers[memberPeer.id] = memberPeer` → `peers[memberPeer.id] = EnginePeer(memberPeer)` -Line 136: `peers[peer.id] = peer` → `peers[peer.id] = EnginePeer(peer)` - -- [ ] **Step 3.7: Migrate `Ranks.swift`** - -File: `submodules/TelegramCore/Sources/TelegramEngine/Peers/Ranks.swift` - -Line 60: `var peers: [PeerId: Peer] = [:]` → `var peers: [EnginePeer.Id: EnginePeer] = [:]` -Line 62: `peers[user.id] = user` → `peers[user.id] = EnginePeer(user)` -Line 68: `peers[peer.id] = peer` → `peers[peer.id] = EnginePeer(peer)` - -- [ ] **Step 3.8: Migrate `ChannelMembers.swift`** - -File: `submodules/TelegramCore/Sources/TelegramEngine/Peers/ChannelMembers.swift` - -Line 102: `var peers: [PeerId: Peer] = [:]` → `var peers: [EnginePeer.Id: EnginePeer] = [:]` -Line 105: `peers[peer.id] = peer` → `peers[peer.id] = EnginePeer(peer)` - -- [ ] **Step 3.9: Post-producer verification** - -Run: -```bash -grep -rnE "^[[:space:]]+var peers: \[PeerId: Peer\] = \[:\]" submodules/TelegramCore/Sources/TelegramEngine/ 2>/dev/null -``` - -Expected: no output (all 8 have been converted). - -Run: -```bash -grep -rnE "^[[:space:]]+var peers: \[EnginePeer\.Id: EnginePeer\] = \[:\]" submodules/TelegramCore/Sources/TelegramEngine/ 2>/dev/null | wc -l -``` - -Expected: `8` (or ` 8`). - ---- - -## Task 4: Drop 5 consumer `.mapValues({ $0._asPeer() })` transforms - -**Purpose:** These consumer-side constructors build a `[EnginePeer.Id: EnginePeer]` source dict locally and currently unwrap to `[PeerId: Peer]` via `.mapValues({ $0._asPeer() })` to feed the old constructor signature. After Task 2, the constructor expects engine values directly — the transform becomes a no-op and is removed. - -**Pattern (applies to every sub-step):** -```swift -// before -peers: peers.mapValues({ $0._asPeer() }) - -// after -peers: peers -``` - -- [ ] **Step 4.1: `ChannelAdminsController.swift:926`** - -File: `submodules/PeerInfoUI/Sources/ChannelAdminsController.swift` - -Line 926 (long line): locate the substring `peers: peers.mapValues({ $0._asPeer() })` and replace with `peers: peers`. - -- [ ] **Step 4.2: `ChannelMembersSearchContainerNode.swift:994`** - -File: `submodules/PeerInfoUI/Sources/ChannelMembersSearchContainerNode.swift` - -Line 994: replace `peers: peers.mapValues({ $0._asPeer() })` → `peers: peers`. - -- [ ] **Step 4.3: `ChannelMembersSearchContainerNode.swift:998`** - -Same file, line 998: replace `peers: peers.mapValues({ $0._asPeer() })` → `peers: peers`. - -- [ ] **Step 4.4: `ChannelMembersSearchControllerNode.swift:409`** - -File: `submodules/PeerInfoUI/Sources/ChannelMembersSearchControllerNode.swift` - -Line 409: replace `peers: peers.mapValues({ $0._asPeer() })` → `peers: peers`. - -- [ ] **Step 4.5: `ChannelMembersSearchControllerNode.swift:413`** - -Same file, line 413: replace `peers: peers.mapValues({ $0._asPeer() })` → `peers: peers`. - -- [ ] **Step 4.6: Post-Task-4 verification** - -Run: -```bash -grep -rnE "peers\.mapValues\(\{ \$0\._asPeer\(\) \}\)" --include="*.swift" submodules/ 2>/dev/null -``` - -Expected: no output (all 5 drops applied). If any remain, locate and drop. - ---- - -## Task 5: Drop 6 consumer `EnginePeer(peer).displayTitle(...)` read-wraps - -**Purpose:** Each site extracts `peer` from `participant.peers[X]`, wraps with `EnginePeer(peer)` to call `.displayTitle(...)`. After Task 2 the extracted `peer` is already `EnginePeer` — drop the wrap. - -**Pattern (applies to every sub-step):** -```swift -// before -EnginePeer(peer).displayTitle(strings: ..., displayOrder: ...) - -// after -peer.displayTitle(strings: ..., displayOrder: ...) -``` - -- [ ] **Step 5.1: `ChannelAdminsController.swift:297`** - -File: `submodules/PeerInfoUI/Sources/ChannelAdminsController.swift`, line 297. - -Replace: -```swift -peerText = strings.Channel_Management_PromotedBy(EnginePeer(peer).displayTitle(strings: strings, displayOrder: nameDisplayOrder)).string -``` -with: -```swift -peerText = strings.Channel_Management_PromotedBy(peer.displayTitle(strings: strings, displayOrder: nameDisplayOrder)).string -``` - -The adjacent `peer.id == participant.peer.id` comparison at line 294 stays unchanged (both are `EnginePeer.Id`). - -- [ ] **Step 5.2: `ChannelMembersSearchContainerNode.swift:839`** - -File: `submodules/PeerInfoUI/Sources/ChannelMembersSearchContainerNode.swift`, line 839. - -Replace: -```swift -label = presentationData.strings.Channel_Management_PromotedBy(EnginePeer(peer).displayTitle(strings: presentationData.strings, displayOrder: presentationData.nameDisplayOrder)).string -``` -with: -```swift -label = presentationData.strings.Channel_Management_PromotedBy(peer.displayTitle(strings: presentationData.strings, displayOrder: presentationData.nameDisplayOrder)).string -``` - -- [ ] **Step 5.3: `ChannelMembersSearchContainerNode.swift:870`** - -Same file, line 870. - -Replace: -```swift -label = presentationData.strings.Channel_Management_RemovedBy(EnginePeer(peer).displayTitle(strings: presentationData.strings, displayOrder: presentationData.nameDisplayOrder)).string -``` -with: -```swift -label = presentationData.strings.Channel_Management_RemovedBy(peer.displayTitle(strings: presentationData.strings, displayOrder: presentationData.nameDisplayOrder)).string -``` - -- [ ] **Step 5.4: `ChannelMembersSearchContainerNode.swift:1091`** - -Same file, line 1091. - -Replace: -```swift -label = presentationData.strings.Channel_Management_PromotedBy(EnginePeer(peer).displayTitle(strings: presentationData.strings, displayOrder: presentationData.nameDisplayOrder)).string -``` -with: -```swift -label = presentationData.strings.Channel_Management_PromotedBy(peer.displayTitle(strings: presentationData.strings, displayOrder: presentationData.nameDisplayOrder)).string -``` - -- [ ] **Step 5.5: `ChannelMembersSearchContainerNode.swift:1122`** - -Same file, line 1122. - -Replace: -```swift -label = presentationData.strings.Channel_Management_RemovedBy(EnginePeer(peer).displayTitle(strings: presentationData.strings, displayOrder: presentationData.nameDisplayOrder)).string -``` -with: -```swift -label = presentationData.strings.Channel_Management_RemovedBy(peer.displayTitle(strings: presentationData.strings, displayOrder: presentationData.nameDisplayOrder)).string -``` - -- [ ] **Step 5.6: `ChannelBlacklistController.swift:165`** - -File: `submodules/PeerInfoUI/Sources/ChannelBlacklistController.swift`, line 165. - -Replace: -```swift -text = .text(strings.Channel_Management_RemovedBy(EnginePeer(peer).displayTitle(strings: strings, displayOrder: nameDisplayOrder)).string, .secondary) -``` -with: -```swift -text = .text(strings.Channel_Management_RemovedBy(peer.displayTitle(strings: strings, displayOrder: nameDisplayOrder)).string, .secondary) -``` - -- [ ] **Step 5.7: Post-Task-5 verification** - -Run: -```bash -grep -rnE "EnginePeer\(peer\)\.displayTitle" --include="*.swift" submodules/PeerInfoUI/ 2>/dev/null -``` - -Expected: no output within PeerInfoUI. (Other modules may still have unrelated `EnginePeer(peer).displayTitle` usages on non-RCP-peers peers — those are out of scope.) - -Run specifically for the 6 migrated sites: -```bash -grep -n "EnginePeer(peer)\.displayTitle" submodules/PeerInfoUI/Sources/ChannelAdminsController.swift submodules/PeerInfoUI/Sources/ChannelMembersSearchContainerNode.swift submodules/PeerInfoUI/Sources/ChannelBlacklistController.swift 2>/dev/null -``` - -Expected: no output. - ---- - -## Task 6: Add 1 consumer unwrap at ChatRecentActionsHistoryTransition - -**Purpose:** The one site that iterates `participant.peers` and inserts values into a `SimpleDictionary` container. After Task 2, the iterated `peer` is `EnginePeer`; the outer container still expects raw `Peer`. Unwrap at the insertion site. - -**Files:** -- Modify: `submodules/TelegramUI/Components/Chat/ChatRecentActionsController/Sources/ChatRecentActionsHistoryTransition.swift:673` - -- [ ] **Step 6.1: Replace insertion line** - -In `submodules/TelegramUI/Components/Chat/ChatRecentActionsController/Sources/ChatRecentActionsHistoryTransition.swift`: - -Context (lines 672–674, unchanged outside line 673): -```swift -for (_, peer) in participant.peers { - peers[peer.id] = peer -} -``` - -After edit: -```swift -for (_, peer) in participant.peers { - peers[peer.id] = peer._asPeer() -} -``` - -- [ ] **Step 6.2: Spot-check nearby wave-41 unwrap (reference, no change)** - -Line 675 in the same function is `peers[participant.peer.id] = participant.peer._asPeer()` — a wave-41 artifact, unrelated to this wave. Leave unchanged. - ---- - -## Task 7: Full build verification - -**Purpose:** Verify the atomic change set compiles. Produces the ONLY real test signal for this wave. - -**Files:** None modified; this is a build run. - -- [ ] **Step 7.1: Run the full build** - -Run: -```bash -source ~/.zshrc 2>/dev/null; python3 build-system/Make/Make.py --overrideXcodeVersion \ - --cacheDir ~/telegram-bazel-cache \ - build \ - --configurationPath build-system/appstore-configuration.json \ - --gitCodesigningRepository git@gitlab.com:peter-iakovlev/fastlanematch.git \ - --gitCodesigningType development --gitCodesigningUseCurrent --buildNumber=1 --configuration=debug_sim_arm64 \ - --continueOnError -``` - -Expected: build succeeds. Look for `INFO: Build completed successfully` near the end. - -- [ ] **Step 7.2: If build fails — triage** - -Expected failure patterns (from wave-41 lesson, budget 2–3 iterations): - -1. **Missing producer wrap** — compiler error `cannot assign value of type 'Peer' to subscript of type 'EnginePeer'` (or similar) at a TelegramCore producer file → check that file's `var peers:` decl was converted AND all insertion RHS values are wrapped. -2. **Missed consumer site** — compiler error at a `.displayTitle` call on a raw Peer → find `EnginePeer(peer).displayTitle` site that Task 5 missed; drop the wrap. -3. **Mismatched mapValues drop** — `cannot convert value of type '[EnginePeer.Id: EnginePeer]' to expected argument type '[PeerId: Peer]'` → the spec's risk #3 triggered (a `.mapValues` site had a raw-Peer source after all); replace the drop with `peers.mapValues(EnginePeer.init)` at that site instead. -4. **New grep surface** — compiler complains about a site not in this plan → add it to the commit's scope; log it to the outcome doc. - -Apply fixes, re-run Step 7.1. Repeat up to 3 iterations before re-evaluating scope. - -- [ ] **Step 7.3: Post-build final grep audit** - -Run: -```bash -grep -rnE "participant\.peers\[[^]]+\]" --include="*.swift" submodules/ 2>/dev/null -``` - -Expected: the same 6 read sites as Step 1.1 (now without `EnginePeer(peer)` wraps). - -Run: -```bash -grep -rnE "peers\.mapValues\(\{ \$0\._asPeer\(\) \}\)" --include="*.swift" submodules/ 2>/dev/null -``` - -Expected: no output. - -Run: -```bash -grep -n "public let peers: \[" submodules/TelegramCore/Sources/TelegramEngine/Peers/ChannelParticipants.swift -``` - -Expected: `11: public let peers: [EnginePeer.Id: EnginePeer]`. - ---- - -## Task 8: Atomic commit - -**Purpose:** Land all wave-44 edits in ONE commit. Explicitly enumerate files in `git add` (wave-39 lesson — re-confirmed in waves 41, 42, 43) to avoid pulling in the pre-existing working-tree WIP listed in the spec's risk section (`ListView.swift`, `ChatMessageTransitionNode.swift`, tulsi/, TgVoip/, libx264/). - -**Files:** Commits all 14 wave-44 files. - -- [ ] **Step 8.1: Confirm working-tree state** - -Run: -```bash -git status --short -``` - -Expected (pre-existing WIP, unchanged): -- ` m build-system/bazel-rules/sourcekit-bazel-bsp` -- ` M submodules/Display/Source/ListView.swift` (do NOT include) -- ` M submodules/TelegramUI/Sources/ChatMessageTransitionNode.swift` (do NOT include) -- `?? build-system/tulsi/` (do NOT include) -- `?? submodules/TgVoip/` (do NOT include) -- `?? third-party/libx264/` (do NOT include) - -Plus the wave-44 modified files: -- ` M submodules/TelegramCore/Sources/TelegramEngine/Peers/ChannelParticipants.swift` -- ` M submodules/TelegramCore/Sources/TelegramEngine/Messages/RequestStartBot.swift` -- ` M submodules/TelegramCore/Sources/TelegramEngine/Peers/ChannelOwnershipTransfer.swift` -- ` M submodules/TelegramCore/Sources/TelegramEngine/Peers/JoinChannel.swift` -- ` M submodules/TelegramCore/Sources/TelegramEngine/Peers/AddPeerMember.swift` -- ` M submodules/TelegramCore/Sources/TelegramEngine/Peers/PeerAdmins.swift` -- ` M submodules/TelegramCore/Sources/TelegramEngine/Peers/ChannelBlacklist.swift` -- ` M submodules/TelegramCore/Sources/TelegramEngine/Peers/Ranks.swift` -- ` M submodules/TelegramCore/Sources/TelegramEngine/Peers/ChannelMembers.swift` -- ` M submodules/PeerInfoUI/Sources/ChannelAdminsController.swift` -- ` M submodules/PeerInfoUI/Sources/ChannelMembersSearchContainerNode.swift` -- ` M submodules/PeerInfoUI/Sources/ChannelMembersSearchControllerNode.swift` -- ` M submodules/PeerInfoUI/Sources/ChannelBlacklistController.swift` -- ` M submodules/TelegramUI/Components/Chat/ChatRecentActionsController/Sources/ChatRecentActionsHistoryTransition.swift` - -If the set of wave-44-modified files doesn't match exactly (extra or missing), STOP and investigate before committing. - -- [ ] **Step 8.2: Stage only wave-44 files** - -Run: -```bash -git add \ - submodules/TelegramCore/Sources/TelegramEngine/Peers/ChannelParticipants.swift \ - submodules/TelegramCore/Sources/TelegramEngine/Messages/RequestStartBot.swift \ - submodules/TelegramCore/Sources/TelegramEngine/Peers/ChannelOwnershipTransfer.swift \ - submodules/TelegramCore/Sources/TelegramEngine/Peers/JoinChannel.swift \ - submodules/TelegramCore/Sources/TelegramEngine/Peers/AddPeerMember.swift \ - submodules/TelegramCore/Sources/TelegramEngine/Peers/PeerAdmins.swift \ - submodules/TelegramCore/Sources/TelegramEngine/Peers/ChannelBlacklist.swift \ - submodules/TelegramCore/Sources/TelegramEngine/Peers/Ranks.swift \ - submodules/TelegramCore/Sources/TelegramEngine/Peers/ChannelMembers.swift \ - submodules/PeerInfoUI/Sources/ChannelAdminsController.swift \ - submodules/PeerInfoUI/Sources/ChannelMembersSearchContainerNode.swift \ - submodules/PeerInfoUI/Sources/ChannelMembersSearchControllerNode.swift \ - submodules/PeerInfoUI/Sources/ChannelBlacklistController.swift \ - submodules/TelegramUI/Components/Chat/ChatRecentActionsController/Sources/ChatRecentActionsHistoryTransition.swift -``` - -- [ ] **Step 8.3: Verify staged set matches expected** - -Run: -```bash -git diff --cached --stat -``` - -Expected: exactly 14 files staged, all from the wave-44 list. If `ListView.swift`, `ChatMessageTransitionNode.swift`, `bazel-rules/sourcekit-bazel-bsp`, `tulsi/`, `TgVoip/`, or `libx264/` appear here, unstage them. - -- [ ] **Step 8.4: Commit** - -Run: -```bash -git commit -m "$(cat <<'EOF' -Postbox -> TelegramEngine wave 44 - -Migrate RenderedChannelParticipant.peers from [PeerId: Peer] to -[EnginePeer.Id: EnginePeer]. Closes the wave-41 ratchet — the public -struct no longer leaks raw Peer types in any field (presences stays -Postbox-typed; separate migration). - -Consumer-surface: -10 bridges. Dropped 6 EnginePeer(peer) read-wraps -at participant.peers[...] extraction sites across -ChannelAdminsController, ChannelMembersSearchContainerNode, -ChannelBlacklistController. Dropped 5 .mapValues({ $0._asPeer() }) -constructor-unwrap transforms in ChannelAdminsController, -ChannelMembersSearchContainerNode, ChannelMembersSearchControllerNode. -Added 1 ._asPeer() at ChatRecentActionsHistoryTransition.swift:673 -where the iterated value is inserted into a raw-Peer SimpleDictionary. - -TelegramCore producers: 8 files build the local peers dict inside -postbox.transaction and wrap at the insertion point. ChannelMembers, -RequestStartBot, ChannelOwnershipTransfer, JoinChannel, AddPeerMember, -PeerAdmins, ChannelBlacklist, Ranks. - -No unit tests in this project; full Telegram/Telegram build verified -under configuration=debug_sim_arm64. - -Co-Authored-By: Claude Opus 4.7 (1M context) -EOF -)" -``` - -- [ ] **Step 8.5: Verify commit** - -Run: -```bash -git log -1 --stat -``` - -Expected: commit with 14 files changed, message starting with `Postbox -> TelegramEngine wave 44`. - -Run: -```bash -git status --short -``` - -Expected: no M- or A-flagged wave-44 files (all committed); only the pre-existing WIP (`ListView.swift`, `ChatMessageTransitionNode.swift`, etc.) remains. - ---- - -## Rollback - -If the wave cannot be completed (e.g., build fails after 4+ iterations and the scope balloons beyond plan): - -```bash -git restore --staged \ - submodules/TelegramCore/Sources/TelegramEngine/Peers/ChannelParticipants.swift \ - submodules/TelegramCore/Sources/TelegramEngine/Messages/RequestStartBot.swift \ - submodules/TelegramCore/Sources/TelegramEngine/Peers/ChannelOwnershipTransfer.swift \ - submodules/TelegramCore/Sources/TelegramEngine/Peers/JoinChannel.swift \ - submodules/TelegramCore/Sources/TelegramEngine/Peers/AddPeerMember.swift \ - submodules/TelegramCore/Sources/TelegramEngine/Peers/PeerAdmins.swift \ - submodules/TelegramCore/Sources/TelegramEngine/Peers/ChannelBlacklist.swift \ - submodules/TelegramCore/Sources/TelegramEngine/Peers/Ranks.swift \ - submodules/TelegramCore/Sources/TelegramEngine/Peers/ChannelMembers.swift \ - submodules/PeerInfoUI/Sources/ChannelAdminsController.swift \ - submodules/PeerInfoUI/Sources/ChannelMembersSearchContainerNode.swift \ - submodules/PeerInfoUI/Sources/ChannelMembersSearchControllerNode.swift \ - submodules/PeerInfoUI/Sources/ChannelBlacklistController.swift \ - submodules/TelegramUI/Components/Chat/ChatRecentActionsController/Sources/ChatRecentActionsHistoryTransition.swift - -git checkout -- \ - submodules/TelegramCore/Sources/TelegramEngine/Peers/ChannelParticipants.swift \ - submodules/TelegramCore/Sources/TelegramEngine/Messages/RequestStartBot.swift \ - submodules/TelegramCore/Sources/TelegramEngine/Peers/ChannelOwnershipTransfer.swift \ - submodules/TelegramCore/Sources/TelegramEngine/Peers/JoinChannel.swift \ - submodules/TelegramCore/Sources/TelegramEngine/Peers/AddPeerMember.swift \ - submodules/TelegramCore/Sources/TelegramEngine/Peers/PeerAdmins.swift \ - submodules/TelegramCore/Sources/TelegramEngine/Peers/ChannelBlacklist.swift \ - submodules/TelegramCore/Sources/TelegramEngine/Peers/Ranks.swift \ - submodules/TelegramCore/Sources/TelegramEngine/Peers/ChannelMembers.swift \ - submodules/PeerInfoUI/Sources/ChannelAdminsController.swift \ - submodules/PeerInfoUI/Sources/ChannelMembersSearchContainerNode.swift \ - submodules/PeerInfoUI/Sources/ChannelMembersSearchControllerNode.swift \ - submodules/PeerInfoUI/Sources/ChannelBlacklistController.swift \ - submodules/TelegramUI/Components/Chat/ChatRecentActionsController/Sources/ChatRecentActionsHistoryTransition.swift -``` - -Then document what was learned in an outcome doc and update `project_postbox_refactor_next_wave.md`. - ---- - -## Success criteria (from spec) - -1. ✅ `ChannelParticipants.swift` has `peers: [EnginePeer.Id: EnginePeer]` declaration (Task 2). -2. ✅ All 8 TelegramCore producers compile with wrapped inserts (Task 3). -3. ✅ All 5 consumer `.mapValues({ $0._asPeer() })` transforms are removed (Task 4). -4. ✅ All 6 consumer `EnginePeer(peer).displayTitle(...)` wraps on extracted dict values are removed (Task 5). -5. ✅ `ChatRecentActionsHistoryTransition.swift:673` uses `peer._asPeer()` for the SimpleDictionary insertion value (Task 6). -6. ✅ Full `Telegram/Telegram` build (`configuration=debug_sim_arm64`) is clean — **one** atomic commit (Tasks 7, 8). -7. ✅ Grep post-migration: `participant.peers[` returns only engine-typed call sites; no residual `EnginePeer(peer)` on `.peers[...]` extractions (Steps 5.7, 7.3). diff --git a/docs/superpowers/plans/2026-04-24-renderedchannelparticipant-peer-engine-peer-migration.md b/docs/superpowers/plans/2026-04-24-renderedchannelparticipant-peer-engine-peer-migration.md deleted file mode 100644 index 9ac710ea08..0000000000 --- a/docs/superpowers/plans/2026-04-24-renderedchannelparticipant-peer-engine-peer-migration.md +++ /dev/null @@ -1,860 +0,0 @@ -# Wave 41 — `RenderedChannelParticipant.peer → EnginePeer` Implementation Plan - -> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. - -**Goal:** Migrate `TelegramCore.RenderedChannelParticipant.peer` from Postbox `Peer` to TelegramCore `EnginePeer`. Drop ~37 bridges (net ~−14 after adds) and eliminate 2 Shape-C ratchet wraps installed by wave 39. - -**Architecture:** Single atomic commit. One TelegramCore struct field change + 16 TelegramCore internal construction sites wrapped with `EnginePeer(peer)` + 17 consumer files updated: ZERO sites untouched (~160), ~32 DROP sites unwrapped, 9 CAST sites rewritten to pattern-match, 3 ADD-ASPEER sites append `._asPeer()`, 7 ADD-WRAP consumer constructors wrap raw `Peer` with `EnginePeer`. - -**Tech Stack:** Swift, Bazel (`Make.py` wrapper), TelegramCore, Postbox → TelegramEngine refactor conventions per `CLAUDE.md`. - -**Build command:** -```sh -source ~/.zshrc 2>/dev/null; python3 build-system/Make/Make.py --overrideXcodeVersion --cacheDir ~/telegram-bazel-cache build --configurationPath build-system/appstore-configuration.json --gitCodesigningRepository git@gitlab.com:peter-iakovlev/fastlanematch.git --gitCodesigningType development --gitCodesigningUseCurrent --buildNumber=1 --configuration=debug_sim_arm64 --continueOnError -``` - ---- - -## File Structure - -**Created:** none. - -**Modified (27 files):** - -TelegramCore (10 files): -- `submodules/TelegramCore/Sources/TelegramEngine/Peers/ChannelParticipants.swift` — struct field type + init param + Equatable impl -- `submodules/TelegramCore/Sources/TelegramEngine/Messages/RequestStartBot.swift` — 1 constructor wrap -- `submodules/TelegramCore/Sources/TelegramEngine/Peers/AddPeerMember.swift` — 1 constructor wrap -- `submodules/TelegramCore/Sources/TelegramEngine/Peers/ChannelAdminEventLogs.swift` — 7 constructor wraps -- `submodules/TelegramCore/Sources/TelegramEngine/Peers/ChannelBlacklist.swift` — 1 constructor wrap -- `submodules/TelegramCore/Sources/TelegramEngine/Peers/ChannelMembers.swift` — 1 constructor wrap -- `submodules/TelegramCore/Sources/TelegramEngine/Peers/ChannelOwnershipTransfer.swift` — 2 constructor wraps -- `submodules/TelegramCore/Sources/TelegramEngine/Peers/JoinChannel.swift` — 1 constructor wrap -- `submodules/TelegramCore/Sources/TelegramEngine/Peers/PeerAdmins.swift` — 1 constructor wrap -- `submodules/TelegramCore/Sources/TelegramEngine/Peers/Ranks.swift` — 1 constructor wrap - -PeerInfoUI (6 files): -- `submodules/PeerInfoUI/Sources/ChannelAdminsController.swift` -- `submodules/PeerInfoUI/Sources/ChannelBlacklistController.swift` -- `submodules/PeerInfoUI/Sources/ChannelMembersController.swift` -- `submodules/PeerInfoUI/Sources/ChannelMembersSearchContainerNode.swift` -- `submodules/PeerInfoUI/Sources/ChannelMembersSearchControllerNode.swift` -- `submodules/PeerInfoUI/Sources/ChannelPermissionsController.swift` - -Other consumers (11 files): -- `submodules/SearchPeerMembers/Sources/SearchPeerMembers.swift` -- `submodules/TelegramUI/Components/AdminUserActionsSheet/Sources/AdminUserActionsSheet.swift` -- `submodules/TelegramUI/Components/Chat/ChatRecentActionsController/Sources/ChatRecentActionsController.swift` -- `submodules/TelegramUI/Components/Chat/ChatRecentActionsController/Sources/ChatRecentActionsFilterController.swift` -- `submodules/TelegramUI/Components/Chat/ChatRecentActionsController/Sources/ChatRecentActionsHistoryTransition.swift` -- `submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoMembers.swift` -- `submodules/TelegramUI/Components/ShareWithPeersScreen/Sources/ShareWithPeersScreenState.swift` -- `submodules/TelegramUI/Components/Stories/StoryContainerScreen/Sources/StoryContentLiveChatComponent.swift` -- `submodules/TelegramUI/Sources/ChatControllerAdminBanUsers.swift` -- `submodules/TemporaryCachedPeerDataManager/Sources/ChannelMemberCategoryListContext.swift` *(no `participant.peer` edits needed — all ZERO; file touched only if build surfaces type issues)* -- `submodules/TemporaryCachedPeerDataManager/Sources/PeerChannelMemberCategoriesContextsManager.swift` *(no edits expected — only `item.peer.id` reference is ZERO)* - ---- - -## Task 1: Migrate the struct definition - -**File:** `submodules/TelegramCore/Sources/TelegramEngine/Peers/ChannelParticipants.swift` - -- [ ] **Step 1.1: Edit struct field, init param, and Equatable impl** - -Replace the entire struct body: - -```swift -public struct RenderedChannelParticipant: Equatable { - public let participant: ChannelParticipant - public let peer: EnginePeer - public let peers: [PeerId: Peer] - public let presences: [PeerId: PeerPresence] - - public init(participant: ChannelParticipant, peer: EnginePeer, peers: [PeerId: Peer] = [:], presences: [PeerId: PeerPresence] = [:]) { - self.participant = participant - self.peer = peer - self.peers = peers - self.presences = presences - } - - public static func ==(lhs: RenderedChannelParticipant, rhs: RenderedChannelParticipant) -> Bool { - return lhs.participant == rhs.participant && lhs.peer == rhs.peer - } -} -``` - -Note: the file already imports both `Postbox` (for `Peer`/`PeerId`/`PeerPresence`) and TelegramCore internal symbols (`EnginePeer` visible from within the same module). No import changes needed. - ---- - -## Task 2: Wrap TelegramCore-internal constructor sites - -Each site receives a raw `Peer` and must now wrap it with `EnginePeer(peer)`. All edits are identical in shape. - -- [ ] **Step 2.1:** `submodules/TelegramCore/Sources/TelegramEngine/Messages/RequestStartBot.swift:65` - -Before: -```swift -return .channelParticipant(RenderedChannelParticipant(participant: participant, peer: peer, peers: peers, presences: presences)) -``` -After: -```swift -return .channelParticipant(RenderedChannelParticipant(participant: participant, peer: EnginePeer(peer), peers: peers, presences: presences)) -``` - -- [ ] **Step 2.2:** `submodules/TelegramCore/Sources/TelegramEngine/Peers/AddPeerMember.swift:255` - -Before: -```swift -return (currentParticipant, RenderedChannelParticipant(participant: updatedParticipant, peer: memberPeer, peers: peers, presences: presences)) -``` -After: -```swift -return (currentParticipant, RenderedChannelParticipant(participant: updatedParticipant, peer: EnginePeer(memberPeer), peers: peers, presences: presences)) -``` - -- [ ] **Step 2.3:** `submodules/TelegramCore/Sources/TelegramEngine/Peers/ChannelAdminEventLogs.swift` — 7 constructor wraps - -Line 271: -```swift -action = .participantInvite(RenderedChannelParticipant(participant: participant, peer: peer)) -// becomes: -action = .participantInvite(RenderedChannelParticipant(participant: participant, peer: EnginePeer(peer))) -``` - -Line 279 (two constructors on one line): -```swift -action = .participantToggleBan(prev: RenderedChannelParticipant(participant: prevParticipant, peer: prevPeer), new: RenderedChannelParticipant(participant: newParticipant, peer: newPeer)) -// becomes: -action = .participantToggleBan(prev: RenderedChannelParticipant(participant: prevParticipant, peer: EnginePeer(prevPeer)), new: RenderedChannelParticipant(participant: newParticipant, peer: EnginePeer(newPeer))) -``` - -Line 287 (two constructors on one line): -```swift -action = .participantToggleAdmin(prev: RenderedChannelParticipant(participant: prevParticipant, peer: prevPeer), new: RenderedChannelParticipant(participant: newParticipant, peer: newPeer)) -// becomes: -action = .participantToggleAdmin(prev: RenderedChannelParticipant(participant: prevParticipant, peer: EnginePeer(prevPeer)), new: RenderedChannelParticipant(participant: newParticipant, peer: EnginePeer(newPeer))) -``` - -Line 483 (two constructors on one line): -```swift -action = .participantSubscriptionExtended(prev: RenderedChannelParticipant(participant: prevParticipant, peer: prevPeer), new: RenderedChannelParticipant(participant: newParticipant, peer: newPeer)) -// becomes: -action = .participantSubscriptionExtended(prev: RenderedChannelParticipant(participant: prevParticipant, peer: EnginePeer(prevPeer)), new: RenderedChannelParticipant(participant: newParticipant, peer: EnginePeer(newPeer))) -``` - -- [ ] **Step 2.4:** `submodules/TelegramCore/Sources/TelegramEngine/Peers/ChannelBlacklist.swift:140` - -Before: -```swift -return (currentParticipant, RenderedChannelParticipant(participant: updatedParticipant, peer: memberPeer, peers: peers, presences: presences), isMember) -``` -After: -```swift -return (currentParticipant, RenderedChannelParticipant(participant: updatedParticipant, peer: EnginePeer(memberPeer), peers: peers, presences: presences), isMember) -``` - -- [ ] **Step 2.5:** `submodules/TelegramCore/Sources/TelegramEngine/Peers/ChannelMembers.swift:115` - -Before: -```swift -items.append(RenderedChannelParticipant(participant: participant, peer: peer, peers: peers, presences: renderedPresences)) -``` -After: -```swift -items.append(RenderedChannelParticipant(participant: participant, peer: EnginePeer(peer), peers: peers, presences: renderedPresences)) -``` - -- [ ] **Step 2.6:** `submodules/TelegramCore/Sources/TelegramEngine/Peers/ChannelOwnershipTransfer.swift:180` - -Before: -```swift -return [(currentCreator, RenderedChannelParticipant(participant: updatedPreviousCreator, peer: accountUser, peers: peers, presences: presences)), (currentParticipant, RenderedChannelParticipant(participant: updatedParticipant, peer: user, peers: peers, presences: presences))] -``` -After: -```swift -return [(currentCreator, RenderedChannelParticipant(participant: updatedPreviousCreator, peer: EnginePeer(accountUser), peers: peers, presences: presences)), (currentParticipant, RenderedChannelParticipant(participant: updatedParticipant, peer: EnginePeer(user), peers: peers, presences: presences))] -``` - -- [ ] **Step 2.7:** `submodules/TelegramCore/Sources/TelegramEngine/Peers/JoinChannel.swift:82` - -Before: -```swift -return RenderedChannelParticipant(participant: updatedParticipant, peer: peer, peers: peers, presences: presences) -``` -After: -```swift -return RenderedChannelParticipant(participant: updatedParticipant, peer: EnginePeer(peer), peers: peers, presences: presences) -``` - -- [ ] **Step 2.8:** `submodules/TelegramCore/Sources/TelegramEngine/Peers/PeerAdmins.swift:262` - -Before: -```swift -return (currentParticipant, RenderedChannelParticipant(participant: updatedParticipant, peer: adminPeer, peers: peers, presences: presences)) -``` -After: -```swift -return (currentParticipant, RenderedChannelParticipant(participant: updatedParticipant, peer: EnginePeer(adminPeer), peers: peers, presences: presences)) -``` - -- [ ] **Step 2.9:** `submodules/TelegramCore/Sources/TelegramEngine/Peers/Ranks.swift:95` - -Before: -```swift -return (currentParticipant, RenderedChannelParticipant(participant: updatedParticipant, peer: user, peers: peers, presences: presences)) -``` -After: -```swift -return (currentParticipant, RenderedChannelParticipant(participant: updatedParticipant, peer: EnginePeer(user), peers: peers, presences: presences)) -``` - ---- - -## Task 3: Consumer — PeerInfoUI/ChannelAdminsController.swift - -**File:** `submodules/PeerInfoUI/Sources/ChannelAdminsController.swift` - -- [ ] **Step 3.1:** Line 326 — DROP `EnginePeer(participant.peer)` wrap. - -Before: -```swift -return ItemListPeerItem(presentationData: presentationData, systemStyle: .glass, dateTimeFormat: dateTimeFormat, nameDisplayOrder: nameDisplayOrder, context: arguments.context, peer: EnginePeer(participant.peer), presence: participant.presences[participant.peer.id].flatMap { EnginePeer.Presence($0) }, text: peerText.isEmpty ? .presence : .text(peerText, .secondary), label: label, editing: editing, revealOptions: revealOptions, switchValue: nil, enabled: enabled, selectable: true, sectionId: self.section, action: action, setPeerIdWithRevealedOptions: { previousId, id in -``` -After: replace `peer: EnginePeer(participant.peer)` → `peer: participant.peer` (leave the rest of the line intact). - -- [ ] **Step 3.2:** Line 921 — DROP `._asPeer()` in constructor. - -Before: -```swift -result.append(RenderedChannelParticipant(participant: .creator(id: peer.id, adminInfo: nil, rank: rank), peer: peer._asPeer(), presences: presences)) -``` -After: -```swift -result.append(RenderedChannelParticipant(participant: .creator(id: peer.id, adminInfo: nil, rank: rank), peer: peer, presences: presences)) -``` -(`peer` here is already `EnginePeer` — confirmed by surrounding code where `creatorPeer: EnginePeer?` is assigned from this same loop variable.) - -- [ ] **Step 3.3:** Line 926 — DROP `._asPeer()` in constructor. - -Before: -```swift -result.append(RenderedChannelParticipant(participant: .member(id: peer.id, invitedAt: 0, adminInfo: ChannelParticipantAdminInfo(rights: TelegramChatAdminRights(rights: .internal_groupSpecific), promotedBy: creator.id, canBeEditedByAccountPeer: creator.id == context.account.peerId), banInfo: nil, rank: rank, subscriptionUntilDate: nil), peer: peer._asPeer(), peers: peers.mapValues({ $0._asPeer() }), presences: presences)) -``` -After: change `peer: peer._asPeer()` → `peer: peer`. Leave `peers.mapValues({ $0._asPeer() })` intact — `peers` field is unchanged. - ---- - -## Task 4: Consumer — PeerInfoUI/ChannelBlacklistController.swift - -**File:** `submodules/PeerInfoUI/Sources/ChannelBlacklistController.swift` - -- [ ] **Step 4.1:** Line 170 (or 381 — the site installed by wave 39; the file has one site `EnginePeer(participant.peer)`) - -Before: -```swift -peer: EnginePeer(participant.peer) -``` -After: -```swift -peer: participant.peer -``` - -Note: the file may have a single such site; use: -``` -grep -n 'EnginePeer(participant\.peer)' submodules/PeerInfoUI/Sources/ChannelBlacklistController.swift -``` -and DROP every match. - ---- - -## Task 5: Consumer — PeerInfoUI/ChannelMembersController.swift - -**File:** `submodules/PeerInfoUI/Sources/ChannelMembersController.swift` - -- [ ] **Step 5.1:** Line 305 — CAST rewrite. - -Before: -```swift -if let user = participant.peer as? TelegramUser, let _ = user.botInfo { -``` -After: -```swift -if case let .user(user) = participant.peer, let _ = user.botInfo { -``` - -- [ ] **Step 5.2:** Line 334 — DROP wrap. - -Before: -```swift -peer: EnginePeer(participant.peer) -``` -After: -```swift -peer: participant.peer -``` - -- [ ] **Step 5.3:** Line 707 — DROP wrap (the wave-39-installed Shape-C wrap). - -Before: -```swift -peer: EnginePeer(participant.peer) -``` -After: -```swift -peer: participant.peer -``` - ---- - -## Task 6: Consumer — PeerInfoUI/ChannelMembersSearchContainerNode.swift - -**File:** `submodules/PeerInfoUI/Sources/ChannelMembersSearchContainerNode.swift` - -This file has the most sites (4 CAST, 3 DROP pairs, 3 ADD-WRAP constructor sites). - -- [ ] **Step 6.1:** Line 212 — DROP two wraps on one line. - -Before: -```swift -peer: .peer(peer: EnginePeer(participant.peer), chatPeer: EnginePeer(participant.peer)), -``` -After: -```swift -peer: .peer(peer: participant.peer, chatPeer: participant.peer), -``` - -- [ ] **Step 6.2:** Line 223 — DROP wrap. - -Before: -```swift -interaction.peerSelected(EnginePeer(participant.peer), participant) -``` -After: -```swift -interaction.peerSelected(participant.peer, participant) -``` - -- [ ] **Step 6.3:** Line 752 — CAST rewrite. - -Before: -```swift -if excludeBots, let user = participant.peer as? TelegramUser, user.botInfo != nil { -``` -After: -```swift -if excludeBots, case let .user(user) = participant.peer, user.botInfo != nil { -``` - -- [ ] **Step 6.4:** Line 884 — CAST rewrite. Same pattern as 6.3. - -- [ ] **Step 6.5:** Line 987 — ADD-WRAP constructor. - -Before: -```swift -renderedParticipant = RenderedChannelParticipant(participant: .creator(id: peer.id, adminInfo: nil, rank: nil), peer: peer) -``` -After: -```swift -renderedParticipant = RenderedChannelParticipant(participant: .creator(id: peer.id, adminInfo: nil, rank: nil), peer: EnginePeer(peer)) -``` -(`peer` here is raw `Peer` from `peerView.peers[participant.peerId]` — confirmed by surrounding iteration code.) - -- [ ] **Step 6.6:** Line 994 — ADD-WRAP constructor. - -Change `peer: peer` to `peer: EnginePeer(peer)`. Full site for reference: -```swift -renderedParticipant = RenderedChannelParticipant(participant: .member(id: peer.id, invitedAt: 0, adminInfo: ChannelParticipantAdminInfo(rights: TelegramChatAdminRights(rights: TelegramChatAdminRightsFlags.peerSpecific(peer: .legacyGroup(group))), promotedBy: creatorPeer?.id ?? context.account.peerId, canBeEditedByAccountPeer: creatorPeer?.id == context.account.peerId), banInfo: nil, rank: nil, subscriptionUntilDate: nil), peer: peer, peers: peers.mapValues({ $0._asPeer() })) -``` -Change only `peer: peer,` → `peer: EnginePeer(peer),`. - -- [ ] **Step 6.7:** Line 998 — ADD-WRAP constructor. - -```swift -renderedParticipant = RenderedChannelParticipant(participant: .member(id: peer.id, invitedAt: 0, adminInfo: nil, banInfo: nil, rank: nil, subscriptionUntilDate: nil), peer: peer, peers: peers.mapValues({ $0._asPeer() })) -``` -Change only `peer: peer,` → `peer: EnginePeer(peer),`. - -- [ ] **Step 6.8:** Line 1052 — CAST rewrite. Same pattern as 6.3. - -- [ ] **Step 6.9:** Line 1136 — CAST rewrite. Same pattern as 6.3. - ---- - -## Task 7: Consumer — PeerInfoUI/ChannelMembersSearchControllerNode.swift - -**File:** `submodules/PeerInfoUI/Sources/ChannelMembersSearchControllerNode.swift` - -- [ ] **Step 7.1:** Line 148 — DROP wrap. - -Before: -```swift -peer: EnginePeer(participant.peer) -``` -After: -```swift -peer: participant.peer -``` -(The line has the wrap appearing twice — search the file for `EnginePeer(participant.peer)` and drop each occurrence. Use Edit with `replace_all` if unambiguous.) - -- [ ] **Step 7.2:** Line 404 — ADD-WRAP constructor. - -Before: -```swift -renderedParticipant = RenderedChannelParticipant(participant: .creator(id: peer.id, adminInfo: nil, rank: nil), peer: peer, presences: peerView.peerPresences) -``` -After: -```swift -renderedParticipant = RenderedChannelParticipant(participant: .creator(id: peer.id, adminInfo: nil, rank: nil), peer: EnginePeer(peer), presences: peerView.peerPresences) -``` - -- [ ] **Step 7.3:** Line 409 — ADD-WRAP constructor. - -Change `peer: peer,` → `peer: EnginePeer(peer),` in the full line: -```swift -renderedParticipant = RenderedChannelParticipant(participant: .member(id: peer.id, invitedAt: 0, adminInfo: ChannelParticipantAdminInfo(rights: TelegramChatAdminRights(rights: TelegramChatAdminRightsFlags.peerSpecific(peer: EnginePeer(mainPeer))), promotedBy: creator.id, canBeEditedByAccountPeer: creator.id == context.account.peerId), banInfo: nil, rank: nil, subscriptionUntilDate: nil), peer: peer, peers: peers.mapValues({ $0._asPeer() }), presences: peerView.peerPresences) -``` - -- [ ] **Step 7.4:** Line 413 — ADD-WRAP constructor. Same `peer: peer,` → `peer: EnginePeer(peer),`. - -- [ ] **Step 7.5:** Line 516 — CAST rewrite. - -Before: -```swift -if let user = participant.peer as? TelegramUser, user.botInfo != nil { -``` -After: -```swift -if case let .user(user) = participant.peer, user.botInfo != nil { -``` - -- [ ] **Step 7.6:** Line 558 — CAST rewrite. Same pattern as 7.5. - ---- - -## Task 8: Consumer — PeerInfoUI/ChannelPermissionsController.swift - -**File:** `submodules/PeerInfoUI/Sources/ChannelPermissionsController.swift` - -- [ ] **Step 8.1:** Lines 480 and 483 — DROP wraps. - -Both lines contain `EnginePeer(participant.peer)`. Change each to `participant.peer`. - -If the two occurrences are unambiguous, use Edit with `replace_all=true` on `EnginePeer(participant.peer)` → `participant.peer`. - ---- - -## Task 9: Consumer — SearchPeerMembers/SearchPeerMembers.swift - -**File:** `submodules/SearchPeerMembers/Sources/SearchPeerMembers.swift` - -- [ ] **Step 9.1:** Lines 30, 36, 61, 76 — DROP wraps. - -All four sites are `EnginePeer(participant.peer)`. Use Edit with `replace_all=true`: -- old: `EnginePeer(participant.peer)` -- new: `participant.peer` - -Verify with `grep -n 'EnginePeer(participant\.peer)' submodules/SearchPeerMembers/Sources/SearchPeerMembers.swift` → should return empty after edit. - ---- - -## Task 10: Consumer — ChatRecentActionsController.swift - -**File:** `submodules/TelegramUI/Components/Chat/ChatRecentActionsController/Sources/ChatRecentActionsController.swift` - -- [ ] **Step 10.1:** Line 359 — DROP wrap. - -Before: -```swift -EnginePeer(participant.peer) -``` -After: -```swift -participant.peer -``` - ---- - -## Task 11: Consumer — ChatRecentActionsFilterController.swift - -**File:** `submodules/TelegramUI/Components/Chat/ChatRecentActionsController/Sources/ChatRecentActionsFilterController.swift` - -- [ ] **Step 11.1:** Line 217 — DROP wrap. - -Change `EnginePeer(participant.peer)` → `participant.peer` on line 217. - -- [ ] **Step 11.2:** Line 445 — ADD-WRAP constructor rewrite. - -Before: -```swift -if let peer = peer, case let .user(user) = peer { - return RenderedChannelParticipant(participant: .member(id: user.id, invitedAt: 0, adminInfo: nil, banInfo: nil, rank: nil, subscriptionUntilDate: nil), peer: user) -} -``` -After: -```swift -if let peer = peer, case let .user(user) = peer { - return RenderedChannelParticipant(participant: .member(id: user.id, invitedAt: 0, adminInfo: nil, banInfo: nil, rank: nil, subscriptionUntilDate: nil), peer: .user(user)) -} -``` -(`.user(user)` is the enum case `EnginePeer.user(TelegramUser)`. Alternative: `peer: EnginePeer(user)` or `peer: peer` — but `peer: peer` reuses the already-unwrapped EnginePeer and is the cleanest. Use `peer: peer`.) - -Preferred after: -```swift -if let peer = peer, case let .user(user) = peer { - return RenderedChannelParticipant(participant: .member(id: user.id, invitedAt: 0, adminInfo: nil, banInfo: nil, rank: nil, subscriptionUntilDate: nil), peer: peer) -} -``` - ---- - -## Task 12: Consumer — ChatRecentActionsHistoryTransition.swift - -**File:** `submodules/TelegramUI/Components/Chat/ChatRecentActionsController/Sources/ChatRecentActionsHistoryTransition.swift` - -This is the highest-volume consumer file (12 `EnginePeer(new.peer)` sites + 2 ADD-ASPEER sites). - -- [ ] **Step 12.1:** DROP all `EnginePeer(new.peer)` wraps. - -Use Edit with `replace_all=true`: -- old: `EnginePeer(new.peer)` -- new: `new.peer` - -After: grep `EnginePeer(new\.peer)` should return empty. - -- [ ] **Step 12.2:** Line 675 — ADD-ASPEER. - -Before: -```swift -peers[participant.peer.id] = participant.peer -``` -After: -```swift -peers[participant.peer.id] = participant.peer._asPeer() -``` -(Target dict is `SimpleDictionary`; the value side needs raw Peer.) - -- [ ] **Step 12.3:** Line 2275 — ADD-ASPEER. - -Before: -```swift -peers[new.peer.id] = new.peer -``` -After: -```swift -peers[new.peer.id] = new.peer._asPeer() -``` - ---- - -## Task 13: Consumer — PeerInfoMembers.swift - -**File:** `submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoMembers.swift` - -- [ ] **Step 13.1:** Line 33 — ADD-ASPEER. - -Before: -```swift -var peer: Peer { - switch self { - case let .channelMember(participant, _): - return participant.peer -``` -After: -```swift -var peer: Peer { - switch self { - case let .channelMember(participant, _): - return participant.peer._asPeer() -``` - -No other edits in this file. The `participant.peer.id` accesses at lines 22, 44 are ZERO; `item.peer.id` at line 171 is ZERO. - ---- - -## Task 14: Consumer — ShareWithPeersScreenState.swift - -**File:** `submodules/TelegramUI/Components/ShareWithPeersScreen/Sources/ShareWithPeersScreenState.swift` - -- [ ] **Step 14.1:** Line 558 — DROP wrap. - -Before: -```swift -peers.append(EnginePeer(participant.peer)) -``` -After: -```swift -peers.append(participant.peer) -``` - -- [ ] **Step 14.2:** Line 566 — CAST rewrite. - -Before: -```swift -if let user = participant.peer as? TelegramUser, user.botInfo != nil { -``` -After: -```swift -if case let .user(user) = participant.peer, user.botInfo != nil { -``` - -- [ ] **Step 14.3:** Line 576 — DROP wrap. - -Before: -```swift -peers.append(EnginePeer(participant.peer)) -``` -After: -```swift -peers.append(participant.peer) -``` - ---- - -## Task 15: Consumer — AdminUserActionsSheet.swift - -**File:** `submodules/TelegramUI/Components/AdminUserActionsSheet/Sources/AdminUserActionsSheet.swift` - -This file has ~6 `EnginePeer(peer.peer)` / `EnginePeer(component.peers[0].peer)` wraps and many ZERO sites. - -- [ ] **Step 15.1:** Use Edit with `replace_all=true`: -- old: `EnginePeer(peer.peer)` -- new: `peer.peer` - -This covers lines 284, 522, 523. - -- [ ] **Step 15.2:** Edit the `EnginePeer(component.peers[0].peer)` sites at lines 404, 416, 417. - -Use Edit with `replace_all=true`: -- old: `EnginePeer(component.peers[0].peer)` -- new: `component.peers[0].peer` - -- [ ] **Step 15.3:** Verify no other `EnginePeer(` wraps around `.peer` accesses remain on `RenderedChannelParticipant`. Run: -``` -grep -n 'EnginePeer(.*\.peer)' submodules/TelegramUI/Components/AdminUserActionsSheet/Sources/AdminUserActionsSheet.swift -``` -Confirm remaining matches are on non-RCP types (e.g., some other context-derived peer). - ---- - -## Task 16: Consumer — StoryContentLiveChatComponent.swift - -**File:** `submodules/TelegramUI/Components/Stories/StoryContainerScreen/Sources/StoryContentLiveChatComponent.swift` - -- [ ] **Step 16.1:** Line 370 — DROP `._asPeer()` in constructor. - -Before: -```swift -peer: author._asPeer() -``` -After: -```swift -peer: author -``` -(`author` is `EnginePeer` — confirmed by the surrounding code that uses `author.id` and by the `chatPeer` signal's return type.) - ---- - -## Task 17: Consumer — ChatControllerAdminBanUsers.swift - -**File:** `submodules/TelegramUI/Sources/ChatControllerAdminBanUsers.swift` - -- [ ] **Step 17.1:** Line 226 — ADD-WRAP constructor. - -Before: -```swift -let peer = author -renderedParticipants.append(RenderedChannelParticipant( - participant: participant, - peer: peer -)) -``` -After: -```swift -let peer = author -renderedParticipants.append(RenderedChannelParticipant( - participant: participant, - peer: EnginePeer(peer) -)) -``` -(Confirmed `author` is raw `Peer` via `presentMultiBanMessageOptions(... authors: [Peer], ...)` signature on line 45.) - -- [ ] **Step 17.2:** Line 372 — DROP `._asPeer()` in constructor. - -Before: -```swift -peer: authorPeer._asPeer() -``` -After: -```swift -peer: authorPeer -``` -(Confirmed `authorPeer` is `EnginePeer?` at line 327 via `engine.data.get(Peer.Peer(id:))` signal; already guard-unwrapped.) - -- [ ] **Step 17.3:** Line 757 — DROP `._asPeer()` in constructor. - -Same edit pattern as 17.2: `peer: authorPeer._asPeer()` → `peer: authorPeer`. - ---- - -## Task 18: Full build verification - -- [ ] **Step 18.1:** Run the full build with `--continueOnError`. - -```sh -source ~/.zshrc 2>/dev/null; python3 build-system/Make/Make.py --overrideXcodeVersion --cacheDir ~/telegram-bazel-cache build --configurationPath build-system/appstore-configuration.json --gitCodesigningRepository git@gitlab.com:peter-iakovlev/fastlanematch.git --gitCodesigningType development --gitCodesigningUseCurrent --buildNumber=1 --configuration=debug_sim_arm64 --continueOnError -``` - -Expected: build success. First-pass-clean is the goal (wave-39 pattern applies — classification is exact, migration is mechanical, no inference-bearing return types). - -If the build fails, expect errors only in files in this plan. Any error outside the plan's file list is either: -- a pre-existing unrelated WIP (e.g., `ChatMessageTransitionNode.swift`) — not a wave-41 issue -- a genuine miss in pre-flight classification — record which file, update the plan, and re-run - -For each error in wave-41 files: -1. Read the error -2. Classify: is it a shape we mis-identified (ZERO that's not actually transparent) or a new shape (dict subscript, function arg to a `Peer`-typed param, etc.)? -3. Apply the appropriate fix (`._asPeer()` if raw Peer needed; unwrap the wrap if EnginePeer needed) -4. Re-run the build - -Budget: 1–3 build iterations. - -- [ ] **Step 18.2:** Post-build grep verification. - -Run these greps and confirm they return only the expected residual matches: - -```sh -grep -rn 'EnginePeer(participant\.peer)' submodules/ --include='*.swift' | grep -v submodules/TelegramCore/ | grep -v submodules/Postbox/ -``` -Expected: empty. - -```sh -grep -rn 'EnginePeer(new\.peer)' submodules/ --include='*.swift' | grep -v submodules/TelegramCore/ -``` -Expected: empty. - -```sh -grep -rn 'participant\.peer as\? TelegramUser' submodules/ --include='*.swift' -``` -Expected: empty. - -```sh -grep -n 'public let peer:' submodules/TelegramCore/Sources/TelegramEngine/Peers/ChannelParticipants.swift -``` -Expected: `public let peer: EnginePeer`. - ---- - -## Task 19: Commit - -- [ ] **Step 19.1:** Stage only wave-41 files (explicitly enumerate — wave-39 lesson). - -```sh -git status --short -``` - -Inspect the output. Only wave-41 files should appear as modified. If pre-existing WIP (e.g., `submodules/TelegramUI/Sources/ChatMessageTransitionNode.swift`) is also modified, do NOT include it in the commit. - -```sh -git add \ - submodules/TelegramCore/Sources/TelegramEngine/Peers/ChannelParticipants.swift \ - submodules/TelegramCore/Sources/TelegramEngine/Messages/RequestStartBot.swift \ - submodules/TelegramCore/Sources/TelegramEngine/Peers/AddPeerMember.swift \ - submodules/TelegramCore/Sources/TelegramEngine/Peers/ChannelAdminEventLogs.swift \ - submodules/TelegramCore/Sources/TelegramEngine/Peers/ChannelBlacklist.swift \ - submodules/TelegramCore/Sources/TelegramEngine/Peers/ChannelMembers.swift \ - submodules/TelegramCore/Sources/TelegramEngine/Peers/ChannelOwnershipTransfer.swift \ - submodules/TelegramCore/Sources/TelegramEngine/Peers/JoinChannel.swift \ - submodules/TelegramCore/Sources/TelegramEngine/Peers/PeerAdmins.swift \ - submodules/TelegramCore/Sources/TelegramEngine/Peers/Ranks.swift \ - submodules/PeerInfoUI/Sources/ChannelAdminsController.swift \ - submodules/PeerInfoUI/Sources/ChannelBlacklistController.swift \ - submodules/PeerInfoUI/Sources/ChannelMembersController.swift \ - submodules/PeerInfoUI/Sources/ChannelMembersSearchContainerNode.swift \ - submodules/PeerInfoUI/Sources/ChannelMembersSearchControllerNode.swift \ - submodules/PeerInfoUI/Sources/ChannelPermissionsController.swift \ - submodules/SearchPeerMembers/Sources/SearchPeerMembers.swift \ - submodules/TelegramUI/Components/AdminUserActionsSheet/Sources/AdminUserActionsSheet.swift \ - submodules/TelegramUI/Components/Chat/ChatRecentActionsController/Sources/ChatRecentActionsController.swift \ - submodules/TelegramUI/Components/Chat/ChatRecentActionsController/Sources/ChatRecentActionsFilterController.swift \ - submodules/TelegramUI/Components/Chat/ChatRecentActionsController/Sources/ChatRecentActionsHistoryTransition.swift \ - submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoMembers.swift \ - submodules/TelegramUI/Components/ShareWithPeersScreen/Sources/ShareWithPeersScreenState.swift \ - submodules/TelegramUI/Components/Stories/StoryContainerScreen/Sources/StoryContentLiveChatComponent.swift \ - submodules/TelegramUI/Sources/ChatControllerAdminBanUsers.swift \ - docs/superpowers/specs/2026-04-24-renderedchannelparticipant-peer-engine-peer-migration-design.md \ - docs/superpowers/plans/2026-04-24-renderedchannelparticipant-peer-engine-peer-migration.md -``` - -(Add any additional files the build iterations surfaced.) - -Run `git status --short` and confirm only staged wave-41 files are green, and any unrelated WIP is still marked as unstaged. - -- [ ] **Step 19.2:** Commit. - -```sh -git commit -m "$(cat <<'EOF' -Postbox -> TelegramEngine wave 41 - -Migrate RenderedChannelParticipant.peer from Postbox `Peer` to -TelegramCore `EnginePeer`. 27 files touched: 10 TelegramCore -(1 struct + 9 files with constructor wraps) + 17 consumer files. - -Drops the 2 Shape-C wraps installed by wave 39 (ChannelMembersController -and ChannelBlacklistController) plus ~37 additional EnginePeer(...) / -._asPeer() bridges across the consumer surface. Net ~-14 bridges -after the 16 TelegramCore-internal EnginePeer(peer) wraps and the 7 -consumer ADD-WRAP constructor sites. RCP.peers and RCP.presences -dictionaries remain Postbox-typed (deferred). -EOF -)" -``` - -- [ ] **Step 19.3:** Confirm commit landed and working tree is clean except for pre-existing WIP. - -```sh -git status --short -git log -1 --oneline -``` - ---- - -## Task 20: Log the wave outcome - -- [ ] **Step 20.1:** Append wave 41 entry to `docs/superpowers/postbox-refactor-log.md`. - -Format (matching prior wave entries): - -```markdown -## Wave 41 outcome — RenderedChannelParticipant.peer: Peer → EnginePeer (2026-04-24) - -Landed as commit ``. 27 files / ~45 site edits / net ~-14 bridges. - -**Shape distribution:** -- TelegramCore: 16 constructor sites wrapped with `EnginePeer(peer)` across 9 files + struct field migrated in ChannelParticipants.swift -- Consumers: ~32 DROP (EnginePeer/._asPeer unwraps), 9 CAST (as? TelegramUser → if case let .user), 3 ADD-ASPEER, 7 ADD-WRAP constructor sites - -**First-pass-clean:** . Extends wave-39 lesson: first-pass-clean -is achievable when classification is exact and all patterns are mechanical. - -**Ratchet economics:** drops 2 wave-39 Shape-C wraps -(ChannelMembersController:707, ChannelBlacklistController:381) and installs 7 ADD-WRAP -consumer constructor sites as ratchet markers for a future -`RenderedChannelParticipant.peers: [PeerId: Peer] → [EnginePeer.Id: EnginePeer]` wave. - -**Spec:** `docs/superpowers/specs/2026-04-24-renderedchannelparticipant-peer-engine-peer-migration-design.md`. -**Plan:** `docs/superpowers/plans/2026-04-24-renderedchannelparticipant-peer-engine-peer-migration.md`. -``` - -- [ ] **Step 20.2:** Update the `project_postbox_refactor_next_wave.md` memory file with the wave 41 outcome and the wave 42 candidate (likely `PeerInfoScreenData.peer → EnginePeer`). - -- [ ] **Step 20.3:** Commit docs updates. - -```sh -git add docs/superpowers/postbox-refactor-log.md -git commit -m "$(cat <<'EOF' -docs: log wave 41 outcome -EOF -)" -``` diff --git a/docs/superpowers/plans/2026-04-24-sendaspeer-engine-peer-migration.md b/docs/superpowers/plans/2026-04-24-sendaspeer-engine-peer-migration.md deleted file mode 100644 index 56c804e215..0000000000 --- a/docs/superpowers/plans/2026-04-24-sendaspeer-engine-peer-migration.md +++ /dev/null @@ -1,666 +0,0 @@ -# Wave 35: `SendAsPeer.peer: Peer → EnginePeer` Implementation Plan - -> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. - -**Goal:** Migrate the public field `SendAsPeer.peer` from the Postbox `Peer` protocol to the TelegramCore `EnginePeer` enum in a single atomic commit. Drops 3 `._asPeer()` bridges at construction sites, collapses 6 redundant `EnginePeer(peer.peer)` wraps, rewrites 1 `peer.peer as? TelegramChannel` downcast to an enum pattern, and adds `EnginePeer(channel)` wraps at 2 raw-`TelegramChannel` construction sites. No outflow `._asPeer()` bridges need to be added for this wave (unlike wave 34's `ContactListPeer.peer(peer:)` bridge). - -**Architecture:** One atomic commit. The field-type change is necessarily atomic (half-migrated SendAsPeer doesn't compile), so all edits land together. TelegramCore's `_internal_*SendAsAvailablePeers` functions keep `import Postbox` — only `SendAsPeer`'s public surface changes. No new wrappers, no new typealiases. The manual `==` body is replaced with synthesized Equatable (EnginePeer is Equatable). - -**Tech Stack:** Swift, Bazel build via Make.py wrapper. No tests — verification is build success + targeted grep checks. - -**Spec:** `docs/superpowers/specs/2026-04-24-sendaspeer-engine-peer-migration-design.md` - ---- - -## File Structure - -**Modified files (7 expected — 1 TelegramCore + 6 consumer. Plus 2 "verify no-edit" files.)** - -| File | Edit count | Category | -|---|---|---| -| `submodules/TelegramCore/Sources/TelegramEngine/Messages/SendAsPeers.swift` | ~7 spot edits (struct change + 4 constructor wraps + drop manual `==`) | α | -| `submodules/TelegramUI/Components/Chat/ChatSendAsContextMenu/Sources/ChatSendAsPeerListContextItem.swift` | ~5 (1 cast rewrite + 4 wrap drops) | γ | -| `submodules/TelegramUI/Sources/Chat/ChatControllerLoadDisplayNode.swift` | 3 (1 bridge-drop + 2 EnginePeer wraps on raw channel) | δ | -| `submodules/TelegramUI/Components/Chat/ChatTextInputPanelNode/Sources/ChatTextInputPanelComponent.swift` | 1 (bridge-drop) | δ | -| `submodules/TelegramUI/Components/Chat/ChatTextInputPanelNode/Sources/ChatTextInputPanelNode.swift` | 1 (wrap collapse) | δ | -| `submodules/TelegramUI/Components/Stories/StoryContainerScreen/Sources/StoryItemSetContainerViewSendMessage.swift` | ~4 (1 bridge-drop + 1 flatMap simplify + 1 map simplify) | δ | - -**Verify-only (no edits expected):** -| File | Reason | -|---|---| -| `submodules/ChatPresentationInterfaceState/Sources/ChatPresentationInterfaceState.swift` | Holds `[SendAsPeer]?` at collection level, no `.peer` access. | -| `submodules/TelegramUI/Components/Stories/StoryContainerScreen/Sources/StoryItemSetContainerComponent.swift` | Passes `currentSendAsPeer` through to `ChatSendAsPeerListContextItem` which keeps taking `[SendAsPeer]`. | - -**EnginePeer enum case mapping (used in cast rewrite):** - -| Postbox concrete | EnginePeer case | -|---|---| -| `TelegramChannel` | `.channel(TelegramChannel)` | -| `TelegramGroup` | `.legacyGroup(TelegramGroup)` | -| `TelegramUser` | `.user(TelegramUser)` | - ---- - -## Task 1: Edit `SendAsPeers.swift` — struct definition + constructor wraps - -**Files:** -- Modify: `submodules/TelegramCore/Sources/TelegramEngine/Messages/SendAsPeers.swift` - -Foundational change. Without it, none of the consumer edits compile. - -- [ ] **Step 1.1: Update the SendAsPeer struct field, init parameter, and drop manual `==`** - -Edit: - -```swift -// OLD -public struct SendAsPeer: Equatable { - public let peer: Peer - public let subscribers: Int32? - public let isPremiumRequired: Bool - - public init(peer: Peer, subscribers: Int32?, isPremiumRequired: Bool) { - self.peer = peer - self.subscribers = subscribers - self.isPremiumRequired = isPremiumRequired - } - - public static func ==(lhs: SendAsPeer, rhs: SendAsPeer) -> Bool { - return lhs.peer.isEqual(rhs.peer) && lhs.subscribers == rhs.subscribers && lhs.isPremiumRequired == rhs.isPremiumRequired - } -} -``` - -```swift -// NEW -public struct SendAsPeer: Equatable { - public let peer: EnginePeer - public let subscribers: Int32? - public let isPremiumRequired: Bool - - public init(peer: EnginePeer, subscribers: Int32?, isPremiumRequired: Bool) { - self.peer = peer - self.subscribers = subscribers - self.isPremiumRequired = isPremiumRequired - } -} -``` - -Use the Edit tool with the OLD block as `old_string` and the NEW block as `new_string`. Swift synthesizes Equatable for structs where every stored property is Equatable: `EnginePeer` is Equatable, `Int32?` is Equatable, `Bool` is Equatable — so the manual `==` is no longer needed. - -- [ ] **Step 1.2: Wrap raw Postbox `Peer` values at the four constructor sites** - -Sites at lines 64, 170, 236, 330. Each binds a raw Postbox `Peer` (from `transaction.getPeer(peerId)` or `peers.map { ... }`) and passes it to the `SendAsPeer(peer: ...)` init. Wrap each with `EnginePeer(...)`. - -Edit (line 64, inside `_internal_cachedPeerSendAsAvailablePeers`, cache-hit branch): - -```swift -// OLD - peers.append(SendAsPeer(peer: peer, subscribers: subscribers, isPremiumRequired: cached.premiumRequiredPeerIds.contains(peer.id))) -``` - -```swift -// NEW - peers.append(SendAsPeer(peer: EnginePeer(peer), subscribers: subscribers, isPremiumRequired: cached.premiumRequiredPeerIds.contains(peer.id))) -``` - -Edit (line 170, inside `_internal_peerSendAsAvailablePeers`, network-response map): - -```swift -// OLD - return peers.map { SendAsPeer(peer: $0, subscribers: subscribers[$0.id], isPremiumRequired: premiumRequiredPeerIds.contains($0.id)) } -``` - -```swift -// NEW - return peers.map { SendAsPeer(peer: EnginePeer($0), subscribers: subscribers[$0.id], isPremiumRequired: premiumRequiredPeerIds.contains($0.id)) } -``` - -Edit (line 236, inside `_internal_cachedLiveStorySendAsAvailablePeers`, cache-hit branch): - -```swift -// OLD - peers.append(SendAsPeer(peer: peer, subscribers: subscribers, isPremiumRequired: cached.premiumRequiredPeerIds.contains(peer.id))) -``` - -```swift -// NEW - peers.append(SendAsPeer(peer: EnginePeer(peer), subscribers: subscribers, isPremiumRequired: cached.premiumRequiredPeerIds.contains(peer.id))) -``` - -Note: lines 64 and 236 have identical text. If you prefer `replace_all=true`, do a grep first to confirm the count is exactly 2, then apply once. - -Edit (line 330, inside `_internal_liveStorySendAsAvailablePeers`, network-response map): - -```swift -// OLD - return peers.map { SendAsPeer(peer: $0, subscribers: subscribers[$0.id], isPremiumRequired: premiumRequiredPeerIds.contains($0.id)) } -``` - -```swift -// NEW - return peers.map { SendAsPeer(peer: EnginePeer($0), subscribers: subscribers[$0.id], isPremiumRequired: premiumRequiredPeerIds.contains($0.id)) } -``` - -Same remark as above: lines 170 and 330 are identical — one `replace_all=true` covers both if the count is exactly 2. - -- [ ] **Step 1.3: Verify** — read the updated file and confirm: - - The struct's `peer` field is now `EnginePeer` - - The init parameter is `peer: EnginePeer` - - Manual `==` has been removed - - All 4 constructor sites wrap with `EnginePeer(...)` - - `peer.peer.id` accesses inside the caching loops (lines 87, 90, 259, 262) remain unchanged (`EnginePeer.id` typealias to `PeerId` keeps them valid) - -Do not commit yet. - ---- - -## Task 2: Edit `ChatSendAsPeerListContextItem.swift` — cast rewrite + wrap collapse - -**Files:** -- Modify: `submodules/TelegramUI/Components/Chat/ChatSendAsContextMenu/Sources/ChatSendAsPeerListContextItem.swift` - -1 Postbox-concrete downcast rewrite + 4 `EnginePeer(peer.peer)` wrap drops. - -- [ ] **Step 2.1: Rewrite the `peer.peer as? TelegramChannel` downcast at line 73** - -Edit: - -```swift -// OLD - } else if let subscribers = peer.subscribers { - if let peer = peer.peer as? TelegramChannel { - if case .broadcast = peer.info { -``` - -```swift -// NEW - } else if let subscribers = peer.subscribers { - if case let .channel(channel) = peer.peer { - if case .broadcast = channel.info { -``` - -Note: the original `if let peer = peer.peer as? TelegramChannel` shadows the outer `peer: SendAsPeer` loop variable. The rewrite uses `channel` to avoid shadowing. Any subsequent uses of `peer.info`, `peer.flags`, etc. inside the inner `if let peer = ...` block must be renamed to `channel.*`. - -Read lines 70–90 before editing to see the full extent of the shadowed-`peer` scope, and ensure every reference to `peer.info` (and any sibling field access like `peer.flags`, `peer.username`, etc.) within the inner block is rewritten to `channel.*`. The snippet above captures the only `peer.info` site from the inventory. - -- [ ] **Step 2.2: Drop `EnginePeer(peer.peer)` wraps at lines 89, 110, 116, 121** - -The field `peer.peer` is now `EnginePeer`, so `EnginePeer(peer.peer)` becomes a type error. Drop the wrap. - -Read the full lines first to confirm each site's shape. Expected patterns (edit one at a time with enough surrounding context to make each unique — the four sites likely differ in surrounding tokens): - -For each of the four sites, the pattern to eliminate is `EnginePeer(peer.peer)` → `peer.peer`. Example: - -```swift -// OLD - let title = EnginePeer(peer.peer).displayTitle(strings: strings, displayOrder: nameDisplayOrder) -``` - -```swift -// NEW - let title = peer.peer.displayTitle(strings: strings, displayOrder: nameDisplayOrder) -``` - -Identify each of the four sites (lines 89, 110, 116, 121) by reading the file, then apply one Edit per site using enough surrounding context (usually 1–2 tokens before/after the `EnginePeer(peer.peer)` subexpression) to make the `old_string` unique. - -If all four lines reduce to the same substring pattern (e.g., `EnginePeer(peer.peer)` as a standalone subexpression), `replace_all=true` on the substring `EnginePeer(peer.peer)` → `peer.peer` is safe — but **first** grep to confirm the count is exactly 4 and no other meaning is captured. - -Run before: `grep -cE "EnginePeer\(peer\.peer\)" submodules/TelegramUI/Components/Chat/ChatSendAsContextMenu/Sources/ChatSendAsPeerListContextItem.swift` - -Expected: 4. - -- [ ] **Step 2.3: Verify** — grep: - -Run: `grep -nE "peer\.peer\s+(as\?|is)\s+Telegram|EnginePeer\(peer\.peer\)" submodules/TelegramUI/Components/Chat/ChatSendAsContextMenu/Sources/ChatSendAsPeerListContextItem.swift` - -Expected: zero matches. - ---- - -## Task 3: Edit `ChatControllerLoadDisplayNode.swift` — bridge-drop + raw-channel wraps - -**Files:** -- Modify: `submodules/TelegramUI/Sources/Chat/ChatControllerLoadDisplayNode.swift` - -1 `._asPeer()` bridge-drop at line 772 + 2 `EnginePeer(channel)` wraps for raw `TelegramChannel` at lines 805 and 823. - -- [ ] **Step 3.1: Bridge-drop at line 772** - -Edit: - -```swift -// OLD - return SendAsPeer(peer: peer._asPeer(), subscribers: nil, isPremiumRequired: false) -``` - -```swift -// NEW - return SendAsPeer(peer: peer, subscribers: nil, isPremiumRequired: false) -``` - -Verification: the surrounding signal chain binds `peer` as `EnginePeer` (from `context.engine.data.get(TelegramEngine.EngineData.Item.Peer.Peer(id: ...))`). The `._asPeer()` bridge is no longer needed. - -If the line text differs from the OLD block above (e.g., different field order or trailing arguments), read the file around line 772 and adjust the `old_string` to match byte-for-byte before editing. - -- [ ] **Step 3.2: Wrap raw `TelegramChannel` at line 805** - -Read lines 800–812 to see the bound `channel` variable. The construction site should be `SendAsPeer(peer: channel, ...)` where `channel: TelegramChannel` is raw Postbox. - -Edit: - -```swift -// OLD - SendAsPeer(peer: channel, subscribers: subscribers, isPremiumRequired: isPremiumRequired) -``` - -```swift -// NEW - SendAsPeer(peer: EnginePeer(channel), subscribers: subscribers, isPremiumRequired: isPremiumRequired) -``` - -If the surrounding context differs (different field values), match the actual line text when writing `old_string`. - -- [ ] **Step 3.3: Wrap raw `TelegramChannel` at line 823** - -Same pattern as Step 3.2. Read lines 818–830 first, identify the `SendAsPeer(peer: channel, ...)` construction site, and wrap `channel` with `EnginePeer(...)`. - -If the line text at 805 and 823 is identical, `replace_all=true` on the substring `SendAsPeer(peer: channel,` → `SendAsPeer(peer: EnginePeer(channel),` covers both. **First** grep to confirm the count: - -Run before: `grep -cE "SendAsPeer\(peer: channel," submodules/TelegramUI/Sources/Chat/ChatControllerLoadDisplayNode.swift` - -Expected: 2. - -- [ ] **Step 3.4: Verify** — grep: - -Run: `grep -nE "SendAsPeer\(peer:\s+\w+\._asPeer\(\)|SendAsPeer\(peer:\s+channel," submodules/TelegramUI/Sources/Chat/ChatControllerLoadDisplayNode.swift` - -Expected: zero matches. Lines 792, 826, 835, 844 retaining `.peer.id` accesses are expected and correct. - ---- - -## Task 4: Edit `ChatTextInputPanelComponent.swift` — bridge-drop - -**Files:** -- Modify: `submodules/TelegramUI/Components/Chat/ChatTextInputPanelNode/Sources/ChatTextInputPanelComponent.swift` - -1 `._asPeer()` bridge-drop. - -- [ ] **Step 4.1: Bridge-drop at line 847** - -Read lines 843–853 to confirm the surrounding signal chain and the type of `sendAsConfiguration.currentPeer` (expected: `EnginePeer`). - -Edit: - -```swift -// OLD - let sendAsPeers = [SendAsPeer(peer: sendAsConfiguration.currentPeer._asPeer(), subscribers: nil, isPremiumRequired: false)] -``` - -```swift -// NEW - let sendAsPeers = [SendAsPeer(peer: sendAsConfiguration.currentPeer, subscribers: nil, isPremiumRequired: false)] -``` - -If the actual line text wraps across multiple lines or uses different field values, match the real text byte-for-byte when writing `old_string`. - -- [ ] **Step 4.2: Verify** — grep: - -Run: `grep -nE "SendAsPeer\(peer:.*\._asPeer\(\)" submodules/TelegramUI/Components/Chat/ChatTextInputPanelNode/Sources/ChatTextInputPanelComponent.swift` - -Expected: zero matches. - ---- - -## Task 5: Edit `ChatTextInputPanelNode.swift` — wrap collapse - -**Files:** -- Modify: `submodules/TelegramUI/Components/Chat/ChatTextInputPanelNode/Sources/ChatTextInputPanelNode.swift` - -1 `EnginePeer(peer)` wrap collapse at line 1625. - -- [ ] **Step 5.1: Collapse `EnginePeer(peer)` wrap** - -Read lines 1615–1630 to see the full context. `peer` is bound from a preceding `var currentPeer = sendAsPeers.first(where: { $0.peer.id == ... })?.peer` (lines 1620–1622). After migration, `.peer` returns `EnginePeer`, so `EnginePeer(peer)` on an `EnginePeer` is a type error. - -Exact edit depends on the actual line text. Example shape: - -```swift -// OLD (at or near line 1625) - let enginePeer = EnginePeer(peer) -``` - -```swift -// NEW - let enginePeer = peer -``` - -Read lines 1623–1628 first and write the Edit with byte-accurate `old_string`. If the bound variable is then used as `enginePeer.displayTitle(...)`, consider whether the rename can be eliminated entirely (e.g., rename `peer` uses downstream), but prefer the minimal edit for commit clarity. - -Lines 1616, 1620, 1622, 2948, 5370 should remain unchanged — they perform `.peer.id` comparisons or `.first(where:)` lookups that work identically on `[SendAsPeer]` with `EnginePeer`-typed `.peer`. - -- [ ] **Step 5.2: Verify** — grep: - -Run: `grep -nE "EnginePeer\(peer\)" submodules/TelegramUI/Components/Chat/ChatTextInputPanelNode/Sources/ChatTextInputPanelNode.swift` - -Expected: zero matches. If any remain, inspect each — they may be unrelated wraps on non-SendAsPeer-sourced `peer` variables (in which case they must stay). - ---- - -## Task 6: Edit `StoryItemSetContainerViewSendMessage.swift` — multi-site cleanup - -**Files:** -- Modify: `submodules/TelegramUI/Components/Stories/StoryContainerScreen/Sources/StoryItemSetContainerViewSendMessage.swift` - -1 bridge-drop + 1 flatMap simplify + 1 map simplify. Many other `.peer.id` / `.peer` accesses remain unchanged. - -- [ ] **Step 6.1: Bridge-drop at line 249** - -Read lines 244–254 to confirm `accountPeer` is typed as `EnginePeer` upstream. - -Edit: - -```swift -// OLD - availablePeers.append(SendAsPeer( - peer: accountPeer._asPeer(), - subscribers: nil, - isPremiumRequired: false - )) -``` - -```swift -// NEW - availablePeers.append(SendAsPeer( - peer: accountPeer, - subscribers: nil, - isPremiumRequired: false - )) -``` - -If the actual layout (whitespace, line breaks) differs from the OLD block, match the real text byte-for-byte when writing `old_string`. - -- [ ] **Step 6.2: Simplify flatMap at line 4080** - -`EnginePeer.init` as a function reference expects a raw `Peer` and returns `EnginePeer`. After migration, `sendAsPeer?.peer` is already `EnginePeer?`, so `.flatMap(EnginePeer.init)` is both unnecessary and a type error. - -Edit: - -```swift -// OLD - myPeer: (sendAsPeer?.peer).flatMap(EnginePeer.init), -``` - -```swift -// NEW - myPeer: sendAsPeer?.peer, -``` - -Read lines 4078–4082 first to confirm the surrounding labeled-argument layout and match byte-for-byte. - -- [ ] **Step 6.3: Simplify map at line 4081** - -`.map({ EnginePeer($0.peer) })` wraps each already-`EnginePeer` value in `EnginePeer(...)` — a type error. Drop the wrap. - -Edit: - -```swift -// OLD - availableSendAsPeers: component.isEmbeddedInCamera ? [] : (self.sendAsData?.availablePeers.map({ EnginePeer($0.peer) }) ?? []), -``` - -```swift -// NEW - availableSendAsPeers: component.isEmbeddedInCamera ? [] : (self.sendAsData?.availablePeers.map({ $0.peer }) ?? []), -``` - -Read lines 4079–4083 first to confirm the exact line text. - -- [ ] **Step 6.4: Verify** — grep: - -Run: `grep -nE "SendAsPeer\(peer:.*\._asPeer\(\)|EnginePeer\(\$0\.peer\)|\(sendAsPeer\?\.peer\)\.flatMap\(EnginePeer\.init\)" submodules/TelegramUI/Components/Stories/StoryContainerScreen/Sources/StoryItemSetContainerViewSendMessage.swift` - -Expected: zero matches. - -Retained-as-is accesses (inventory-verified correct after migration): `.peer.id` at lines 254, 688, 4088, 4089, 4327, 4333, 4340, 4356, 4372; optional chaining at 4050, 4068, 4069. These should NOT be edited. - ---- - -## Task 7: Verify "no-edit" consumer files - -**Files:** -- Read: `submodules/ChatPresentationInterfaceState/Sources/ChatPresentationInterfaceState.swift` -- Read: `submodules/TelegramUI/Components/Stories/StoryContainerScreen/Sources/StoryItemSetContainerComponent.swift` - -Sanity-check: confirm neither file contains `.peer as?`/`is`, `EnginePeer(.peer)`, or `._asPeer()` patterns tied to SendAsPeer. If any such pattern is found, fold the fix into the relevant task above before the build pass. - -- [ ] **Step 7.1: Grep ChatPresentationInterfaceState.swift** - -Run: `grep -nE "SendAsPeer|sendAsPeers" submodules/ChatPresentationInterfaceState/Sources/ChatPresentationInterfaceState.swift` - -Expected shape: field declaration, init param, assignment, equality comparison, `updatedSendAsPeers(_:)` method — all at the `[SendAsPeer]?` collection level. No `.peer` field access. - -- [ ] **Step 7.2: Grep StoryItemSetContainerComponent.swift** - -Run: `grep -nE "SendAsPeer|currentSendAsPeer|\.peer\b" submodules/TelegramUI/Components/Stories/StoryContainerScreen/Sources/StoryItemSetContainerComponent.swift | grep -iE "sendAsPeer|\.peer"` - -Read lines 3056–3072 to confirm `sendMessageContext.currentSendAsPeer` is only passed through to `ChatSendAsPeerListContextItem` (which keeps `[SendAsPeer]`) or accessed for `.peer.id` comparisons — neither requires an edit. - -If the verification shows an edit is needed, add the edit as an additional step under the relevant Task 2–6. Do not edit here silently. - ---- - -## Task 8: Build verification (first pass) - -- [ ] **Step 8.1: Run the full build with `--continueOnError`** - -Run: - -```bash -source ~/.zshrc 2>/dev/null && python3 build-system/Make/Make.py --overrideXcodeVersion --cacheDir ~/telegram-bazel-cache build --configurationPath build-system/appstore-configuration.json --gitCodesigningRepository git@gitlab.com:peter-iakovlev/fastlanematch.git --gitCodesigningType development --gitCodesigningUseCurrent --buildNumber=1 --configuration=debug_sim_arm64 --continueOnError 2>&1 | tee /tmp/wave35-build.log -``` - -Expected outcome: ideally clean. Realistic outcome: 0–5 errors at sites the inventory missed. - -- [ ] **Step 8.2: Triage build errors** - -Likely error patterns and their fixes: - -| Error | Fix | -|---|---| -| `cannot convert value of type 'EnginePeer' to expected argument type 'Peer'` at site passing `peer.peer` | Add `._asPeer()` bridge: `peer.peer._asPeer()` | -| `cannot convert value of type 'Peer' to expected argument type 'EnginePeer'` at `SendAsPeer(peer: ...)` | Add wrap: `SendAsPeer(peer: EnginePeer(), ...)` | -| `value of type 'EnginePeer' has no member 'isEqual'` | Replace with `==` | -| `pattern of type 'TelegramChannel' cannot match values of type 'EnginePeer'` | Missed C2 — rewrite to `if case .channel(let channel) = peer.peer` form | -| `cannot invoke initializer for type 'EnginePeer' with an argument list of type '(EnginePeer)'` | Missed wrap collapse — drop `EnginePeer(...)` | -| `extraneous argument label 'peer:' in call` or similar on `SendAsPeer(...)` | Check that the construction arg is `EnginePeer`, not raw — add `EnginePeer(...)` wrap | - -For each error, identify the file:line, apply the appropriate fix, and re-run the build until clean. - -- [ ] **Step 8.3: Iterate to clean build** - -Re-run the build after each batch of fixes. The wave is complete when the build returns 0 errors for the targeted configuration. - -If 10+ unexpected errors surface, halt and reassess: the inventory was significantly incomplete and the wave may need to be split into pre-cleanup commits. Discuss with user before continuing. - ---- - -## Task 9: Post-build grep validations - -- [ ] **Step 9.1: Bridge-drop validation** - -Run: - -```bash -grep -rn "SendAsPeer(peer:.*\._asPeer()" submodules/ --include="*.swift" | grep -v "^submodules/TelegramCore/" | grep -v "^submodules/Postbox/" -``` - -Expected: zero hits. If any remain, those are missed bridge-drops — fix and re-run Task 8. - -- [ ] **Step 9.2: Wrap-collapse validation** - -Run: - -```bash -for f in submodules/TelegramUI/Components/Chat/ChatSendAsContextMenu/Sources/ChatSendAsPeerListContextItem.swift \ - submodules/TelegramUI/Sources/Chat/ChatControllerLoadDisplayNode.swift \ - submodules/TelegramUI/Components/Chat/ChatTextInputPanelNode/Sources/ChatTextInputPanelComponent.swift \ - submodules/TelegramUI/Components/Chat/ChatTextInputPanelNode/Sources/ChatTextInputPanelNode.swift \ - submodules/TelegramUI/Components/Stories/StoryContainerScreen/Sources/StoryItemSetContainerViewSendMessage.swift; do - echo "=== $f ===" - grep -nE "EnginePeer\(peer\.peer\)|EnginePeer\(\$0\.peer\)|\(sendAsPeer\?\.peer\)\.flatMap\(EnginePeer\.init\)" "$f" -done -``` - -Expected: zero hits across all 5 files. - -- [ ] **Step 9.3: C2 cast validation** - -Run: - -```bash -grep -nE "peer\.peer\s+(as\?|is)\s+Telegram" submodules/TelegramUI/Components/Chat/ChatSendAsContextMenu/Sources/ChatSendAsPeerListContextItem.swift -``` - -Expected: zero hits. - -- [ ] **Step 9.4: Construction-site validation** - -Ensure all `SendAsPeer(peer: ...)` construction sites outside TelegramCore provide `EnginePeer`: - -```bash -grep -rnE "SendAsPeer\(peer:" submodules/ --include="*.swift" | grep -v "^submodules/TelegramCore/" -``` - -Inspect each hit. Expected forms: `SendAsPeer(peer: , ...)` or `SendAsPeer(peer: EnginePeer(), ...)`. Anything of the form `SendAsPeer(peer: , ...)` is a miss — fix. - -If any of the validations fail, return to Task 8 to fix. - ---- - -## Task 10: Atomic commit + memory + log update - -- [ ] **Step 10.1: Stage and review** - -Run: - -```bash -git status --short -git diff --stat -``` - -Confirm exactly 6 modified Swift files (1 TelegramCore + 5 consumer — or 7 if Task 7 surfaced a needed edit). Files expected: -- `submodules/TelegramCore/Sources/TelegramEngine/Messages/SendAsPeers.swift` -- `submodules/TelegramUI/Components/Chat/ChatSendAsContextMenu/Sources/ChatSendAsPeerListContextItem.swift` -- `submodules/TelegramUI/Sources/Chat/ChatControllerLoadDisplayNode.swift` -- `submodules/TelegramUI/Components/Chat/ChatTextInputPanelNode/Sources/ChatTextInputPanelComponent.swift` -- `submodules/TelegramUI/Components/Chat/ChatTextInputPanelNode/Sources/ChatTextInputPanelNode.swift` -- `submodules/TelegramUI/Components/Stories/StoryContainerScreen/Sources/StoryItemSetContainerViewSendMessage.swift` - -WIP from earlier (`build-system/bazel-rules/sourcekit-bazel-bsp`, `ChatListFilterPresetController.swift`, `ChatListFilterPresetListController.swift`, untracked `build-system/tulsi/` / `submodules/TgVoip/` / `third-party/libx264/`) should NOT be staged. - -The `docs/superpowers/plans/2026-04-22-claude-md-reorganization.md` untracked file should ALSO remain unstaged. - -- [ ] **Step 10.2: Stage only the wave-35 files** - -Run: - -```bash -git add submodules/TelegramCore/Sources/TelegramEngine/Messages/SendAsPeers.swift \ - submodules/TelegramUI/Components/Chat/ChatSendAsContextMenu/Sources/ChatSendAsPeerListContextItem.swift \ - submodules/TelegramUI/Sources/Chat/ChatControllerLoadDisplayNode.swift \ - submodules/TelegramUI/Components/Chat/ChatTextInputPanelNode/Sources/ChatTextInputPanelComponent.swift \ - submodules/TelegramUI/Components/Chat/ChatTextInputPanelNode/Sources/ChatTextInputPanelNode.swift \ - submodules/TelegramUI/Components/Stories/StoryContainerScreen/Sources/StoryItemSetContainerViewSendMessage.swift -``` - -If Task 7 surfaced an additional file, append it here. - -- [ ] **Step 10.3: Commit** - -Run: - -```bash -git commit -m "$(cat <<'EOF' -Postbox -> TelegramEngine wave 35: SendAsPeer.peer Peer -> EnginePeer - -Migrates the public field `SendAsPeer.peer` from the Postbox `Peer` -protocol to the TelegramCore `EnginePeer` enum. Internal -`_internal_*SendAsAvailablePeers` bodies keep `import Postbox` (they still -call `postbox.transaction`) and wrap raw peer values with `EnginePeer(peer)` -at the SendAsPeer constructor sites. Manual `==` body dropped in favor of -synthesized Equatable. - -Consumer-side cascade in 5 files: - - 3 `._asPeer()` bridge-drops at SendAsPeer constructor sites - - 6 redundant `EnginePeer(peer.peer)` / `EnginePeer($0.peer)` wrap - drops (the field is now EnginePeer, so the wrap fails to compile) - - 1 `peer.peer as? TelegramChannel` downcast rewritten to - `if case let .channel(channel) = peer.peer` enum-pattern form - - 2 `EnginePeer(channel)` wraps added where raw `TelegramChannel` is - passed into `SendAsPeer(peer: ...)` - - 1 `(sendAsPeer?.peer).flatMap(EnginePeer.init)` simplified to - `sendAsPeer?.peer` (already `EnginePeer?`) - -Files modified: - submodules/TelegramCore/Sources/TelegramEngine/Messages/SendAsPeers.swift - submodules/TelegramUI/Components/Chat/ChatSendAsContextMenu/Sources/ChatSendAsPeerListContextItem.swift - submodules/TelegramUI/Sources/Chat/ChatControllerLoadDisplayNode.swift - submodules/TelegramUI/Components/Chat/ChatTextInputPanelNode/Sources/ChatTextInputPanelComponent.swift - submodules/TelegramUI/Components/Chat/ChatTextInputPanelNode/Sources/ChatTextInputPanelNode.swift - submodules/TelegramUI/Components/Stories/StoryContainerScreen/Sources/StoryItemSetContainerViewSendMessage.swift - -Plan: docs/superpowers/plans/2026-04-24-sendaspeer-engine-peer-migration.md -Spec: docs/superpowers/specs/2026-04-24-sendaspeer-engine-peer-migration-design.md - -Co-Authored-By: Claude Opus 4.7 (1M context) -EOF -)" -``` - -- [ ] **Step 10.4: Update CLAUDE.md wave counter** - -Edit `CLAUDE.md` to bump the "Waves landed so far" line from "34 waves" to "35 waves" and update the "as of" date if the commit lands after 2026-04-24. - -- [ ] **Step 10.5: Append wave outcome to the postbox-refactor-log** - -Append a "Wave 35 outcome" section to `docs/superpowers/postbox-refactor-log.md` documenting: -- Actual files touched and edit counts vs. plan -- Any inventory undercounts surfaced by Task 8 -- Any lessons learned (e.g., whether the flatMap/map simplifications were actually type-required or whether they could have been left as redundant-but-compiling wraps) - -Keep concise. - -- [ ] **Step 10.6: Commit the docs update** - -Run: - -```bash -git add CLAUDE.md docs/superpowers/postbox-refactor-log.md -git commit -m "$(cat <<'EOF' -docs: add wave 35 outcome (SendAsPeer.peer Peer→EnginePeer) - -Co-Authored-By: Claude Opus 4.7 (1M context) -EOF -)" -``` - -- [ ] **Step 10.7: Update the next-wave memory** - -Update `/Users/isaac/.claude/projects/-Users-isaac-build-telegram-telegram-ios/memory/project_postbox_refactor_next_wave.md`: -- Add wave 35 to the "Latest commits" section -- Move SendAsPeer migration from "Wave 34+ candidates → Downstream Peer-typed APIs" to landed -- Record the inventory undercount ratio (actual-files-touched ÷ pre-flight-file-count) for calibration of future Peer-typed-API waves -- Update the "Recommended wave 35" section to reflect the new wave 36 recommendation. Candidates to promote: `makePeerInfoController` (largest Peer-typed-API remaining), `ContactListPeer.peer(peer:)` case payload, `canSendMessagesToPeer(_:)` parameter, accountManager-side engine path, Shape-C resourceData module pick - -Use the Edit tool on the memory file. No git commit needed (memory lives outside the repo). - ---- - -## Risks and notes - -- **Inner `peer` shadowing in ChatSendAsPeerListContextItem:73.** The original `if let peer = peer.peer as? TelegramChannel` shadows the outer `peer: SendAsPeer` loop variable. The rewrite uses `channel` to avoid shadowing. Verify every reference to `peer.info` (and any sibling field access) within the old inner-if scope is updated to `channel.*` — Step 2.1's instructions cover this, but it's easy to miss a field reference. -- **`replace_all` correctness.** Whenever the plan suggests `replace_all=true`, verify the count first via grep. If the count is unexpected, revert to per-site Edits with surrounding context. -- **Inventory undercount.** Wave 34 undercounted by ~30%. The Explore agent for wave 35 explicitly included `.peer as?`/`is`/outflow-helper patterns, so the expected ratio is lower, but budget for 1–3 inventory-missed sites surfacing in Task 8. -- **Name collisions (do NOT touch).** `[EnginePeer]` arrays in `LiveStreamSettingsScreen.swift`, `ShareWithPeersScreen.swift`, and `ChatSendStarsScreen.swift` named `sendAsPeers` / `availableSendAsPeers` are unrelated. `ChatPanelInterfaceInteraction` callbacks named `openSendAsPeer` take `(ASDisplayNode, ContextGesture?)`, not `SendAsPeer`. `initialSendAsPeerId` parameters are `PeerId`-typed. If Task 8 surfaces errors in any of these files, the fix likely indicates a wrong cascade from a real SendAsPeer site — do NOT migrate those files as part of this wave. -- **WIP isolation.** Pre-existing modifications to `ChatListFilterPresetController.swift`, `ChatListFilterPresetListController.swift`, the `sourcekit-bazel-bsp` submodule marker, and untracked `build-system/tulsi/` / `submodules/TgVoip/` / `third-party/libx264/` / `docs/superpowers/plans/2026-04-22-claude-md-reorganization.md` are user WIP — do NOT stage them. Use the explicit `git add ` form in Step 10.2. diff --git a/docs/superpowers/plans/2026-04-25-clearpeerhistory-openclearhistory-engine-peer.md b/docs/superpowers/plans/2026-04-25-clearpeerhistory-openclearhistory-engine-peer.md deleted file mode 100644 index 1b847bd2d5..0000000000 --- a/docs/superpowers/plans/2026-04-25-clearpeerhistory-openclearhistory-engine-peer.md +++ /dev/null @@ -1,116 +0,0 @@ -# Wave 54: ClearPeerHistory.init + openClearHistory `chatPeer: Peer → EnginePeer` - -> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. - -**Goal:** Migrate the `chatPeer:` parameter type on both `ClearPeerHistory.init` and `openClearHistory` from `Peer` to `EnginePeer`. Closes wave-53's deferred sibling. - -**Wave shape:** Bundled method-signature migration (familiar from waves 41/44/47/50/53). Mechanical `as?`/`is` cluster on a single field, with EnginePeer.init boundary lifts at each call site. - -**Tech Stack:** Swift, Bazel, Make.py. - ---- - -## Pre-Flight Inventory (validated 2026-04-25) - -**2 files modified, 16 edits.** - -### File 1: `submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoScreen.swift` (PIS) - -| Line | Current | After | Note | -|---|---|---|---| -| 3213 | `func openClearHistory(... peer: Peer, chatPeer: Peer) {` | `... chatPeer: EnginePeer)` | type-site | -| 3230 | `EnginePeer(chatPeer).compactDisplayTitle` | `chatPeer.compactDisplayTitle` | drop wrap | -| 3232 | `EnginePeer(chatPeer).compactDisplayTitle` | `chatPeer.compactDisplayTitle` | drop wrap | -| 3251 | `EnginePeer(chatPeer).compactDisplayTitle` | `chatPeer.compactDisplayTitle` | drop wrap | -| 3269 | `EnginePeer(chatPeer).compactDisplayTitle` | `chatPeer.compactDisplayTitle` | drop wrap | -| 7416 | `init(... peer: Peer, chatPeer: Peer, cachedData: ...)` | `... chatPeer: EnginePeer, cachedData: ...` | type-site | -| 7421 | `} else if chatPeer is TelegramSecretChat {` | `} else if case .secretChat = chatPeer {` | conversion | -| 7425 | `} else if let group = chatPeer as? TelegramGroup {` | `} else if case let .legacyGroup(group) = chatPeer {` | conversion | -| 7436 | `} else if let channel = chatPeer as? TelegramChannel {` | `} else if case let .channel(channel) = chatPeer {` | conversion | -| 7464 | `if let user = chatPeer as? TelegramUser, user.botInfo != nil {` | `if case let .user(user) = chatPeer, user.botInfo != nil {` | conversion | - -`peer:` parameter stays Peer-typed in both functions: `openClearHistory` doesn't reference `peer` in its body; `ClearPeerHistory.init` uses only `peer.id == context.account.peerId` (line 7417), which works on Peer (and would also work on EnginePeer, but migrating it would require 6 boundary lifts at PISPBA call sites for no internal benefit). - -### File 2: `submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoScreenPerformButtonAction.swift` (PISPBA) - -| Line | Current | After | Note | -|---|---|---|---| -| 851 | `chatPeer: chatPeer._asPeer()` | `chatPeer: chatPeer` | drop wave-53 ADD | -| 857 | `chatPeer: user` | `chatPeer: EnginePeer(user)` | boundary lift (TelegramUser) | -| 1067 | `chatPeer: channel` | `chatPeer: EnginePeer(channel)` | boundary lift (TelegramChannel) | -| 1073 | `chatPeer: channel` | `chatPeer: EnginePeer(channel)` | boundary lift (TelegramChannel) | -| 1234 | `chatPeer: group` | `chatPeer: EnginePeer(group)` | boundary lift (TelegramGroup) | -| 1240 | `chatPeer: group` | `chatPeer: EnginePeer(group)` | boundary lift (TelegramGroup) | - -### Net accounting - -- **Drops:** 5 (4 `EnginePeer(chatPeer).compactDisplayTitle` + 1 `_asPeer()` bridge from wave 53). -- **Adds:** 5 boundary lifts (5 `EnginePeer(...)` wraps at PISPBA call sites). -- **Conversions:** 4 (`is`/`as?` → `case let`). -- **Type-site:** 2 (signature changes on PIS:3213 and PIS:7416). - -Net internal-bridge progress: `5 drops − 5 adds = 0 raw count`. But ratchet kills 4 internal display-call wraps (`EnginePeer(chatPeer).compactDisplayTitle` patterns) which is the hot path; only call-site boundary lifts remain. Closes wave-53's deferred ADD at PISPBA:851. - ---- - -## Tasks - -### Task 1: PIS signature edits + body wrap drops - -- [ ] **Step 1: Edit `openClearHistory` signature at PIS:3213** - -Replace `peer: Peer, chatPeer: Peer)` with `peer: Peer, chatPeer: EnginePeer)`. - -- [ ] **Step 2: Drop 4 `EnginePeer(chatPeer).compactDisplayTitle` wraps** - -`replace_all=true` of `EnginePeer(chatPeer).compactDisplayTitle` → `chatPeer.compactDisplayTitle`. (Only 4 occurrences in the file, all in `openClearHistory` body; verified by grep.) - -- [ ] **Step 3: Edit `ClearPeerHistory.init` signature at PIS:7416** - -Replace `peer: Peer, chatPeer: Peer, cachedData:` with `peer: Peer, chatPeer: EnginePeer, cachedData:`. - -- [ ] **Step 4: Convert PIS:7421 `is TelegramSecretChat`** - -Replace `} else if chatPeer is TelegramSecretChat {` with `} else if case .secretChat = chatPeer {`. - -- [ ] **Step 5: Convert PIS:7425 `as? TelegramGroup`** - -Replace `} else if let group = chatPeer as? TelegramGroup {` with `} else if case let .legacyGroup(group) = chatPeer {`. - -- [ ] **Step 6: Convert PIS:7436 `as? TelegramChannel`** - -Replace `} else if let channel = chatPeer as? TelegramChannel {` with `} else if case let .channel(channel) = chatPeer {`. - -- [ ] **Step 7: Convert PIS:7464 `as? TelegramUser`** - -Replace `if let user = chatPeer as? TelegramUser, user.botInfo != nil {` with `if case let .user(user) = chatPeer, user.botInfo != nil {`. - -### Task 2: PISPBA call-site lifts + bridge drop - -- [ ] **Step 1: Drop wave-53 `_asPeer()` bridge at PISPBA:851** - -Replace `chatPeer: chatPeer._asPeer()` with `chatPeer: chatPeer`. - -- [ ] **Step 2: Lift PISPBA:857 `chatPeer: user`** - -Replace `peer: user, chatPeer: user)` with `peer: user, chatPeer: EnginePeer(user))`. - -- [ ] **Step 3: Lift channel call sites (PISPBA:1067 + 1073)** - -`replace_all=true` of `chatPeer: channel` → `chatPeer: EnginePeer(channel)`. Verify exactly 2 hits flipped. - -- [ ] **Step 4: Lift group call sites (PISPBA:1234 + 1240)** - -`replace_all=true` of `chatPeer: group` → `chatPeer: EnginePeer(group)`. Verify exactly 2 hits flipped. - -### Task 3: Build verification - -- [ ] **Step 1: Run full build with `--continueOnError`.** - -Forecast 1 iteration. Risk: hidden `chatPeer` access on Peer-typed shape elsewhere (none expected — body audit complete). - -### Task 4: Commit + log - -- [ ] **Step 1: Commit wave with the two file paths explicitly.** -- [ ] **Step 2: Update `docs/superpowers/postbox-refactor-log.md` and the memory file.** -- [ ] **Step 3: Commit log.** diff --git a/docs/superpowers/plans/2026-04-25-peerinfo-enclosingpeer-engine-peer.md b/docs/superpowers/plans/2026-04-25-peerinfo-enclosingpeer-engine-peer.md deleted file mode 100644 index 4e3fdf4a09..0000000000 --- a/docs/superpowers/plans/2026-04-25-peerinfo-enclosingpeer-engine-peer.md +++ /dev/null @@ -1,516 +0,0 @@ -# Wave 50: enclosingPeer Peer? → EnginePeer? Implementation Plan - -> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. - -**Goal:** Migrate the PeerInfo members chain's `enclosingPeer` field from raw Postbox `Peer?` to `EnginePeer?` (wave 50 of the Postbox → TelegramEngine refactor). - -**Architecture:** Cross-file private struct-field migration with stored-form ratchet. Edits stay inside `submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/`. Replaces `as? TelegramChannel` / `as? TelegramGroup` casts with `case let .channel(...)` / `case let .legacyGroup(...)` (wave-41/45 idiom), drops `is TelegramChannel` checks for `case .channel = ...` (wave-41 always-false-warning fix), and removes 5 internal `_asPeer()` / `EnginePeer(...)` / `flatMap(EnginePeer.init)` bridges. The engine.data subscription at PIMP:354 already returns `EnginePeer?` — this wave closes the demote-then-promote ratchet. - -**Tech Stack:** Swift, Bazel via `Make.py`, no unit tests (per `CLAUDE.md`). Verification is the full-project debug-sim-arm64 build with `--continueOnError`. - -**Iteration budget:** 1–2 (target first-pass-clean; recent first-pass-clean streak: waves 42, 43*, 45, 46, 48, 49 — *wave 43 took 2 iterations). - -**Note on TDD:** This project has no unit tests (CLAUDE.md "No tests are used at the moment"). The standard TDD test-first cycle in the skill template does not apply. Each task instead writes the edits, then verifies via Bazel build + residue grep. - ---- - -## File Structure - -| File | Role | Changes | -|---|---|---| -| `submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/ListItems/PeerInfoScreenMemberItem.swift` (PSMI) | List-item view-model + node | Type-change stored field + init param; 4 cast/is-check rewrites; 1 `flatMap(EnginePeer.init)` simplification | -| `submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/Panes/PeerInfoMembersPane.swift` (PIMP) | Members-pane node + helpers | 3 func sigs + 1 stored field type-change; 4 cast/is-check rewrites; 1 `EnginePeer(...)` wrap drop; 2 `_asPeer()` drops | -| `submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoProfileItems.swift` (PSPB) | Profile-items builder (non-settings members section) | 1 boundary `_asPeer()` drop at the call site that constructs the migrated init | - -No public-API ripple — `PeerInfoScreenMemberItem` and `PeerInfoMembersPaneNode` are local to the PeerInfoScreen module. - ---- - -## Task 1: PSMI.swift — type changes + cast/is-check rewrites + flatMap simplification - -**Files:** -- Modify: `submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/ListItems/PeerInfoScreenMemberItem.swift` - -**Edits in this task:** 7 (1 stored-field type, 1 init-param type, 2 cast→case-let, 2 is→case, 1 flatMap simplification). - -- [ ] **Step 1: Change stored field type at line 23** - -Find: - -```swift - let enclosingPeer: Peer? -``` - -Replace with: - -```swift - let enclosingPeer: EnginePeer? -``` - -- [ ] **Step 2: Change init parameter type at line 34** - -Find: - -```swift - enclosingPeer: Peer?, -``` - -Replace with: - -```swift - enclosingPeer: EnginePeer?, -``` - -- [ ] **Step 3: Rewrite cast at line 152 (TelegramChannel)** - -Find: - -```swift - if let channel = item.enclosingPeer as? TelegramChannel, channel.hasPermission(.editRank) { -``` - -Replace with: - -```swift - if case let .channel(channel) = item.enclosingPeer, channel.hasPermission(.editRank) { -``` - -- [ ] **Step 4: Rewrite cast at line 154 (TelegramGroup)** - -Find: - -```swift - } else if let group = item.enclosingPeer as? TelegramGroup, !group.hasBannedPermission(.banEditRank) { -``` - -Replace with: - -```swift - } else if case let .legacyGroup(group) = item.enclosingPeer, !group.hasBannedPermission(.banEditRank) { -``` - -- [ ] **Step 5: Simplify flatMap at line 178** - -Find: - -```swift - let actions = availableActionsForMemberOfPeer(accountPeerId: item.context.accountPeerId, peer: item.enclosingPeer.flatMap(EnginePeer.init), member: item.member) -``` - -Replace with: - -```swift - let actions = availableActionsForMemberOfPeer(accountPeerId: item.context.accountPeerId, peer: item.enclosingPeer, member: item.member) -``` - -- [ ] **Step 6: Rewrite is-check at line 181** - -Find: - -```swift - if actions.contains(.promote) && item.enclosingPeer is TelegramChannel { -``` - -Replace with: - -```swift - if actions.contains(.promote), case .channel = item.enclosingPeer { -``` - -- [ ] **Step 7: Rewrite is-check at line 187** - -Find: - -```swift - if item.enclosingPeer is TelegramChannel { -``` - -Replace with: - -```swift - if case .channel = item.enclosingPeer { -``` - ---- - -## Task 2: PIMP.swift — signatures + stored field + body rewrites + demotion drops - -**Files:** -- Modify: `submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/Panes/PeerInfoMembersPane.swift` - -**Edits in this task:** 11 (3 func sigs + 1 stored-field type + 4 cast/is rewrites + 1 EnginePeer wrap drop + 2 `_asPeer()` drops). - -- [ ] **Step 1: Change `func item(...)` signature at line 92** - -Find: - -```swift - func item(context: AccountContext, presentationData: PresentationData, enclosingPeer: Peer, addMemberAction: @escaping () -> Void, action: @escaping (PeerInfoMember, PeerMembersListAction) -> Void, contextAction: ((PeerInfoMember, ASDisplayNode, ContextGesture?) -> Void)?) -> ListViewItem { -``` - -Replace with: - -```swift - func item(context: AccountContext, presentationData: PresentationData, enclosingPeer: EnginePeer, addMemberAction: @escaping () -> Void, action: @escaping (PeerInfoMember, PeerMembersListAction) -> Void, contextAction: ((PeerInfoMember, ASDisplayNode, ContextGesture?) -> Void)?) -> ListViewItem { -``` - -- [ ] **Step 2: Rewrite cast at line 113 (TelegramChannel, non-optional context)** - -Find: - -```swift - if let channel = enclosingPeer as? TelegramChannel, channel.hasPermission(.editRank) { -``` - -Replace with: - -```swift - if case let .channel(channel) = enclosingPeer, channel.hasPermission(.editRank) { -``` - -- [ ] **Step 3: Rewrite cast at line 115 (TelegramGroup, non-optional context)** - -Find: - -```swift - } else if let group = enclosingPeer as? TelegramGroup, !group.hasBannedPermission(.banEditRank) { -``` - -Replace with: - -```swift - } else if case let .legacyGroup(group) = enclosingPeer, !group.hasBannedPermission(.banEditRank) { -``` - -- [ ] **Step 4: Drop the `EnginePeer(...)` wrap at line 139** - -Find: - -```swift - let actions = availableActionsForMemberOfPeer(accountPeerId: context.account.peerId, peer: EnginePeer(enclosingPeer), member: member) -``` - -Replace with: - -```swift - let actions = availableActionsForMemberOfPeer(accountPeerId: context.account.peerId, peer: enclosingPeer, member: member) -``` - -`availableActionsForMemberOfPeer` takes `peer: EnginePeer?` (PeerInfoData.swift:2314); Swift auto-wraps the non-optional `enclosingPeer: EnginePeer` to optional. - -- [ ] **Step 5: Rewrite is-check at line 142 (non-optional context)** - -Find: - -```swift - if actions.contains(.promote) && enclosingPeer is TelegramChannel { -``` - -Replace with: - -```swift - if actions.contains(.promote), case .channel = enclosingPeer { -``` - -- [ ] **Step 6: Rewrite is-check at line 148 (non-optional context)** - -Find: - -```swift - if enclosingPeer is TelegramChannel { -``` - -Replace with: - -```swift - if case .channel = enclosingPeer { -``` - -- [ ] **Step 7: Change `preparedTransition` signature at line 271** - -Find: - -```swift -private func preparedTransition(from fromEntries: [PeerMembersListEntry], to toEntries: [PeerMembersListEntry], context: AccountContext, presentationData: PresentationData, enclosingPeer: Peer, addMemberAction: @escaping () -> Void, action: @escaping (PeerInfoMember, PeerMembersListAction) -> Void, contextAction: ((PeerInfoMember, ASDisplayNode, ContextGesture?) -> Void)?) -> PeerMembersListTransaction { -``` - -Replace with: - -```swift -private func preparedTransition(from fromEntries: [PeerMembersListEntry], to toEntries: [PeerMembersListEntry], context: AccountContext, presentationData: PresentationData, enclosingPeer: EnginePeer, addMemberAction: @escaping () -> Void, action: @escaping (PeerInfoMember, PeerMembersListAction) -> Void, contextAction: ((PeerInfoMember, ASDisplayNode, ContextGesture?) -> Void)?) -> PeerMembersListTransaction { -``` - -- [ ] **Step 8: Change stored field type at line 293** - -Find: - -```swift - private var enclosingPeer: Peer? -``` - -Replace with: - -```swift - private var enclosingPeer: EnginePeer? -``` - -- [ ] **Step 9: Drop `_asPeer()` at line 361** - -Find: - -```swift - strongSelf.enclosingPeer = enclosingPeer._asPeer() -``` - -Replace with: - -```swift - strongSelf.enclosingPeer = enclosingPeer -``` - -- [ ] **Step 10: Drop `_asPeer()` at line 363** - -Find: - -```swift - strongSelf.updateState(enclosingPeer: enclosingPeer._asPeer(), state: state, presentationData: presentationData) -``` - -Replace with: - -```swift - strongSelf.updateState(enclosingPeer: enclosingPeer, state: state, presentationData: presentationData) -``` - -- [ ] **Step 11: Change `updateState` signature at line 442** - -Find: - -```swift - private func updateState(enclosingPeer: Peer, state: PeerInfoMembersState, presentationData: PresentationData) { -``` - -Replace with: - -```swift - private func updateState(enclosingPeer: EnginePeer, state: PeerInfoMembersState, presentationData: PresentationData) { -``` - -The pass-through call sites at PIMP:275, :276, :437, :438, :451, :485 require no edit — types flow through transparently. - ---- - -## Task 3: PSPB.swift — boundary lift at members-section call site - -**Files:** -- Modify: `submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoProfileItems.swift` - -**Edits in this task:** 1. - -- [ ] **Step 1: Drop `_asPeer()` at line 852** - -Find: - -```swift - items[.peerMembers]!.append(PeerInfoScreenMemberItem(id: member.id, context: .account(context), enclosingPeer: peer._asPeer(), member: member, isAccount: false, action: isAccountPeer ? { _ in -``` - -Replace with: - -```swift - items[.peerMembers]!.append(PeerInfoScreenMemberItem(id: member.id, context: .account(context), enclosingPeer: peer, member: member, isAccount: false, action: isAccountPeer ? { _ in -``` - -`peer` here is the closure-bound `EnginePeer` from the `data.peer` source pipeline (`PeerInfoScreenData.peer: EnginePeer?` post-wave-42, unwrapped to non-optional `EnginePeer` and being passed to a now-`EnginePeer?` param — auto-promotes to optional). - -The other `PeerInfoScreenMemberItem(...)` construction at `PeerInfoSettingsItems.swift:132` passes `enclosingPeer: nil`, which is valid for either optional type — no edit. - ---- - -## Task 4: Full-project Bazel build - -**Files:** none (verification only). - -- [ ] **Step 1: Run the build with `--continueOnError`** - -Run: - -```sh -source ~/.zshrc 2>/dev/null; python3 build-system/Make/Make.py --overrideXcodeVersion \ - --cacheDir ~/telegram-bazel-cache \ - build \ - --configurationPath build-system/appstore-configuration.json \ - --gitCodesigningRepository git@gitlab.com:peter-iakovlev/fastlanematch.git \ - --gitCodesigningType development --gitCodesigningUseCurrent \ - --buildNumber=1 --configuration=debug_sim_arm64 --continueOnError -``` - -Expected: clean build (`bazel build complete` or equivalent green output). - -- [ ] **Step 2: If build fails, triage iteration** - -If errors land in `PeerInfoScreenMemberItem.swift` or `PeerInfoMembersPane.swift` or `PeerInfoProfileItems.swift`: -- Read the failing line. -- Common failure modes from prior waves: - - **Always-false `is` warning under `-warnings-as-errors`**: leftover `is TelegramX` not converted in step. Re-grep `enclosingPeer is Telegram` over the 3 files. - - **Always-failing `as?` cast warning**: leftover `as? TelegramX` not converted. Re-grep `enclosingPeer.*as\?`. - - **Type mismatch on closure-capture alias**: a `strongSelf.enclosingPeer` or `self.enclosingPeer` site missed a `_asPeer()` drop. Re-grep `enclosingPeer\._asPeer\|EnginePeer\(enclosingPeer`. - - **Unused variable warning**: a binding from `case let .channel(channel)` not actually used. Re-read the body. - -Fix in place and re-run step 1. Budget: 2 iterations. - -If errors land outside those 3 files: **STOP**. The wave was supposed to be self-contained. Re-read the spec, identify the missed call site, decide whether to add it or abandon the wave. - ---- - -## Task 5: Post-edit residue grep - -**Files:** none (verification only). - -- [ ] **Step 1: Bridge residue grep** - -Run: - -```sh -grep -rnE "enclosingPeer\._asPeer|EnginePeer\(enclosingPeer\)|enclosingPeer\.flatMap\(EnginePeer" \ - submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/ -``` - -Expected: empty output. - -- [ ] **Step 2: Cast/is-check residue grep** - -Run: - -```sh -grep -rnE "enclosingPeer.*as\? TelegramChannel|enclosingPeer.*as\? TelegramGroup|enclosingPeer is TelegramChannel" \ - submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/ -``` - -Expected: empty output. - -- [ ] **Step 3: Sanity check — `enclosingPeer` references should now exclusively type-resolve to EnginePeer** - -Run: - -```sh -grep -nE ": Peer\b" submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/ListItems/PeerInfoScreenMemberItem.swift submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/Panes/PeerInfoMembersPane.swift -``` - -Expected: no `enclosingPeer: Peer` or `enclosingPeer: Peer?` annotations remain. (Other `: Peer` annotations on unrelated symbols are fine.) - ---- - -## Task 6: Commit the wave - -**Files:** none (git only). - -- [ ] **Step 1: Stage the 3 modified files** - -```sh -git add \ - submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/ListItems/PeerInfoScreenMemberItem.swift \ - submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/Panes/PeerInfoMembersPane.swift \ - submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoProfileItems.swift -``` - -- [ ] **Step 2: Confirm staging is clean** - -```sh -git status --short | grep -v "^??" -``` - -Expected output: only the 3 staged files (lines starting with `M ` or `A `). If other modified files appear, they predate the wave (per CLAUDE.md memory: build-system/bazel-rules/sourcekit-bazel-bsp submodule marker is pre-existing WIP). - -- [ ] **Step 3: Commit** - -```sh -git commit -m "$(cat <<'EOF' -Postbox -> TelegramEngine wave 50 - -Migrate enclosingPeer Peer? -> EnginePeer? across PeerInfoScreenMemberItem -+ PeerInfoMembersPaneNode + 1 PSPB call site. 19 edits / 3 files. - -Drops 5 internal bridges: 2 _asPeer() demotions at PIMP:361/363, 1 -EnginePeer(enclosingPeer) wrap at PIMP:139, 1 flatMap(EnginePeer.init) -at PSMI:178, 1 boundary _asPeer() lift at PSPB:852. - -Closes the wave-48-pattern internal-demotion-and-external-re-promotion -ratchet at PIMP:354-363 (engine.data subscription returns EnginePeer?, -previously demoted to Peer? at storage). - -All `as? TelegramChannel` / `as? TelegramGroup` casts converted to -`case let .channel(...)` / `case let .legacyGroup(...)` (wave-41/45 -idiom). All `is TelegramChannel` checks converted to -`case .channel = ...` (wave-41 always-false-warning fix). - -Co-Authored-By: Claude Opus 4.7 (1M context) -EOF -)" -``` - -- [ ] **Step 4: Verify commit** - -```sh -git log --oneline -1 -``` - -Expected: shows the wave 50 commit. - ---- - -## Task 7: Update outcome log + memory - -**Files:** -- Modify: `docs/superpowers/postbox-refactor-log.md` -- Modify: `~/.claude/projects/-Users-isaac-build-telegram-telegram-ios/memory/project_postbox_refactor_next_wave.md` - -- [ ] **Step 1: Append wave 50 outcome to refactor log** - -Add a "Wave 50 outcome" entry at the appropriate chronological position in `docs/superpowers/postbox-refactor-log.md`. Use the wave 49 outcome entry as the template. Include: -- Commit hash (from Task 6 step 4). -- Iteration count (1 if first-pass-clean; 2 if Task 4 step 2 fired once). -- Net-bridge accounting: −5 internal bridges (2 `_asPeer()` + 1 `EnginePeer(...)` wrap + 1 `flatMap(EnginePeer.init)` + 1 boundary `_asPeer()` lift). 0 ADD wraps. 0 boundary lifts net new. -- Bazel build duration (from Task 4 step 1 output). -- Any wave-specific lessons surfaced. - -- [ ] **Step 2: Update wave-50-next-wave memory** - -Edit `~/.claude/projects/-Users-isaac-build-telegram-telegram-ios/memory/project_postbox_refactor_next_wave.md`: -- Promote wave 50 outcome line into the "Latest commits" section using the format of the wave 49 entry. -- Update the top frontmatter `description` to reflect wave 50 landed and propose wave 51. -- Promote the wave-51 candidate (`PeerInfoGroupsInCommonPaneNode.PeerEntry.peer: Peer → EnginePeer`) to the top of the "Wave 51 candidates" section, replacing the now-stale "Wave 50 candidates" header. Re-run the broader grep if needed: - -```sh -grep -rnE "^\s*(let|var|public let|public var|private let|private var) [a-zA-Z_]+: Peer\??$|^\s*(let|var|public let|public var|private let|private var) [a-zA-Z_]+: Peer\? = " \ - submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/ --include="*.swift" | grep -v "EnginePeer" -``` - -- [ ] **Step 3: Commit the doc update** - -```sh -git add docs/superpowers/postbox-refactor-log.md -git commit -m "$(cat <<'EOF' -docs: log wave 50 outcome - -Co-Authored-By: Claude Opus 4.7 (1M context) -EOF -)" -``` - -(Memory file updates are not committed — they live outside the repo.) - ---- - -## Net delta projection (from spec) - -| Category | Count | Sites | -|---|---|---| -| Internal bridge drops | −5 | PIMP:361, PIMP:363, PIMP:139, PSMI:178, PSPB:852 | -| Boundary lifts (net new) | 0 | source pipeline already EnginePeer? | -| ADD wraps | 0 | no Peer-only property accesses on bare `enclosingPeer` | -| Cast→case-let conversions | 4 | PSMI:152/154, PIMP:113/115 | -| `is`→`case` conversions | 4 | PSMI:181/187, PIMP:142/148 | -| Type annotations updated | 6 | PSMI:23/34, PIMP:92/271/293/442 | - -**Total commit footprint:** 19 line edits across 3 files, plus a docs commit for the outcome log. diff --git a/docs/superpowers/plans/2026-04-25-peerinfoscreendata-linked-peers-engine-peer.md b/docs/superpowers/plans/2026-04-25-peerinfoscreendata-linked-peers-engine-peer.md deleted file mode 100644 index 8abbf566ef..0000000000 --- a/docs/superpowers/plans/2026-04-25-peerinfoscreendata-linked-peers-engine-peer.md +++ /dev/null @@ -1,106 +0,0 @@ -# Wave 49 — `PeerInfoScreenData.linkedDiscussionPeer` + `.linkedMonoforumPeer` `Peer? → EnginePeer?` (bundle) - -**Date:** 2026-04-25 -**Predecessor:** Wave 48 (commit `1e4c2eea33`) — savedMessagesPeer single-field migration. -**Shape:** Cross-file bundled struct-field migration (2 sibling fields, 2 files). Both fields are module-internal; no external consumer references them on `PeerInfoScreenData`. Bundled because both fields: -- Share a sibling declaration site in `PeerInfoData.swift`. -- Have parallel local-source patterns (raw `Peer?` from `peerView.peers[id]` dict lookup; **not** an engine signal as in wave 48). -- Are both consumed in `PeerInfoProfileItems.swift` only. -- Migrating one without the other adds friction at the source-construction sites where they're computed together. - -## Pre-flight inventory - -`grep -rEn "(\w+\??)\.linkedDiscussionPeer\b|(\w+\??)\.linkedMonoforumPeer\b" submodules/ Telegram/`: -- `submodules/PeerInfoUI/Sources/ChannelDiscussionGroupSetupController.swift:600,651` — references are on a local `view` object (different type, NOT PeerInfoScreenData). Out of scope. -- All `data.linkedDiscussionPeer` / `data.linkedMonoforumPeer` accesses live in PIPI within the PeerInfoScreen module. - -Within scope: - -### `PeerInfoData.swift` (storage class + 2 init sites that compute the locals) - -| Site | Code | Action | -|------|------|--------| -| :396 | `let linkedDiscussionPeer: Peer?` (field decl) | Type → `EnginePeer?` | -| :397 | `let linkedMonoforumPeer: Peer?` (field decl) | Type → `EnginePeer?` | -| :453 | `linkedDiscussionPeer: Peer?,` (init param) | Type → `EnginePeer?` | -| :454 | `linkedMonoforumPeer: Peer?,` (init param) | Type → `EnginePeer?` | -| :498 | `self.linkedDiscussionPeer = linkedDiscussionPeer` | No change | -| :499 | `self.linkedMonoforumPeer = linkedMonoforumPeer` | No change | -| :1038, :1111, :1631 | `linkedDiscussionPeer: nil,` (init kwargs) | No change | -| :1039, :1112, :1632 | `linkedMonoforumPeer: nil,` (init kwargs) | No change | -| :1836 | `var discussionPeer: Peer?` (local) | Type → `EnginePeer?` | -| :1838 | `discussionPeer = peer` (where `peer = peerView.peers[linkedDiscussionPeerId]`, raw `Peer`) | Wrap → `discussionPeer = EnginePeer(peer)` | -| :1841 | `var monoforumPeer: Peer?` (local) | Type → `EnginePeer?` | -| :1843 | `monoforumPeer = peerView.peers[linkedMonoforumId]` (dict lookup, `Peer?`) | Wrap → `monoforumPeer = peerView.peers[linkedMonoforumId].flatMap(EnginePeer.init)` | -| :2131 | `var discussionPeer: Peer?` (local, parallel to :1836) | Type → `EnginePeer?` | -| :2133 | `discussionPeer = peer` (parallel to :1838) | Wrap → `discussionPeer = EnginePeer(peer)` | -| :2136 | `var monoforumPeer: Peer?` (local, parallel to :1841) | Type → `EnginePeer?` | -| :2138 | `monoforumPeer = peerView.peers[linkedMonoforumId]` (parallel to :1843) | Wrap with `.flatMap(EnginePeer.init)` | -| :1878, :1879, :2216, :2217 | init kwargs `linkedDiscussionPeer: discussionPeer,` / `linkedMonoforumPeer: monoforumPeer,` | No change (locals migrate; pass through) | - -That's **12 edits** in PID. Note the `var` declarations and assignments at :1836–:1843 and :2131–:2138 are *parallel pairs* (verified by grep). Use `replace_all=true` for the duplicate snippets. - -### `PeerInfoProfileItems.swift` (3 edits) - -| Site | Code | Action | -|------|------|--------| -| :1098 | `if let peer = data.linkedDiscussionPeer { ... }` | No change (binding works on `EnginePeer?`) | -| :1099 | `if let addressName = peer.addressName, !addressName.isEmpty {` | No change — `EnginePeer.addressName` forwarded (verified at `submodules/TelegramCore/Sources/TelegramEngine/Peers/Peer.swift:461`) | -| :1102 | `discussionGroupTitle = EnginePeer(peer).displayTitle(strings: ..., displayOrder: ...)` | **Drop wrap** → `peer.displayTitle(...)` | -| :1197 | `if let monoforumPeer = data.linkedMonoforumPeer as? TelegramChannel {` | **Pattern rewrite** → `if case let .channel(monoforumPeer) = data.linkedMonoforumPeer {` | -| :1198 | `monoforumPeer.sendPaidMessageStars` | No change — `sendPaidMessageStars` is a `TelegramChannel` property (`SyncCore_TelegramChannel.swift:215`); `case .channel` binds to `TelegramChannel` | -| :1404 | `if let linkedDiscussionPeer = data.linkedDiscussionPeer {` | No change (binding works) | -| :1406 | `if let addressName = linkedDiscussionPeer.addressName, !addressName.isEmpty {` | No change (forwarded) | -| :1409 | `peerTitle = EnginePeer(linkedDiscussionPeer).displayTitle(...)` | **Drop wrap** → `linkedDiscussionPeer.displayTitle(...)` | - -3 edits in PIPI. - -## EnginePeer property forwarding audit - -- `EnginePeer.addressName` — forwarded at `Peer.swift:461`. ✓ -- `EnginePeer.displayTitle(strings:displayOrder:)` — defined as `EnginePeer` instance method (used elsewhere via `EnginePeer(...).displayTitle(...)` pattern; once we have an `EnginePeer`, it's directly callable). ✓ -- `case .channel` binding payload is `TelegramChannel`. ✓ -- `TelegramChannel.sendPaidMessageStars` — exists (`SyncCore_TelegramChannel.swift:215`). ✓ - -## Net bridge count - -- **ADDs (4):** boundary lifts at PID:1838 (`EnginePeer(peer)`), PID:1843 (`.flatMap(EnginePeer.init)`), PID:2133, PID:2138. These lift the Postbox-typed `peerView.peers[...]` value to the engine type at the boundary — the correct semantic position for a Postbox→Engine refactor (mirrors wave 42 where `peer.flatMap(EnginePeer.init)` lift was added at PID:1620). -- **DROPs (2):** PIPI:1102 and :1409 lose `EnginePeer(...)` wraps around `displayTitle` calls. -- **Net text bridges:** +2. **But:** the ADDs are correct boundary lifts; the field-typed-as-`EnginePeer?` is the canonical state. The 2 displayTitle DROPs are the actual ratchet value. -- **Plus:** 1 cleaner pattern (PIPI:1197 `as?` cast → `case let .channel`), no text saving but better Swift idiom. - -## Edit list - -### `PeerInfoData.swift` (12 edits, but Edit text uses `replace_all=true` to bundle parallel pairs) - -1. Line 396: `let linkedDiscussionPeer: Peer?` → `let linkedDiscussionPeer: EnginePeer?` -2. Line 397: `let linkedMonoforumPeer: Peer?` → `let linkedMonoforumPeer: EnginePeer?` -3. Line 453: `linkedDiscussionPeer: Peer?,` → `linkedDiscussionPeer: EnginePeer?,` -4. Line 454: `linkedMonoforumPeer: Peer?,` → `linkedMonoforumPeer: EnginePeer?,` -5. Lines 1836 + 2131 (`replace_all=true` over `var discussionPeer: Peer?`): → `var discussionPeer: EnginePeer?` -6. Lines 1838 + 2133 (`replace_all=true` over `discussionPeer = peer`): → `discussionPeer = EnginePeer(peer)` -7. Lines 1841 + 2136 (`replace_all=true` over `var monoforumPeer: Peer?`): → `var monoforumPeer: EnginePeer?` -8. Lines 1843 + 2138 (`replace_all=true` over `monoforumPeer = peerView.peers[linkedMonoforumId]`): → `monoforumPeer = peerView.peers[linkedMonoforumId].flatMap(EnginePeer.init)` - -### `PeerInfoProfileItems.swift` (3 edits) - -9. Line 1102: `discussionGroupTitle = EnginePeer(peer).displayTitle(strings: presentationData.strings, displayOrder: presentationData.nameDisplayOrder)` → `discussionGroupTitle = peer.displayTitle(strings: presentationData.strings, displayOrder: presentationData.nameDisplayOrder)` -10. Line 1197: `if let monoforumPeer = data.linkedMonoforumPeer as? TelegramChannel {` → `if case let .channel(monoforumPeer) = data.linkedMonoforumPeer {` -11. Line 1409: `peerTitle = EnginePeer(linkedDiscussionPeer).displayTitle(strings: presentationData.strings, displayOrder: presentationData.nameDisplayOrder)` → `peerTitle = linkedDiscussionPeer.displayTitle(strings: presentationData.strings, displayOrder: presentationData.nameDisplayOrder)` - -## Out of scope - -- `PeerInfoScreenData.chatPeer` — large blast radius. Defer. -- `PeerInfoScreenMemberItem.enclosingPeer`. Defer. - -## Build & verify - -Standard Bazel command. Expected 1 iteration if forwarding audit holds; 2 if a `displayTitle` overload-resolution surprise surfaces. - -## Commit - -`Postbox -> TelegramEngine wave 49`. Body: bundle + edits summary + ADD/DROP accounting. - -## Outcome capture - -Append Wave 49 entry to `docs/superpowers/postbox-refactor-log.md`; update memory file. diff --git a/docs/superpowers/plans/2026-04-25-peerinfoscreendata-savedmessagespeer-engine-peer.md b/docs/superpowers/plans/2026-04-25-peerinfoscreendata-savedmessagespeer-engine-peer.md deleted file mode 100644 index fcbab698e1..0000000000 --- a/docs/superpowers/plans/2026-04-25-peerinfoscreendata-savedmessagespeer-engine-peer.md +++ /dev/null @@ -1,70 +0,0 @@ -# Wave 48 — `PeerInfoScreenData.savedMessagesPeer` `Peer? → EnginePeer?` - -**Date:** 2026-04-25 -**Predecessor:** Wave 47 (commit `d7b7536440`) — stored PHN.peer single-file private migration. -**Shape:** Cross-file struct-field migration. Storage class is internal to PeerInfoScreen module; no external consumer references PSD.savedMessagesPeer. - -## Target - -`submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoData.swift`, `PeerInfoScreenData.savedMessagesPeer: Peer?` at line 388. - -## Pre-flight inventory - -`grep -rEn "(\w+\??)\.savedMessagesPeer\b" submodules/ Telegram/` → matches only inside `submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/`. No external consumer. The same field name appears in unrelated places (TelegramEngineMessages.swift, ChatListUI, etc.) but those are different declarations on different types. - -Within PeerInfoScreen module: - -| Site | Code | Action | -|------|------|--------| -| `PeerInfoData.swift:388` | `let savedMessagesPeer: Peer?` (struct field decl) | Type change → `EnginePeer?` | -| `PeerInfoData.swift:444` | `savedMessagesPeer: Peer?,` (init param) | Type change → `EnginePeer?` | -| `PeerInfoData.swift:489` | `self.savedMessagesPeer = savedMessagesPeer` (assignment) | No change (passthrough) | -| `PeerInfoData.swift:1029` | `savedMessagesPeer: nil,` (init kwarg) | No change (`nil` works for either) | -| `PeerInfoData.swift:1102` | `savedMessagesPeer: nil,` | No change | -| `PeerInfoData.swift:1313–1317` | `let savedMessagesPeer: Signal` (local) | No change — already `EnginePeer?` | -| `PeerInfoData.swift:1622` | `savedMessagesPeer: savedMessagesPeer?._asPeer(),` | **Drop bridge** → `savedMessagesPeer: savedMessagesPeer,` | -| `PeerInfoData.swift:1869` | `savedMessagesPeer: nil,` | No change | -| `PeerInfoData.swift:2207` | `savedMessagesPeer: nil,` | No change | -| `PeerInfoScreen.swift:5399` | `peer: self.data?.savedMessagesPeer.flatMap(EnginePeer.init) ?? self.data?.peer,` | **Drop bridge** → `peer: self.data?.savedMessagesPeer ?? self.data?.peer,` | -| `PeerInfoScreen.swift:5805` | same as :5399 | Same drop | - -Total edits: 5 (3 in PID, 2 in PIS). - -## EnginePeer / read-site audit - -The local signal at `PeerInfoData.swift:1313` already produces `EnginePeer?` from `engine.data.subscribe(TelegramEngine.EngineData.Item.Peer.Peer(...))`. The `?._asPeer()` at line 1622 was an artificial demotion. Migrating the field type to `EnginePeer?` removes both the demotion at the storage site and the `flatMap(EnginePeer.init)` re-promotions at the read sites — a clean ratchet. - -PIS:5399 and :5805 use the field as input to `headerNode.update(... peer: ...)`, whose `peer` parameter has been `EnginePeer?` since wave 45. The `??` coalescing operand is `self.data?.peer` (already `EnginePeer?`). Result: drop the `.flatMap(EnginePeer.init)` and the expression compiles. - -## Edit list - -### PeerInfoData.swift (3 edits) - -1. Line 388: `let savedMessagesPeer: Peer?` → `let savedMessagesPeer: EnginePeer?` -2. Line 444: `savedMessagesPeer: Peer?,` → `savedMessagesPeer: EnginePeer?,` -3. Line 1622: `savedMessagesPeer: savedMessagesPeer?._asPeer(),` → `savedMessagesPeer: savedMessagesPeer,` - -### PeerInfoScreen.swift (2 edits, identical text) - -4. Line 5399: `peer: self.data?.savedMessagesPeer.flatMap(EnginePeer.init) ?? self.data?.peer,` → `peer: self.data?.savedMessagesPeer ?? self.data?.peer,` -5. Line 5805: same - -Use `replace_all=true` for the PIS edit since the matched text appears at both call sites verbatim. - -## Out of scope - -- `PeerInfoScreenData.chatPeer` — large blast radius (5 `as? TelegramX` checks downstream + ClearPeerHistory init parameter), defer. -- `PeerInfoScreenData.linkedDiscussionPeer`, `linkedMonoforumPeer` — both have `as? TelegramChannel` consumer sites in `PeerInfoProfileItems.swift`. Defer. -- `PeerInfoScreenMemberItem.enclosingPeer` — defer (separate target). - -## Build & verify - -Same Bazel command as wave 47. Expected 1-iteration first-pass-clean (single-pattern bridge removal, no enum-case rewrites, no Peer-only property access). - -## Commit - -`Postbox -> TelegramEngine wave 48`. Body lists the 5-edit summary and notes −3 internal bridges (1 PID + 2 PIS, identical PIS text appears twice). - -## Outcome capture - -Append a Wave 48 entry to `docs/superpowers/postbox-refactor-log.md` and update memory file `project_postbox_refactor_next_wave.md`. diff --git a/docs/superpowers/plans/2026-04-25-phn-peer-stored-field-engine-peer.md b/docs/superpowers/plans/2026-04-25-phn-peer-stored-field-engine-peer.md deleted file mode 100644 index 773f2bb01a..0000000000 --- a/docs/superpowers/plans/2026-04-25-phn-peer-stored-field-engine-peer.md +++ /dev/null @@ -1,62 +0,0 @@ -# Wave 47 — `PeerInfoHeaderNode.peer` stored field `Peer? → EnginePeer?` - -**Date:** 2026-04-25 -**Predecessor:** Wave 46 (commit `5ca99da5a7`) — PeerInfo avatar chain. -**Shape:** Single-file stored-field type migration. No external API change (field is `private`). - -## Target - -`submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoHeaderNode.swift`, stored field `private var peer: Peer?` at line 92. - -## Pre-flight inventory - -`grep -n "self\.peer\b" PeerInfoHeaderNode.swift` returns exactly 3 references: - -| Line | Code | Site type | Action | -|------|------|-----------|--------| -| 426 | `if let peer = self.peer, peer.profileImageRepresentations.isEmpty && gallery {` | Read | None — `profileImageRepresentations` is forwarded by `EnginePeer` (see `submodules/TelegramCore/Sources/TelegramEngine/Peers/Peer.swift:485`). Compiles unchanged. | -| 521 | `self.peer = peer?._asPeer()` | Assignment | Drop the bridge → `self.peer = peer`. The `peer` parameter is already `EnginePeer?` after wave 45. | -| 2049–2054 | `guard let self, let peer = self.peer, ...` followed by `peer: EnginePeer(peer),` | Read | Drop the wrap at line 2054 → `peer: peer,`. | - -External access check: `grep -rn "headerNode\.peer\b" submodules/ Telegram/` returns empty. The field is private; only same-file siblings touch it. - -EnginePeer forwarding (re-confirmed at plan time): -- `profileImageRepresentations` — forwarded (Peer.swift:485). ✓ -- `EnginePeer(peer)` (PHN:2054) — accepts `EnginePeer` directly when the local is already `EnginePeer`; drop the constructor. - -Field-declaration change is the only "type" change needed. The 3 callers' adjustments are mechanical bridge drops. - -## Edit list - -1. Line 92: `private var peer: Peer?` → `private var peer: EnginePeer?` -2. Line 521: `self.peer = peer?._asPeer()` → `self.peer = peer` -3. Line 2054: `peer: EnginePeer(peer),` → `peer: peer,` - -Total: 3 edits in 1 file. - -## Out of scope - -- `PeerInfoData.swift:355,487` — different classes' `self.peer` assignments (different types). Audit confirms these are `RenderedChannelParticipant.peer` and similar — already migrated in earlier waves or owned by other types. -- `PeerInfoAvatarTransformContainerNode.peer` (line 223) — already `EnginePeer?` after wave 46. - -## Build & verify - -```sh -source ~/.zshrc 2>/dev/null; \ -python3 build-system/Make/Make.py --overrideXcodeVersion \ - --cacheDir ~/telegram-bazel-cache build \ - --configurationPath build-system/appstore-configuration.json \ - --gitCodesigningRepository git@gitlab.com:peter-iakovlev/fastlanematch.git \ - --gitCodesigningType development --gitCodesigningUseCurrent \ - --buildNumber=1 --configuration=debug_sim_arm64 -``` - -Expected: 1-iteration first-pass-clean. Only PeerInfoScreen + TelegramUI recompile. - -## Commit - -`Postbox -> TelegramEngine wave 47`. Body lists the 3-edit summary and notes -3 internal bridges. - -## Outcome capture - -Append a Wave 47 entry to `docs/superpowers/postbox-refactor-log.md` and update memory file `project_postbox_refactor_next_wave.md`. diff --git a/docs/superpowers/plans/2026-04-26-postbox-wave-103-chat-recent-actions-controller-node.md b/docs/superpowers/plans/2026-04-26-postbox-wave-103-chat-recent-actions-controller-node.md deleted file mode 100644 index 68d5d0311b..0000000000 --- a/docs/superpowers/plans/2026-04-26-postbox-wave-103-chat-recent-actions-controller-node.md +++ /dev/null @@ -1,347 +0,0 @@ -# Wave 103: ChatRecentActionsControllerNode peer Peer → EnginePeer Implementation Plan - -> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. - -**Goal:** Migrate `ChatRecentActionsControllerNode`'s stored `peer: Peer` field to `EnginePeer`, dropping the `_asPeer()` boundary call at the single caller site (wave 103 of the Postbox → TelegramEngine refactor). - -**Architecture:** Wave-71-shadow close. Single-file private stored-form migration plus a 1-line caller drop. The caller (`ChatRecentActionsController`) already holds `peer: EnginePeer` and demotes once before passing into the node init. The wave drops the demotion and rewrites 3 `as? TelegramChannel` downcasts inside the node body to `case let .channel(...)` (wave-41/45 idiom). All scope is within `submodules/TelegramUI/Components/Chat/ChatRecentActionsController/Sources/`. - -**Tech Stack:** Swift, Bazel via `Make.py`, no unit tests (per `CLAUDE.md`). Verification is the full-project debug-sim-arm64 build. - -**Iteration budget:** 1 (target first-pass-clean given the 7-edit scope and validated pre-flight grep). - -**Note on TDD:** This project has no unit tests. The standard TDD test-first cycle does not apply. Each task writes the edits, then verifies via Bazel build + residue grep. - ---- - -## File Structure - -| File | Role | Changes | -|---|---|---| -| `submodules/TelegramUI/Components/Chat/ChatRecentActionsController/Sources/ChatRecentActionsControllerNode.swift` (CRACN) | Recent-actions screen controller node | Drop `import Postbox`, retype stored field + init param, rewrite 3 `as? TelegramChannel` downcasts (6 edits) | -| `submodules/TelegramUI/Components/Chat/ChatRecentActionsController/Sources/ChatRecentActionsController.swift` (CRAC) | Recent-actions screen controller (caller) | Drop `_asPeer()` at the node init (1 edit) | - -No public-API ripple — `ChatRecentActionsControllerNode` is local to the module and has a single caller verified by grep. - ---- - -## Task 1: CRACN.swift — drop `import Postbox` + type changes + downcast rewrites - -**Files:** -- Modify: `submodules/TelegramUI/Components/Chat/ChatRecentActionsController/Sources/ChatRecentActionsControllerNode.swift` - -**Edits in this task:** 6 (1 import drop, 1 stored-field retype, 1 init-param retype, 3 cast → case-let). - -- [ ] **Step 1: Drop `import Postbox` at line 5** - -Find: - -```swift -import Postbox -``` - -Replace with: (delete the line entirely) - -This file imports `TelegramCore` at line 4, which provides the `EnginePeer` type and the typealiases needed for the rest of this task. - -- [ ] **Step 2: Retype stored field at line 46** - -Find: - -```swift - private let peer: Peer -``` - -Replace with: - -```swift - private let peer: EnginePeer -``` - -- [ ] **Step 3: Retype init parameter at line 111** - -Find: - -```swift - init(context: AccountContext, controller: ChatRecentActionsController, peer: Peer, presentationData: PresentationData, pushController: @escaping (ViewController) -> Void, presentController: @escaping (ViewController, PresentationContextType, Any?) -> Void, getNavigationController: @escaping () -> NavigationController?) { -``` - -Replace with: - -```swift - init(context: AccountContext, controller: ChatRecentActionsController, peer: EnginePeer, presentationData: PresentationData, pushController: @escaping (ViewController) -> Void, presentController: @escaping (ViewController, PresentationContextType, Any?) -> Void, getNavigationController: @escaping () -> NavigationController?) { -``` - -- [ ] **Step 4: Rewrite downcast at line 899** - -Find: - -```swift - if let peer = strongSelf.peer as? TelegramChannel { -``` - -Replace with: - -```swift - if case let .channel(peer) = strongSelf.peer { -``` - -The bound name `peer` is preserved so the inner block (`switch peer.info { case .group: ... }`) ports verbatim. `case let .channel(peer)` binds `peer: TelegramChannel` directly (the associated value of `EnginePeer.channel`). - -- [ ] **Step 5: Rewrite downcast at line 948** - -Find: - -```swift - if let channel = self.peer as? TelegramChannel, case .broadcast = channel.info { -``` - -Replace with: - -```swift - if case let .channel(channel) = self.peer, case .broadcast = channel.info { -``` - -The compound condition (`, case .broadcast = channel.info`) ports verbatim because the bound `channel` is still `TelegramChannel`-typed. - -- [ ] **Step 6: Rewrite downcast at line 1088** - -Find: - -```swift - if let channel = self.peer as? TelegramChannel { -``` - -Replace with: - -```swift - if case let .channel(channel) = self.peer { -``` - -The inner block (`channel.hasPermission(.banMembers)`, `case .broadcast = channel.info`) ports verbatim. - -The `self.peer.id` accesses at lines 145, 161, 1138, 1490 require no edit — `EnginePeer.id` is a typealiased `PeerId`, identical at the call sites. - ---- - -## Task 2: CRAC.swift — drop boundary `_asPeer()` - -**Files:** -- Modify: `submodules/TelegramUI/Components/Chat/ChatRecentActionsController/Sources/ChatRecentActionsController.swift` - -**Edits in this task:** 1. - -- [ ] **Step 1: Drop `_asPeer()` at line 277** - -Find: - -```swift - self.displayNode = ChatRecentActionsControllerNode(context: self.context, controller: self, peer: self.peer._asPeer(), presentationData: self.presentationData, pushController: { [weak self] c in -``` - -Replace with: - -```swift - self.displayNode = ChatRecentActionsControllerNode(context: self.context, controller: self, peer: self.peer, presentationData: self.presentationData, pushController: { [weak self] c in -``` - -`ChatRecentActionsController.peer` is already declared `EnginePeer` at line 42 (`public init(context: AccountContext, peer: EnginePeer, ...)`) — the type carries through to the now-`EnginePeer`-typed init parameter. - ---- - -## Task 3: Full-project Bazel build - -**Files:** none (verification only). - -- [ ] **Step 1: Run the build** - -Run: - -```sh -source ~/.zshrc 2>/dev/null; python3 build-system/Make/Make.py --overrideXcodeVersion \ - --cacheDir ~/telegram-bazel-cache \ - build \ - --configurationPath build-system/appstore-configuration.json \ - --gitCodesigningRepository git@gitlab.com:peter-iakovlev/fastlanematch.git \ - --gitCodesigningType development --gitCodesigningUseCurrent \ - --buildNumber=1 --configuration=debug_sim_arm64 -``` - -Expected: clean build (`bazel build complete` or equivalent green output). No `--continueOnError` because the small scope makes the first error informative. - -Build cost projection: consumer-only, ~25s. If it exceeds ~60s, suspect a cascade leak. - -- [ ] **Step 2: If build fails, triage iteration** - -If errors land in `ChatRecentActionsControllerNode.swift` or `ChatRecentActionsController.swift`: -- Read the failing line. -- Common failure modes from prior waves: - - **Always-false `is` warning under `-warnings-as-errors`:** none expected here (pre-flight grep confirmed no `is TelegramChannel` checks on `self.peer`). If one surfaces anyway, convert to `case .channel = self.peer`. - - **Always-failing `as?` cast warning:** leftover `as? TelegramX` not converted in step 4/5/6. Re-grep `(self|strongSelf)\.peer as\?` over the file. - - **Type mismatch on closure-capture alias:** none expected here (pre-flight grep confirmed only `strongSelf.peer` and `self.peer` aliases, both ride the type change). - - **Type mismatch on `.id` access:** would indicate a regression in the `EnginePeer.Id` typealias — STOP and re-read CLAUDE.md, this is not a wave-103 issue. - - **Unused-variable warning under `-warnings-as-errors`:** a `case let .channel(peer)` binding not used inside the body. Re-read step 4/5/6 — if the inner block never references the bound name, switch to `case .channel = ...` and remove the binding. - -Fix in place and re-run step 1. Budget: 2 iterations. - -If errors land outside those 2 files: **STOP**. The wave was supposed to be self-contained. Re-read the spec, identify the missed call site, decide whether to add it or abandon the wave. - ---- - -## Task 4: Post-edit residue grep - -**Files:** none (verification only). - -- [ ] **Step 1: Cast residue grep** - -Run: - -```sh -grep -nE "(self|strongSelf)\.peer as\? Telegram(Channel|Group|User)" \ - submodules/TelegramUI/Components/Chat/ChatRecentActionsController/Sources/ -``` - -Expected: empty output. - -- [ ] **Step 2: Boundary `_asPeer()` residue grep** - -Run: - -```sh -grep -nE "self\.peer\._asPeer\(\)" \ - submodules/TelegramUI/Components/Chat/ChatRecentActionsController/Sources/ -``` - -Expected: empty output. - -- [ ] **Step 3: `import Postbox` residue grep** - -Run: - -```sh -grep -rn "^import Postbox$" \ - submodules/TelegramUI/Components/Chat/ChatRecentActionsController/Sources/ -``` - -Expected: empty output. The module is now Postbox-import-free. - -- [ ] **Step 4: Sanity check — `peer: Peer` annotations** - -Run: - -```sh -grep -nE "peer: Peer\b" \ - submodules/TelegramUI/Components/Chat/ChatRecentActionsController/Sources/ChatRecentActionsControllerNode.swift -``` - -Expected: empty output. (The 3 `as? TelegramChannel` downcasts on `self.peer` were the only sources; both `peer: Peer` annotations on stored field and init param are now `peer: EnginePeer`.) - ---- - -## Task 5: Commit the wave - -**Files:** none (git only). - -- [ ] **Step 1: Stage the 2 modified files** - -```sh -git add \ - submodules/TelegramUI/Components/Chat/ChatRecentActionsController/Sources/ChatRecentActionsControllerNode.swift \ - submodules/TelegramUI/Components/Chat/ChatRecentActionsController/Sources/ChatRecentActionsController.swift -``` - -- [ ] **Step 2: Confirm staging is clean** - -```sh -git status --short | grep -v "^??" -``` - -Expected output: only the 2 staged files (lines starting with `M `). If other modified files appear, they predate the wave (per CLAUDE.md memory: `build-system/bazel-rules/sourcekit-bazel-bsp` submodule marker is pre-existing WIP). - -- [ ] **Step 3: Commit** - -```sh -git commit -m "$(cat <<'EOF' -Postbox -> TelegramEngine wave 103 - -Migrate ChatRecentActionsControllerNode.peer Peer -> EnginePeer. -Closes the wave-71 shadow: caller already held EnginePeer and demoted -at the boundary. 7 edits / 2 files. - -Drops 1 boundary _asPeer() at ChatRecentActionsController:277, drops -import Postbox at ChatRecentActionsControllerNode:5, rewrites 3 -`as? TelegramChannel` downcasts to `case let .channel(...)` (wave-41/45 -idiom). - -Co-Authored-By: Claude Opus 4.7 (1M context) -EOF -)" -``` - -- [ ] **Step 4: Verify commit** - -```sh -git log --oneline -1 -``` - -Expected: shows the wave 103 commit as HEAD. - ---- - -## Task 6: Update outcome log + memory - -**Files:** -- Modify: `docs/superpowers/postbox-refactor-log.md` -- Modify: `~/.claude/projects/-Users-isaac-build-telegram-telegram-ios/memory/project_postbox_refactor_next_wave.md` -- Modify: `~/.claude/projects/-Users-isaac-build-telegram-telegram-ios/memory/MEMORY.md` - -- [ ] **Step 1: Append wave 103 outcome to refactor log** - -Append a "Wave 103 outcome" entry at the chronological end of `docs/superpowers/postbox-refactor-log.md`. Use the most recent wave-outcome entry as a structural template. Include: -- Commit hash (from Task 5 step 4). -- Iteration count (1 if first-pass-clean; 2 if Task 3 step 2 fired). -- Net-bridge accounting: −1 boundary `_asPeer()` (CRAC:277), −1 `import Postbox` (CRACN:5). 0 ADD wraps. 3 cast → case-let conversions (CRACN:899/948/1088). -- Bazel build duration (from Task 3 step 1 output). -- Wave-shape note: wave-71-shadow close, single-iter target validated. - -- [ ] **Step 2: Update next-wave memory** - -Edit `~/.claude/projects/-Users-isaac-build-telegram-telegram-ios/memory/project_postbox_refactor_next_wave.md`: -- Add the wave 103 outcome line into the recent-waves section (commit hash + 7-edit / 2-file / 1-iter summary). -- Remove the now-stale `ChatRecentActionsControllerNode.peer: Peer -> EnginePeer` candidate line (currently bullet 5 in the candidates list). -- Update the top frontmatter `description` to reflect wave 103 landed and propose wave 104. -- Promote the next candidate (likely one of: `cachedResourceRepresentation` foundational facade, `RenderedPeer` cascade kickoff, `SelectivePrivacyPeer` foundational, or another Shape-C/D mini-refactor) to the top of the candidates list. - -- [ ] **Step 3: Update MEMORY.md index** - -Edit `~/.claude/projects/-Users-isaac-build-telegram-telegram-ios/memory/MEMORY.md`: -- Update the `[Postbox refactor next wave]` line to mention wave 103 landed and shift the "Wave 103+ Shape-C/D candidates" framing forward to "Wave 104+ candidates". - -- [ ] **Step 4: Commit the doc update** - -```sh -git add docs/superpowers/postbox-refactor-log.md -git commit -m "$(cat <<'EOF' -docs: log wave 103 outcome - -Co-Authored-By: Claude Opus 4.7 (1M context) -EOF -)" -``` - -(Memory file updates at `~/.claude/projects/-Users-isaac-build-telegram-telegram-ios/memory/` are not committed — they live outside the repo.) - ---- - -## Net delta projection (from spec) - -| Category | Count | Sites | -|---|---|---| -| Internal bridge drops | −1 | CRAC:277 (`_asPeer()`) | -| `import Postbox` drops | −1 | CRACN:5 | -| ADD wraps | 0 | no Peer-only property accesses on bare `self.peer` | -| Cast → case-let conversions | 3 | CRACN:899, CRACN:948, CRACN:1088 | -| Type annotations updated | 2 | CRACN:46 (stored field), CRACN:111 (init param) | -| Postbox-free module count | +1 | `Components/Chat/ChatRecentActionsController/` joins the list | - -**Total commit footprint:** 7 line edits across 2 files, plus a docs commit for the outcome log. diff --git a/docs/superpowers/plans/2026-04-26-postbox-wave-103-retry-account-manager-store-resource-data-drain.md b/docs/superpowers/plans/2026-04-26-postbox-wave-103-retry-account-manager-store-resource-data-drain.md deleted file mode 100644 index efc202c33d..0000000000 --- a/docs/superpowers/plans/2026-04-26-postbox-wave-103-retry-account-manager-store-resource-data-drain.md +++ /dev/null @@ -1,260 +0,0 @@ -# Wave 103 (retry): accountManager.mediaBox.storeResourceData drain Implementation Plan - -> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. - -**Goal:** Drain 5 remaining `accountManager.mediaBox.storeResourceData(...)` Shape-A sites against the wave-94 `AccountManagerResources.storeResourceData(id:data:synchronous:)` facade. Wave 103 (retry) of the Postbox → TelegramEngine refactor, after the abandonment of the original wave-103 plan. - -**Architecture:** Wave-shape-G drain. Pure call-site rewrite; no facade addition, no TelegramCore touch, no public-API change. 5 sites across 2 consumer files (`ThemeUpdateManager.swift`, `WallpaperResources.swift`) migrated via 3 `Edit` calls (1 single + 2 `replace_all=true` batches). - -**Tech Stack:** Swift, Bazel via `Make.py`, no unit tests (per `CLAUDE.md`). Verification is the full-project debug-sim-arm64 build. - -**Iteration budget:** 1 (target first-pass-clean given mechanical scope and validated facade). - -**Note on TDD:** This project has no unit tests. Each task writes the edits, then verifies via Bazel build + residue grep. - ---- - -## File Structure - -| File | Role | Changes | -|---|---|---| -| `submodules/TelegramUI/Sources/ThemeUpdateManager.swift` | Theme-update background sync | 1 site migrated | -| `submodules/WallpaperResources/Sources/WallpaperResources.swift` | Wallpaper resource pipeline | 4 sites migrated via 2 `replace_all=true` batches | - -No public-API ripple — both files are leaf consumers of the wave-94 facade. - ---- - -## Task 1: ThemeUpdateManager.swift — single-site migration - -**Files:** -- Modify: `submodules/TelegramUI/Sources/ThemeUpdateManager.swift` - -**Edits in this task:** 1. - -- [ ] **Step 1: Migrate the storeResourceData call at line 112** - -Find: - -```swift - accountManager.mediaBox.storeResourceData(file.file.resource.id, data: fullSizeData, synchronous: true) -``` - -Replace with: - -```swift - accountManager.resources.storeResourceData(id: EngineMediaResource.Id(file.file.resource.id), data: fullSizeData, synchronous: true) -``` - -`accountManager` here is closure-captured from `presentationThemeSettingsUpdated(_:)` scope, typed `AccountManager`. The facade is exposed via `public extension AccountManager { var resources: AccountManagerResources }`. - ---- - -## Task 2: WallpaperResources.swift — two batched migrations - -**Files:** -- Modify: `submodules/WallpaperResources/Sources/WallpaperResources.swift` - -**Edits in this task:** 2 (each `replace_all=true`, covering 2 sites apiece). - -- [ ] **Step 1: Migrate the `reference.resource.id` pattern (lines 973, 1214)** - -Use `Edit` with `replace_all=true`: - -Find: - -```swift -accountManager.mediaBox.storeResourceData(reference.resource.id, data: data) -``` - -Replace with: - -```swift -accountManager.resources.storeResourceData(id: EngineMediaResource.Id(reference.resource.id), data: data) -``` - -Both sites share identical text (verified by pre-flight grep). `replace_all=true` handles both atomically. - -- [ ] **Step 2: Migrate the `file.file.resource.id` pattern (lines 1260, 1523)** - -Use `Edit` with `replace_all=true`: - -Find: - -```swift -accountManager.mediaBox.storeResourceData(file.file.resource.id, data: fullSizeData) -``` - -Replace with: - -```swift -accountManager.resources.storeResourceData(id: EngineMediaResource.Id(file.file.resource.id), data: fullSizeData) -``` - -Both sites share identical text. `replace_all=true` handles both atomically. - ---- - -## Task 3: Full-project Bazel build - -**Files:** none (verification only). - -- [ ] **Step 1: Run the build** - -```sh -source ~/.zshrc 2>/dev/null; python3 build-system/Make/Make.py --overrideXcodeVersion \ - --cacheDir ~/telegram-bazel-cache \ - build \ - --configurationPath build-system/appstore-configuration.json \ - --gitCodesigningRepository git@gitlab.com:peter-iakovlev/fastlanematch.git \ - --gitCodesigningType development --gitCodesigningUseCurrent \ - --buildNumber=1 --configuration=debug_sim_arm64 -``` - -Expected: clean build (`bazel build complete` / `INFO: Build completed successfully`). No `--continueOnError` because the small scope makes the first error informative. - -Build cost projection: WallpaperResources is foundational with wide rebuild fan-out; expect ~30-90s. - -- [ ] **Step 2: If build fails, triage iteration** - -Common failure modes: -- **`EngineMediaResource.Id` not in scope** — verify `import TelegramCore` is at the top of the failing file (it should be — pre-flight inventoried both files have it). If absent, add it. -- **Type mismatch on `id:` parameter** — would suggest an unexpected `MediaResourceId` subtype. STOP and re-read; the migration assumed `MediaResource.id: MediaResourceId` for both `reference.resource` and `file.file.resource`. Both should resolve to `MediaResourceId` per Postbox protocol. -- **`accountManager.resources` not in scope** — the `public extension AccountManager` exists in TelegramCore (wave 94). If unreachable, the consumer's BUILD might be missing a TelegramCore dep — but both files already use TelegramCore types, so this should not happen. STOP if it does. - -If errors land outside those 2 files: **STOP and report BLOCKED**. The wave is supposed to be self-contained. - -Fix in place and re-run step 1. Budget: 2 iterations. - ---- - -## Task 4: Post-edit residue grep - -**Files:** none (verification only). - -- [ ] **Step 1: Verify zero remaining `accountManager.mediaBox.storeResourceData` in the 2 touched files** - -Run: - -```sh -grep -rn "accountManager\.mediaBox\.storeResourceData" \ - submodules/TelegramUI/Sources/ThemeUpdateManager.swift \ - submodules/WallpaperResources/Sources/WallpaperResources.swift -``` - -Expected: empty output. - ---- - -## Task 5: Commit the wave - -**Files:** none (git only). - -- [ ] **Step 1: Stage the 2 modified files** - -```sh -git add \ - submodules/TelegramUI/Sources/ThemeUpdateManager.swift \ - submodules/WallpaperResources/Sources/WallpaperResources.swift -``` - -- [ ] **Step 2: Confirm staging is clean** - -```sh -git status --short | grep -v "^??" -``` - -Expected output: only the 2 staged files (lines starting with `M `). The line `m build-system/bazel-rules/sourcekit-bazel-bsp` is pre-existing WIP and should NOT appear in the staged list. - -- [ ] **Step 3: Commit** - -```sh -git commit -m "$(cat <<'EOF' -Postbox -> TelegramEngine wave 103 (retry) - -Drain 5 accountManager.mediaBox.storeResourceData(...) Shape-A sites -that the wave-94/95-99 sweep missed. All 5 migrated to -accountManager.resources.storeResourceData(id: EngineMediaResource.Id(...)) -against the existing wave-94 facade. - -Sites: ThemeUpdateManager:112 (with synchronous: true), -WallpaperResources:973, 1214 (reference.resource.id pattern, replace_all), -WallpaperResources:1260, 1523 (file.file.resource.id pattern, replace_all). - -5 sites / 2 files / 3 Edit calls. Consumer-only build. - -Wave-103 retry after the abandonment of ChatRecentActionsControllerNode -peer migration; see postbox-refactor-log "Wave 103 outcome" for the -forensics. - -Co-Authored-By: Claude Opus 4.7 (1M context) -EOF -)" -``` - -- [ ] **Step 4: Verify commit** - -```sh -git log --oneline -1 -``` - -Expected: shows the wave 103 (retry) commit as HEAD. - ---- - -## Task 6: Update outcome log + memory - -**Files:** -- Modify: `docs/superpowers/postbox-refactor-log.md` -- Modify: `~/.claude/projects/-Users-isaac-build-telegram-telegram-ios/memory/project_postbox_refactor_next_wave.md` -- Modify: `~/.claude/projects/-Users-isaac-build-telegram-telegram-ios/memory/MEMORY.md` - -- [ ] **Step 1: Append wave 103 (retry) outcome to refactor log** - -Append a "Wave 103 (retry) outcome" entry to `docs/superpowers/postbox-refactor-log.md`. Include: -- Commit hash (from Task 5 step 4). -- Iteration count (1 if first-pass-clean; 2 if Task 3 step 2 fired). -- Bazel build duration. -- Net-delta accounting: −5 raw `mediaBox.X` accesses, +5 facade calls, +5 `EngineMediaResource.Id(...)` wraps (canonical engine-side, not Postbox bridges). -- Wave-shape note: G drain, validates the wave-94 facade across an additional 2-module footprint. - -- [ ] **Step 2: Update next-wave memory** - -Edit `project_postbox_refactor_next_wave.md`: -- Add wave 103 (retry) outcome line into the recent-waves section. -- Mark the 5 sites as drained; remove from candidate inventories (the file currently lists "Wave 95+ candidates" with stale storeResourceData entries — clean those up). -- Update the top frontmatter `description` to reflect wave 103 (retry) landed. -- Promote next candidate. Options: 7-site `resourceData(...)` drain (would need a new facade method or use existing `data(resource:)`), DirectMediaImageCache Shape-C/D, or pivot to a foundational wave. - -- [ ] **Step 3: Update MEMORY.md index** - -Edit `~/.claude/projects/-Users-isaac-build-telegram-telegram-ios/memory/MEMORY.md`: -- Update the `[Postbox refactor next wave]` line to mention wave 103 (retry) landed. - -- [ ] **Step 4: Commit the doc update** - -```sh -git add docs/superpowers/postbox-refactor-log.md -git commit -m "$(cat <<'EOF' -docs: log wave 103 (retry) outcome - -Co-Authored-By: Claude Opus 4.7 (1M context) -EOF -)" -``` - -(Memory file updates are not committed — they live outside the repo.) - ---- - -## Net delta projection - -| Category | Count | Sites | -|---|---|---| -| Raw `mediaBox.X` access drops | −5 | TUM:112 + WR:973, 1214, 1260, 1523 | -| Facade calls added | +5 | same sites, migrated form | -| `EngineMediaResource.Id(...)` wraps | +5 | canonical engine-side constructs (not Postbox bridges) | -| `import Postbox` drops | 0 | both files retain Postbox import for unrelated symbols | -| Postbox-free module count | 0 | no module dropped from the import list | - -**Total commit footprint:** 5 line edits (3 Edit calls) across 2 files, plus a docs commit for the outcome log. diff --git a/docs/superpowers/plans/2026-04-26-postbox-wave-104-account-manager-resource-data-drain-3-sites.md b/docs/superpowers/plans/2026-04-26-postbox-wave-104-account-manager-resource-data-drain-3-sites.md deleted file mode 100644 index de643a1f87..0000000000 --- a/docs/superpowers/plans/2026-04-26-postbox-wave-104-account-manager-resource-data-drain-3-sites.md +++ /dev/null @@ -1,331 +0,0 @@ -# Wave 104: accountManager.mediaBox.resourceData drain (3 clean sites) Implementation Plan - -> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. - -**Goal:** Drain 3 of 8 `accountManager.mediaBox.resourceData(...)` Shape-A sites against the existing wave-32 / wave-94 `AccountManagerResources.data(resource:)` facade. Wave 104 of the Postbox → TelegramEngine refactor. - -**Architecture:** Wave-shape-G drain with a documented consumer field rename. Single-file consumer migration in `submodules/WallpaperResources/Sources/WallpaperResources.swift`. 3 call rewrites + 3 consumer-side `.complete` → `.isComplete` renames, 6 Edit calls total. The remaining 5 of the original 8 `resourceData` candidates are deferred (2 cross a `MediaResourceData` flow-out cascade, 3 are coupled to postbox-side via `combineLatest` typed tuples). - -**Tech Stack:** Swift, Bazel via `Make.py`, no unit tests. Verification is the full-project debug-sim-arm64 build. - -**Iteration budget:** 1 (target first-pass-clean given verified pre-flight inventory). - -**Note on TDD:** This project has no unit tests. Each task writes the edits, then verifies via Bazel build + residue grep. - ---- - -## File Structure - -| File | Role | Changes | -|---|---|---| -| `submodules/WallpaperResources/Sources/WallpaperResources.swift` | Wallpaper resource pipeline | 3 call rewrites + 3 consumer renames | - -No public-API ripple — leaf-consumer migration against an existing facade. - ---- - -## Task 1: WallpaperResources.swift — call rewrites (3 edits) - -**Files:** -- Modify: `submodules/WallpaperResources/Sources/WallpaperResources.swift` - -**Edits in this task:** 3. - -- [ ] **Step 1: Migrate the call at line 957 (`reference.resource` argument)** - -Find: - -```swift - let maybeFetched = accountManager.mediaBox.resourceData(reference.resource, option: .complete(waitUntilFetchStatus: false), attemptSynchronously: synchronousLoad) -``` - -Replace with: - -```swift - let maybeFetched = accountManager.resources.data(resource: EngineMediaResource(reference.resource), attemptSynchronously: synchronousLoad) -``` - -Note: `waitUntilFetchStatus: false` is omitted because the facade default is `false`. The site explicitly passed `false`, so behavior is preserved. - -- [ ] **Step 2: Migrate the call at line 1164 (`fileReference.media.resource` argument)** - -Find: - -```swift - let maybeFetched = accountManager.mediaBox.resourceData(fileReference.media.resource, option: .complete(waitUntilFetchStatus: false), attemptSynchronously: synchronousLoad) -``` - -Replace with: - -```swift - let maybeFetched = accountManager.resources.data(resource: EngineMediaResource(fileReference.media.resource), attemptSynchronously: synchronousLoad) -``` - -Same `waitUntilFetchStatus: false` omission rationale. - -- [ ] **Step 3: Migrate the call at line 1264 (`file.file.resource` argument, no option)** - -Find: - -```swift - return accountManager.mediaBox.resourceData(file.file.resource) -``` - -Replace with: - -```swift - return accountManager.resources.data(resource: EngineMediaResource(file.file.resource)) -``` - -The original used the underlying `MediaBox.resourceData(_ resource:)` overload's defaults — facade defaults match exactly (`pathExtension: nil`, `waitUntilFetchStatus: false`, `attemptSynchronously: false`). - ---- - -## Task 2: WallpaperResources.swift — consumer-side `.complete` → `.isComplete` renames (3 edits) - -**Files:** -- Modify: `submodules/WallpaperResources/Sources/WallpaperResources.swift` - -**Edits in this task:** 3. - -`EngineMediaResource.ResourceData` exposes `.isComplete` (renamed from `MediaResourceData.complete`). All three migrated call sites have a single consumer-side `.complete` access on the migrated result that needs renaming. - -- [ ] **Step 1: Rename `maybeData.complete` at line 961 (consumer of site 957)** - -Find: - -```swift - if maybeData.complete { -``` - -Replace with: - -```swift - if maybeData.isComplete { -``` - -The leading whitespace (8 spaces) must match exactly. - -- [ ] **Step 2: Rename `maybeData.complete` at line 1168 (consumer of site 1164)** - -Find: - -```swift - if maybeData.complete && isSupportedTheme { -``` - -Replace with: - -```swift - if maybeData.isComplete && isSupportedTheme { -``` - -The leading whitespace (16 spaces) must match exactly. - -- [ ] **Step 3: Rename `data.complete` at line 1266 (consumer of site 1264)** - -Find: - -```swift - if data.complete, let imageData = try? Data(contentsOf: URL(fileURLWithPath: data.path)) { -``` - -Replace with: - -```swift - if data.isComplete, let imageData = try? Data(contentsOf: URL(fileURLWithPath: data.path)) { -``` - -The leading whitespace (36 spaces) must match exactly. - -The `data.path` access on the same line is unchanged — both `MediaResourceData.path` and `EngineMediaResource.ResourceData.path` are `String`. - ---- - -## Sites NOT touched (deferred) - -For the implementer's awareness — these `.complete` accesses on UNRELATED bindings stay raw and are NOT to be renamed: - -- `WallpaperResources.swift:968` — `return data.complete ? try? Data(contentsOf: URL(fileURLWithPath: data.path)) : nil` — this `data` is bound from `account.postbox.mediaBox.resourceData(...)` (postbox-side, not migrated). STAYS `.complete`. -- Other `.complete` accesses elsewhere in the file that aren't on the 3 migrated bindings — STAY. - -The 3 renames target only the 3 specific lines listed in Task 2 steps 1-3. Do NOT use `replace_all=true` for renames — bindings differ per scope. - ---- - -## Task 3: Full-project Bazel build - -**Files:** none (verification only). - -- [ ] **Step 1: Run the build** - -```sh -source ~/.zshrc 2>/dev/null; python3 build-system/Make/Make.py --overrideXcodeVersion \ - --cacheDir ~/telegram-bazel-cache \ - build \ - --configurationPath build-system/appstore-configuration.json \ - --gitCodesigningRepository git@gitlab.com:peter-iakovlev/fastlanematch.git \ - --gitCodesigningType development --gitCodesigningUseCurrent \ - --buildNumber=1 --configuration=debug_sim_arm64 -``` - -Expected: clean build (`bazel build complete` / `INFO: Build completed successfully`). No `--continueOnError`. Build cost projection: ~30-60s (consumer-only, foundational module rebuild fan-out). - -- [ ] **Step 2: If build fails, triage iteration** - -Common failure modes: -- **`EngineMediaResource` constructor not found** — verify `import TelegramCore` at the top of WallpaperResources.swift (it should already be there). If missing, add it. -- **Type mismatch on `resource:` parameter** — would suggest the argument expression isn't `MediaResource`-typed. STOP and check the actual type at the failing site. -- **Type mismatch on `.isComplete` rename** — if the closure parameter binding is somehow inferred wrong (e.g., Swift inferred the OLD `MediaResourceData` type because the call rewrite didn't take effect), the rename will fail. Re-read the diff and verify the call rewrite landed. -- **`data.path` type mismatch** — should not happen; both types expose `path: String`. If it does, STOP and re-read. - -If errors land outside WallpaperResources.swift: STOP and report BLOCKED. The wave is supposed to be self-contained. - -Iteration budget: 2. - ---- - -## Task 4: Post-edit residue grep - -**Files:** none (verification only). - -- [ ] **Step 1: Verify the 3 migrated call sites are gone** - -Run: - -```sh -grep -nE "accountManager\.mediaBox\.resourceData\(" submodules/WallpaperResources/Sources/WallpaperResources.swift -``` - -Expected: exactly 3 lines remaining (L33, L59, L401 — the deferred combineLatest sites). The migrated lines (originally 957, 1164, 1264) should NOT appear. - -- [ ] **Step 2: Verify the 3 renames are applied** - -Run: - -```sh -grep -nE "maybeData\.complete\b" submodules/WallpaperResources/Sources/WallpaperResources.swift -``` - -Expected: empty output. Both `maybeData.complete` accesses (originally L961, L1168) should be gone. - -```sh -grep -nE "if data\.complete," submodules/WallpaperResources/Sources/WallpaperResources.swift -``` - -Expected: no line at L1266 (the migrated site). Other `data.complete` accesses on postbox-side bindings (e.g., L968) may remain — those are out of scope. - ---- - -## Task 5: Commit the wave - -**Files:** none (git only). - -- [ ] **Step 1: Stage the 1 modified file** - -```sh -git add submodules/WallpaperResources/Sources/WallpaperResources.swift -``` - -- [ ] **Step 2: Confirm staging is clean** - -```sh -git status --short | grep -v "^??" -``` - -Expected: only the 1 staged file (line starting with `M `). The line `m build-system/bazel-rules/sourcekit-bazel-bsp` is pre-existing WIP and should NOT appear in the staged list. - -- [ ] **Step 3: Commit** - -```sh -git commit -m "$(cat <<'EOF' -Postbox -> TelegramEngine wave 104 - -Drain 3 accountManager.mediaBox.resourceData(...) Shape-A sites against -the existing wave-32 / wave-94 AccountManagerResources.data(resource:) -facade. Sites: WallpaperResources:957 (reference.resource), :1164 -(fileReference.media.resource), :1264 (file.file.resource). - -Migration: accountManager.mediaBox.resourceData(X, option: .complete( -waitUntilFetchStatus: false)[, attemptSynchronously: Y]) -> accountManager -.resources.data(resource: EngineMediaResource(X)[, attemptSynchronously: -Y]). Plus 3 consumer-side .complete -> .isComplete renames at L961, -L1168, L1266 to match EngineMediaResource.ResourceData field name. - -3 sites / 1 file / 6 Edit calls. Consumer-only build. - -Deferred: 2 sites in FetchCachedRepresentations.swift (482, 490) flow -data: MediaResourceData into fetchCachedScaled*Representation cascade; -3 sites in WallpaperResources (33, 59, 401) coupled to postbox-side via -combineLatest typed tuples. - -Co-Authored-By: Claude Opus 4.7 (1M context) -EOF -)" -``` - -- [ ] **Step 4: Verify commit** - -```sh -git log --oneline -1 -``` - -Expected: shows the wave 104 commit as HEAD. - ---- - -## Task 6: Update outcome log + memory - -**Files:** -- Modify: `docs/superpowers/postbox-refactor-log.md` -- Modify: `~/.claude/projects/-Users-isaac-build-telegram-telegram-ios/memory/project_postbox_refactor_next_wave.md` -- Modify: `~/.claude/projects/-Users-isaac-build-telegram-telegram-ios/memory/MEMORY.md` - -- [ ] **Step 1: Append wave 104 outcome to refactor log** - -Append a "Wave 104 outcome" entry to `docs/superpowers/postbox-refactor-log.md` matching the format of "Wave 103 (retry) outcome". Include: -- Commit hash (from Task 5 step 4). -- Iteration count (1 if first-pass-clean; 2 if Task 3 step 2 fired). -- Bazel build duration (from Task 3 step 1 output). -- Net-delta accounting: −3 raw `mediaBox.X` accesses, +3 facade calls, +3 `EngineMediaResource(...)` wraps, +3 consumer field renames. -- Wave-shape note: G drain with documented consumer field rename. The pre-flight identified a `MediaResourceData`-typed-function-parameter barrier (`fetchCachedScaled*Representation` family) that forced 2 sites into the deferred bucket — illustrates the wave-71-shadow lesson applied to result-type cascades, not just peer migrations. - -- [ ] **Step 2: Update next-wave memory** - -Edit `project_postbox_refactor_next_wave.md`: -- Add wave 104 outcome line into the recent-waves section. -- Update accountManager-side facade drain status table: `resourceData` count drops from 8 → 5 (3 drained, 5 deferred). -- Add a new section (or extend an existing one) documenting the "Postbox-typed-function-parameter barrier" pattern, with `Message.peers: SimpleDictionary` (wave-103 lesson) and now `fetchCachedScaled*Representation(resourceData: MediaResourceData)` as the two known instances. - -- [ ] **Step 3: Update MEMORY.md index** - -Edit `~/.claude/projects/-Users-isaac-build-telegram-telegram-ios/memory/MEMORY.md`: -- Update the `[Postbox refactor next wave]` line to mention wave 104 landed. - -- [ ] **Step 4: Commit the doc update** - -```sh -git add docs/superpowers/postbox-refactor-log.md -git commit -m "$(cat <<'EOF' -docs: log wave 104 outcome - -Co-Authored-By: Claude Opus 4.7 (1M context) -EOF -)" -``` - -(Memory file updates are not committed — they live outside the repo.) - ---- - -## Net delta projection - -| Category | Count | Sites | -|---|---|---| -| Raw `mediaBox.X` access drops | −3 | WR:957, 1164, 1264 | -| Facade calls added | +3 | same sites, migrated form | -| `EngineMediaResource(...)` wraps | +3 | canonical engine-side, not Postbox bridges | -| Consumer field renames | +3 | WR:961 (`maybeData.complete` → `.isComplete`), WR:1168 (same), WR:1266 (`data.complete` → `.isComplete`) | -| `import Postbox` drops | 0 | WallpaperResources retains import for unrelated symbols | - -**Total commit footprint:** 6 line edits in 1 file, plus a docs commit for the outcome log. diff --git a/docs/superpowers/plans/2026-04-26-postbox-wave-105-device-contact-info-subject-engine-peer.md b/docs/superpowers/plans/2026-04-26-postbox-wave-105-device-contact-info-subject-engine-peer.md deleted file mode 100644 index a191faea48..0000000000 --- a/docs/superpowers/plans/2026-04-26-postbox-wave-105-device-contact-info-subject-engine-peer.md +++ /dev/null @@ -1,489 +0,0 @@ -# Wave 105: DeviceContactInfoSubject enum payload Peer? → EnginePeer? Implementation Plan - -> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. - -**Goal:** Migrate `DeviceContactInfoSubject` enum's 3 case payloads + 2 callback signatures + 1 computed property from raw Postbox `Peer?` to `EnginePeer?`. Wave 105 of the Postbox → TelegramEngine refactor. - -**Architecture:** Multi-module enum-payload migration (wave-91 shape). 17 edits across 5 files. AccountContext.swift hosts the enum + property. DeviceContactInfoController.swift is the primary consumer. 4 construction sites in TelegramUI/PeerInfoUI/StoryContainerScreen/ChatController. Net wrap delta: −8 (drops 10, adds 2 at Chat-side construction barriers documented per spec). - -**Tech Stack:** Swift, Bazel via `Make.py`, no unit tests. Verification is the full-project debug-sim-arm64 build. - -**Iteration budget:** 1-3 (wave-91 precedent: 2 iter for similar shape). - -**Note on TDD:** No unit tests in this project. Each task writes the edits, then verifies via Bazel build + residue grep. - ---- - -## File Structure - -| File | Role | Edits | -|---|---|---| -| `submodules/AccountContext/Sources/AccountContext.swift` | Enum definition + computed property | 4 type-line edits | -| `submodules/PeerInfoUI/Sources/DeviceContactInfoController.swift` | Primary consumer | 9 edits (5 `_asPeer` drops + 3 `.flatMap` simplifications + 1 downcast rewrite) | -| `submodules/TelegramUI/Sources/ChatControllerOpenAttachmentMenu.swift` | Chat-side construction (Pattern E ADD bridges) | 1 Edit (replace_all=true covers 2 sites) | -| `submodules/TelegramUI/Components/Stories/StoryContainerScreen/Sources/StoryItemSetContainerViewSendMessage.swift` | Story-side construction | 1 edit | -| `submodules/TelegramUI/Sources/OpenChatMessage.swift` | OpenChatMessage construction | 1 edit | - ---- - -## Task 1: AccountContext.swift — enum + computed property type changes - -**File:** `submodules/AccountContext/Sources/AccountContext.swift` - -- [ ] **Step 1: Migrate the 3 enum case payloads (single Edit covers consecutive lines)** - -Find: - -```swift -public enum DeviceContactInfoSubject { - case vcard(Peer?, DeviceContactStableId?, DeviceContactExtendedData) - case filter(peer: Peer?, contactId: DeviceContactStableId?, contactData: DeviceContactExtendedData, completion: (Peer?, DeviceContactExtendedData) -> Void) - case create(peer: Peer?, contactData: DeviceContactExtendedData, isSharing: Bool, shareViaException: Bool, completion: (Peer?, DeviceContactStableId, DeviceContactExtendedData) -> Void) - - public var peer: Peer? { -``` - -Replace with: - -```swift -public enum DeviceContactInfoSubject { - case vcard(EnginePeer?, DeviceContactStableId?, DeviceContactExtendedData) - case filter(peer: EnginePeer?, contactId: DeviceContactStableId?, contactData: DeviceContactExtendedData, completion: (EnginePeer?, DeviceContactExtendedData) -> Void) - case create(peer: EnginePeer?, contactData: DeviceContactExtendedData, isSharing: Bool, shareViaException: Bool, completion: (EnginePeer?, DeviceContactStableId, DeviceContactExtendedData) -> Void) - - public var peer: EnginePeer? { -``` - -This single Edit covers all 4 type-line changes in `AccountContext.swift`. The `contactData: DeviceContactExtendedData` computed property (lines 719-727) is unaffected. - ---- - -## Task 2: DeviceContactInfoController.swift — Pattern D downcast rewrite (1 edit) - -**File:** `submodules/PeerInfoUI/Sources/DeviceContactInfoController.swift` - -- [ ] **Step 1: Rewrite the `as? TelegramUser` downcast at line 849** - -Find: - -```swift - if let peer = peer as? TelegramUser { -``` - -Replace with: - -```swift - if case let .user(peer) = peer { -``` - -The leading whitespace (8 spaces) must match exactly. The outer `peer: EnginePeer?` (from `case let .create(peer, ...) = subject` at L845) is shadowed inside the if-body by `peer: TelegramUser` (the `.user` case associated value). Inner body access (`peer.firstName`, `peer.lastName`, `peer.phone`) works on the rebinding. - ---- - -## Task 3: DeviceContactInfoController.swift — Pattern C `.flatMap` simplifications (3 edits) - -**File:** `submodules/PeerInfoUI/Sources/DeviceContactInfoController.swift` - -- [ ] **Step 1: Simplify `.vcard` case body at line 942** - -Find: - -```swift - case let .vcard(peer, id, data): - contactData = .single((peer.flatMap(EnginePeer.init), id, data)) -``` - -Replace with: - -```swift - case let .vcard(peer, id, data): - contactData = .single((peer, id, data)) -``` - -- [ ] **Step 2: Simplify `.filter` case body at line 944** - -Find: - -```swift - case let .filter(peer, id, data, _): - contactData = .single((peer.flatMap(EnginePeer.init), id, data)) -``` - -Replace with: - -```swift - case let .filter(peer, id, data, _): - contactData = .single((peer, id, data)) -``` - -- [ ] **Step 3: Simplify `.create` case body at line 946** - -Find: - -```swift - case let .create(peer, data, share, shareViaExceptionValue, _): - contactData = .single((peer.flatMap(EnginePeer.init), nil, data)) -``` - -Replace with: - -```swift - case let .create(peer, data, share, shareViaExceptionValue, _): - contactData = .single((peer, nil, data)) -``` - -After Task 1's enum migration, the destructured `peer: EnginePeer?` is the target type — `.flatMap(EnginePeer.init)` becomes a redundant round-trip. - ---- - -## Task 4: DeviceContactInfoController.swift — Pattern B `_asPeer` drops at completion calls (2 edits) - -**File:** `submodules/PeerInfoUI/Sources/DeviceContactInfoController.swift` - -- [ ] **Step 1: Drop `_asPeer()` at completion call line 1105** - -Find: - -```swift - completion(peerAndContactData.0?._asPeer(), filteredData) -``` - -Replace with: - -```swift - completion(peerAndContactData.0, filteredData) -``` - -`peerAndContactData.0` is `EnginePeer?` from the typed signal at L939. Completion's first parameter type changes from `Peer?` to `EnginePeer?` per Task 1. - -- [ ] **Step 2: Drop `_asPeer()` at completion call line 1224** - -Find: - -```swift - completion(contactIdAndData.2?._asPeer(), contactIdAndData.0, contactIdAndData.1) -``` - -Replace with: - -```swift - completion(contactIdAndData.2, contactIdAndData.0, contactIdAndData.1) -``` - -`contactIdAndData.2` is `EnginePeer?` per the typed signal `(DeviceContactStableId, DeviceContactExtendedData, EnginePeer?)?` declared at L1175. - ---- - -## Task 5: DeviceContactInfoController.swift — Pattern A `_asPeer` drops at construction (3 edits) - -**File:** `submodules/PeerInfoUI/Sources/DeviceContactInfoController.swift` - -- [ ] **Step 1: Drop `_asPeer()` at line 1289** - -Find: - -```swift - replaceControllerImpl?(deviceContactInfoController(context: context, environment: environment, subject: .vcard(peer?._asPeer(), contactId, contactData), completed: nil, cancelled: nil)) -``` - -Replace with: - -```swift - replaceControllerImpl?(deviceContactInfoController(context: context, environment: environment, subject: .vcard(peer, contactId, contactData), completed: nil, cancelled: nil)) -``` - -- [ ] **Step 2: Drop `_asPeer()` at line 1443** - -Find: - -```swift - parentController.present(deviceContactInfoController(context: ShareControllerAppAccountContext(context: context), environment: ShareControllerAppEnvironment(sharedContext: context.sharedContext), subject: .create(peer: peer?._asPeer(), contactData: contactData, isSharing: false, shareViaException: false, completion: { peer, stableId, contactData in -``` - -Replace with: - -```swift - parentController.present(deviceContactInfoController(context: ShareControllerAppAccountContext(context: context), environment: ShareControllerAppEnvironment(sharedContext: context.sharedContext), subject: .create(peer: peer, contactData: contactData, isSharing: false, shareViaException: false, completion: { peer, stableId, contactData in -``` - -- [ ] **Step 3: Drop `_asPeer()` at line 1489** - -Find: - -```swift - controller?.present(context.sharedContext.makeDeviceContactInfoController(context: ShareControllerAppAccountContext(context: context), environment: ShareControllerAppEnvironment(sharedContext: context.sharedContext), subject: .create(peer: peer?._asPeer(), contactData: contactData, isSharing: peer != nil, shareViaException: false, completion: { _, _, _ in -``` - -Replace with: - -```swift - controller?.present(context.sharedContext.makeDeviceContactInfoController(context: ShareControllerAppAccountContext(context: context), environment: ShareControllerAppEnvironment(sharedContext: context.sharedContext), subject: .create(peer: peer, contactData: contactData, isSharing: peer != nil, shareViaException: false, completion: { _, _, _ in -``` - -All 3 sites have `peer` source already typed as `EnginePeer?` per inventory. - ---- - -## Task 6: ChatControllerOpenAttachmentMenu.swift — Pattern E ADD wraps (1 Edit, 2 sites via replace_all=true) - -**File:** `submodules/TelegramUI/Sources/ChatControllerOpenAttachmentMenu.swift` - -- [ ] **Step 1: Add `.flatMap(EnginePeer.init)` wrap at lines 683 and 1850** - -Use Edit with `replace_all=true`. Find: - -```swift -subject: .filter(peer: peerAndContactData.0, contactId: nil, contactData: contactData, completion: { peer, contactData in -``` - -Replace with: - -```swift -subject: .filter(peer: peerAndContactData.0.flatMap(EnginePeer.init), contactId: nil, contactData: contactData, completion: { peer, contactData in -``` - -`replace_all=true` is required — both sites at L683 and L1850 share identical text. The upstream signal type is `(Peer?, DeviceContactExtendedData?)` (verified at L634 and L1822); `.flatMap(EnginePeer.init)` wraps `Peer?` to `EnginePeer?` to satisfy the migrated `.filter(peer: EnginePeer?, ...)` signature. - ---- - -## Task 7: StoryItemSetContainerViewSendMessage.swift — Pattern A `_asPeer` drop (1 edit) - -**File:** `submodules/TelegramUI/Components/Stories/StoryContainerScreen/Sources/StoryItemSetContainerViewSendMessage.swift` - -- [ ] **Step 1: Drop `_asPeer()` at line 2132** - -Find: - -```swift - let contactController = component.context.sharedContext.makeDeviceContactInfoController(context: ShareControllerAppAccountContext(context: component.context), environment: ShareControllerAppEnvironment(sharedContext: component.context.sharedContext), subject: .filter(peer: peerAndContactData.0?._asPeer(), contactId: nil, contactData: contactData, completion: { [weak self, weak view] peer, contactData in -``` - -Replace with: - -```swift - let contactController = component.context.sharedContext.makeDeviceContactInfoController(context: ShareControllerAppAccountContext(context: component.context), environment: ShareControllerAppEnvironment(sharedContext: component.context.sharedContext), subject: .filter(peer: peerAndContactData.0, contactId: nil, contactData: contactData, completion: { [weak self, weak view] peer, contactData in -``` - -`peerAndContactData.0` is `EnginePeer?` from the typed signal at this site (the presence of `?._asPeer()` confirms it). - ---- - -## Task 8: OpenChatMessage.swift — Pattern A `_asPeer` drop (1 edit) - -**File:** `submodules/TelegramUI/Sources/OpenChatMessage.swift` - -- [ ] **Step 1: Drop `_asPeer()` at line 443** - -Find: - -```swift - let controller = deviceContactInfoController(context: ShareControllerAppAccountContext(context: params.context), environment: ShareControllerAppEnvironment(sharedContext: params.context.sharedContext), updatedPresentationData: params.updatedPresentationData, subject: .vcard(peer?._asPeer(), nil, contactData), completed: nil, cancelled: nil) -``` - -Replace with: - -```swift - let controller = deviceContactInfoController(context: ShareControllerAppAccountContext(context: params.context), environment: ShareControllerAppEnvironment(sharedContext: params.context.sharedContext), updatedPresentationData: params.updatedPresentationData, subject: .vcard(peer, nil, contactData), completed: nil, cancelled: nil) -``` - -`peer` source is already `EnginePeer?` (the `?._asPeer()` confirms the source type). - ---- - -## Task 9: Full-project Bazel build - -**Files:** none (verification only). - -- [ ] **Step 1: Run the build with `--continueOnError`** - -```sh -source ~/.zshrc 2>/dev/null; python3 build-system/Make/Make.py --overrideXcodeVersion \ - --cacheDir ~/telegram-bazel-cache \ - build \ - --configurationPath build-system/appstore-configuration.json \ - --gitCodesigningRepository git@gitlab.com:peter-iakovlev/fastlanematch.git \ - --gitCodesigningType development --gitCodesigningUseCurrent \ - --buildNumber=1 --configuration=debug_sim_arm64 --continueOnError -``` - -`--continueOnError` enabled — multi-module wave; surface all errors at once if iter-1 fails. - -Expected: clean build. AccountContext is foundational; expect 60-180s build cost. - -- [ ] **Step 2: If build fails, triage iteration** - -Common failure modes (per wave-91 precedent): -- **Type mismatch on a destructured `peer`** — a destructure body may use `peer.X` where `X` is a Peer-protocol-only method not on EnginePeer. Pre-flight inventory found ZERO such sites, but verify the failing line. -- **`.id` access on EnginePeer? doesn't compile** — would indicate an EnginePeer.Id typealias regression (very unlikely; would have failed all prior waves). -- **`case let .user(peer) = peer` doesn't compile** — verify the outer `peer` is `EnginePeer?` (after migration) and not still `Peer?`. -- **A construction site missed an `_asPeer()` drop** — re-grep `_asPeer\(\)` over the 5 touched files. -- **Hidden `Peer?`-typed completion call site** — would indicate an unmigrated callback consumer. Re-grep across consumer module sources. - -If errors land outside the 5 touched files: STOP and report BLOCKED — the wave is supposed to be self-contained. - -Iteration budget: 3. - ---- - -## Task 10: Post-edit residue grep - -**Files:** none (verification only). - -- [ ] **Step 1: Construction-site `_asPeer` residue (expected empty)** - -```sh -grep -nE "subject:\s*\.(vcard|filter|create)\(.*_asPeer\(\)" \ - submodules/PeerInfoUI/Sources/DeviceContactInfoController.swift \ - submodules/TelegramUI/Components/Stories/StoryContainerScreen/Sources/StoryItemSetContainerViewSendMessage.swift \ - submodules/TelegramUI/Sources/OpenChatMessage.swift -``` - -- [ ] **Step 2: Completion `_asPeer` residue (expected empty)** - -```sh -grep -nE "completion\(.*_asPeer\(\)" submodules/PeerInfoUI/Sources/DeviceContactInfoController.swift -``` - -- [ ] **Step 3: `.flatMap(EnginePeer.init)` simplification residue (expected empty)** - -```sh -grep -nE "peer\.flatMap\(EnginePeer\.init\)" submodules/PeerInfoUI/Sources/DeviceContactInfoController.swift -``` - -- [ ] **Step 4: Downcast residue (expected empty)** - -```sh -grep -nE "peer as\? TelegramUser" submodules/PeerInfoUI/Sources/DeviceContactInfoController.swift -``` - -- [ ] **Step 5: ADD wraps applied (expected 2 lines)** - -```sh -grep -nE "peerAndContactData\.0\.flatMap\(EnginePeer\.init\)" submodules/TelegramUI/Sources/ChatControllerOpenAttachmentMenu.swift -``` - -Expected: 2 lines (originally L683 and L1850, line numbers may have shifted slightly). - ---- - -## Task 11: Commit the wave - -**Files:** none (git only). - -- [ ] **Step 1: Stage the 5 modified files** - -```sh -git add \ - submodules/AccountContext/Sources/AccountContext.swift \ - submodules/PeerInfoUI/Sources/DeviceContactInfoController.swift \ - submodules/TelegramUI/Sources/ChatControllerOpenAttachmentMenu.swift \ - submodules/TelegramUI/Components/Stories/StoryContainerScreen/Sources/StoryItemSetContainerViewSendMessage.swift \ - submodules/TelegramUI/Sources/OpenChatMessage.swift -``` - -- [ ] **Step 2: Confirm staging** - -```sh -git status --short | grep -v "^??" -``` - -Expected: 5 staged files (lines starting with `M `). The pre-existing `m build-system/bazel-rules/sourcekit-bazel-bsp` WIP marker should NOT appear in staged. - -- [ ] **Step 3: Commit** - -```sh -git commit -m "$(cat <<'EOF' -Postbox -> TelegramEngine wave 105 - -Migrate DeviceContactInfoSubject enum 3 case Peer? payloads + 2 callback -(Peer?, ...) -> Void signatures + 1 computed peer: Peer? property to -EnginePeer?. Wave-91-pattern multi-module enum-payload migration. - -Drops 10 wraps: -- 5 _asPeer() at construction sites: DeviceContactInfoController:1289, - 1443, 1489 + StoryItemSetContainerViewSendMessage:2132 + - OpenChatMessage:443. -- 2 _asPeer() at completion-call sites: - DeviceContactInfoController:1105, 1224. -- 3 .flatMap(EnginePeer.init) simplifications at - DeviceContactInfoController:942, 944, 946. - -Adds 2 ADD bridges: ChatControllerOpenAttachmentMenu:683, 1850 — both -construct .filter(peer:) from peerAndContactData.0 typed (Peer?, ...); -.flatMap(EnginePeer.init) wraps to EnginePeer?. Net wrap delta: -8. - -Plus 1 downcast rewrite: DeviceContactInfoController:849 — `if let peer -= peer as? TelegramUser` to `if case let .user(peer) = peer`. - -5 files / 17 edits. - -Co-Authored-By: Claude Opus 4.7 (1M context) -EOF -)" -``` - -- [ ] **Step 4: Verify commit** - -```sh -git log --oneline -1 -``` - ---- - -## Task 12: Update outcome log + memory - -**Files:** -- Modify: `docs/superpowers/postbox-refactor-log.md` -- Modify: `~/.claude/projects/-Users-isaac-build-telegram-telegram-ios/memory/project_postbox_refactor_next_wave.md` -- Modify: `~/.claude/projects/-Users-isaac-build-telegram-telegram-ios/memory/MEMORY.md` - -- [ ] **Step 1: Append wave 105 outcome to refactor log** - -Include: -- Commit hash (from Task 11 step 4). -- Iteration count (1 if first-pass-clean; 2-3 if Task 9 step 2 fired). -- Bazel build duration. -- Net-delta accounting: −10 wrap drops, +2 ADD wraps, +1 downcast rewrite. Net −8 wraps. -- Wave-shape note: wave-91-pattern multi-module enum-payload migration with full pre-flight inventory clearing layers 1-4 of the wave-71-shadow checklist. Documents the value of thorough pre-flight inventory: 17 mechanical edits with 0 surprises. - -- [ ] **Step 2: Update next-wave memory** - -Edit `project_postbox_refactor_next_wave.md`: -- Add wave 105 outcome line into the recent-waves section. -- Mark `DeviceContactInfoSubject` candidate as drained (currently bullet 9 in deferred list). -- Promote next candidate. - -- [ ] **Step 3: Update MEMORY.md index** - -Update the `[Postbox refactor next wave]` line. - -- [ ] **Step 4: Commit the doc update** - -```sh -git add docs/superpowers/postbox-refactor-log.md -git commit -m "$(cat <<'EOF' -docs: log wave 105 outcome - -Co-Authored-By: Claude Opus 4.7 (1M context) -EOF -)" -``` - -(Memory file updates not committed — they live outside the repo.) - ---- - -## Net delta projection - -| Category | Count | Sites | -|---|---|---| -| `_asPeer()` drops at construction | −5 | DCIC:1289, 1443, 1489 + SISCVSM:2132 + OCM:443 | -| `_asPeer()` drops at completion calls | −2 | DCIC:1105, 1224 | -| `.flatMap(EnginePeer.init)` simplifications | −3 | DCIC:942, 944, 946 | -| `.flatMap(EnginePeer.init)` ADD wraps | +2 | CCOAM:683, 1850 | -| Downcast → case-let | +1 | DCIC:849 | -| Type annotations migrated | 4 | AccountContext: 3 enum cases + 1 computed property | - -**Total commit footprint:** 17 line edits across 5 files, plus a docs commit for the outcome log. - -**Net wrap delta:** **−8** (the wave's headline metric). diff --git a/docs/superpowers/plans/2026-04-26-postbox-wave-106-import-drop-sweep.md b/docs/superpowers/plans/2026-04-26-postbox-wave-106-import-drop-sweep.md deleted file mode 100644 index b36195daf1..0000000000 --- a/docs/superpowers/plans/2026-04-26-postbox-wave-106-import-drop-sweep.md +++ /dev/null @@ -1,493 +0,0 @@ -# Wave 106: Speculative `import Postbox` Drop Sweep (round 2) Implementation Plan - -> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. - -**Goal:** Drop `import Postbox` from any consumer-module Swift file in `submodules/` whose remaining content no longer references a Postbox-only symbol. Wave 106 of the Postbox → TelegramEngine refactor — round 2 of the wave-93 speculative-drop sweep. - -**Architecture:** Procedural sweep with build-feedback loop. (1) inventory candidates → (2) pre-flight regex pre-restore → (3) drop imports en masse → (4) build with `--continueOnError` → (5) restore failures → iterate → (6) final clean build → (7) optional BUILD-dep sweep → (8) single atomic commit. No code semantic changes — only `import` and BUILD `deps` lines. - -**Tech Stack:** Swift, Bazel via `Make.py`, `grep`/`sed` for inventory, no unit tests. Verification is the full-project debug-sim-arm64 build. - -**Iteration budget:** 2-5 build cycles (wave-93 precedent: 2 iter — drop, restore, clean). - -**Note on TDD:** No unit tests in this project. Each task verifies via Bazel build + diff inspection. Build feedback IS the test. - -**Spec:** `docs/superpowers/specs/2026-04-26-postbox-wave-106-import-drop-sweep-design.md`. - ---- - -## File Structure - -| Artifact | Role | -|---|---| -| `/tmp/wave106-candidates.txt` | All consumer files currently `import Postbox` | -| `/tmp/wave106-skiplist.txt` | Files that match preemptive-restore regex (keep import) | -| `/tmp/wave106-droplist.txt` | candidates − skiplist; files to edit | -| `/tmp/wave106-build-iterN.log` | Per-iteration build log | -| `/tmp/wave106-restore-iterN.txt` | Files needing restore after iter N | -| `/tmp/wave106-final-droplist.txt` | Net dropped files after all iterations | -| `submodules/**/*.swift` | Edited files (single-line Edit each) | -| `submodules/**/BUILD` | (Optional Step 7) packages with no remaining Postbox imports | - ---- - -## Task 1: Pre-flight WIP check - -**File:** none (read-only). - -- [ ] **Step 1: Verify clean working tree (modulo known-persistent state)** - -Run: - -```sh -git status --short -``` - -Expected output: - -``` - m build-system/bazel-rules/sourcekit-bazel-bsp -?? build-system/tulsi/ -?? submodules/TgVoip/ -?? third-party/libx264/ -``` - -If output contains anything else (modified `M` files, other untracked dirs), HALT — there is unrelated WIP that would get tangled with the wave commit. Resolve before proceeding. - -- [ ] **Step 2: Confirm we are on `master`** - -Run: - -```sh -git branch --show-current -``` - -Expected: `master`. If not, stop and ask. - ---- - -## Task 2: Inventory candidate files - -**File:** none (read-only). - -- [ ] **Step 1: Build the candidate list** - -Run: - -```sh -grep -rl "^import Postbox" submodules --include="*.swift" \ - | grep -v "^submodules/Postbox/" \ - | grep -v "^submodules/TelegramCore/" \ - | grep -v "^submodules/TelegramApi/" \ - | sort -u > /tmp/wave106-candidates.txt -wc -l /tmp/wave106-candidates.txt -``` - -Expected: between ~700 and ~1200 files (wave-93-era was ~1200; waves 94-105 may have peeled some). - -- [ ] **Step 2: Sanity-check the exclusion filters worked** - -Run: - -```sh -grep -E "^submodules/(Postbox|TelegramCore|TelegramApi)/" /tmp/wave106-candidates.txt | head -5 -``` - -Expected: empty output (no excluded paths leaked through). - ---- - -## Task 3: Build the skip-list via preemptive regex - -**File:** none (read-only). - -- [ ] **Step 1: Run the combined skip-regex against candidates** - -The skip-regex is the union of three tiers from the spec. Run: - -```sh -grep -El "\bPostbox\b|\bMediaBox\b|\bMediaResource\b|\bMediaResourceData\b|\bMediaResourceId\b|\bPostboxCoding\b|\bPostboxDecoder\b|\bPostboxEncoder\b|\bMemoryBuffer\b|\bTempBoxFile\b|\bValueBoxKey\b|\bPostboxView\b|\bcombinedView\b|\bPeerId\b|\bMessageId\b|\bMediaId\b|\bMessageIndex\b|\bMessageAndThreadId\b|\bPeerNameIndex\b|\bStoryId\b|\bItemCollectionId\b|\bFetchResourceSourceType\b|\bFetchResourceError\b|\bPeer\b|\bMessage\b|\bMedia\b" \ - $(cat /tmp/wave106-candidates.txt) \ - | sort -u > /tmp/wave106-skiplist.txt -wc -l /tmp/wave106-skiplist.txt -``` - -Expected: most of the candidate list (likely 600-1100 files matched) — `\bPeer\b`, `\bMessage\b`, `\bMedia\b` are deliberately broad and catch many false positives. False positives are SAFE — they just mean fewer drops, not bad drops. - -- [ ] **Step 2: Compute the drop-list** - -Run: - -```sh -comm -23 /tmp/wave106-candidates.txt /tmp/wave106-skiplist.txt > /tmp/wave106-droplist.txt -wc -l /tmp/wave106-droplist.txt -head -20 /tmp/wave106-droplist.txt -``` - -Expected: 5-50 files in the drop-list (wave 93 had 12). If 0, the regex is over-matching — halt and revisit. If >100, the regex is under-matching — halt, expand patterns, re-run. - -- [ ] **Step 3: Spot-verify 3 random drop candidates** - -Run for each of 3 files from the head of the drop-list: - -```sh -head -3 /tmp/wave106-droplist.txt | while read f; do - echo "=== $f ===" - grep -nE "Postbox|MediaBox|MediaResource|PeerId|MessageId|MediaId|MessageIndex" "$f" | head -5 -done -``` - -Expected: Only `import Postbox` line appears. If any other Postbox-token appears, the file should have been skipped — add the missing pattern to the regex in Step 1, redo Steps 1-2, and re-spot-check. - ---- - -## Task 4: Drop `import Postbox` from drop-list files - -**Files:** every path listed in `/tmp/wave106-droplist.txt`. - -- [ ] **Step 1: Read each drop-list file's import block to locate the exact `import Postbox` line** - -For each file in the drop-list, the line is `import Postbox` (exact match, no whitespace variations expected). Use a single-purpose `sed` to remove it from all drop-list files: - -```sh -while read f; do - sed -i '' '/^import Postbox$/d' "$f" -done < /tmp/wave106-droplist.txt -``` - -The `sed -i ''` syntax is BSD/macOS specific — required on Darwin. - -- [ ] **Step 2: Verify the imports were removed** - -Run: - -```sh -grep -lE "^import Postbox$" $(cat /tmp/wave106-droplist.txt) | wc -l -``` - -Expected: 0 (no file in the drop-list still contains `import Postbox`). - -- [ ] **Step 3: Verify no other lines were touched** - -Run: - -```sh -git diff --stat | tail -5 -git diff --shortstat -``` - -Expected: same number of files modified as drop-list size. Each file should show `-1` insertion (or `-1` deletion). If any file shows multiple deletions, something went wrong — `git checkout -- $(cat /tmp/wave106-droplist.txt)` and investigate. - ---- - -## Task 5: Build iteration 1 — capture failures - -**File:** none (build only). - -- [ ] **Step 1: Run the build with `--continueOnError`** - -Run: - -```sh -source ~/.zshrc 2>/dev/null && \ -python3 build-system/Make/Make.py --overrideXcodeVersion \ - --cacheDir ~/telegram-bazel-cache \ - build \ - --configurationPath build-system/appstore-configuration.json \ - --gitCodesigningRepository git@gitlab.com:peter-iakovlev/fastlanematch.git \ - --gitCodesigningType development --gitCodesigningUseCurrent --buildNumber=1 \ - --configuration=debug_sim_arm64 \ - --continueOnError 2>&1 | tee /tmp/wave106-build-iter1.log -``` - -Expected: Build completes (with errors). Wall-clock 30-260s depending on cache state. - -- [ ] **Step 2: Extract failing files** - -Run: - -```sh -grep -E ":[0-9]+:[0-9]+: error:" /tmp/wave106-build-iter1.log \ - | awk -F: '{print $1}' \ - | sort -u > /tmp/wave106-restore-iter1.txt -wc -l /tmp/wave106-restore-iter1.txt -cat /tmp/wave106-restore-iter1.txt -``` - -Expected: a subset of the drop-list. Wave 93 saw 5 of 12 needing restore. If the count > 50% of drop-list, the regex is missing a major pattern — HALT, analyze the failure cluster, add the missing pattern to Task 3 Step 1, restart from Task 4. - -- [ ] **Step 3: Verify no errors in TelegramCore/Postbox/TelegramApi** - -Run: - -```sh -grep -E "^submodules/(TelegramCore|Postbox|TelegramApi)/" /tmp/wave106-restore-iter1.txt -``` - -Expected: empty. If non-empty: HALT immediately, `git checkout -- submodules/`, and revert the wave — scope drift indicates the candidate filter or sed pattern is wrong. - ---- - -## Task 6: Restore failing files (iter 1) - -**Files:** every path in `/tmp/wave106-restore-iter1.txt`. - -- [ ] **Step 1: Re-add `import Postbox` to each failing file** - -Use awk uniformly (BSD `sed -i '' 'i\'` line-continuation is fragile inside shell loops). Insert `import Postbox` immediately before `import TelegramCore` if present, else immediately after the first existing `import ` line: - -```sh -while read f; do - awk ' - BEGIN { added = 0 } - !added && /^import TelegramCore$/ { print "import Postbox"; print; added = 1; next } - { print } - END { - if (!added) { - # fallback path was not used — try post-first-import injection - # (this END block is a no-op; awk cannot re-emit lines after END) - } - } - ' "$f" > "$f.tmp" - if ! grep -q "^import Postbox$" "$f.tmp"; then - # no TelegramCore anchor found — fall back to "after first import" - awk ' - BEGIN { added = 0 } - !added && /^import / { print; print "import Postbox"; added = 1; next } - { print } - ' "$f" > "$f.tmp" - fi - mv "$f.tmp" "$f" -done < /tmp/wave106-restore-iter1.txt -``` - -- [ ] **Step 2: Verify restorations** - -Run: - -```sh -grep -L "^import Postbox$" $(cat /tmp/wave106-restore-iter1.txt) -``` - -Expected: empty (every file in the restore list now contains `import Postbox` again). - -- [ ] **Step 3: Update the working drop-list** - -Run: - -```sh -comm -23 /tmp/wave106-droplist.txt /tmp/wave106-restore-iter1.txt > /tmp/wave106-final-droplist.txt -wc -l /tmp/wave106-final-droplist.txt -``` - -This is the current "successfully dropped" set. - ---- - -## Task 7: Build iteration 2 — verify clean (or iterate further) - -**File:** none (build only). - -- [ ] **Step 1: Re-run the build with `--continueOnError`** - -Run: - -```sh -source ~/.zshrc 2>/dev/null && \ -python3 build-system/Make/Make.py --overrideXcodeVersion \ - --cacheDir ~/telegram-bazel-cache \ - build \ - --configurationPath build-system/appstore-configuration.json \ - --gitCodesigningRepository git@gitlab.com:peter-iakovlev/fastlanematch.git \ - --gitCodesigningType development --gitCodesigningUseCurrent --buildNumber=1 \ - --configuration=debug_sim_arm64 \ - --continueOnError 2>&1 | tee /tmp/wave106-build-iter2.log -``` - -- [ ] **Step 2: Extract any new failures** - -Run: - -```sh -grep -E ":[0-9]+:[0-9]+: error:" /tmp/wave106-build-iter2.log \ - | awk -F: '{print $1}' \ - | sort -u > /tmp/wave106-restore-iter2.txt -wc -l /tmp/wave106-restore-iter2.txt -``` - -- [ ] **Step 3: If non-empty, repeat Task 6 with `iter2.txt` and run Task 7 again as iter3.** - -Stop when: -- `restore-iterN.txt` is empty → proceed to Task 8. -- `N == 5` → HALT (diminishing returns); commit what is green via Task 9. - -Each repeat: substitute `iter1` → `iter2` → `iter3` etc. throughout. Update the final-droplist after each restore: `comm -23 /tmp/wave106-final-droplist.txt /tmp/wave106-restore-iterN.txt > /tmp/wave106-final-droplist.txt.new && mv /tmp/wave106-final-droplist.txt.new /tmp/wave106-final-droplist.txt`. - ---- - -## Task 8: Final clean build (no `--continueOnError`) - -**File:** none (build only). - -- [ ] **Step 1: Run a clean build to confirm no inter-module ordering issue was masked** - -Run: - -```sh -source ~/.zshrc 2>/dev/null && \ -python3 build-system/Make/Make.py --overrideXcodeVersion \ - --cacheDir ~/telegram-bazel-cache \ - build \ - --configurationPath build-system/appstore-configuration.json \ - --gitCodesigningRepository git@gitlab.com:peter-iakovlev/fastlanematch.git \ - --gitCodesigningType development --gitCodesigningUseCurrent --buildNumber=1 \ - --configuration=debug_sim_arm64 2>&1 | tail -30 -``` - -Expected: build success, no `error:` lines in the tail. If failure: an inter-module visibility issue exists that `--continueOnError` masked. Restore the final-droplist file(s) implicated by the error, repeat Task 7 / Task 8. - ---- - -## Task 9 (optional): BUILD-dep sweep - -**Files:** various `submodules/*/BUILD` files. - -This step removes `//submodules/Postbox` from any Bazel package whose Swift sources no longer contain `import Postbox`. Skip this task if iteration time is constrained — the import drops alone are the core wave value; deps trim is housekeeping. - -- [ ] **Step 1: Find packages whose `BUILD` still depends on `//submodules/Postbox` but whose `Sources/**/*.swift` no longer imports it** - -Run: - -```sh -for build in $(find submodules -name BUILD -not -path "submodules/Postbox/*"); do - pkg_dir=$(dirname "$build") - if grep -q "//submodules/Postbox" "$build" 2>/dev/null; then - if ! grep -rq "^import Postbox$" "$pkg_dir" --include="*.swift" 2>/dev/null; then - echo "$build" - fi - fi -done > /tmp/wave106-build-deps-candidates.txt -wc -l /tmp/wave106-build-deps-candidates.txt -cat /tmp/wave106-build-deps-candidates.txt -``` - -Expected: 0-5 candidates. If 0, skip to Task 10. - -- [ ] **Step 2: For each candidate BUILD, locate the `//submodules/Postbox` line and remove it via Edit** - -Note that BUILD files often list deps as either `"//submodules/Postbox"` (string) or via aliases. Use Read to inspect each, then Edit to drop just the dep line. The exact string pattern varies — typically `"//submodules/Postbox",` on its own line within a `deps = [ ... ]` block. - -For each candidate file, Read the lines around the match, then Edit to remove the line preserving the surrounding bracket structure. - -- [ ] **Step 3: Re-run the clean build (no `--continueOnError`) to confirm no dep was load-bearing** - -Run the same command as Task 8 Step 1. - -If failure: a transitive dep was being satisfied through Postbox. Restore the dep line(s) implicated by the error and re-run. - ---- - -## Task 10: Commit the wave - -**File:** `git`. - -- [ ] **Step 1: Inspect final diff statistics** - -Run: - -```sh -git diff --stat -git diff --shortstat -``` - -Expected: N file modifications, all `-1` line changes (just `import Postbox` lines), possibly plus a small number of BUILD diffs from Task 9. - -- [ ] **Step 2: Confirm only allowed paths are touched** - -Run: - -```sh -git diff --name-only | grep -vE "^submodules/" | head -5 -git diff --name-only | grep -E "^submodules/(Postbox|TelegramCore|TelegramApi)/" | head -5 -``` - -Both expected: empty. If either has output: HALT — rogue changes exist; investigate before committing. - -- [ ] **Step 3: Stage only the modified Swift and BUILD files** - -Run: - -```sh -git add $(git diff --name-only) -git status --short -``` - -Expected: all changes staged with `M`. Untracked dirs (`build-system/tulsi/`, `submodules/TgVoip/`, `third-party/libx264/`) and the `m` submodule marker remain untouched. - -- [ ] **Step 4: Commit with the wave message** - -Substitute `` with the count from `/tmp/wave106-final-droplist.txt`, `` with the total restored across iterations, and `` with the BUILD deps removed (0 if Task 9 skipped). - -```sh -N=$(wc -l < /tmp/wave106-final-droplist.txt | tr -d ' ') -M=$(cat /tmp/wave106-restore-iter*.txt 2>/dev/null | sort -u | wc -l | tr -d ' ') -K=$(git diff --cached --name-only | grep -c BUILD) - -git commit -m "$(cat < TelegramEngine wave 106 (import drop sweep round 2) - -Speculative drop of \`import Postbox\` in $N files where the last -Postbox-typed symbol reference was peeled off by waves 94-105. -Methodology: pattern-based pre-flight skip + drop + build-feedback -restore loop (wave-93-validated recipe). $M files restored after build. -$K BUILD deps removed. - -Co-Authored-By: Claude Opus 4.7 (1M context) -EOF -)" -git status --short -``` - -Expected: clean commit, working tree returns to the known-persistent untracked-only state. - ---- - -## Task 11: Update memory file with wave outcome - -**File:** `/Users/isaac/.claude/projects/-Users-isaac-build-telegram-telegram-ios/memory/project_postbox_refactor_next_wave.md`. - -- [ ] **Step 1: Read the current memory file to find the recent-commits section** - -Read the top section listing wave commits. - -- [ ] **Step 2: Insert a wave-106 line below the wave-105 entry** - -Append (substituting the actual commit hash from `git log -1 --format=%H | head -c 10`): - -```markdown -- `` — wave 106: speculative `import Postbox` drop sweep round 2. files dropped, restored after build feedback. Methodology re-run of wave 93 (`72de7c4fd5`) with expanded pre-flight regex (added bare-name escapes `\bPeer\b`/`\bMessage\b`/`\bMedia\b` per wave-93 lesson). BUILD deps removed. build cycles. -``` - -Update the memory file's `description:` frontmatter to reflect wave 106 as the latest. - ---- - -## Halt-and-revert recipe (if anything goes seriously wrong) - -If at any point the build fails in TelegramCore/Postbox/TelegramApi, or iteration count exceeds 5 with non-trivial residue, or scope drifts beyond the spec: - -```sh -git checkout -- submodules/ -git status --short # should match the pre-flight expected output -``` - -The wave is fully reversible until Task 10 commits. - ---- - -## Plan Self-Review Notes - -- **Spec coverage:** Tasks 1-11 map 1:1 to the 8-step procedure in the spec plus pre-flight (Task 1) and post-commit memory update (Task 11). Halt conditions appear in Tasks 5/7/9 and the final halt-and-revert recipe. -- **Placeholder scan:** No TBDs/TODOs. All ``/``/``/`` are explicitly substituted via shell expansion in Step 4 of Task 10. -- **Type/method consistency:** Single-purpose tasks operating on filesystem and grep — no method-name drift risk. -- **Iteration shape:** Tasks 5-7 form the iteration loop; Task 8 is the validation gate; Task 9 is optional housekeeping; Task 10 commits. diff --git a/docs/superpowers/plans/2026-04-26-postbox-wave-106-pivot-engine-data-incremental.md b/docs/superpowers/plans/2026-04-26-postbox-wave-106-pivot-engine-data-incremental.md deleted file mode 100644 index fdf4edb3b9..0000000000 --- a/docs/superpowers/plans/2026-04-26-postbox-wave-106-pivot-engine-data-incremental.md +++ /dev/null @@ -1,223 +0,0 @@ -# Wave 106 Pivot: engine `data(resource:incremental:)` facade extension + 1-site drain - -> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. - -**Goal:** Pivot wave 106 from the abandoned import-drop sweep to a small facade-extension wave. Add an `incremental: Bool = false` parameter to `TelegramEngine.Resources.data(resource:)`, drain the 1 live `account.postbox.mediaBox.resourceData(..., option: .incremental(...))` consumer site (`ChatInterfaceStateContextMenus.swift:1327`). - -**Background — wave 106 (pure sweep) abandoned 2026-04-26:** Inventory of 576 candidate files showed every one of them legitimately references at least one Postbox-tier token (Postbox/MediaBox/MediaResource/protocol-Peer/protocol-Message/protocol-Media/typealiased identifier). Wave 93's pure import-sweep pattern is exhausted at the file granularity — no single-file orphans remain. See spec `docs/superpowers/specs/2026-04-26-postbox-wave-106-import-drop-sweep-design.md` (committed) for the abandoned methodology. - -**Architecture:** Wave-shape G (facade addition + small validation drain). 2 file edits (1 in TelegramCore, 1 in TelegramUI). Single-iter expected. - -**Tech Stack:** Swift, Bazel via `Make.py`, no unit tests. Verification is the full-project debug-sim-arm64 build. - -**Iteration budget:** 1-2 (TelegramCore touch incurs ~210-260s build). - ---- - -## File Structure - -| File | Role | Edits | -|---|---|---| -| `submodules/TelegramCore/Sources/TelegramEngine/Resources/TelegramEngineResources.swift` | Add `incremental` param to `data(resource:)` facade | 1 Edit (signature + body) | -| `submodules/TelegramUI/Sources/ChatInterfaceStateContextMenus.swift` | Migrate L1327 call site | 1 Edit (call + `data.complete` → `data.isComplete`) | - ---- - -## Task 1: Extend the engine `data(resource:)` facade with `incremental:` parameter - -**File:** `submodules/TelegramCore/Sources/TelegramEngine/Resources/TelegramEngineResources.swift` - -- [ ] **Step 1: Edit the `data(resource:)` facade signature and body** - -Find at line 453-466: - -```swift - public func data( - resource: EngineMediaResource, - pathExtension: String? = nil, - waitUntilFetchStatus: Bool = false, - attemptSynchronously: Bool = false - ) -> Signal { - return self.account.postbox.mediaBox.resourceData( - resource._asResource(), - pathExtension: pathExtension, - option: .complete(waitUntilFetchStatus: waitUntilFetchStatus), - attemptSynchronously: attemptSynchronously - ) - |> map { EngineMediaResource.ResourceData($0) } - } -``` - -Replace with: - -```swift - public func data( - resource: EngineMediaResource, - pathExtension: String? = nil, - waitUntilFetchStatus: Bool = false, - incremental: Bool = false, - attemptSynchronously: Bool = false - ) -> Signal { - let option: MediaBoxFetchDataOption = incremental - ? .incremental(waitUntilFetchStatus: waitUntilFetchStatus) - : .complete(waitUntilFetchStatus: waitUntilFetchStatus) - return self.account.postbox.mediaBox.resourceData( - resource._asResource(), - pathExtension: pathExtension, - option: option, - attemptSynchronously: attemptSynchronously - ) - |> map { EngineMediaResource.ResourceData($0) } - } -``` - -The `incremental` parameter is inserted between `waitUntilFetchStatus` and `attemptSynchronously`. Existing call sites passing only labeled-or-trailing arguments remain compatible because Swift requires labels for these (no positional ordering issue). - ---- - -## Task 2: Migrate the consumer call site - -**File:** `submodules/TelegramUI/Sources/ChatInterfaceStateContextMenus.swift` - -- [ ] **Step 1: Edit L1327 — replace `account.postbox.mediaBox.resourceData(...)` with engine facade** - -Find at line 1327: - -```swift - let _ = (context.account.postbox.mediaBox.resourceData(largest.resource, option: .incremental(waitUntilFetchStatus: false)) -``` - -Replace with: - -```swift - let _ = (context.engine.resources.data(resource: EngineMediaResource(largest.resource), incremental: true) -``` - -- [ ] **Step 2: Rename downstream `data.complete` field access to `data.isComplete`** - -Find at line 1330: - -```swift - if data.complete, let imageData = try? Data(contentsOf: URL(fileURLWithPath: data.path)) { -``` - -Replace with: - -```swift - if data.isComplete, let imageData = try? Data(contentsOf: URL(fileURLWithPath: data.path)) { -``` - -The `.path` field name is unchanged (both `MediaResourceData` and `EngineMediaResource.ResourceData` use `path`). - ---- - -## Task 3: Verify residue and build - -- [ ] **Step 1: Residue grep for the migrated expression** - -Run: - -```sh -grep -nE "context\.account\.postbox\.mediaBox\.resourceData\(.*option: \.incremental" submodules/TelegramUI/Sources/ChatInterfaceStateContextMenus.swift -``` - -Expected: empty. - -- [ ] **Step 2: Verify the new facade signature compiles without breaking existing callers** - -Existing call sites of `engine.resources.data(resource:)` use these forms (per wave 32+ history): -- `engine.resources.data(resource: EngineMediaResource(x))` — default args, fine -- `engine.resources.data(resource: EngineMediaResource(x), pathExtension: "ext")` — labeled, fine -- `engine.resources.data(resource: EngineMediaResource(x), waitUntilFetchStatus: true)` — labeled, fine - -Adding `incremental: Bool = false` between `waitUntilFetchStatus` and `attemptSynchronously` doesn't reorder existing call sites because all parameters use labels. Confirm with grep: - -```sh -grep -rnE "engine\.resources\.data\(resource:" submodules --include="*.swift" | wc -l -``` - -Just for visibility — number of existing call sites that should remain green. - -- [ ] **Step 3: Run the full clean build** - -Run: - -```sh -source ~/.zshrc 2>/dev/null && \ -python3 build-system/Make/Make.py --overrideXcodeVersion \ - --cacheDir ~/telegram-bazel-cache \ - build \ - --configurationPath build-system/appstore-configuration.json \ - --gitCodesigningRepository git@gitlab.com:peter-iakovlev/fastlanematch.git \ - --gitCodesigningType development --gitCodesigningUseCurrent --buildNumber=1 \ - --configuration=debug_sim_arm64 2>&1 | tail -30 -``` - -Expected: build success, no errors. If failure, fix in place and re-run (single iter expected). - ---- - -## Task 4: Commit the wave - -- [ ] **Step 1: Inspect diff** - -Run: - -```sh -git diff --stat -``` - -Expected: 2 files modified. - -- [ ] **Step 2: Stage and commit** - -```sh -git add submodules/TelegramCore/Sources/TelegramEngine/Resources/TelegramEngineResources.swift \ - submodules/TelegramUI/Sources/ChatInterfaceStateContextMenus.swift - -git commit -m "$(cat <<'EOF' -Postbox -> TelegramEngine wave 106 (pivot: engine data() incremental facade + 1-site drain) - -Original wave 106 pure import-drop sweep abandoned: 576 candidate files -all genuinely reference Postbox-tier tokens; wave 93's pattern exhausted -at file granularity (no single-file orphans remain). - -Pivot: extend engine.resources.data(resource:) facade with -`incremental: Bool = false` parameter. Drain the 1 live consumer site -(ChatInterfaceStateContextMenus:1327) plus consumer-side -`data.complete` -> `data.isComplete` rename. - -Co-Authored-By: Claude Opus 4.7 (1M context) -EOF -)" -``` - ---- - -## Task 5: Update memory file - -**File:** `/Users/isaac/.claude/projects/-Users-isaac-build-telegram-telegram-ios/memory/project_postbox_refactor_next_wave.md` - -- [ ] **Step 1: Update frontmatter description and append wave 106 entries** - -Update the `description:` line to reflect wave 106 (pivot). - -Append two lines under the recent-commits section: -- One for the abandoned wave 106 import-drop sweep with the key finding (sweep pattern exhausted, save future sessions a re-attempt). -- One for the wave 106 pivot commit hash with cost/yield. - -- [ ] **Step 2: Append a "Wave 106 ABANDONED" subsection** documenting the import-sweep exhaustion finding so future sessions don't re-attempt the pure sweep shape. Note the regex set tested and the conclusion ("any consumer file with `import Postbox` legitimately needs at least one Tier-1/Tier-2 token"). - ---- - -## Halt-and-revert recipe - -If build fails for non-trivial reasons (more than 1 iter): - -```sh -git checkout -- submodules/TelegramCore/Sources/TelegramEngine/Resources/TelegramEngineResources.swift \ - submodules/TelegramUI/Sources/ChatInterfaceStateContextMenus.swift -git status --short -``` - -Wave is reversible until Task 4 commits. diff --git a/docs/superpowers/plans/2026-04-30-typing-draft-send-delay.md b/docs/superpowers/plans/2026-04-30-typing-draft-send-delay.md deleted file mode 100644 index c2e2c5d5f3..0000000000 --- a/docs/superpowers/plans/2026-04-30-typing-draft-send-delay.md +++ /dev/null @@ -1,703 +0,0 @@ -# Typing-Draft Send Delay Implementation Plan - -> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. - -**Goal:** Park outgoing messages in `PendingMessageManager` after their content is uploaded, releasing them only when the typing-draft for the matching `(peerId, threadId)` clears. - -**Architecture:** Add a per-account Postbox view (`.allTypingDrafts`) that exposes the live `Set` of currently-active typing drafts. Subscribe once at `PendingMessageManager.init`. Add a parked state (`.waitingForSendGate`) to `PendingMessageState` and a forward parking lot dictionary on the manager. Gate at three sites (single-send, album-send, forward-send); drain on view updates that remove keys. - -**Tech Stack:** Swift, Bazel, Postbox view system, SwiftSignalKit. - -**Spec:** `docs/superpowers/specs/2026-04-30-typing-draft-send-delay-design.md` - -**Build verification command (used by every task that compiles code):** - -```sh -source ~/.zshrc 2>/dev/null; python3 build-system/Make/Make.py --overrideXcodeVersion --cacheDir ~/telegram-bazel-cache build --configurationPath build-system/appstore-configuration.json --gitCodesigningRepository git@gitlab.com:peter-iakovlev/fastlanematch.git --gitCodesigningType development --gitCodesigningUseCurrent --buildNumber=1 --configuration=debug_sim_arm64 --continueOnError -``` - -This codebase has **no unit tests** (per `CLAUDE.md`). Verification is "full build green" at each step plus manual exercise after final task. - ---- - -## File Structure - -**Files created:** -- `submodules/Postbox/Sources/AllTypingDraftsView.swift` — new Postbox view tracking the set of active typing-draft keys. - -**Files modified:** -- `submodules/Postbox/Sources/Views.swift` — register the new view key. -- `submodules/TelegramCore/Sources/State/PendingMessageManager.swift` — gate insertion, drain, subscription, parked-state plumbing. - -**No BUILD edits needed:** Postbox `BUILD` uses `glob(["Sources/**/*.swift"])`, so the new file is auto-picked up. - ---- - -## Task 1: Add `MutableAllTypingDraftsView` / `AllTypingDraftsView` - -**Files:** -- Create: `submodules/Postbox/Sources/AllTypingDraftsView.swift` - -This task adds the Postbox view file. It is **not yet wired** into `PostboxViewKey` (Task 2), so this commit alone will not change behavior. - -- [ ] **Step 1: Create `AllTypingDraftsView.swift`** - -```swift -import Foundation - -final class MutableAllTypingDraftsView: MutablePostboxView { - fileprivate var keys: Set - - init(postbox: PostboxImpl) { - self.keys = Set(postbox.currentTypingDrafts.keys) - } - - func replay(postbox: PostboxImpl, transaction: PostboxTransaction) -> Bool { - if transaction.updatedTypingDrafts.isEmpty { - return false - } - var updated = false - for (key, update) in transaction.updatedTypingDrafts { - if update.value != nil { - if self.keys.insert(key).inserted { - updated = true - } - } else { - if self.keys.remove(key) != nil { - updated = true - } - } - } - return updated - } - - func refreshDueToExternalTransaction(postbox: PostboxImpl) -> Bool { - let new = Set(postbox.currentTypingDrafts.keys) - if new == self.keys { - return false - } - self.keys = new - return true - } - - func immutableView() -> PostboxView { - return AllTypingDraftsView(self) - } -} - -public final class AllTypingDraftsView: PostboxView { - public let keys: Set - - init(_ view: MutableAllTypingDraftsView) { - self.keys = view.keys - } -} -``` - -- [ ] **Step 2: Verify the build (file is unwired, so it must compile standalone)** - -Run the build command from the header. Expected: **success**. Common failure modes: `currentTypingDrafts` access scope (already `fileprivate(set)`, accessible from same-module file); `transaction.updatedTypingDrafts` shape (already `[PeerAndThreadId: PostboxImpl.TypingDraftUpdate]` per `PostboxTransaction.swift:59`). - -- [ ] **Step 3: Commit** - -```bash -git add submodules/Postbox/Sources/AllTypingDraftsView.swift -git commit -m "Postbox: add AllTypingDraftsView tracking Set of active typing drafts" -``` - ---- - -## Task 2: Register `.allTypingDrafts` in `PostboxViewKey` - -**Files:** -- Modify: `submodules/Postbox/Sources/Views.swift` - -- [ ] **Step 1: Add the case to the enum** - -In `submodules/Postbox/Sources/Views.swift` line 105, append `.allTypingDrafts` after `.typingDrafts(...)`: - -```swift - case typingDrafts(PeerAndThreadId) - case allTypingDrafts -``` - -- [ ] **Step 2: Add hash arm** - -In the `hash(into:)` switch (the new arm goes alongside the existing `case let .typingDrafts(peerId):` arm at line 232–233): - -```swift - case let .typingDrafts(peerId): - hasher.combine(peerId) - case .allTypingDrafts: - hasher.combine(22) -``` - -The constant `22` is the next free hash-tag (existing tags use 0–21). - -- [ ] **Step 3: Add `==` arm** - -In the `==(lhs:rhs:)` switch (line 551–556 area): - -```swift - case let .typingDrafts(peerId): - if case .typingDrafts(peerId) = rhs { - return true - } else { - return false - } - case .allTypingDrafts: - if case .allTypingDrafts = rhs { - return true - } else { - return false - } -``` - -- [ ] **Step 4: Wire `postboxViewForKey`** - -In the `postboxViewForKey(postbox:key:)` switch (line 684–685 area): - -```swift - case let .typingDrafts(peerId): - return MutableTypingDraftsView(postbox: postbox, peerAndThreadId: peerId) - case .allTypingDrafts: - return MutableAllTypingDraftsView(postbox: postbox) - } -} -``` - -- [ ] **Step 5: Verify the build** - -Run the build command. Expected: **success**. The view is now constructible but no consumer subscribes yet. - -- [ ] **Step 6: Commit** - -```bash -git add submodules/Postbox/Sources/Views.swift -git commit -m "Postbox: wire .allTypingDrafts view key into PostboxViewKey" -``` - ---- - -## Task 3: Add `.waitingForSendGate` state and update related switches - -**Files:** -- Modify: `submodules/TelegramCore/Sources/State/PendingMessageManager.swift` - -This task introduces the new `PendingMessageState` case and extends every switch that needs to know about it. No gate insertion happens yet — the new case is unreachable, so behavior is unchanged. - -- [ ] **Step 1: Add the case to `PendingMessageState`** - -Edit `private enum PendingMessageState` (line 28). After the `.waitingToBeSent` case, add: - -```swift - case waitingToBeSent(groupId: Int64?, content: PendingMessageUploadedContentAndReuploadInfo) - case waitingForSendGate(groupId: Int64?, content: PendingMessageUploadedContentAndReuploadInfo) -``` - -- [ ] **Step 2: Extend the `groupId` computed property** - -In the same `var groupId: Int64?` switch (line 37–54), add an arm right after the `.waitingToBeSent` arm: - -```swift - case let .waitingToBeSent(groupId, _): - return groupId - case let .waitingForSendGate(groupId, _): - return groupId -``` - -- [ ] **Step 3: Extend `dataForPendingMessageGroup` to accept parked members as ready** - -Find `private func dataForPendingMessageGroup(_ groupId: Int64)` (line 753). After the `.waitingToBeSent` arm, add a parallel arm: - -```swift - case let .waitingToBeSent(contextGroupId, content): - if contextGroupId == groupId { - result.append((context, id, content)) - } - case let .waitingForSendGate(contextGroupId, content): - if contextGroupId == groupId { - result.append((context, id, content)) - } -``` - -This lets a partially-parked album drain correctly once the gate opens. - -- [ ] **Step 4: Exclude parked state from `updatePendingMediaUploads`** - -Find `private func updatePendingMediaUploads()` (line 262). Inside its `switch context.state { ... }`, the existing arms cover `.waitingForUploadToStart` and `.uploading`. Parked state is post-upload and should NOT report progress. The switch already has a `default: break` — `.waitingForSendGate` falls through it automatically. **No edit required**, but verify by re-reading the function after the previous edits compile. - -- [ ] **Step 5: Verify the build** - -Run the build command. Expected: **success**. Swift will reject the build if any `switch context.state { ... }` becomes non-exhaustive — fix any such switches by adding a `case .waitingForSendGate: ...` arm matching the closest existing parallel state. Likely candidates: - -- `private enum PendingMessageState`'s `groupId` switch — handled in Step 2. -- `dataForPendingMessageGroup` switch — handled in Step 3. -- The forward branch in `beginSendingMessages` (line ~614, doesn't switch directly). -- Any other `switch .state` blocks (search with `grep -n "switch.*\.state" submodules/TelegramCore/Sources/State/PendingMessageManager.swift`). - -If the compiler reports a non-exhaustive switch elsewhere, add an arm that mirrors the `.waitingToBeSent` arm in that switch, or `case .waitingForSendGate: break` if the new state is irrelevant to that site. - -- [ ] **Step 6: Commit** - -```bash -git add submodules/TelegramCore/Sources/State/PendingMessageManager.swift -git commit -m "PendingMessageManager: add .waitingForSendGate state and update related switches" -``` - ---- - -## Task 4: Add manager-level subscription and parked-state fields - -**Files:** -- Modify: `submodules/TelegramCore/Sources/State/PendingMessageManager.swift` - -Adds the dictionary, the disposable, the subscription in `init`, the disposal in `deinit`, and a stub `handleLiveTypingDraftsUpdate` that only stores the set (drain is wired in Task 5). - -- [ ] **Step 1: Add stored fields** - -In `public final class PendingMessageManager` (line 205), after the existing `private var pendingMessageIds = Set()` (line 232), add: - -```swift - private var pendingMessageIds = Set() - private var liveTypingDraftKeys: Set = [] - private let allTypingDraftsDisposable = MetaDisposable() - private var forwardSendGateGroups: [PeerAndThreadId: [[(PendingMessageContext, Message, ForwardSourceInfoAttribute)]]] = [:] - private let beginSendingMessagesDisposables = DisposableSet() -``` - -(The first and last lines are already present; the three new lines insert between them.) - -- [ ] **Step 2: Subscribe in `init`** - -In `init(network:postbox:accountPeerId:auxiliaryMethods:stateManager:localInputActivityManager:messageMediaPreuploadManager:revalidationContext:)` (line 243), after the field assignments (line 252), add: - -```swift - self.revalidationContext = revalidationContext - - let queue = self.queue - self.allTypingDraftsDisposable.set( - (postbox.combinedView(keys: [.allTypingDrafts]) - |> deliverOn(queue)).start(next: { [weak self] view in - self?.handleLiveTypingDraftsUpdate(view) - }) - ) - } -``` - -- [ ] **Step 3: Dispose in `deinit`** - -In `deinit` (line 255–260), append: - -```swift - deinit { - self.beginSendingMessagesDisposables.dispose() - for (_, disposable) in self.newTopicDisposables { - disposable.dispose() - } - self.allTypingDraftsDisposable.dispose() - } -``` - -- [ ] **Step 4: Add the handler (no drain yet)** - -Add this new private method anywhere in the class (e.g. just before `private func updatePendingMediaUploads()` at line 262): - -```swift - private func handleLiveTypingDraftsUpdate(_ combined: CombinedView) { - assert(self.queue.isCurrent()) - - let new: Set - if let view = combined.views[.allTypingDrafts] as? AllTypingDraftsView { - new = view.keys - } else { - new = [] - } - self.liveTypingDraftKeys = new - } -``` - -This handler is functional — it tracks the live key set correctly. Task 5 augments it to also fire `drainSendGate` for keys that just cleared. - -- [ ] **Step 5: Verify the build** - -Run the build command. Expected: **success**. `CombinedView` is in scope because `Postbox` is already imported at the top of the file. `MetaDisposable` and `Queue` come from `SwiftSignalKit` (already imported). - -- [ ] **Step 6: Commit** - -```bash -git add submodules/TelegramCore/Sources/State/PendingMessageManager.swift -git commit -m "PendingMessageManager: subscribe to .allTypingDrafts and add parking-lot fields" -``` - ---- - -## Task 5: Add gate predicates, drain, and wire the single-message gate - -**Files:** -- Modify: `submodules/TelegramCore/Sources/State/PendingMessageManager.swift` - -Combined task: introduces the predicates, the `drainSendGate` body, augments `handleLiveTypingDraftsUpdate` to call drain, and wires the **first** insertion site (single-message). After this task, single non-grouped messages park correctly when the peer is live-typing and unpark when the draft clears. - -- [ ] **Step 1: Add `shouldGateSend` and `isSendGateOpen` private helpers** - -Anywhere in the `PendingMessageManager` class (group them next to `handleLiveTypingDraftsUpdate` from Task 4): - -```swift - private func shouldGateSend(messageId: MessageId, threadId: Int64?) -> Bool { - if messageId.namespace == Namespaces.Message.ScheduledCloud { - return false - } - if messageId.peerId.namespace == Namespaces.Peer.SecretChat { - return false - } - if messageId.peerId == self.accountPeerId { - return false - } - if threadId == Message.newTopicThreadId { - return false - } - return true - } - - private func isSendGateOpen(for key: PeerAndThreadId) -> Bool { - return !self.liveTypingDraftKeys.contains(key) - } -``` - -- [ ] **Step 2: Augment `handleLiveTypingDraftsUpdate` to call drain** - -Replace the body of `handleLiveTypingDraftsUpdate(_:)` (added in Task 4) with the cleared-key drain logic: - -```swift - private func handleLiveTypingDraftsUpdate(_ combined: CombinedView) { - assert(self.queue.isCurrent()) - - let new: Set - if let view = combined.views[.allTypingDrafts] as? AllTypingDraftsView { - new = view.keys - } else { - new = [] - } - let cleared = self.liveTypingDraftKeys.subtracting(new) - self.liveTypingDraftKeys = new - for key in cleared { - self.drainSendGate(key: key) - } - } -``` - -- [ ] **Step 3: Add the `drainSendGate` body** - -Add this new private method next to `handleLiveTypingDraftsUpdate`: - -```swift - private func drainSendGate(key: PeerAndThreadId) { - assert(self.queue.isCurrent()) - - // (1) Single-message drain: snapshot then commit in messageId.id order. - var singleDrains: [(context: PendingMessageContext, messageId: MessageId, content: PendingMessageUploadedContentAndReuploadInfo)] = [] - for (id, context) in self.messageContexts { - if id.peerId != key.peerId { - continue - } - if context.threadId != key.threadId { - continue - } - if case let .waitingForSendGate(groupId, content) = context.state, groupId == nil { - singleDrains.append((context, id, content)) - } - } - singleDrains.sort(by: { $0.messageId.id < $1.messageId.id }) - for entry in singleDrains { - self.commitSendingSingleMessage(messageContext: entry.context, messageId: entry.messageId, content: entry.content) - } - - // (2) Grouped-album drain: collect distinct groupIds whose members match the key, - // iterate ascending by min messageId.id, fire commitSendingMessageGroup. - var groupKeys: [(groupId: Int64, minMessageId: Int32)] = [] - var seenGroupIds = Set() - for (id, context) in self.messageContexts { - if id.peerId != key.peerId { - continue - } - if context.threadId != key.threadId { - continue - } - if case let .waitingForSendGate(groupId, _) = context.state, let groupId = groupId { - if !seenGroupIds.contains(groupId) { - seenGroupIds.insert(groupId) - groupKeys.append((groupId, id.id)) - } else { - if let index = groupKeys.firstIndex(where: { $0.groupId == groupId }), id.id < groupKeys[index].minMessageId { - groupKeys[index].minMessageId = id.id - } - } - } - } - groupKeys.sort(by: { $0.minMessageId < $1.minMessageId }) - for (groupId, _) in groupKeys { - if let data = self.dataForPendingMessageGroup(groupId) { - self.commitSendingMessageGroup(groupId: groupId, messages: data) - } - } - - // (3) Forward drain: pop parked groups for this key in FIFO order; fire each. - if let parkedGroups = self.forwardSendGateGroups.removeValue(forKey: key) { - for messages in parkedGroups { - for (context, _, _) in messages { - context.state = .sending(groupId: nil) - } - let sendMessage: Signal = self.sendGroupMessagesContent(network: self.network, postbox: self.postbox, stateManager: self.stateManager, accountPeerId: self.accountPeerId, group: messages.map { data in - let (_, message, forwardInfo) = data - return (message.id, PendingMessageUploadedContentAndReuploadInfo(content: .forward(forwardInfo), reuploadInfo: nil, cacheReferenceKey: nil)) - }) - |> map { _ -> PendingMessageResult in - return .progress(1.0) - } - messages[0].0.sendDisposable.set((sendMessage - |> deliverOn(self.queue)).start()) - } - } - - self.updateWaitingUploads(peerId: key.peerId) - self.updatePendingMediaUploads() - } -``` - -The forward dispatch block mirrors the existing forward-fire code at lines 719–731 of `PendingMessageManager.swift`. Keep them in sync if either changes. - -- [ ] **Step 4: Wire the single-message gate at `beginSendingMessage`** - -Replace `private func beginSendingMessage(messageContext:messageId:groupId:content:)` (line 738) with: - -```swift - private func beginSendingMessage(messageContext: PendingMessageContext, messageId: MessageId, groupId: Int64?, content: PendingMessageUploadedContentAndReuploadInfo) { - if let groupId = groupId { - messageContext.state = .waitingToBeSent(groupId: groupId, content: content) - } else { - let key = PeerAndThreadId(peerId: messageId.peerId, threadId: messageContext.threadId) - if self.shouldGateSend(messageId: messageId, threadId: messageContext.threadId) && !self.isSendGateOpen(for: key) { - messageContext.state = .waitingForSendGate(groupId: nil, content: content) - } else { - self.commitSendingSingleMessage(messageContext: messageContext, messageId: messageId, content: content) - } - } - self.updatePendingMediaUploads() - } -``` - -- [ ] **Step 5: Verify the build** - -Run the build command. Expected: **success**. - -- [ ] **Step 6: Commit** - -```bash -git add submodules/TelegramCore/Sources/State/PendingMessageManager.swift -git commit -m "PendingMessageManager: wire typing-draft gate at single-message send + drain" -``` - ---- - -## Task 6: Wire the album-send gate at `commitSendingMessageGroup` - -**Files:** -- Modify: `submodules/TelegramCore/Sources/State/PendingMessageManager.swift` - -- [ ] **Step 1: Replace `commitSendingMessageGroup`** - -Replace `private func commitSendingMessageGroup(groupId:messages:)` (line 794) with: - -```swift - private func commitSendingMessageGroup(groupId: Int64, messages: [(messageContext: PendingMessageContext, messageId: MessageId, content: PendingMessageUploadedContentAndReuploadInfo)]) { - let firstMessageId = messages[0].messageId - let firstThreadId = messages[0].messageContext.threadId - let key = PeerAndThreadId(peerId: firstMessageId.peerId, threadId: firstThreadId) - if self.shouldGateSend(messageId: firstMessageId, threadId: firstThreadId) && !self.isSendGateOpen(for: key) { - for entry in messages { - entry.messageContext.state = .waitingForSendGate(groupId: groupId, content: entry.content) - } - return - } - - for (context, _, _) in messages { - context.state = .sending(groupId: groupId) - } - let sendMessage: Signal = self.sendGroupMessagesContent(network: self.network, postbox: self.postbox, stateManager: self.stateManager, accountPeerId: self.accountPeerId, group: messages.map { ($0.1, $0.2) }) - |> map { next -> PendingMessageResult in - return .progress(1.0) - } - messages[0].0.sendDisposable.set((sendMessage - |> deliverOn(self.queue)).start()) - } -``` - -Album members share `(peerId, threadId)` by construction (the album fires once every member is post-upload in the same `groupId`). - -- [ ] **Step 2: Verify the build** - -Run the build command. Expected: **success**. - -- [ ] **Step 3: Commit** - -```bash -git add submodules/TelegramCore/Sources/State/PendingMessageManager.swift -git commit -m "PendingMessageManager: wire typing-draft gate at album send" -``` - ---- - -## Task 7: Wire the forward-send gate inside `beginSendingMessages` - -**Files:** -- Modify: `submodules/TelegramCore/Sources/State/PendingMessageManager.swift` - -- [ ] **Step 1: Replace the forward-dispatch loop** - -The existing forward-dispatch loop is at lines 714–733 inside `beginSendingMessages`. Replace exactly the body of `for messages in countedMessageGroups { ... }` with the gate-aware version: - -```swift - for messages in countedMessageGroups { - if messages.isEmpty { - continue - } - - let firstMessage = messages[0].1 - let key = PeerAndThreadId(peerId: firstMessage.id.peerId, threadId: firstMessage.threadId) - if strongSelf.shouldGateSend(messageId: firstMessage.id, threadId: firstMessage.threadId) && !strongSelf.isSendGateOpen(for: key) { - for (context, _, forwardInfo) in messages { - context.state = .waitingForSendGate(groupId: nil, content: PendingMessageUploadedContentAndReuploadInfo(content: .forward(forwardInfo), reuploadInfo: nil, cacheReferenceKey: nil)) - } - if strongSelf.forwardSendGateGroups[key] == nil { - strongSelf.forwardSendGateGroups[key] = [] - } - strongSelf.forwardSendGateGroups[key]!.append(messages) - continue - } - - for (context, _, _) in messages { - context.state = .sending(groupId: nil) - } - - let sendMessage: Signal = strongSelf.sendGroupMessagesContent(network: strongSelf.network, postbox: strongSelf.postbox, stateManager: strongSelf.stateManager, accountPeerId: strongSelf.accountPeerId, group: messages.map { data in - let (_, message, forwardInfo) = data - return (message.id, PendingMessageUploadedContentAndReuploadInfo(content: .forward(forwardInfo), reuploadInfo: nil, cacheReferenceKey: nil)) - }) - |> map { next -> PendingMessageResult in - return .progress(1.0) - } - messages[0].0.sendDisposable.set((sendMessage - |> deliverOn(strongSelf.queue)).start()) - } -``` - -The non-gated branch is the existing code, copied verbatim. The gated branch parks every context in `.waitingForSendGate` and appends the whole tuple-array onto `forwardSendGateGroups[key]`. The drain in `Task 5` reads from this dict. - -- [ ] **Step 2: Verify the build** - -Run the build command. Expected: **success**. - -- [ ] **Step 3: Commit** - -```bash -git add submodules/TelegramCore/Sources/State/PendingMessageManager.swift -git commit -m "PendingMessageManager: wire typing-draft gate at forward send" -``` - ---- - -## Task 8: Clean up parked forwards in `updatePendingMessageIds` removal loop - -**Files:** -- Modify: `submodules/TelegramCore/Sources/State/PendingMessageManager.swift` - -When a message is removed from `pendingMessageIds` (e.g. user discarded it, or it was force-deleted), the existing loop disposes context-level state. Parked single/album state lives on the `PendingMessageContext` and gets reset when `state = .none`. Parked forwards live in `forwardSendGateGroups`, which the existing loop does not touch — patch that here. - -- [ ] **Step 1: Add cleanup for `forwardSendGateGroups` in `updatePendingMessageIds`** - -In `updatePendingMessageIds(_:)` (line 284), after the `for id in removedMessageIds { ... }` loop (closes around line 323), add a forward-cleanup pass before `if !addedMessageIds.isEmpty { ... }`: - -```swift - if !removedMessageIds.isEmpty && !self.forwardSendGateGroups.isEmpty { - for (key, parkedGroups) in self.forwardSendGateGroups { - var rebuilt: [[(PendingMessageContext, Message, ForwardSourceInfoAttribute)]] = [] - for group in parkedGroups { - let filtered = group.filter { entry in - return !removedMessageIds.contains(entry.1.id) - } - if !filtered.isEmpty { - rebuilt.append(filtered) - } - } - if rebuilt.isEmpty { - self.forwardSendGateGroups.removeValue(forKey: key) - } else { - self.forwardSendGateGroups[key] = rebuilt - } - } - } -``` - -- [ ] **Step 2: Verify the build** - -Run the build command. Expected: **success**. - -- [ ] **Step 3: Commit** - -```bash -git add submodules/TelegramCore/Sources/State/PendingMessageManager.swift -git commit -m "PendingMessageManager: cleanup parked forwards on pending-message removal" -``` - ---- - -## Task 9: Manual verification - -**Files:** None (verification-only). - -This codebase has no unit tests, so the final acceptance gate is a manual exercise on a debug simulator build. Skip if you don't have a working two-device test setup; in that case, re-confirm only the build is green. - -- [ ] **Step 1: Confirm full build is still green** - -Run the build command from the header. Expected: **success**. - -- [ ] **Step 2: 1:1 chat, text-send delay** - -Setup: log in to two real Telegram accounts on two devices/simulators (account A and account B). Open the A↔B 1:1 chat on both. - -- On B, begin live-typing a draft (Telegram clients with the live-typing-drafts feature emit the typing-draft updates; if B doesn't expose live drafts, simulate by triggering whatever flow populates `transaction.combineTypingDrafts(...)` in your test environment). -- On A, immediately type and send a text message. Confirm: the message appears with a "sending" indicator and does **not** complete until B's draft clears or commits. Once B's draft is cleared, A's message sends within ~1 second. - -- [ ] **Step 3: Album / grouped-media delay** - -Repeat Step 2 with an album of two photos sent from A while B is live-typing. Expected: all album members upload (you can see progress finish), then all sit parked at "sending" until the gate opens. - -- [ ] **Step 4: Forward delay** - -Repeat with a forwarded message (forward a message from a third chat into A↔B while B is live-typing). Expected: forward parks until the gate opens. - -- [ ] **Step 5: Negative — Saved Messages skip** - -In Saved Messages (chat with self), send any message. Confirm: never delays, regardless of typing-draft state. There should be no typing draft for the self peer in the first place — this is just an existence check that the skip-rule does its job. - -- [ ] **Step 6: Negative — secret chat skip** - -In a secret chat, send a message. Confirm: never delays. Server-side, secret chats don't emit typing-draft updates — this verifies the explicit skip-check. - -- [ ] **Step 7: Negative — scheduled message skip (defensive)** - -The `Namespaces.Message.ScheduledCloud` skip in `shouldGateSend` is defensive — in practice, scheduled messages are stored in the scheduled queue and only enter `PendingMessageManager` at delivery time, by which point they've been re-created with cloud namespace. Verifying the defensive branch directly is awkward and not strictly required. If you have an instrumentation path that forces a scheduled-namespace message through `beginSendingMessages`, confirm it doesn't park. - -- [ ] **Step 8: Multi-thread — gate is per-thread** - -In a forum/topic group, on B begin live-typing in topic 1 only. On A, send a message to topic 2 of the same group. Expected: A's message to topic 2 is **not** delayed. - ---- - -## Self-review notes (already applied inline) - -- **Spec coverage:** every section of `2026-04-30-typing-draft-send-delay-design.md` maps to a task — Postbox view (Tasks 1–2), state machine extension (Task 3), subscription (Task 4), predicates + drain + single-send (Task 5), album (Task 6), forwards (Task 7), removal cleanup (Task 8), manual verification (Task 9). -- **Type names verified against actual code:** `PendingMessageState`, `PendingMessageContext`, `PendingMessageUploadedContentAndReuploadInfo`, `ForwardSourceInfoAttribute`, `PendingMessageResult`, `Signal`, `MetaDisposable`, `Queue`, `CombinedView`, `Namespaces.Message.ScheduledCloud`, `Namespaces.Peer.SecretChat`, `Message.newTopicThreadId`, `PeerAndThreadId`, `combineTypingDrafts`, `currentTypingDrafts`, `transaction.updatedTypingDrafts`, `update.value`. All names match the source. -- **`postponeSending` (paid-message) interaction:** untouched. Composes via state-machine ordering (paid postpone gates upload-start; this gate sits post-upload). -- **No unused-private-function warnings:** every helper is introduced together with its first caller (predicates + drain + first call site combined in Task 5). diff --git a/docs/superpowers/plans/2026-05-01-groupref-ssrc-discovery.md b/docs/superpowers/plans/2026-05-01-groupref-ssrc-discovery.md deleted file mode 100644 index 39fb15075b..0000000000 --- a/docs/superpowers/plans/2026-05-01-groupref-ssrc-discovery.md +++ /dev/null @@ -1,1121 +0,0 @@ -# GroupInstanceReferenceImpl Reactive SSRC Discovery — Implementation Plan - -> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. - -**Goal:** Replace `GroupInstanceReferenceImpl`'s test-SFU-only `ActiveAudioSsrcs` discovery path with a per-receiver `webrtc::FrameTransformerInterface` that observes incoming SSRCs at the depacketizer-to-decoder boundary, buffers their first ≤1 s of frames, drives an audio recvonly transceiver to be added via the existing `_requestMediaChannelDescriptions` callback, and flushes the buffer once renegotiation completes — restoring audio in real Telegram group calls without a startup gap. - -**Architecture:** A single `GRAudioFrameTransformer` instance is installed on every audio receiver in this `GroupInstanceReferenceInternal` (mid=0 sendrecv outgoing, plus each recvonly transceiver as it's added). It maintains a per-SSRC state machine (`kBuffering` → `kDrained`) and exposes `releaseSsrc(ssrc)` for the discovery flow to call after `onRenegotiationComplete`. A 250 ms debounce coalesces bursts into one renegotiation. The `ActiveAudioSsrcs` data-channel mechanism (test-SFU only) is removed from both the Go SFU and the C++ ReferenceImpl so the tap is the single discovery path in test and production. - -**Tech Stack:** C++17, WebRTC `FrameTransformerInterface` API, Bazel 8.4.2, the existing tgcalls test bench (Go/Pion SFU + `tgcalls_cli` integration tests). - ---- - -## Reference: Spec & key call-sites - -- **Spec:** `docs/superpowers/specs/2026-05-01-groupref-ssrc-discovery-design.md` -- **WebRTC plumbing reference:** `third-party/webrtc/webrtc/api/frame_transformer_interface.h` (the `FrameTransformerInterface` / `TransformableFrameInterface` / `TransformedFrameCallback` contract); `third-party/webrtc/webrtc/media/engine/webrtc_voice_engine.cc:2240-2266` (the unsignaled→signaled stream promotion path that lets buffered frames flow into the same receive stream). -- **C++ files we modify:** `submodules/TgVoipWebrtc/tgcalls/tgcalls/group/GroupInstanceReferenceImpl.cpp` (only `.cpp`; the `.h` doesn't change). -- **Go file we modify:** `submodules/TgVoipWebrtc/tgcalls/tools/go_sfu/sfu.go`. -- **Docs to refresh:** `submodules/TgVoipWebrtc/CLAUDE.md` (ReferenceImpl section), `submodules/TgVoipWebrtc/tgcalls/tools/cli/CLAUDE.md` (group-mode SSRC discovery flow), `submodules/TgVoipWebrtc/tgcalls/tools/go_sfu/CLAUDE.md` (drop the `ActiveAudioSsrcs` mention). - -## File structure - -| File | Change | Responsibility | -|---|---|---| -| `submodules/TgVoipWebrtc/tgcalls/tgcalls/group/GroupInstanceReferenceImpl.cpp` | modify | Add `GRAudioFrameTransformer` (anonymous-namespace), wire into `start()` and `renegotiate()`, add `handleDiscoveredAudioSsrc` / `scheduleDiscoveryRenegotiation`, delete `handleActiveAudioSsrcs` and its dispatch, call `releaseSsrc` in `onRenegotiationComplete`, add `_audioFrameTransformer` and `_discoveryRenegotiationScheduled` members. | -| `submodules/TgVoipWebrtc/tgcalls/tools/go_sfu/sfu.go` | modify | Delete `buildActiveSSRCsMessage`, `broadcastActiveSSRCs`, both call-sites (post-Join goroutine line 330, Leave line 1061). The `participantSSRCs` audio-collection helper used by `broadcastActiveSSRCs` is otherwise unused; remove it. | -| `submodules/TgVoipWebrtc/CLAUDE.md` | modify | Update the "GroupInstanceReferenceImpl" section: SSRC discovery now via tap; remove "ActiveAudioSsrcs" reference; add note that `_audioFrameTransformer` is the seam where e2e decrypt will land. | -| `submodules/TgVoipWebrtc/tgcalls/tools/cli/CLAUDE.md` | modify | Remove the `ActiveAudioSsrcs` line from the group-mode flow description. | -| `submodules/TgVoipWebrtc/tgcalls/tools/go_sfu/CLAUDE.md` | modify | Remove "ActiveAudioSsrcs" from the `sfu.go` bullet. | - -No new files. No iOS code touched. No CLI test-tool code touched (we ride on the existing `--mute-participants` and per-SSRC level invariants from the previous fix). - ---- - -## Test bench reference - -The existing CLI test (built earlier in this branch) is the integration harness. After every code change, the regression sweep is: - -```bash -/Users/isaac/build/telegram/telegram-ios/build-input/bazel-8.4.2-darwin-arm64 \ - build //submodules/TgVoipWebrtc/tgcalls/tools/cli:tgcalls_cli 2>&1 | tail -3 - -# T1: All-Reference, no mute — must SUCCESS -/Users/isaac/build/telegram/telegram-ios/bazel-bin/submodules/TgVoipWebrtc/tgcalls/tools/cli/tgcalls_cli \ - --mode group --participants 0 --reference-participants 3 --duration 6 --quiet -# Expected: "Result: SUCCESS", exit code 0 - -# T2: Mixed (2C+2R) — must SUCCESS -/Users/isaac/build/telegram/telegram-ios/bazel-bin/submodules/TgVoipWebrtc/tgcalls/tools/cli/tgcalls_cli \ - --mode group --participants 2 --reference-participants 2 --duration 6 --quiet - -# T3: All-Reference with P0 muted — must SUCCESS (muted-peer invariant) -/Users/isaac/build/telegram/telegram-ios/bazel-bin/submodules/TgVoipWebrtc/tgcalls/tools/cli/tgcalls_cli \ - --mode group --participants 0 --reference-participants 3 --mute-participants 0 --duration 6 --quiet - -# T4: Mixed muted (custom side muted) — must SUCCESS -/Users/isaac/build/telegram/telegram-ios/bazel-bin/submodules/TgVoipWebrtc/tgcalls/tools/cli/tgcalls_cli \ - --mode group --participants 1 --reference-participants 2 --mute-participants 0 --duration 6 --quiet - -# T5: Mixed muted (reference side muted) — must SUCCESS -/Users/isaac/build/telegram/telegram-ios/bazel-bin/submodules/TgVoipWebrtc/tgcalls/tools/cli/tgcalls_cli \ - --mode group --participants 2 --reference-participants 1 --mute-participants 2 --duration 6 --quiet -``` - -Tasks below name a specific subset of T1–T5 to run as the verification step. Always run **all five** before the final commit of each task — the muted-peer invariant from the audio-level fix is the strongest detector for routing regressions. - ---- - -### Task 1: Delete `ActiveAudioSsrcs` from the test SFU - -**Files:** -- Modify: `submodules/TgVoipWebrtc/tgcalls/tools/go_sfu/sfu.go` - -**Why first:** Forces every subsequent test run to exercise the discovery path we're about to build. Until the tap is in, all-Reference tests will fail (expected); mixed tests will still pass (CustomImpl discovers via raw RTP). This intentional regression is the visible TDD-red for the rest of the plan. - -- [ ] **Step 1: Read the current state** - -Confirm the three locations with: - -```bash -grep -n "broadcastActiveSSRCs\|buildActiveSSRCsMessage" \ - /Users/isaac/build/telegram/telegram-ios/submodules/TgVoipWebrtc/tgcalls/tools/go_sfu/sfu.go -``` - -Expected output: -``` -330: s.broadcastActiveSSRCs() -886:// broadcastActiveSSRCs sends the current set of active audio SSRCs to all connected participants. -888:func (s *SFU) broadcastActiveSSRCs() { -911: msg := buildActiveSSRCsMessage(ssrcs) -986:func buildActiveSSRCsMessage(ssrcs []int32) string { -1061: s.broadcastActiveSSRCs() -``` - -- [ ] **Step 2: Delete the two call-sites** - -Remove the line `s.broadcastActiveSSRCs()` at line 330 (inside the post-Join goroutine, immediately above `s.broadcastActiveVideoSSRCs()`). Remove the line `s.broadcastActiveSSRCs()` at line 1061 (inside `Leave`, immediately above `s.broadcastActiveVideoSSRCs()`). - -- [ ] **Step 3: Delete `broadcastActiveSSRCs` and `buildActiveSSRCsMessage`** - -Delete the entire function `broadcastActiveSSRCs` (the doc-comment at line 886 through the closing `}` of the function around line 916, including the `participantSSRCs` map it builds locally). - -Delete the entire function `buildActiveSSRCsMessage` (line 986 through line 996). - -- [ ] **Step 4: Verify nothing else references them** - -```bash -grep -n "broadcastActiveSSRCs\|buildActiveSSRCsMessage\|ActiveAudioSsrcs" \ - /Users/isaac/build/telegram/telegram-ios/submodules/TgVoipWebrtc/tgcalls/tools/go_sfu/sfu.go -``` - -Expected output: empty. - -- [ ] **Step 5: Build** - -```bash -/Users/isaac/build/telegram/telegram-ios/build-input/bazel-8.4.2-darwin-arm64 \ - build //submodules/TgVoipWebrtc/tgcalls/tools/cli:tgcalls_cli 2>&1 | tail -3 -``` - -Expected: `INFO: Build completed successfully`. - -- [ ] **Step 6: Run T1 (all-Reference) — confirm RED** - -```bash -/Users/isaac/build/telegram/telegram-ios/bazel-bin/submodules/TgVoipWebrtc/tgcalls/tools/cli/tgcalls_cli \ - --mode group --participants 0 --reference-participants 3 --duration 6 --quiet -echo "EXIT=$?" -``` - -Expected: `Result: FAILED`, `Audio received: 0/3`, `EXIT=1`. (No discovery → no recvonly transceivers → no audio.) - -- [ ] **Step 7: Run T2 (mixed) — confirm partial regression** - -```bash -/Users/isaac/build/telegram/telegram-ios/bazel-bin/submodules/TgVoipWebrtc/tgcalls/tools/cli/tgcalls_cli \ - --mode group --participants 2 --reference-participants 2 --duration 6 --quiet -echo "EXIT=$?" -``` - -Expected: `Result: FAILED`. CustomImpl peers will still discover ReferenceImpl audio via raw RTP (so they receive ReferenceImpl audio), but ReferenceImpl peers cannot discover anyone (so they receive nothing). `Audio received` will report something less than 4/4. - -- [ ] **Step 8: Commit the intentional regression** - -```bash -cd /Users/isaac/build/telegram/telegram-ios -git add submodules/TgVoipWebrtc/tgcalls/tools/go_sfu/sfu.go -git commit -m "$(cat <<'EOF' -test sfu: remove ActiveAudioSsrcs broadcast - -The test-only ActiveAudioSsrcs colibri message is being replaced by -ReferenceImpl's per-receiver FrameTransformer-based discovery (next -commits). Removing the message first forces every subsequent test -run to exercise the new code path — keeping the message in place -would let test passes mask production-real bugs. - -T1/T2 currently FAIL as expected; T3-T5 likewise — the muted-peer -invariant cannot hold without working discovery. All restored by the -end of this PR. - -Co-Authored-By: Claude Opus 4.7 (1M context) -EOF -)" -``` - ---- - -### Task 2: Delete `handleActiveAudioSsrcs` from `GroupInstanceReferenceImpl` - -**Files:** -- Modify: `submodules/TgVoipWebrtc/tgcalls/tgcalls/group/GroupInstanceReferenceImpl.cpp` - -**Why now:** The handler is now dead code (no SFU sends `ActiveAudioSsrcs` anymore). Removing it before adding the new path means we don't temporarily have two SSRC-add paths that could both insert the same entry into `_remoteSsrcs`. - -- [ ] **Step 1: Confirm the call sites** - -```bash -grep -n "handleActiveAudioSsrcs\|colibriClass.*ActiveAudio" \ - /Users/isaac/build/telegram/telegram-ios/submodules/TgVoipWebrtc/tgcalls/tgcalls/group/GroupInstanceReferenceImpl.cpp -``` - -Expected: -``` -1060: if (colibriClass == "ActiveAudioSsrcs") { -1061: handleActiveAudioSsrcs(json); -1063: void handleActiveAudioSsrcs(json11::Json const &json) { -``` - -- [ ] **Step 2: Read the dispatch site** - -Read lines 1048–1067 of `GroupInstanceReferenceImpl.cpp` to confirm the surrounding context of `onDataChannelMessage`. - -- [ ] **Step 3: Remove the dispatch (lines 1056–1067)** - -Inside `onDataChannelMessage`, locate the `colibriClass == "ActiveAudioSsrcs"` branch and the comment immediately above (`// ActiveVideoSsrcs and SenderVideoConstraints are handled by the` ... `// setRequestedVideoChannels() in response.`). Delete the JSON parse block, the colibriClass extraction, and the if-branch that calls `handleActiveAudioSsrcs(json)`. - -The remaining body of `onDataChannelMessage` should consist of the `_dataChannelMessageReceived` forwarding only: - -```cpp - void onDataChannelMessage(std::string const &msg) { - // Forward all data channel messages to the application. - // Audio SSRCs are now discovered by the per-receiver frame - // transformer (see GRAudioFrameTransformer); video channel - // requests are app-driven via setRequestedVideoChannels. - if (_dataChannelMessageReceived) { - _dataChannelMessageReceived(msg); - } - } -``` - -- [ ] **Step 4: Delete `handleActiveAudioSsrcs`** - -Delete the entire function `handleActiveAudioSsrcs(json11::Json const &json)` (starts at the line that previously matched `1063: void handleActiveAudioSsrcs(json11::Json const &json) {`, ends at the matching `}`). It's roughly 60 lines including the diff loop and the `_requestMediaChannelDescriptions` call. - -- [ ] **Step 5: Verify nothing else references it** - -```bash -grep -n "handleActiveAudioSsrcs\|ActiveAudioSsrcs" \ - /Users/isaac/build/telegram/telegram-ios/submodules/TgVoipWebrtc/tgcalls/tgcalls/group/GroupInstanceReferenceImpl.cpp -``` - -Expected: empty. - -- [ ] **Step 6: Build** - -```bash -/Users/isaac/build/telegram/telegram-ios/build-input/bazel-8.4.2-darwin-arm64 \ - build //submodules/TgVoipWebrtc/tgcalls/tools/cli:tgcalls_cli 2>&1 | tail -3 -``` - -Expected: `INFO: Build completed successfully`. - -- [ ] **Step 7: Run T1 — still RED, same reason** - -```bash -/Users/isaac/build/telegram/telegram-ios/bazel-bin/submodules/TgVoipWebrtc/tgcalls/tools/cli/tgcalls_cli \ - --mode group --participants 0 --reference-participants 3 --duration 6 --quiet -echo "EXIT=$?" -``` - -Expected: `Result: FAILED`, `EXIT=1`. (No regression added beyond Task 1; we just deleted dead code.) - -- [ ] **Step 8: Commit** - -```bash -cd /Users/isaac/build/telegram/telegram-ios -git add submodules/TgVoipWebrtc/tgcalls/tgcalls/group/GroupInstanceReferenceImpl.cpp -git commit -m "$(cat <<'EOF' -GroupInstanceReferenceImpl: remove handleActiveAudioSsrcs - -ActiveAudioSsrcs was a test-SFU-only colibri message. With the test -SFU no longer sending it, the handler is dead code. Removing now -before introducing the new discovery path so we don't briefly have -two paths inserting into _remoteSsrcs. - -Co-Authored-By: Claude Opus 4.7 (1M context) -EOF -)" -``` - ---- - -### Task 3: Add `GRAudioFrameTransformer` skeleton (no behavior yet) - -**Files:** -- Modify: `submodules/TgVoipWebrtc/tgcalls/tgcalls/group/GroupInstanceReferenceImpl.cpp` - -**Why staged:** Adding the class first as a do-nothing pass-through transformer lets us verify the WebRTC plumbing works (the catch-all transformer never breaks audio, OnTransformedFrame is reachable) before we layer on the per-SSRC state machine. Initially we also install nothing — the class just compiles. - -- [ ] **Step 1: Locate the anonymous namespace insertion point** - -Read lines 109–148 of `GroupInstanceReferenceImpl.cpp` to confirm where the anonymous namespace ends (the `} // anonymous namespace` line). - -- [ ] **Step 2: Add the class right before `} // anonymous namespace`** - -Insert the following code immediately before the closing `} // anonymous namespace` (after `GRCreateSDPObserver`): - -```cpp -// --- Per-receiver audio frame transformer --- -// -// One instance is installed (via `RtpReceiverInterface::SetDepacketizerToDecoderFrameTransformer`) -// on every audio receiver in this GroupInstanceReferenceInternal: -// - mid=0 sendrecv outgoing audio (its receive side acts as the catch-all -// for unsignaled SSRCs); -// - each recvonly audio transceiver added by the SSRC-discovery flow. -// -// Behavior per SSRC: -// - First-sight (no entry yet): notify discovery; buffer the frame. -// - kBuffering (waiting for renegotiation): append to per-SSRC FIFO. -// - kDrained (releaseSsrc has fired): pass through immediately. -// -// `releaseSsrc(ssrc)` is invoked by ReferenceImpl on the media thread -// from `onRenegotiationComplete` once a recvonly transceiver owns the -// SSRC. The transformer drains the per-SSRC FIFO via OnTransformedFrame -// and transitions the entry to kDrained. -// -// `decryptHook` is reserved for the e2e fix (separate PR). Today it is -// nullptr and the transformer just forwards frames unchanged. -class GRAudioFrameTransformer : public webrtc::FrameTransformerInterface { -public: - using SsrcCallback = std::function; - using DecryptHook = std::function; - - GRAudioFrameTransformer(SsrcCallback onNewSsrc, - DecryptHook decrypt, - rtc::Thread* mediaThread) - : _onNewSsrc(std::move(onNewSsrc)), - _decrypt(std::move(decrypt)), - _mediaThread(mediaThread) {} - - // Stub — to be filled in Task 4. - void Transform(std::unique_ptr frame) override { - // Pass-through for now (verifies plumbing). - webrtc::MutexLock lock(&_mu); - const uint32_t ssrc = frame->GetSsrc(); - rtc::scoped_refptr sink; - auto it = _perSsrcSinks.find(ssrc); - if (it != _perSsrcSinks.end()) { - sink = it->second; - } else if (_broadcastSink) { - sink = _broadcastSink; - } - if (!sink) return; - sink->OnTransformedFrame(std::move(frame)); - } - - // Stub — to be filled in Task 4. - void releaseSsrc(uint32_t /*ssrc*/) {} - - void RegisterTransformedFrameCallback( - rtc::scoped_refptr cb) override { - webrtc::MutexLock lock(&_mu); - _broadcastSink = std::move(cb); - } - void RegisterTransformedFrameSinkCallback( - rtc::scoped_refptr cb, - uint32_t ssrc) override { - webrtc::MutexLock lock(&_mu); - _perSsrcSinks[ssrc] = std::move(cb); - } - void UnregisterTransformedFrameCallback() override { - webrtc::MutexLock lock(&_mu); - _broadcastSink = nullptr; - } - void UnregisterTransformedFrameSinkCallback(uint32_t ssrc) override { - webrtc::MutexLock lock(&_mu); - _perSsrcSinks.erase(ssrc); - } - -private: - SsrcCallback _onNewSsrc; - DecryptHook _decrypt; - rtc::Thread* _mediaThread; // identity only; not used for thread-affine asserts in this skeleton - - webrtc::Mutex _mu; - rtc::scoped_refptr _broadcastSink RTC_GUARDED_BY(_mu); - std::map> _perSsrcSinks RTC_GUARDED_BY(_mu); -}; -``` - -- [ ] **Step 3: Add a `webrtc::Mutex` include if missing** - -```bash -grep -n "rtc_base/synchronization/mutex.h\|webrtc::Mutex\b" \ - /Users/isaac/build/telegram/telegram-ios/submodules/TgVoipWebrtc/tgcalls/tgcalls/group/GroupInstanceReferenceImpl.cpp | head -5 -``` - -If the include is missing, add to the includes near the top of the file (after the existing webrtc includes): - -```cpp -#include "rtc_base/synchronization/mutex.h" -``` - -- [ ] **Step 4: Build** - -```bash -/Users/isaac/build/telegram/telegram-ios/build-input/bazel-8.4.2-darwin-arm64 \ - build //submodules/TgVoipWebrtc/tgcalls/tools/cli:tgcalls_cli 2>&1 | tail -10 -``` - -Expected: `INFO: Build completed successfully`. - -If the build fails on `webrtc::Mutex` — try `#include "api/sequence_checker.h"` and use `webrtc::Mutex` from there, or fall back to `std::mutex` (the rest of the file already uses `` via `_audioLevelsMutex` in `tools/cli/group_participant.cpp`; check what's available in `tgcalls/tgcalls/group/`). - -- [ ] **Step 5: Run T1 — still expected to fail (we haven't installed the transformer yet)** - -```bash -/Users/isaac/build/telegram/telegram-ios/bazel-bin/submodules/TgVoipWebrtc/tgcalls/tools/cli/tgcalls_cli \ - --mode group --participants 0 --reference-participants 3 --duration 6 --quiet -echo "EXIT=$?" -``` - -Expected: `Result: FAILED`, `EXIT=1`. The class is defined but unused — same red as Tasks 1–2. - -- [ ] **Step 6: Commit** - -```bash -cd /Users/isaac/build/telegram/telegram-ios -git add submodules/TgVoipWebrtc/tgcalls/tgcalls/group/GroupInstanceReferenceImpl.cpp -git commit -m "$(cat <<'EOF' -GroupInstanceReferenceImpl: add GRAudioFrameTransformer skeleton - -Pass-through frame transformer scaffolding. Behavior (per-SSRC -buffering, releaseSsrc, decrypt hook) lands in the next commit. - -Co-Authored-By: Claude Opus 4.7 (1M context) -EOF -)" -``` - ---- - -### Task 4: Implement the per-SSRC state machine in `GRAudioFrameTransformer` - -**Files:** -- Modify: `submodules/TgVoipWebrtc/tgcalls/tgcalls/group/GroupInstanceReferenceImpl.cpp` (the class added in Task 3) - -**Why staged:** Once installed (Task 5), this class becomes part of every audio frame's path. Splitting "skeleton" from "behavior" makes the diff small enough to review carefully — bugs here silently drop audio. - -- [ ] **Step 1: Add the `Entry` struct, constants, and `_entries` map to the class** - -Inside `class GRAudioFrameTransformer` (after `_perSsrcSinks` declaration), add: - -```cpp -private: - enum class SsrcState { kBuffering, kDrained }; - - struct Entry { - SsrcState state = SsrcState::kBuffering; - std::deque> buffer; - int64_t firstFrameTimeMs = 0; - }; - - static constexpr int64_t kSsrcDiscoveryTimeoutMs = 1000; - static constexpr size_t kMaxBufferedFramesPerSsrc = 60; - static constexpr size_t kMaxConcurrentBufferedSsrcs = 64; - - void evictExpired_n() RTC_EXCLUSIVE_LOCKS_REQUIRED(_mu); - - std::map _entries RTC_GUARDED_BY(_mu); -``` - -Add `` to the includes if not already present (usually pulled in transitively): - -```bash -grep -n "" /Users/isaac/build/telegram/telegram-ios/submodules/TgVoipWebrtc/tgcalls/tgcalls/group/GroupInstanceReferenceImpl.cpp -``` - -If missing, add `#include ` near the top with the other STL includes. - -- [ ] **Step 2: Replace `Transform` with the real implementation** - -Replace the stub `Transform` body with: - -```cpp - void Transform(std::unique_ptr frame) override { - if (!frame) return; - const uint32_t ssrc = frame->GetSsrc(); - - // Path A: kDrained — pass through. - // Path B: kBuffering — buffer. - // Path C: new SSRC — insert + post discovery + buffer. - // Path D: at the SSRC cap — drop silently. - rtc::scoped_refptr liveSink; - bool notifyDiscovery = false; - std::unique_ptr liveFrame; - { - webrtc::MutexLock lock(&_mu); - evictExpired_n(); - - auto it = _entries.find(ssrc); - if (it == _entries.end()) { - if (_entries.size() >= kMaxConcurrentBufferedSsrcs) { - // Path D: drop without notify, no allocation. - return; - } - Entry entry; - entry.firstFrameTimeMs = rtc::TimeMillis(); - entry.buffer.push_back(std::move(frame)); - _entries.emplace(ssrc, std::move(entry)); - notifyDiscovery = true; - } else if (it->second.state == SsrcState::kBuffering) { - if (it->second.buffer.size() >= kMaxBufferedFramesPerSsrc) { - it->second.buffer.pop_front(); - } - it->second.buffer.push_back(std::move(frame)); - } else { - // kDrained: pick the live sink and emit outside the lock. - auto sinkIt = _perSsrcSinks.find(ssrc); - if (sinkIt != _perSsrcSinks.end()) { - liveSink = sinkIt->second; - } else { - liveSink = _broadcastSink; - } - liveFrame = std::move(frame); - } - } - - if (liveSink && liveFrame) { - liveSink->OnTransformedFrame(std::move(liveFrame)); - } - if (notifyDiscovery && _onNewSsrc) { - _onNewSsrc(ssrc); - } - } -``` - -- [ ] **Step 3: Replace `releaseSsrc` with the real implementation** - -Replace the stub `releaseSsrc` body with: - -```cpp - void releaseSsrc(uint32_t ssrc) { - std::deque> toFlush; - rtc::scoped_refptr sink; - { - webrtc::MutexLock lock(&_mu); - auto it = _entries.find(ssrc); - if (it == _entries.end() || it->second.state == SsrcState::kDrained) { - // Either the SSRC was unknown, or already drained. Mark drained - // so future frames take the live-passthrough path. - if (it == _entries.end()) { - Entry entry; - entry.state = SsrcState::kDrained; - entry.firstFrameTimeMs = rtc::TimeMillis(); - _entries.emplace(ssrc, std::move(entry)); - } - return; - } - it->second.state = SsrcState::kDrained; - toFlush = std::move(it->second.buffer); - - auto sinkIt = _perSsrcSinks.find(ssrc); - if (sinkIt != _perSsrcSinks.end()) { - sink = sinkIt->second; - } else { - sink = _broadcastSink; - } - } - - if (!sink) return; - while (!toFlush.empty()) { - auto f = std::move(toFlush.front()); - toFlush.pop_front(); - sink->OnTransformedFrame(std::move(f)); - } - } -``` - -- [ ] **Step 4: Implement `evictExpired_n`** - -Add this private method definition inside the class (e.g., after `releaseSsrc`): - -```cpp - void evictExpired_n() RTC_EXCLUSIVE_LOCKS_REQUIRED(_mu) { - const int64_t now = rtc::TimeMillis(); - for (auto& [ssrc, entry] : _entries) { - if (entry.state == SsrcState::kBuffering && - !entry.buffer.empty() && - (now - entry.firstFrameTimeMs) > kSsrcDiscoveryTimeoutMs) { - entry.buffer.clear(); - // Leave the entry in kBuffering with empty buffer so we don't - // re-notify discovery. If the application ever recovers - // (renegotiation completes belatedly), releaseSsrc will still - // mark kDrained and live frames will flow through. - } - } - } -``` - -- [ ] **Step 5: Add `rtc::TimeMillis` include if missing** - -```bash -grep -n "rtc::TimeMillis\b\|rtc_base/time_utils.h" \ - /Users/isaac/build/telegram/telegram-ios/submodules/TgVoipWebrtc/tgcalls/tgcalls/group/GroupInstanceReferenceImpl.cpp | head -5 -``` - -If only the call shows up but not the header, add: - -```cpp -#include "rtc_base/time_utils.h" -``` - -near the other rtc_base includes. - -- [ ] **Step 6: Build** - -```bash -/Users/isaac/build/telegram/telegram-ios/build-input/bazel-8.4.2-darwin-arm64 \ - build //submodules/TgVoipWebrtc/tgcalls/tools/cli:tgcalls_cli 2>&1 | tail -10 -``` - -Expected: `INFO: Build completed successfully`. - -- [ ] **Step 7: Run T1 — still expected to fail (transformer still not installed)** - -```bash -/Users/isaac/build/telegram/telegram-ios/bazel-bin/submodules/TgVoipWebrtc/tgcalls/tools/cli/tgcalls_cli \ - --mode group --participants 0 --reference-participants 3 --duration 6 --quiet -echo "EXIT=$?" -``` - -Expected: `Result: FAILED`, `EXIT=1`. Code is built but unused. - -- [ ] **Step 8: Commit** - -```bash -cd /Users/isaac/build/telegram/telegram-ios -git add submodules/TgVoipWebrtc/tgcalls/tgcalls/group/GroupInstanceReferenceImpl.cpp -git commit -m "$(cat <<'EOF' -GroupInstanceReferenceImpl: implement GRAudioFrameTransformer state machine - -Per-SSRC buffer / drain / passthrough. releaseSsrc transitions -kBuffering→kDrained atomically (mark under lock, drain outside lock) -to avoid races. evictExpired_n bounds buffer lifetime to 1s. - -Caps: kMaxConcurrentBufferedSsrcs=64, kMaxBufferedFramesPerSsrc=60. -Worst-case memory ≈ 308 KB. - -Co-Authored-By: Claude Opus 4.7 (1M context) -EOF -)" -``` - ---- - -### Task 5: Wire the transformer into `start()` (catch-all only) and observe discovery callback fires - -**Files:** -- Modify: `submodules/TgVoipWebrtc/tgcalls/tgcalls/group/GroupInstanceReferenceImpl.cpp` - -**Why staged:** Install on the catch-all and prove `Transform` fires (via the `_onNewSsrc` callback). Discovery doesn't yet drive a renegotiation — that's the next task. After this task, T1 should still FAIL but with the discovery callback observably firing. - -- [ ] **Step 1: Add the member field** - -Locate the `Audio.` block in the private member section (around line 1556 — `_outgoingAudioTrack`, `_outgoingAudioTransceiver`). Add immediately after: - -```cpp - // Per-receiver audio frame transformer (catch-all + every recvonly). - rtc::scoped_refptr _audioFrameTransformer; -``` - -- [ ] **Step 2: Add a forward declaration for `handleDiscoveredAudioSsrc` (function defined in Task 6)** - -Inside the class, near the other private method declarations / definitions for `handleActiveAudioSsrcs`-replacement work — for now, declare a stub: - -```cpp - void handleDiscoveredAudioSsrc(uint32_t ssrc) { - // To be implemented in Task 6. - RTC_LOG(LS_INFO) << "GroupRef: discovered audio SSRC " << ssrc; - } -``` - -Place this near the existing media-thread methods (e.g., near `wireRemoteAudioLevelSinks`). - -- [ ] **Step 3: Construct + install the transformer in `start()`** - -Locate the block after `_outgoingAudioTransceiver` is created (around line 386, immediately after the `params.encodings[0].max_bitrate_bps = ...; _outgoingAudioTransceiver->sender()->SetParameters(params);` block). Insert before `_outgoingAudioTrack->set_enabled(false); // Muted by default.`: - -```cpp - // Install the audio frame transformer on mid=0's receiver. The - // receive side of this sendrecv transceiver is PeerConnection's - // catch-all for unsignaled SSRCs, so the transformer captures - // every previously-unseen remote SSRC. The same instance is - // attached to each recvonly receiver in renegotiate() so that - // live audio passes through the transformer consistently - // (and so the e2e PR has a single attachment point). - _audioFrameTransformer = rtc::make_ref_counted( - /*onNewSsrc=*/[weak, threads = _threads](uint32_t ssrc) { - threads->getMediaThread()->PostTask([weak, ssrc]() { - if (auto strong = weak.lock()) { - strong->handleDiscoveredAudioSsrc(ssrc); - } - }); - }, - /*decrypt=*/nullptr, // wired by the e2e PR - /*mediaThread=*/_threads->getMediaThread().get()); - _outgoingAudioTransceiver->receiver() - ->SetDepacketizerToDecoderFrameTransformer(_audioFrameTransformer); -``` - -Note: `weak` is the `weak_ptr` already in scope earlier in `start()`. Verify by re-reading the start of `start()`: - -```bash -sed -n '173,195p' /Users/isaac/build/telegram/telegram-ios/submodules/TgVoipWebrtc/tgcalls/tgcalls/group/GroupInstanceReferenceImpl.cpp -``` - -If `weak` is not in scope at the insertion point, declare locally: - -```cpp - const auto weak = std::weak_ptr(shared_from_this()); -``` - -- [ ] **Step 4: Build** - -```bash -/Users/isaac/build/telegram/telegram-ios/build-input/bazel-8.4.2-darwin-arm64 \ - build //submodules/TgVoipWebrtc/tgcalls/tools/cli:tgcalls_cli 2>&1 | tail -10 -``` - -Expected: `INFO: Build completed successfully`. - -- [ ] **Step 5: Run T1 with verbose output — confirm discovery callback fires** - -```bash -/Users/isaac/build/telegram/telegram-ios/bazel-bin/submodules/TgVoipWebrtc/tgcalls/tools/cli/tgcalls_cli \ - --mode group --participants 0 --reference-participants 3 --duration 6 2>&1 \ - | grep "discovered audio SSRC" | head -10 -``` - -Expected: at least one `GroupRef: discovered audio SSRC ` line per remote peer per participant. (Logs go through `LogSinkImpl` which writes to a per-participant log file then deletes; if the grep returns nothing, briefly add `fprintf(stderr, "...")` mirroring the RTC_LOG to verify, then revert before commit.) - -- [ ] **Step 6: Run T1 (full) — still expected to FAIL** - -```bash -/Users/isaac/build/telegram/telegram-ios/bazel-bin/submodules/TgVoipWebrtc/tgcalls/tools/cli/tgcalls_cli \ - --mode group --participants 0 --reference-participants 3 --duration 6 --quiet -echo "EXIT=$?" -``` - -Expected: `Result: FAILED`. The handler is a logging stub; no recvonly transceiver is added; audio is dropped (no `OnTransformedFrame` call yet because the entry is `kBuffering` indefinitely). - -- [ ] **Step 7: Commit** - -```bash -cd /Users/isaac/build/telegram/telegram-ios -git add submodules/TgVoipWebrtc/tgcalls/tgcalls/group/GroupInstanceReferenceImpl.cpp -git commit -m "$(cat <<'EOF' -GroupInstanceReferenceImpl: install GRAudioFrameTransformer on mid=0 - -The transformer is now in the depacketizer path of mid=0's receiver -(PeerConnection's catch-all for unsignaled audio). Every previously- -unseen SSRC fires the discovery callback, which currently just logs. -The next commit drives renegotiation and flushes buffered audio. - -Co-Authored-By: Claude Opus 4.7 (1M context) -EOF -)" -``` - ---- - -### Task 6: Implement `handleDiscoveredAudioSsrc` + `scheduleDiscoveryRenegotiation` and call `releaseSsrc` from `onRenegotiationComplete` - -**Files:** -- Modify: `submodules/TgVoipWebrtc/tgcalls/tgcalls/group/GroupInstanceReferenceImpl.cpp` - -**Why staged:** This is the GREEN step — the test harness should pass for the first time after this task. Wiring discovery → renegotiation → release closes the loop, but until we also install the transformer on each recvonly receiver (Task 7), live frames after the flush continue to take the catch-all path. That's tolerable today (catch-all is the same instance) but Task 7 makes it explicit and future-proof. - -- [ ] **Step 1: Add `_discoveryRenegotiationScheduled` member** - -In the private member section, near `_isRenegotiating`: - -```cpp - // Discovery-renegotiation debounce. - bool _discoveryRenegotiationScheduled = false; -``` - -- [ ] **Step 2: Replace the `handleDiscoveredAudioSsrc` stub with the real implementation** - -```cpp - // Single entry point for adding a remote audio SSRC. Runs on the - // media thread (posted to from the worker-thread frame transformer - // callback). - void handleDiscoveredAudioSsrc(uint32_t ssrc) { - if (ssrc == 0) return; - if (ssrc == _outgoingSsrc) return; - if (_remoteSsrcs.count(ssrc) > 0) return; - - std::string mid = std::to_string(_nextMid++); - RemoteSsrcInfo info; - info.mid = mid; - _remoteSsrcs.emplace(ssrc, std::move(info)); - - if (_requestMediaChannelDescriptions) { - _requestMediaChannelDescriptions({ssrc}, - [](std::vector&&) {}); - } - scheduleDiscoveryRenegotiation(); - - RTC_LOG(LS_INFO) << "GroupRef: queued discovered audio SSRC " << ssrc - << " (mid=" << mid << ")"; - } -``` - -- [ ] **Step 3: Add `scheduleDiscoveryRenegotiation`** - -Place near the existing `renegotiate()` method: - -```cpp - static constexpr int kDiscoveryRenegotiationDelayMs = 250; - - void scheduleDiscoveryRenegotiation() { - if (_discoveryRenegotiationScheduled) return; - _discoveryRenegotiationScheduled = true; - - const auto weak = std::weak_ptr(shared_from_this()); - _threads->getMediaThread()->PostDelayedTask( - [weak]() { - auto strong = weak.lock(); - if (!strong) return; - strong->_discoveryRenegotiationScheduled = false; - strong->renegotiate(); - }, - webrtc::TimeDelta::Millis(kDiscoveryRenegotiationDelayMs)); - } -``` - -- [ ] **Step 4: Add the `releaseSsrc` loop in `onRenegotiationComplete`** - -Locate `onRenegotiationComplete()` (around line 1314). Insert after `wireRemoteAudioLevelSinks();` and before `_isRenegotiating = false;`: - -```cpp - if (_audioFrameTransformer) { - for (auto& [ssrc, info] : _remoteSsrcs) { - if (info.transceiver && info.transceiver->mid().has_value()) { - _audioFrameTransformer->releaseSsrc(ssrc); - } - } - } -``` - -- [ ] **Step 5: Build** - -```bash -/Users/isaac/build/telegram/telegram-ios/build-input/bazel-8.4.2-darwin-arm64 \ - build //submodules/TgVoipWebrtc/tgcalls/tools/cli:tgcalls_cli 2>&1 | tail -10 -``` - -Expected: `INFO: Build completed successfully`. - -- [ ] **Step 6: Run T1 — should now SUCCESS** - -```bash -/Users/isaac/build/telegram/telegram-ios/bazel-bin/submodules/TgVoipWebrtc/tgcalls/tools/cli/tgcalls_cli \ - --mode group --participants 0 --reference-participants 3 --duration 6 --quiet -echo "EXIT=$?" -``` - -Expected: `Result: SUCCESS`, `Audio received: 3/3`, `EXIT=0`. - -If FAIL: re-read the spec's "Where flushed frames actually go" section. The most likely issue is that the per-SSRC sink callback registered when the unsignaled stream was created is no longer the one routing to the (now-promoted) audio receive stream's decoder. Add a one-shot debug print inside `releaseSsrc` to confirm `sink != nullptr` and `toFlush.size() > 0`. - -- [ ] **Step 7: Run T2-T5 — verify no regressions** - -Run each scenario from the "Test bench reference" block above (T1 through T5). All five must report `Result: SUCCESS` and `EXIT=0`. - -If T3-T5 (muted-peer scenarios) pass: the muted-peer invariant from the previous fix still holds, so the per-receiver audio-level sinks are correctly wired and reading PCM from the post-promotion stream. - -- [ ] **Step 8: Commit** - -```bash -cd /Users/isaac/build/telegram/telegram-ios -git add submodules/TgVoipWebrtc/tgcalls/tgcalls/group/GroupInstanceReferenceImpl.cpp -git commit -m "$(cat <<'EOF' -GroupInstanceReferenceImpl: drive discovery renegotiation, flush buffer - -- handleDiscoveredAudioSsrc inserts into _remoteSsrcs, fires - _requestMediaChannelDescriptions per SSRC, schedules a debounced - renegotiation. -- scheduleDiscoveryRenegotiation coalesces bursts: at most one - renegotiation per 250ms, regardless of how many SSRCs land in - the window. -- onRenegotiationComplete iterates _remoteSsrcs and calls - releaseSsrc(ssrc) for every entry whose transceiver now has a - mid, draining the per-SSRC FIFO into OnTransformedFrame so the - buffered audio plays without a startup gap. - -T1-T5 all pass. - -Co-Authored-By: Claude Opus 4.7 (1M context) -EOF -)" -``` - ---- - -### Task 7: Install `_audioFrameTransformer` on every recvonly transceiver as it's added - -**Files:** -- Modify: `submodules/TgVoipWebrtc/tgcalls/tgcalls/group/GroupInstanceReferenceImpl.cpp` - -**Why now (not in Task 6):** Today the catch-all transformer covers live audio for promoted streams (it's already on the stream from the unsignaled-stream creation path). Explicitly installing it on each recvonly receiver removes our reliance on internal WebRTC stream-promotion behavior carrying the transformer along, and matches the exact attachment pattern the e2e PR will use. - -- [ ] **Step 1: Find the AddTransceiver call in `renegotiate()`** - -```bash -grep -n "AddTransceiver(cricket::MEDIA_TYPE_AUDIO" \ - /Users/isaac/build/telegram/telegram-ios/submodules/TgVoipWebrtc/tgcalls/tgcalls/group/GroupInstanceReferenceImpl.cpp -``` - -Expected: a single hit inside `renegotiate()` (around line 1142). - -- [ ] **Step 2: Attach the transformer right after the transceiver is created** - -Modify the block that handles the success branch of `AddTransceiver`. Original: - -```cpp - auto result = _peerConnection->AddTransceiver(cricket::MEDIA_TYPE_AUDIO, init); - if (result.ok()) { - info.transceiver = result.value(); - RTC_LOG(LS_INFO) << "GroupRef: Added recvonly transceiver for SSRC " << ssrc; - } -``` - -Replace with: - -```cpp - auto result = _peerConnection->AddTransceiver(cricket::MEDIA_TYPE_AUDIO, init); - if (result.ok()) { - info.transceiver = result.value(); - if (_audioFrameTransformer) { - info.transceiver->receiver() - ->SetDepacketizerToDecoderFrameTransformer(_audioFrameTransformer); - } - RTC_LOG(LS_INFO) << "GroupRef: Added recvonly transceiver for SSRC " << ssrc; - } -``` - -- [ ] **Step 3: Build** - -```bash -/Users/isaac/build/telegram/telegram-ios/build-input/bazel-8.4.2-darwin-arm64 \ - build //submodules/TgVoipWebrtc/tgcalls/tools/cli:tgcalls_cli 2>&1 | tail -3 -``` - -Expected: `INFO: Build completed successfully`. - -- [ ] **Step 4: Run T1-T5 — must all SUCCESS** - -```bash -for cfg in \ - "0 3 --duration 6" \ - "2 2 --duration 6" \ - "0 3 --mute-participants 0 --duration 6" \ - "1 2 --mute-participants 0 --duration 6" \ - "2 1 --mute-participants 2 --duration 6"; do - /Users/isaac/build/telegram/telegram-ios/bazel-bin/submodules/TgVoipWebrtc/tgcalls/tools/cli/tgcalls_cli \ - --mode group --participants $cfg --quiet 2>&1 | tail -3 - echo "EXIT=$?"; echo "---" -done -``` - -Each block must end with `Result: SUCCESS` and `EXIT=0`. - -- [ ] **Step 5: Commit** - -```bash -cd /Users/isaac/build/telegram/telegram-ios -git add submodules/TgVoipWebrtc/tgcalls/tgcalls/group/GroupInstanceReferenceImpl.cpp -git commit -m "$(cat <<'EOF' -GroupInstanceReferenceImpl: attach frame transformer to each recvonly receiver - -Live audio for a promoted SSRC was already flowing through our -transformer (carried over from the unsignaled stream creation -path), but we depended on internal WebRTC stream-promotion -behavior to make that work. Explicit per-receiver attachment -removes that dependency and matches what the e2e PR will need. - -Co-Authored-By: Claude Opus 4.7 (1M context) -EOF -)" -``` - ---- - -### Task 8: Documentation refresh - -**Files:** -- Modify: `submodules/TgVoipWebrtc/CLAUDE.md` -- Modify: `submodules/TgVoipWebrtc/tgcalls/tools/cli/CLAUDE.md` -- Modify: `submodules/TgVoipWebrtc/tgcalls/tools/go_sfu/CLAUDE.md` - -- [ ] **Step 1: Update `submodules/TgVoipWebrtc/CLAUDE.md` — ReferenceImpl section** - -Find the "GroupInstanceReferenceImpl" section. Update the "Dynamic Participant Handling → Audio" sub-bullet: - -Before (or similar): -> 1. SFU sends `{"colibriClass":"ActiveAudioSsrcs","ssrcs":[54321,98765]}` over data channel -> 2. Client diffs against known SSRCs -> 3. New SSRCs: add recvonly audio transceiver → renegotiate (new offer + constructed answer mirroring offer mids) -> 4. Removed SSRCs: clean up from tracking map - -After: -> 1. `GRAudioFrameTransformer` (installed on mid=0's receiver and on every recvonly audio receiver) sees a frame with an unknown SSRC at the depacketizer→decoder boundary, buffers it, and notifies the media thread. -> 2. `handleDiscoveredAudioSsrc` inserts the SSRC into `_remoteSsrcs`, fires `_requestMediaChannelDescriptions({ssrc}, ...)` (matches CustomImpl's contract), and schedules a 250 ms-debounced renegotiation. -> 3. Renegotiation adds a recvonly transceiver bound to the new SSRC; `buildRemoteAnswer` includes the SSRC on the new m-line; `WebRtcVoiceReceiveChannel::AddRecvStream` promotes the existing unsignaled stream in place. -> 4. `onRenegotiationComplete` calls `_audioFrameTransformer->releaseSsrc(ssrc)`, which drains the buffered FIFO via `OnTransformedFrame` so the user hears the participant's first ~250–500 ms of audio without a gap. -> 5. Subsequent live frames for the SSRC pass through the transformer's `kDrained` branch directly to the decoder. -> -> The `colibriClass=ActiveAudioSsrcs` data-channel mechanism (test-SFU only) was removed; the tap is the single discovery path. Removed-SSRC handling is the same as CustomImpl's: stale recvonly transceivers stay in the SDP indefinitely; participant departures are tracked at the application layer (MTProto). - -- [ ] **Step 2: Update `submodules/TgVoipWebrtc/tgcalls/tools/cli/CLAUDE.md` — group flow** - -Find the "Architecture (Group)" section. Remove the bullet about `ActiveAudioSsrcs` ("SSRC discovery: SFU broadcasts `ActiveAudioSsrcs` and `ActiveVideoSsrcs` ...") and replace with: - -> SSRC discovery: video SSRCs are broadcast via `ActiveVideoSsrcs` (used by the test app's `dataChannelMessageReceived` callback to call `setRequestedVideoChannels`). Audio SSRCs are discovered by `GroupInstanceReferenceImpl`'s per-receiver `GRAudioFrameTransformer` directly from incoming RTP — same shape CustomImpl uses (`receiveUnknownSsrcPacket` → `_requestMediaChannelDescriptions`). - -- [ ] **Step 3: Update `submodules/TgVoipWebrtc/tgcalls/tools/go_sfu/CLAUDE.md`** - -In the bullet that lists `sfu.go`'s responsibilities, remove the phrase `'ActiveAudioSsrcs'/`ActiveVideoSsrcs' broadcasting` and replace with `ActiveVideoSsrcs broadcasting` (audio is no longer broadcast). - -- [ ] **Step 4: Verify builds still work after the doc changes (defensive)** - -```bash -/Users/isaac/build/telegram/telegram-ios/build-input/bazel-8.4.2-darwin-arm64 \ - build //submodules/TgVoipWebrtc/tgcalls/tools/cli:tgcalls_cli 2>&1 | tail -3 -``` - -Expected: `INFO: Build completed successfully` (no source files touched, but a no-op build verifies the docs don't accidentally break a generated file). - -- [ ] **Step 5: Commit** - -```bash -cd /Users/isaac/build/telegram/telegram-ios -git add submodules/TgVoipWebrtc/CLAUDE.md \ - submodules/TgVoipWebrtc/tgcalls/tools/cli/CLAUDE.md \ - submodules/TgVoipWebrtc/tgcalls/tools/go_sfu/CLAUDE.md -git commit -m "$(cat <<'EOF' -docs: ReferenceImpl SSRC discovery via per-receiver frame transformer - -Document the new GRAudioFrameTransformer-based audio SSRC discovery -flow in both the tgcalls library overview and the test-bench notes. -Drop ActiveAudioSsrcs references — the message no longer exists. - -Co-Authored-By: Claude Opus 4.7 (1M context) -EOF -)" -``` - ---- - -### Task 9: Final regression sweep - -**Files:** none changed. - -- [ ] **Step 1: Run the full sweep** - -```bash -echo "=== T1: All-Reference no mute ===" -/Users/isaac/build/telegram/telegram-ios/bazel-bin/submodules/TgVoipWebrtc/tgcalls/tools/cli/tgcalls_cli \ - --mode group --participants 0 --reference-participants 3 --duration 6 --quiet | tail -3 -echo "EXIT=$?" - -echo "=== T2: Mixed (2C+2R) no mute ===" -/Users/isaac/build/telegram/telegram-ios/bazel-bin/submodules/TgVoipWebrtc/tgcalls/tools/cli/tgcalls_cli \ - --mode group --participants 2 --reference-participants 2 --duration 6 --quiet | tail -3 -echo "EXIT=$?" - -echo "=== T3: All-Reference, P0 muted ===" -/Users/isaac/build/telegram/telegram-ios/bazel-bin/submodules/TgVoipWebrtc/tgcalls/tools/cli/tgcalls_cli \ - --mode group --participants 0 --reference-participants 3 --mute-participants 0 --duration 6 --quiet | tail -3 -echo "EXIT=$?" - -echo "=== T4: Mixed (1C+2R), custom muted ===" -/Users/isaac/build/telegram/telegram-ios/bazel-bin/submodules/TgVoipWebrtc/tgcalls/tools/cli/tgcalls_cli \ - --mode group --participants 1 --reference-participants 2 --mute-participants 0 --duration 6 --quiet | tail -3 -echo "EXIT=$?" - -echo "=== T5: Mixed (2C+1R), reference muted ===" -/Users/isaac/build/telegram/telegram-ios/bazel-bin/submodules/TgVoipWebrtc/tgcalls/tools/cli/tgcalls_cli \ - --mode group --participants 2 --reference-participants 1 --mute-participants 2 --duration 6 --quiet | tail -3 -echo "EXIT=$?" -``` - -Expected: every block ends with `Result: SUCCESS` and `EXIT=0`. - -- [ ] **Step 2: Confirm muted-peer level invariant explicitly (T3 verbose)** - -```bash -/Users/isaac/build/telegram/telegram-ios/bazel-bin/submodules/TgVoipWebrtc/tgcalls/tools/cli/tgcalls_cli \ - --mode group --participants 0 --reference-participants 3 --mute-participants 0 --duration 6 2>&1 \ - | grep -E "Validate" | head -5 -``` - -Expected: -``` -Validate: OK: P1 (ref) reported muted P0 (ssrc=...) at max level 0.000 -Validate: OK: P2 (ref) reported muted P0 (ssrc=...) at max level 0.000 -``` - -- [ ] **Step 3: Confirm no leftover `ActiveAudioSsrcs` references** - -```bash -grep -rn "ActiveAudioSsrcs\|handleActiveAudioSsrcs\|broadcastActiveSSRCs\|buildActiveSSRCsMessage" \ - /Users/isaac/build/telegram/telegram-ios/submodules/TgVoipWebrtc/ 2>/dev/null | grep -v ".log\|.o\|index/\|bazel-" -``` - -Expected: empty (or only matches inside `.git/`). - -- [ ] **Step 4: Confirm git log structure** - -```bash -cd /Users/isaac/build/telegram/telegram-ios -git log --oneline -10 -``` - -Expected to see 8 new commits from this PR (Tasks 1, 2, 3, 4, 5, 6, 7, 8) since the previous baseline. - -- [ ] **Step 5: This task has no commit** - -The sweep is verification-only. - ---- - -## Out of scope (do NOT touch in this PR) - -- `descriptor.e2eEncryptDecrypt` wiring. The seam (`DecryptHook` constructor parameter on `GRAudioFrameTransformer`) is in place; the actual decrypt callback is the next PR. -- Outgoing-audio SSRC>int31 masking. Separate fix. -- Push-style discovery via a new `GroupInstanceInterface::addIncomingAudioSsrcs(...)` method. -- Removed-SSRC cleanup (recvonly transceivers stay in the SDP indefinitely — same as CustomImpl). -- iOS-side code changes — the existing `_requestMediaChannelDescriptions` callback already serves the discovery path. - ---- - -## Self-review notes - -- **Spec coverage:** Every section of the spec has at least one task. Frame transformer (Tasks 3–4), every-receiver install (Tasks 5, 7), discovery + debounce + release (Task 6), `ActiveAudioSsrcs` removal (Tasks 1–2), docs (Task 8), regression sweep (Task 9). -- **Type / name consistency:** `GRAudioFrameTransformer` (not `GRSsrcTapTransformer`) used everywhere. Member field `_audioFrameTransformer` everywhere. Constants `kSsrcDiscoveryTimeoutMs`, `kMaxBufferedFramesPerSsrc`, `kMaxConcurrentBufferedSsrcs`, `kDiscoveryRenegotiationDelayMs` defined once and referenced once. -- **Placeholder scan:** No "TBD"/"TODO"/"similar to N" — every code-touching step has the actual code. -- **Test verification:** The test bench T1–T5 are referenced by exact CLI invocations, with the muted-peer invariant called out as the strongest signal for routing regressions. Task 1's intentional regression is explicitly framed as TDD-red so the engineer doesn't think they broke something. diff --git a/docs/superpowers/plans/2026-05-01-rich-bubble-instant-page-link-handling.md b/docs/superpowers/plans/2026-05-01-rich-bubble-instant-page-link-handling.md deleted file mode 100644 index c1a523b5a6..0000000000 --- a/docs/superpowers/plans/2026-05-01-rich-bubble-instant-page-link-handling.md +++ /dev/null @@ -1,655 +0,0 @@ -# Rich-bubble instant-page link handling Implementation Plan - -> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. - -**Goal:** Wire URL tap routing and link-highlight feedback into `ChatMessageRichDataBubbleContentNode`, plus stubbed handlers for intra-page anchor scrolling. - -**Architecture:** All changes land in a single Swift file (`ChatMessageRichDataBubbleContentNode.swift`) plus its BUILD file. Tap detection mirrors `InstantPageControllerNode.textItemAtLocation` / `urlForTapLocation` scoped to the bubble's already-built `currentPageLayout`. URL hits return a standard `ChatMessageBubbleContentTapAction(.url(...), rects:, activate:)` which the bubble framework routes through `controllerInteraction.openUrl`. Highlight feedback uses a `LinkHighlightingNode` overlay inside `containerNode`, driven by the `activate` `Promise` exactly like the chat text bubble. Same-page-anchor URLs short-circuit into a no-op `scrollToAnchor(_:)` placeholder for later implementation. - -**Tech Stack:** Swift, AsyncDisplayKit, Bazel (`build-system/Make/Make.py`), modules `Display`, `InstantPageUI`, `ChatControllerInteraction`, `ChatMessageBubbleContentNode`, `TelegramCore`, `SwiftSignalKit`. - -**Reference spec:** `docs/superpowers/specs/2026-05-01-rich-bubble-instant-page-link-handling-design.md` - -**Project context:** No automated tests exist (per `CLAUDE.md`). Per-task verification is "build green" using: - -```sh -source ~/.zshrc 2>/dev/null; python3 build-system/Make/Make.py --overrideXcodeVersion \ - --cacheDir ~/telegram-bazel-cache \ - build \ - --configurationPath build-system/appstore-configuration.json \ - --gitCodesigningRepository git@gitlab.com:peter-iakovlev/fastlanematch.git \ - --gitCodesigningType development --gitCodesigningUseCurrent --buildNumber=1 --configuration=debug_sim_arm64 \ - --continueOnError -``` - -Final manual smoke test runs the app and exercises the feature in the simulator. - ---- - -## File map - -- **Modified:** `submodules/TelegramUI/Components/Chat/ChatMessageRichDataBubbleContentNode/Sources/ChatMessageRichDataBubbleContentNode.swift` — adds tap detection helpers, link-highlight state and overlay management, real `openPeer`/`openUrl` item callbacks, anchor stub, and a populated `tapActionAtPoint`. -- **Modified:** `submodules/TelegramUI/Components/Chat/ChatMessageRichDataBubbleContentNode/BUILD` — adds `//submodules/TelegramUI/Components/ChatControllerInteraction` to `deps`. - -No other files change. - ---- - -### Task 1: Add `ChatControllerInteraction` BUILD dep + import - -The rich-bubble currently does not have access to `ChatControllerInteraction` as an importable module. Sibling modules (e.g. `ChatMessageWebpageBubbleContentNode`) list it explicitly in BUILD deps and import it. We follow the same pattern. - -**Files:** -- Modify: `submodules/TelegramUI/Components/Chat/ChatMessageRichDataBubbleContentNode/BUILD` -- Modify: `submodules/TelegramUI/Components/Chat/ChatMessageRichDataBubbleContentNode/Sources/ChatMessageRichDataBubbleContentNode.swift:1-12` - -- [ ] **Step 1: Add the dep to BUILD** - -In `submodules/TelegramUI/Components/Chat/ChatMessageRichDataBubbleContentNode/BUILD`, add the new dep line at the end of the existing `deps` list (alphabetical order is not enforced in this repo's BUILD files; place it after `ChatMessageItemCommon`): - -Replace: -``` - deps = [ - "//submodules/AsyncDisplayKit", - "//submodules/Display", - "//submodules/TelegramCore", - "//submodules/Postbox", - "//submodules/SSignalKit/SwiftSignalKit", - "//submodules/AccountContext", - "//submodules/InstantPageUI", - "//submodules/TelegramUI/Components/Chat/ChatMessageBubbleContentNode", - "//submodules/TelegramUI/Components/Chat/ChatMessageItemCommon", - "//submodules/TelegramUIPreferences", - ], -``` - -With: -``` - deps = [ - "//submodules/AsyncDisplayKit", - "//submodules/Display", - "//submodules/TelegramCore", - "//submodules/Postbox", - "//submodules/SSignalKit/SwiftSignalKit", - "//submodules/AccountContext", - "//submodules/InstantPageUI", - "//submodules/TelegramUI/Components/Chat/ChatMessageBubbleContentNode", - "//submodules/TelegramUI/Components/Chat/ChatMessageItemCommon", - "//submodules/TelegramUI/Components/ChatControllerInteraction", - "//submodules/TelegramUIPreferences", - ], -``` - -- [ ] **Step 2: Add the import** - -At the top of `submodules/TelegramUI/Components/Chat/ChatMessageRichDataBubbleContentNode/Sources/ChatMessageRichDataBubbleContentNode.swift`, after `import ChatMessageItemCommon` add `import ChatControllerInteraction`: - -Replace: -```swift -import ChatMessageBubbleContentNode -import ChatMessageItemCommon -import InstantPageUI -import TelegramUIPreferences -``` - -With: -```swift -import ChatMessageBubbleContentNode -import ChatMessageItemCommon -import ChatControllerInteraction -import InstantPageUI -import TelegramUIPreferences -``` - -- [ ] **Step 3: Build to verify** - -```sh -source ~/.zshrc 2>/dev/null; python3 build-system/Make/Make.py --overrideXcodeVersion --cacheDir ~/telegram-bazel-cache build --configurationPath build-system/appstore-configuration.json --gitCodesigningRepository git@gitlab.com:peter-iakovlev/fastlanematch.git --gitCodesigningType development --gitCodesigningUseCurrent --buildNumber=1 --configuration=debug_sim_arm64 --continueOnError -``` - -Expected: build succeeds. The new import is unused; Swift does not warn on unused module imports, so `-warnings-as-errors` is fine. - -- [ ] **Step 4: Commit** - -```sh -git add submodules/TelegramUI/Components/Chat/ChatMessageRichDataBubbleContentNode/BUILD submodules/TelegramUI/Components/Chat/ChatMessageRichDataBubbleContentNode/Sources/ChatMessageRichDataBubbleContentNode.swift -git commit -m "Rich bubble: add ChatControllerInteraction dep and import" -``` - ---- - -### Task 2: Add link-progress state, deinit cleanup, and helper stubs - -Before introducing tap-detection or item-callback logic, add the supporting plumbing: progress state, the empty `scrollToAnchor` placeholder, the URL-anchor splitter, and a `currentLoadedWebpage()` accessor. These are private helpers that future tasks will consume — Swift does not warn on unused private functions, so the build stays green. - -**Files:** -- Modify: `submodules/TelegramUI/Components/Chat/ChatMessageRichDataBubbleContentNode/Sources/ChatMessageRichDataBubbleContentNode.swift` - -- [ ] **Step 1: Add the new ivars** - -Locate the existing block of stored properties around lines 18–25: - -```swift - private let containerNode: ContainerNode - private var currentLayoutTiles: [InstantPageTile] = [] - private var visibleTiles: [Int: InstantPageTileNode] = [:] - private var visibleItemsWithNodes: [Int: InstantPageNode] = [:] - private var currentPageLayout: (boundingWidth: CGFloat, layout: InstantPageLayout)? - private var distanceThresholdGroupCount: [Int: Int] = [:] - private var currentLayoutItemsWithNodes: [InstantPageItem] = [] - private var currentExpandedDetails: [Int : Bool]? -``` - -Append the three highlight-related fields immediately after `currentExpandedDetails`: - -```swift - private let containerNode: ContainerNode - private var currentLayoutTiles: [InstantPageTile] = [] - private var visibleTiles: [Int: InstantPageTileNode] = [:] - private var visibleItemsWithNodes: [Int: InstantPageNode] = [:] - private var currentPageLayout: (boundingWidth: CGFloat, layout: InstantPageLayout)? - private var distanceThresholdGroupCount: [Int: Int] = [:] - private var currentLayoutItemsWithNodes: [InstantPageItem] = [] - private var currentExpandedDetails: [Int : Bool]? - private var linkProgressDisposable: Disposable? - private var linkProgressRects: [CGRect]? - private var linkHighlightingNode: LinkHighlightingNode? -``` - -- [ ] **Step 2: Update `deinit` to dispose the link-progress signal** - -Locate the existing empty `deinit` (around line 48): - -```swift - deinit { - } -``` - -Replace with: - -```swift - deinit { - self.linkProgressDisposable?.dispose() - } -``` - -- [ ] **Step 3: Add helper methods at the end of the class** - -Locate the closing brace of the class (the last `}` in the file). Immediately before it, add the four helpers (anchor split, current-loaded-webpage accessor, anchor-scroll stub, and a small TODO note): - -```swift - private func splitAnchor(_ url: String) -> (base: String, anchor: String?) { - if let anchorRange = url.range(of: "#") { - let anchor = String(url[anchorRange.upperBound...]).removingPercentEncoding - let base = String(url[.. TelegramMediaWebpageLoadedContent? { - guard let item = self.item else { - return nil - } - guard let webpage = item.message.media.first(where: { $0 is TelegramMediaWebpage }) as? TelegramMediaWebpage else { - return nil - } - if case let .Loaded(content) = webpage.content { - return content - } - return nil - } - - private func scrollToAnchor(_ anchor: String) { - // TODO: implement intra-page anchor scrolling - let _ = anchor - } -``` - -The `let _ = anchor` line silences any "unused parameter" lint while keeping the parameter name visible. (Required because `-warnings-as-errors` is enabled on this module.) - -- [ ] **Step 4: Build to verify** - -```sh -source ~/.zshrc 2>/dev/null; python3 build-system/Make/Make.py --overrideXcodeVersion --cacheDir ~/telegram-bazel-cache build --configurationPath build-system/appstore-configuration.json --gitCodesigningRepository git@gitlab.com:peter-iakovlev/fastlanematch.git --gitCodesigningType development --gitCodesigningUseCurrent --buildNumber=1 --configuration=debug_sim_arm64 --continueOnError -``` - -Expected: build succeeds. Private functions (even unused) and disposable ivars compile cleanly under `-warnings-as-errors`. - -- [ ] **Step 5: Commit** - -```sh -git add submodules/TelegramUI/Components/Chat/ChatMessageRichDataBubbleContentNode/Sources/ChatMessageRichDataBubbleContentNode.swift -git commit -m "Rich bubble: add link-progress state and anchor-scroll stub" -``` - ---- - -### Task 3: Wire item-level `openPeer` and `openUrl` callbacks - -Replace the stubbed item-callback closures inside the `item.node(...)` invocation. Item nodes themselves emit URL/peer taps via their callback parameters; we route these to `controllerInteraction.openUrl` / `controllerInteraction.openPeer`. `openMedia`, `longPressMedia`, `activatePinchPreview`, `pinchPreviewFinished`, `updateWebEmbedHeight`, and `updateDetailsExpanded` remain explicit no-ops (per spec — out of scope for this change). - -**Files:** -- Modify: `submodules/TelegramUI/Components/Chat/ChatMessageRichDataBubbleContentNode/Sources/ChatMessageRichDataBubbleContentNode.swift` (the `item.node(...)` call inside `updateVisibleItems`, currently at lines ~233–278) - -- [ ] **Step 1: Replace the `item.node(...)` callback block** - -Locate the existing call (the entire block from `if let newNode = item.node(context: ...` through the matching `currentExpandedDetails: ..., getPreloadedResource: { _ in return nil }) {` line). Replace ONLY the trailing-closure callback parameters — keep `context:`, `strings:`, `nameDisplayOrder:`, `theme:`, `sourceLocation:`, `currentExpandedDetails:`, and `getPreloadedResource:` intact. - -Replace the existing block: - -```swift - if let newNode = item.node(context: messageItem.context, strings: messageItem.presentationData.strings, nameDisplayOrder: messageItem.presentationData.nameDisplayOrder, theme: pageTheme, sourceLocation: sourceLocation, openMedia: { [weak self] media in - let _ = self - //self?.openMedia(media) - }, longPressMedia: { [weak self] media in - //self?.longPressMedia(media) - let _ = self - }, activatePinchPreview: { [weak self] sourceNode in - /*guard let strongSelf = self, let controller = strongSelf.controller else { - return - } - let pinchController = makePinchController(sourceNode: sourceNode, getContentAreaInScreenSpace: { - guard let strongSelf = self else { - return CGRect() - } - - let localRect = CGRect(origin: CGPoint(x: 0.0, y: strongSelf.navigationBar.frame.maxY), size: CGSize(width: strongSelf.bounds.width, height: strongSelf.bounds.height - strongSelf.navigationBar.frame.maxY)) - return strongSelf.view.convert(localRect, to: nil) - }) - controller.window?.presentInGlobalOverlay(pinchController)*/ - let _ = self - }, pinchPreviewFinished: { [weak self] itemNode in - /*guard let strongSelf = self else { - return - } - for (_, listItemNode) in strongSelf.visibleItemsWithNodes { - if let listItemNode = listItemNode as? InstantPagePeerReferenceNode { - if listItemNode.frame.intersects(itemNode.frame) && listItemNode.frame.maxY <= itemNode.frame.maxY + 2.0 { - listItemNode.layer.animateAlpha(from: 0.0, to: listItemNode.alpha, duration: 0.25) - break - } - } - }*/ - let _ = self - }, openPeer: { [weak self] peerId in - let _ = self - //self?.openPeer(peerId) - }, openUrl: { [weak self] url in - let _ = self - //self?.openUrl(url) - }, updateWebEmbedHeight: { [weak self] height in - let _ = self - //self?.updateWebEmbedHeight(embedIndex, height) - }, updateDetailsExpanded: { [weak self] expanded in - let _ = self - //self?.updateDetailsExpanded(detailsIndex, expanded) - }, currentExpandedDetails: self.currentExpandedDetails, getPreloadedResource: { _ in return nil }) { -``` - -With: - -```swift - if let newNode = item.node(context: messageItem.context, strings: messageItem.presentationData.strings, nameDisplayOrder: messageItem.presentationData.nameDisplayOrder, theme: pageTheme, sourceLocation: sourceLocation, openMedia: { _ in - // TODO: media handling — out of scope for link wiring - }, longPressMedia: { _ in - // TODO - }, activatePinchPreview: { _ in - // TODO - }, pinchPreviewFinished: { _ in - // TODO - }, openPeer: { [weak self] peer in - guard let self, let item = self.item else { - return - } - item.controllerInteraction.openPeer(peer, .chat(textInputState: nil, subject: nil, peekData: nil), nil, .default) - }, openUrl: { [weak self] urlItem in - guard let self, let item = self.item else { - return - } - let split = self.splitAnchor(urlItem.url) - if let webpage = self.currentLoadedWebpage(), webpage.url == split.base, let anchor = split.anchor { - self.scrollToAnchor(anchor) - return - } - item.controllerInteraction.openUrl(ChatControllerInteraction.OpenUrl( - url: urlItem.url, - concealed: false, - message: item.message, - allowInlineWebpageResolution: urlItem.webpageId != nil - )) - }, updateWebEmbedHeight: { _ in - // TODO - }, updateDetailsExpanded: { _ in - // TODO - }, currentExpandedDetails: self.currentExpandedDetails, getPreloadedResource: { _ in return nil }) { -``` - -Notes on this block: -- `openPeer` parameter is `(EnginePeer) -> Void` (verified against `InstantPageItem.swift:18`) — name it `peer`, not `peerId`. -- `openUrl` parameter is `(InstantPageUrlItem) -> Void` — name it `urlItem` to disambiguate from the outer URL string. -- The same-page-anchor short-circuit calls the empty `scrollToAnchor` stub so future implementation is single-point. -- `urlItem.webpageId != nil` is mapped to `allowInlineWebpageResolution` because the IV's `webpageId` hint signals "this URL was authored as a referenced webpage" — the same intent as the chat flag. -- `concealed: false` for item-emitted URLs (item nodes only emit clearly-typed link items, not free-form anchor-text mismatches). The text-tap path in Task 4 uses `concealed: true` per spec. - -- [ ] **Step 2: Build to verify** - -```sh -source ~/.zshrc 2>/dev/null; python3 build-system/Make/Make.py --overrideXcodeVersion --cacheDir ~/telegram-bazel-cache build --configurationPath build-system/appstore-configuration.json --gitCodesigningRepository git@gitlab.com:peter-iakovlev/fastlanematch.git --gitCodesigningType development --gitCodesigningUseCurrent --buildNumber=1 --configuration=debug_sim_arm64 --continueOnError -``` - -Expected: build succeeds. If a closure-parameter type mismatch is reported, re-check `InstantPageItem.swift:18` for the canonical signature. - -- [ ] **Step 3: Commit** - -```sh -git add submodules/TelegramUI/Components/Chat/ChatMessageRichDataBubbleContentNode/Sources/ChatMessageRichDataBubbleContentNode.swift -git commit -m "Rich bubble: route item-level openPeer/openUrl to controllerInteraction" -``` - ---- - -### Task 4: Implement URL tap detection, highlight feedback, and `tapActionAtPoint` - -Add the tap-detection helpers, the rect-translation helper, the `makeActivate` factory, and the `updateLinkProgressState` view-state applier. Then rewrite `tapActionAtPoint` to use them. This is the largest task; it must land atomically because the helpers and the rewritten `tapActionAtPoint` reference each other. - -**Files:** -- Modify: `submodules/TelegramUI/Components/Chat/ChatMessageRichDataBubbleContentNode/Sources/ChatMessageRichDataBubbleContentNode.swift` - -- [ ] **Step 1: Replace `tapActionAtPoint` and add tap-detection helpers** - -Locate the existing `tapActionAtPoint` (around lines 403–442 with its commented-out `makeActivate` block) and replace the entire method. Then add the new helpers immediately afterward (so they live alongside the related logic). - -Replace the existing method body: - -```swift - override public func tapActionAtPoint(_ point: CGPoint, gesture: TapLongTapOrDoubleTapGesture, isEstimating: Bool) -> ChatMessageBubbleContentTapAction { - if case .tap = gesture { - } else { - if let item = self.item, let subject = item.associatedData.subject, case .messageOptions = subject { - return ChatMessageBubbleContentTapAction(content: .none) - } - } - - /*func makeActivate(_ urlRange: NSRange?) -> (() -> Promise?)? { - return { [weak self] in - guard let self else { - return nil - } - - let promise = Promise() - - self.linkProgressDisposable?.dispose() - - if self.linkProgressRange != nil { - self.linkProgressRange = nil - self.updateLinkProgressState() - } - - self.linkProgressDisposable = (promise.get() |> deliverOnMainQueue).startStrict(next: { [weak self] value in - guard let self else { - return - } - let updatedRange: NSRange? = value ? urlRange : nil - if self.linkProgressRange != updatedRange { - self.linkProgressRange = updatedRange - self.updateLinkProgressState() - } - }) - - return promise - } - }*/ - - return ChatMessageBubbleContentTapAction(content: .none) - } -``` - -With: - -```swift - override public func tapActionAtPoint(_ point: CGPoint, gesture: TapLongTapOrDoubleTapGesture, isEstimating: Bool) -> ChatMessageBubbleContentTapAction { - if case .tap = gesture { - } else { - if let item = self.item, let subject = item.associatedData.subject, case .messageOptions = subject { - return ChatMessageBubbleContentTapAction(content: .none) - } - } - - guard let urlHit = self.urlForTapLocation(point) else { - return ChatMessageBubbleContentTapAction(content: .none) - } - - let split = self.splitAnchor(urlHit.urlItem.url) - if let webpage = self.currentLoadedWebpage(), webpage.url == split.base, let anchor = split.anchor { - return ChatMessageBubbleContentTapAction(content: .custom({ [weak self] in - self?.scrollToAnchor(anchor) - })) - } - - // Default to concealed=true: InstantPageTextItem does not expose a clean - // "attribute substring with displayed range" API, so we cannot compare - // displayed text to the resolved URL the way the chat text bubble does. - // The chat URL handler will show a confirmation when concealed is true - // and the visible text differs from the destination — safer default. - let concealed = true - let url = ChatMessageBubbleContentTapAction.Url(url: urlHit.urlItem.url, concealed: concealed) - let rects = self.computeHighlightRects(item: urlHit.item, parentOffset: urlHit.parentOffset, localPoint: urlHit.localPoint) - return ChatMessageBubbleContentTapAction( - content: .url(url), - rects: rects, - activate: self.makeActivate(item: urlHit.item, parentOffset: urlHit.parentOffset, localPoint: urlHit.localPoint) - ) - } - - private func textItemAtLocation(_ location: CGPoint) -> (item: InstantPageTextItem, parentOffset: CGPoint)? { - guard let layout = self.currentPageLayout?.layout else { - return nil - } - // Translate from bubble-content-node coords to container-/layout-local coords. - let layoutLocation = location.offsetBy(dx: -1.0, dy: -1.0) - for item in layout.items { - let itemFrame = item.frame - if itemFrame.contains(layoutLocation) { - if let item = item as? InstantPageTextItem, item.selectable { - return (item, CGPoint(x: itemFrame.minX - item.frame.minX, y: itemFrame.minY - item.frame.minY)) - } else if let item = item as? InstantPageScrollableItem { - let contentOffset = CGPoint.zero - if let (textItem, parentOffset) = item.textItemAtLocation(layoutLocation.offsetBy(dx: -itemFrame.minX + contentOffset.x, dy: -itemFrame.minY)) { - return (textItem, itemFrame.origin.offsetBy(dx: parentOffset.x - contentOffset.x, dy: parentOffset.y)) - } - } else if let item = item as? InstantPageDetailsItem { - for (_, itemNode) in self.visibleItemsWithNodes { - if let itemNode = itemNode as? InstantPageDetailsNode, itemNode.item === item { - if let (textItem, parentOffset) = itemNode.textItemAtLocation(layoutLocation.offsetBy(dx: -itemFrame.minX, dy: -itemFrame.minY)) { - return (textItem, itemFrame.origin.offsetBy(dx: parentOffset.x, dy: parentOffset.y)) - } - } - } - } - } - } - return nil - } - - private func urlForTapLocation(_ point: CGPoint) -> (item: InstantPageTextItem, urlItem: InstantPageUrlItem, parentOffset: CGPoint, localPoint: CGPoint)? { - guard let (item, parentOffset) = self.textItemAtLocation(point) else { - return nil - } - // Translate bubble-content-node point → text-item-local point. - // (bubble-coords → layout-coords) is `- (1, 1)`; (layout → item-local) is `- item.frame.origin - parentOffset`. - let layoutPoint = point.offsetBy(dx: -1.0, dy: -1.0) - let localPoint = layoutPoint.offsetBy(dx: -item.frame.minX - parentOffset.x, dy: -item.frame.minY - parentOffset.y) - guard let urlItem = item.urlAttribute(at: localPoint) else { - return nil - } - return (item, urlItem, parentOffset, localPoint) - } - - private func computeHighlightRects(item: InstantPageTextItem, parentOffset: CGPoint, localPoint: CGPoint) -> [CGRect] { - // Text item returns rects in its local coords; translate back into containerNode-local coords. - // containerNode is offset by (1, 1) from the bubble-content-node, but the highlight overlay lives - // *inside* containerNode, so we use layout-coords (= containerNode-local) for the rects. - let originX = item.frame.minX + parentOffset.x - let originY = item.frame.minY + parentOffset.y - return item.linkSelectionRects(at: localPoint).map { rect in - rect.offsetBy(dx: originX, dy: originY) - } - } - - private func makeActivate(item: InstantPageTextItem, parentOffset: CGPoint, localPoint: CGPoint) -> (() -> Promise?)? { - return { [weak self, weak item] in - guard let self else { - return nil - } - let promise = Promise() - self.linkProgressDisposable?.dispose() - if self.linkProgressRects != nil { - self.linkProgressRects = nil - self.updateLinkProgressState() - } - self.linkProgressDisposable = (promise.get() |> deliverOnMainQueue).startStrict(next: { [weak self] value in - guard let self else { - return - } - let updated: [CGRect]? - if value, let item { - updated = self.computeHighlightRects(item: item, parentOffset: parentOffset, localPoint: localPoint) - } else { - updated = nil - } - let changed: Bool - if let lhs = self.linkProgressRects, let rhs = updated { - changed = lhs != rhs - } else { - changed = (self.linkProgressRects == nil) != (updated == nil) - } - if changed { - self.linkProgressRects = updated - self.updateLinkProgressState() - } - }) - return promise - } - } - - private func updateLinkProgressState() { - guard let messageItem = self.item else { - return - } - if let rects = self.linkProgressRects, !rects.isEmpty { - let highlightingNode: LinkHighlightingNode - if let current = self.linkHighlightingNode { - highlightingNode = current - } else { - let color: UIColor = messageItem.message.effectivelyIncoming(messageItem.context.account.peerId) - ? messageItem.presentationData.theme.theme.chat.message.incoming.linkHighlightColor - : messageItem.presentationData.theme.theme.chat.message.outgoing.linkHighlightColor - highlightingNode = LinkHighlightingNode(color: color) - self.linkHighlightingNode = highlightingNode - self.containerNode.insertSubnode(highlightingNode, at: 0) - } - highlightingNode.frame = self.containerNode.bounds - highlightingNode.updateRects(rects) - } else if let highlightingNode = self.linkHighlightingNode { - self.linkHighlightingNode = nil - highlightingNode.layer.animateAlpha(from: 1.0, to: 0.0, duration: 0.18, removeOnCompletion: false, completion: { [weak highlightingNode] _ in - highlightingNode?.removeFromSupernode() - }) - } - } -``` - -Notes: -- Coordinate translation: incoming `point` is bubble-content-node-local. The bubble's `containerNode.frame.origin` is `(1, 1)` (set in the `apply` closure around line 96). Subtracting `(1, 1)` once gives container-local = layout-local coordinates. The layout origin is `(0, 0)` inside the container. -- `InstantPageScrollableItem`'s realized node would be the source of truth for content-offset, but the rich-bubble does not surface scroll state and chat instant-pages rarely contain scrollable items. Pass `CGPoint.zero` for v1; if a chat preview ever uses a scrollable, the tap detection will be slightly off but URL-hit will still resolve when the scroll is at top. (Out of scope for this change; document as a follow-up if it becomes user-visible.) -- `[weak item]` in the activate closure avoids retaining the InstantPageTextItem across asynchronous URL resolution. If layout reflows during resolution and the original item is gone, the highlight simply falls back to clearing. -- The `changed` comparison for `[CGRect]?` is spelled out longhand because optional `Equatable` conformance for `[CGRect]?` requires the explicit nil-vs-non-nil discrimination to satisfy `-warnings-as-errors` cleanly. - -- [ ] **Step 2: Build to verify** - -```sh -source ~/.zshrc 2>/dev/null; python3 build-system/Make/Make.py --overrideXcodeVersion --cacheDir ~/telegram-bazel-cache build --configurationPath build-system/appstore-configuration.json --gitCodesigningRepository git@gitlab.com:peter-iakovlev/fastlanematch.git --gitCodesigningType development --gitCodesigningUseCurrent --buildNumber=1 --configuration=debug_sim_arm64 --continueOnError -``` - -Expected: build succeeds. - -Common likely errors and fixes: -- "Cannot find type `InstantPageTextItem` / `InstantPageScrollableItem` / `InstantPageDetailsItem` / `InstantPageDetailsNode` / `InstantPageUrlItem`" → all are public in `InstantPageUI`, already imported; rebuild without `--continueOnError` and re-check the exact error. -- "Cannot find `LinkHighlightingNode`" → it lives in `Display`, already imported. -- "`Promise` is ambiguous" → `Promise` is from `SwiftSignalKit`, already imported. -- A `linkHighlightColor` access that errors with optional unwrap → the type is non-optional `UIColor` on `MessageBubbleColorComponents`; this should compile cleanly. If the compiler reports a different type, drop back to `?? UIColor.clear` and document. - -- [ ] **Step 3: Commit** - -```sh -git add submodules/TelegramUI/Components/Chat/ChatMessageRichDataBubbleContentNode/Sources/ChatMessageRichDataBubbleContentNode.swift -git commit -m "Rich bubble: implement URL tap detection and link-highlight feedback" -``` - ---- - -### Task 5: Manual smoke verification - -There are no automated tests for chat UI in this codebase. The final task is a hands-on smoke test in the simulator. - -**Files:** none modified. Verification only. - -- [ ] **Step 1: Launch the app in the simulator** - -The build command run in earlier tasks produces the app binary; launch via Xcode (open `Telegram-iOS.xcworkspace` if needed) or the Bazel-produced run target. Sign in to a real test account. - -- [ ] **Step 2: Find or send a message with an instant-view preview** - -In a chat, send a Telegram URL that has a rich instant-view preview (e.g. a Telegraph article URL: `https://telegra.ph/Test-page-12-31`, or any t.me link that produces an inline IV preview). The preview should render inside the chat bubble using the rich-data layout (multiple text/image tiles inside one bubble). - -- [ ] **Step 3: Tap a URL inside the inline IV preview** - -A standard URL link inside the preview text: -- Should highlight (semi-transparent rounded rectangle in the bubble's link-highlight color) for the duration of URL resolution. -- Should then route through the chat's URL handler — opening an in-app webview, an external browser, or a peer/chat depending on the URL. - -- [ ] **Step 4: Tap a same-page anchor (if available)** - -Some IV pages contain intra-page anchors like `#section-1`. Tapping such a link should fire the empty `scrollToAnchor` stub — observable as: no navigation, no error, no highlight, no external browser. (The TODO is logged for future work.) - -- [ ] **Step 5: Long-press a URL** - -A long-press on a URL inside the inline preview should trigger the chat's default URL long-press menu (Open / Copy / Share via the standard `controllerInteraction.longTap` path provided by the bubble framework for `.url` taps). The bubble's own custom long-press action sheet is out of scope for this change. - -- [ ] **Step 6: Sign-off** - -If steps 3–5 behave as described, the change is complete. If a step fails, capture: the URL used, observed behavior, and any console output. Common deviations: -- Highlight not appearing → confirm `containerNode` insertion order; the highlight node sits at index 0 below tiles, and tile background must be `.clear` (verify in `InstantPageTileNode`). -- URL resolves to nothing → confirm the upstream chat is correctly forwarding `controllerInteraction.openUrl` (this is the same wiring used by every other chat bubble). -- Anchor tap routes externally → confirm `currentLoadedWebpage()?.url == split.base` is matching; instant-page URLs sometimes carry trailing slashes in source vs. anchor links. - ---- - -## Self-review - -**Spec coverage:** -- Spec §"New private state" → Task 2 Step 1. -- Spec §"deinit disposes" → Task 2 Step 2. -- Spec §"Tap detection" → Task 4 Step 1 (textItemAtLocation, urlForTapLocation). -- Spec §"`tapActionAtPoint` body" → Task 4 Step 1 (full rewrite). -- Spec §"Concealed flag" default `true` → Task 4 Step 1 inline comment. -- Spec §"Highlight feedback" (`makeActivate`, `computeHighlightRects`, `updateLinkProgressState`) → Task 4 Step 1. -- Spec §"Item-callback wiring" → Task 3 Step 1. -- Spec §"Helpers" (`splitAnchor`, `currentLoadedWebpage`, `scrollToAnchor`) → Task 2 Step 3. -- Spec §"Verification" → Task 5 (manual smoke). -- Spec §"Out of scope" stays out of scope; no tasks added. - -All sections covered. - -**Placeholder scan:** TODO markers exist *only* inside the generated stub callbacks (intentional, per spec) and in the body of `scrollToAnchor` (intentional placeholder). No "TBD"/"fill in details"/"similar to Task N" present. - -**Type consistency:** -- `InstantPageTextItem`, `InstantPageUrlItem`, `InstantPageScrollableItem`, `InstantPageDetailsItem`, `InstantPageDetailsNode` — all referenced consistently across tasks. -- `EnginePeer` — implicit via `openPeer` callback signature (verified against `InstantPageItem.swift:18`). -- `ChatControllerInteraction.OpenUrl` initializer parameters (`url:concealed:external:message:allowInlineWebpageResolution:progress:`) — verified against `ChatControllerInteraction.swift:151`. -- `LinkHighlightingNode(color:)` and `updateRects(_:color:)` — verified against `Display/Source/LinkHighlightingNode.swift:334,346`. -- `splitAnchor` returns `(base: String, anchor: String?)`; consumers in Task 3 Step 1 and Task 4 Step 1 destructure with `let split = self.splitAnchor(...)` then access `split.base` / `split.anchor` — consistent. -- `currentLoadedWebpage()` returns `TelegramMediaWebpageLoadedContent?`; consumers use `webpage.url` which is a property of that type — consistent with the existing usage pattern at line 67 of the file. -- `urlForTapLocation` return tuple labels: `(item, urlItem, parentOffset, localPoint)`. Consumed by `tapActionAtPoint` via `urlHit.item`, `urlHit.urlItem`, `urlHit.parentOffset`, `urlHit.localPoint` — consistent. -- `computeHighlightRects` and `makeActivate` both take `(item:parentOffset:localPoint:)` — consistent. diff --git a/docs/superpowers/plans/2026-05-01-rich-bubble-text-selection.md b/docs/superpowers/plans/2026-05-01-rich-bubble-text-selection.md deleted file mode 100644 index af23d2627f..0000000000 --- a/docs/superpowers/plans/2026-05-01-rich-bubble-text-selection.md +++ /dev/null @@ -1,627 +0,0 @@ -# Rich-bubble text selection Implementation Plan - -> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. - -**Goal:** Wire drag-handle text selection inside `ChatMessageRichDataBubbleContentNode`, available only in context-preview mode, with cross-paragraph selection across all visible `InstantPageTextItem`s. - -**Architecture:** Extend `InstantPageTextItem` with a small public surface (`attributedString` + `attributesAtPoint(_:orNearest:)` + `textRangeRects(in:)`). Add a new `InstantPageMultiTextAdapter` that implements `TextNodeProtocol` by aggregating multiple items into one character-indexed view. In the rich-bubble, gate selection on `updateIsExtractedToContextPreview`, mirroring `ChatMessageTextBubbleContentNode`. - -**Tech Stack:** Swift, AsyncDisplayKit, Bazel (`build-system/Make/Make.py`); modules `Display` (TextNodeProtocol, TextRangeRectEdge), `InstantPageUI` (text item + new adapter), `TextSelectionNode`, `ChatControllerInteraction`. - -**Reference spec:** `docs/superpowers/specs/2026-05-01-rich-bubble-text-selection-design.md` - -**Project context:** No automated tests (per `CLAUDE.md`). Per-task verification is "Bazel build green" using: - -```sh -source ~/.zshrc 2>/dev/null; python3 build-system/Make/Make.py --overrideXcodeVersion \ - --cacheDir ~/telegram-bazel-cache \ - build \ - --configurationPath build-system/appstore-configuration.json \ - --gitCodesigningRepository git@gitlab.com:peter-iakovlev/fastlanematch.git \ - --gitCodesigningType development --gitCodesigningUseCurrent --buildNumber=1 --configuration=debug_sim_arm64 \ - --continueOnError -``` - -The final task is a manual smoke test in the simulator. - -**Working-tree note:** The user has unrelated WIP modifications in the tree (notably `submodules/InstantPageUI/Sources/InstantPageLayout.swift`, `InstantPageControllerNode.swift`, `InstantPageTheme.swift`, plus a `lineSpacingFactor: 0.9` addition in the rich-bubble). DO NOT touch those files except for the specific edits this plan calls out. Use `git add ` — never `git add -A` / `git add .`. - ---- - -## File map - -- **Modify:** `submodules/InstantPageUI/Sources/InstantPageTextItem.swift` — promote `attributedString` to public; add a new public `attributesAtPoint(_:orNearest:)` extending the existing internal one; add a new public `textRangeRects(in:)` returning `Display.TextRangeRectEdge`. -- **Create:** `submodules/InstantPageUI/Sources/InstantPageMultiTextAdapter.swift` — new file containing `InstantPageMultiTextAdapter: ASDisplayNode, TextNodeProtocol`. No BUILD changes needed; the file is picked up by `glob(["Sources/**/*.swift"])` and `Display` is already a dep of `InstantPageUI`. -- **Modify:** `submodules/TelegramUI/Components/Chat/ChatMessageRichDataBubbleContentNode/BUILD` — add `//submodules/TextSelectionNode` to `deps`. -- **Modify:** `submodules/TelegramUI/Components/Chat/ChatMessageRichDataBubbleContentNode/Sources/ChatMessageRichDataBubbleContentNode.swift` — add `import TextSelectionNode`, two new ivars, and the lifecycle hooks. - -No other files change. - ---- - -### Task 1: Public surface on `InstantPageTextItem` - -Three accessors become public so the adapter (defined in Task 2, in the same module) and external consumers can compose with the item. - -**Files:** -- Modify: `submodules/InstantPageUI/Sources/InstantPageTextItem.swift` - -- [ ] **Step 1: Promote `attributedString` to public** - -Locate (around line 170): -```swift -public final class InstantPageTextItem: InstantPageItem { - let attributedString: NSAttributedString - public let lines: [InstantPageTextLine] -``` - -Replace with: -```swift -public final class InstantPageTextItem: InstantPageItem { - public let attributedString: NSAttributedString - public let lines: [InstantPageTextLine] -``` - -- [ ] **Step 2: Add public `attributesAtPoint(_:orNearest:)`** - -The existing internal method is at line 272 of `InstantPageTextItem.swift`: - -```swift - func attributesAtPoint(_ point: CGPoint) -> (Int, [NSAttributedString.Key: Any])? { - let transformedPoint = CGPoint(x: point.x, y: point.y) - let boundsWidth = self.frame.width - for i in 0 ..< self.lines.count { - let line = self.lines[i] - - let lineFrame = expandedFrameForLine(line, boundingWidth: boundsWidth, alignment: self.alignment) - if lineFrame.insetBy(dx: -5.0, dy: -5.0).contains(transformedPoint) { - var index = CTLineGetStringIndexForPosition(line.line, CGPoint(x: transformedPoint.x - lineFrame.minX, y: transformedPoint.y - lineFrame.minY)) - if index == self.attributedString.length { - index -= 1 - } else if index != 0 { - var glyphStart: CGFloat = 0.0 - CTLineGetOffsetForStringIndex(line.line, index, &glyphStart) - if transformedPoint.x < glyphStart { - index -= 1 - } - } - if index >= 0 && index < self.attributedString.length { - return (index, self.attributedString.attributes(at: index, effectiveRange: nil)) - } - break - } - } - return nil - } -``` - -Leave that method untouched (it's still used by `urlAttribute(at:)` and `linkSelectionRects(at:)`). Immediately after it, add the new public method: - -```swift - public func attributesAtPoint(_ point: CGPoint, orNearest: Bool) -> (Int, [NSAttributedString.Key: Any])? { - if let direct = self.attributesAtPoint(point) { - return direct - } - guard orNearest, !self.lines.isEmpty else { - return nil - } - - let boundsWidth = self.frame.width - var nearestLineIndex = 0 - var nearestDistance = CGFloat.greatestFiniteMagnitude - for i in 0 ..< self.lines.count { - let lineFrame = expandedFrameForLine(self.lines[i], boundingWidth: boundsWidth, alignment: self.alignment) - let distance: CGFloat - if point.y < lineFrame.minY { - distance = lineFrame.minY - point.y - } else if point.y > lineFrame.maxY { - distance = point.y - lineFrame.maxY - } else { - distance = 0.0 - } - if distance < nearestDistance { - nearestDistance = distance - nearestLineIndex = i - } - } - - let line = self.lines[nearestLineIndex] - let lineFrame = expandedFrameForLine(line, boundingWidth: boundsWidth, alignment: self.alignment) - let clampedX = max(lineFrame.minX, min(lineFrame.maxX, point.x)) - var index = CTLineGetStringIndexForPosition(line.line, CGPoint(x: clampedX - lineFrame.minX, y: 0.0)) - if index == self.attributedString.length { - index -= 1 - } else if index != 0 { - var glyphStart: CGFloat = 0.0 - CTLineGetOffsetForStringIndex(line.line, index, &glyphStart) - if clampedX - lineFrame.minX < glyphStart { - index -= 1 - } - } - guard index >= 0, index < self.attributedString.length else { - return nil - } - return (index, self.attributedString.attributes(at: index, effectiveRange: nil)) - } -``` - -- [ ] **Step 3: Add public `textRangeRects(in:)`** - -The existing internal `rangeRects(in:)` is at line 369 of the file. Leave it untouched. Add a new public method that wraps it and converts the edge type. Place it directly after the existing `rangeRects(in:)` (so the implementations live together). - -```swift - public func textRangeRects(in range: NSRange) -> (rects: [CGRect], start: TextRangeRectEdge, end: TextRangeRectEdge)? { - guard let result = self.rangeRects(in: range), let start = result.start, let end = result.end, !result.rects.isEmpty else { - return nil - } - let startEdge = TextRangeRectEdge(x: start.x, y: start.y, height: start.height) - let endEdge = TextRangeRectEdge(x: end.x, y: end.y, height: end.height) - return (result.rects, startEdge, endEdge) - } -``` - -`TextRangeRectEdge` is in `Display`, which is already imported by `InstantPageTextItem.swift` (verify the imports near the top of the file include `import Display` — it should). - -- [ ] **Step 4: Build to verify** - -```sh -source ~/.zshrc 2>/dev/null; python3 build-system/Make/Make.py --overrideXcodeVersion --cacheDir ~/telegram-bazel-cache build --configurationPath build-system/appstore-configuration.json --gitCodesigningRepository git@gitlab.com:peter-iakovlev/fastlanematch.git --gitCodesigningType development --gitCodesigningUseCurrent --buildNumber=1 --configuration=debug_sim_arm64 --continueOnError -``` - -Expected: build succeeds. - -Note: the user has unrelated WIP that may be breaking the build (a `sideInset` migration in `InstantPageLayout.swift` / `InstantPageControllerNode.swift` / `InstantPageTheme.swift`). If the build fails, check whether the failures mention `sideInset` and are inside those three files. If so, the failure is pre-existing and not from this task — flag it in your report and proceed. If failures are inside `InstantPageTextItem.swift`, those ARE from this task and need fixing. - -- [ ] **Step 5: Commit** - -```sh -git add submodules/InstantPageUI/Sources/InstantPageTextItem.swift -git commit -m "InstantPage: expose text-item attributedString and selection helpers" -``` - ---- - -### Task 2: `InstantPageMultiTextAdapter` - -A `TextNodeProtocol`-conforming `ASDisplayNode` that aggregates multiple `InstantPageTextItem`s into a single character-indexed view, suitable for `TextSelectionNode`. - -**Files:** -- Create: `submodules/InstantPageUI/Sources/InstantPageMultiTextAdapter.swift` - -- [ ] **Step 1: Create the new file with the full adapter** - -Write `submodules/InstantPageUI/Sources/InstantPageMultiTextAdapter.swift` containing exactly: - -```swift -import Foundation -import UIKit -import AsyncDisplayKit -import Display -import TelegramCore - -public final class InstantPageMultiTextAdapter: ASDisplayNode, TextNodeProtocol { - private struct Entry { - let item: InstantPageTextItem - let charOffset: Int - let frameOrigin: CGPoint - } - - private let entries: [Entry] - private let combinedString: NSAttributedString - - public init(items: [InstantPageTextItem]) { - let separator = NSAttributedString(string: "\n\n") - let combined = NSMutableAttributedString() - var entries: [Entry] = [] - for (index, item) in items.enumerated() { - let charOffset = combined.length - entries.append(Entry(item: item, charOffset: charOffset, frameOrigin: item.frame.origin)) - combined.append(item.attributedString) - if index != items.count - 1 { - combined.append(separator) - } - } - self.entries = entries - self.combinedString = combined - super.init() - self.isUserInteractionEnabled = false - } - - public var currentText: NSAttributedString? { - return self.combinedString - } - - public func attributesAtPoint(_ point: CGPoint, orNearest: Bool) -> (Int, [NSAttributedString.Key: Any])? { - for entry in self.entries { - let localPoint = CGPoint(x: point.x - entry.frameOrigin.x, y: point.y - entry.frameOrigin.y) - if let (localIndex, attrs) = entry.item.attributesAtPoint(localPoint, orNearest: false) { - return (entry.charOffset + localIndex, attrs) - } - } - guard orNearest, !self.entries.isEmpty else { - return nil - } - var nearestEntry = self.entries[0] - var nearestDistance = CGFloat.greatestFiniteMagnitude - for entry in self.entries { - let frame = CGRect(origin: entry.frameOrigin, size: entry.item.frame.size) - let distance: CGFloat - if point.y < frame.minY { - distance = frame.minY - point.y - } else if point.y > frame.maxY { - distance = point.y - frame.maxY - } else { - distance = 0.0 - } - if distance < nearestDistance { - nearestDistance = distance - nearestEntry = entry - } - } - let localPoint = CGPoint(x: point.x - nearestEntry.frameOrigin.x, y: point.y - nearestEntry.frameOrigin.y) - if let (localIndex, attrs) = nearestEntry.item.attributesAtPoint(localPoint, orNearest: true) { - return (nearestEntry.charOffset + localIndex, attrs) - } - return nil - } - - public func textRangeRects(in range: NSRange) -> (rects: [CGRect], start: TextRangeRectEdge, end: TextRangeRectEdge)? { - var allRects: [CGRect] = [] - var startEdge: TextRangeRectEdge? - var endEdge: TextRangeRectEdge? - for entry in self.entries { - let itemLength = entry.item.attributedString.length - let entryRange = NSRange(location: entry.charOffset, length: itemLength) - let intersection = NSIntersectionRange(range, entryRange) - if intersection.length == 0 { - continue - } - let localRange = NSRange(location: intersection.location - entry.charOffset, length: intersection.length) - guard let result = entry.item.textRangeRects(in: localRange) else { - continue - } - for rect in result.rects { - allRects.append(rect.offsetBy(dx: entry.frameOrigin.x, dy: entry.frameOrigin.y)) - } - let translatedStart = TextRangeRectEdge(x: result.start.x + entry.frameOrigin.x, y: result.start.y + entry.frameOrigin.y, height: result.start.height) - let translatedEnd = TextRangeRectEdge(x: result.end.x + entry.frameOrigin.x, y: result.end.y + entry.frameOrigin.y, height: result.end.height) - if startEdge == nil { - startEdge = translatedStart - } - endEdge = translatedEnd - } - guard !allRects.isEmpty, let start = startEdge, let end = endEdge else { - return nil - } - return (allRects, start, end) - } -} -``` - -- [ ] **Step 2: Build to verify** - -```sh -source ~/.zshrc 2>/dev/null; python3 build-system/Make/Make.py --overrideXcodeVersion --cacheDir ~/telegram-bazel-cache build --configurationPath build-system/appstore-configuration.json --gitCodesigningRepository git@gitlab.com:peter-iakovlev/fastlanematch.git --gitCodesigningType development --gitCodesigningUseCurrent --buildNumber=1 --configuration=debug_sim_arm64 --continueOnError -``` - -Expected: build succeeds. The new file is picked up automatically by `glob(["Sources/**/*.swift"])` in `submodules/InstantPageUI/BUILD` (already verified). `Display` is already a dep so `TextNodeProtocol` and `TextRangeRectEdge` are reachable. - -If the build fails inside the adapter file, fix and re-build. Pre-existing `sideInset` failures elsewhere are not from this task — see Task 1's note. - -- [ ] **Step 3: Commit** - -```sh -git add submodules/InstantPageUI/Sources/InstantPageMultiTextAdapter.swift -git commit -m "InstantPage: add multi-text adapter aggregating items as a TextNodeProtocol" -``` - ---- - -### Task 3: BUILD dep, import, and ivars - -Bring `TextSelectionNode` into the rich-bubble's BUILD graph and add the two new ivars. The lifecycle methods land in Task 4. - -**Files:** -- Modify: `submodules/TelegramUI/Components/Chat/ChatMessageRichDataBubbleContentNode/BUILD` -- Modify: `submodules/TelegramUI/Components/Chat/ChatMessageRichDataBubbleContentNode/Sources/ChatMessageRichDataBubbleContentNode.swift` - -- [ ] **Step 1: Add `TextSelectionNode` to BUILD deps** - -Locate the deps list. Currently it ends with these entries (order approximate; you'll see `GalleryUI` and `TextLoadingEffect` already present from prior work): - -``` - "//submodules/TelegramUI/Components/Chat/ChatMessageBubbleContentNode", - "//submodules/TelegramUI/Components/Chat/ChatMessageItemCommon", - "//submodules/TelegramUI/Components/ChatControllerInteraction", - "//submodules/TelegramUI/Components/TextLoadingEffect", - "//submodules/TelegramUIPreferences", - "//submodules/GalleryUI", - ], -``` - -Append `"//submodules/TextSelectionNode",` immediately before the closing `],`: - -``` - "//submodules/TelegramUI/Components/Chat/ChatMessageBubbleContentNode", - "//submodules/TelegramUI/Components/Chat/ChatMessageItemCommon", - "//submodules/TelegramUI/Components/ChatControllerInteraction", - "//submodules/TelegramUI/Components/TextLoadingEffect", - "//submodules/TelegramUIPreferences", - "//submodules/GalleryUI", - "//submodules/TextSelectionNode", - ], -``` - -- [ ] **Step 2: Add the import** - -In `submodules/TelegramUI/Components/Chat/ChatMessageRichDataBubbleContentNode/Sources/ChatMessageRichDataBubbleContentNode.swift`, the imports currently look like: - -```swift -import Foundation -import UIKit -import AsyncDisplayKit -import Display -import TelegramCore -import Postbox -import SwiftSignalKit -import AccountContext -import ChatMessageBubbleContentNode -import ChatMessageItemCommon -import ChatControllerInteraction -import InstantPageUI -import TelegramUIPreferences -import TextLoadingEffect -``` - -Append `import TextSelectionNode` immediately after `import TextLoadingEffect`: - -```swift -import Foundation -import UIKit -import AsyncDisplayKit -import Display -import TelegramCore -import Postbox -import SwiftSignalKit -import AccountContext -import ChatMessageBubbleContentNode -import ChatMessageItemCommon -import ChatControllerInteraction -import InstantPageUI -import TelegramUIPreferences -import TextLoadingEffect -import TextSelectionNode -``` - -(There may be additional imports below `TextLoadingEffect` from prior work, e.g. `GalleryUI`. If so, place `import TextSelectionNode` after them — order within the import block doesn't matter as long as you don't break alphabetization that already exists.) - -- [ ] **Step 3: Add the two new ivars** - -Locate the existing block of stored properties (currently around lines 27-32 — the `linkProgress*` and `linkHighlightingNode` group): - -```swift - private var linkProgressDisposable: Disposable? - private var linkProgressRects: [CGRect]? - private var linkHighlightingNode: LinkHighlightingNode? - private var linkProgressView: TextLoadingEffectView? -``` - -Append the two new ivars immediately after `linkProgressView`: - -```swift - private var linkProgressDisposable: Disposable? - private var linkProgressRects: [CGRect]? - private var linkHighlightingNode: LinkHighlightingNode? - private var linkProgressView: TextLoadingEffectView? - private var textSelectionAdapter: InstantPageMultiTextAdapter? - private var textSelectionNode: TextSelectionNode? -``` - -- [ ] **Step 4: Build to verify** - -```sh -source ~/.zshrc 2>/dev/null; python3 build-system/Make/Make.py --overrideXcodeVersion --cacheDir ~/telegram-bazel-cache build --configurationPath build-system/appstore-configuration.json --gitCodesigningRepository git@gitlab.com:peter-iakovlev/fastlanematch.git --gitCodesigningType development --gitCodesigningUseCurrent --buildNumber=1 --configuration=debug_sim_arm64 --continueOnError -``` - -Expected: build succeeds. Unused `import TextSelectionNode` and unused private ivars don't trigger Swift warnings, so `-warnings-as-errors` stays clean. - -- [ ] **Step 5: Commit** - -```sh -git add submodules/TelegramUI/Components/Chat/ChatMessageRichDataBubbleContentNode/BUILD submodules/TelegramUI/Components/Chat/ChatMessageRichDataBubbleContentNode/Sources/ChatMessageRichDataBubbleContentNode.swift -git commit -m "Rich bubble: add TextSelectionNode dep and selection ivars" -``` - ---- - -### Task 4: Lifecycle hooks for entering / leaving context preview - -Override `updateIsExtractedToContextPreview(_:)` to set up the adapter + `TextSelectionNode` when the bubble is lifted into the context-menu preview, and `willUpdateIsExtractedToContextPreview(_:)` to tear them down when it leaves. - -**Files:** -- Modify: `submodules/TelegramUI/Components/Chat/ChatMessageRichDataBubbleContentNode/Sources/ChatMessageRichDataBubbleContentNode.swift` - -- [ ] **Step 1: Replace the empty preview-lifecycle stubs** - -The file currently contains two empty overrides (around the area near `updateSearchTextHighlightState`): - -```swift - override public func willUpdateIsExtractedToContextPreview(_ value: Bool) { - } - - override public func updateIsExtractedToContextPreview(_ value: Bool) { - } -``` - -Replace BOTH with: - -```swift - override public func willUpdateIsExtractedToContextPreview(_ value: Bool) { - if !value, let textSelectionNode = self.textSelectionNode { - self.textSelectionNode = nil - self.textSelectionAdapter = nil - textSelectionNode.highlightAreaNode.layer.animateAlpha(from: 1.0, to: 0.0, duration: 0.2, removeOnCompletion: false) - textSelectionNode.layer.animateAlpha(from: 1.0, to: 0.0, duration: 0.2, removeOnCompletion: false, completion: { [weak textSelectionNode] _ in - textSelectionNode?.highlightAreaNode.removeFromSupernode() - textSelectionNode?.removeFromSupernode() - }) - } - } - - override public func updateIsExtractedToContextPreview(_ value: Bool) { - guard value, self.textSelectionNode == nil, let messageItem = self.item, let layout = self.currentPageLayout?.layout, let rootNode = messageItem.controllerInteraction.chatControllerNode() else { - return - } - - let items = layout.items.compactMap { $0 as? InstantPageTextItem }.filter { $0.selectable && !$0.attributedString.string.isEmpty } - guard !items.isEmpty else { - return - } - - let adapter = InstantPageMultiTextAdapter(items: items) - adapter.frame = self.containerNode.bounds - self.textSelectionAdapter = adapter - self.containerNode.addSubnode(adapter) - - let incoming = messageItem.message.effectivelyIncoming(messageItem.context.account.peerId) - let theme = messageItem.presentationData.theme.theme - let selectionColor = incoming ? theme.chat.message.incoming.textSelectionColor : theme.chat.message.outgoing.textSelectionColor - let knobColor = incoming ? theme.chat.message.incoming.textSelectionKnobColor : theme.chat.message.outgoing.textSelectionKnobColor - - let textSelectionNode = TextSelectionNode( - theme: TextSelectionTheme(selection: selectionColor, knob: knobColor, isDark: theme.overallDarkAppearance), - strings: messageItem.presentationData.strings, - textNodeOrView: .node(adapter), - updateIsActive: { _ in }, - present: { [weak self] c, a in - guard let self, let item = self.item else { - return - } - if let subject = item.associatedData.subject, case let .messageOptions(_, _, info) = subject, case .reply = info { - item.controllerInteraction.presentControllerInCurrent(c, a) - } else { - item.controllerInteraction.presentGlobalOverlayController(c, a) - } - }, - rootView: { [weak rootNode] in - return rootNode?.view - }, - performAction: { [weak self] text, action in - guard let self, let item = self.item else { - return - } - item.controllerInteraction.performTextSelectionAction(item.message, true, text, nil, action) - } - ) - - let enableCopy = (!messageItem.associatedData.isCopyProtectionEnabled && !messageItem.message.isCopyProtected()) || messageItem.message.id.peerId.isVerificationCodes - textSelectionNode.enableCopy = enableCopy - textSelectionNode.enableQuote = false - textSelectionNode.enableTranslate = true - textSelectionNode.enableShare = true - textSelectionNode.enableLookup = true - - textSelectionNode.frame = self.containerNode.bounds - textSelectionNode.highlightAreaNode.frame = self.containerNode.bounds - self.containerNode.addSubnode(textSelectionNode.highlightAreaNode) - self.containerNode.addSubnode(textSelectionNode) - self.textSelectionNode = textSelectionNode - } -``` - -Notes on this block: -- `chatControllerNode()` returns `ASDisplayNode?` from `ChatControllerInteraction`. The `rootView` closure weakly captures it. -- `TextSelectionTheme(selection:knob:isDark:)` — verified against `submodules/TextSelectionNode/Sources/TextSelectionNode.swift:66`. -- `TextSelectionNode(theme:strings:textNodeOrView:updateIsActive:present:rootView:externalKnobSurface:performAction:)` — verified against the same file at line 296. We omit `externalKnobSurface` (defaulted to `nil`). -- `controllerInteraction.performTextSelectionAction(_:_:_:_:_:)` signature `(Message?, Bool, NSAttributedString, [MessageTextEntity]?, TextSelectionAction)` — verified against `ChatControllerInteraction.swift:263`. -- The `subject` pattern `case let .messageOptions(_, _, info) = subject, case .reply = info` mirrors `ChatMessageTextBubbleContentNode.swift:1651-1654`. -- `enableLookup` defaults to `true` on `TextSelectionNode`; we set it explicitly for clarity. -- The capture `[weak self]` in `present` and `performAction` is enough; we don't need to retain `self` from inside those closures because the bubble node stays alive while the selection node does. - -- [ ] **Step 2: Build to verify** - -```sh -source ~/.zshrc 2>/dev/null; python3 build-system/Make/Make.py --overrideXcodeVersion --cacheDir ~/telegram-bazel-cache build --configurationPath build-system/appstore-configuration.json --gitCodesigningRepository git@gitlab.com:peter-iakovlev/fastlanematch.git --gitCodesigningType development --gitCodesigningUseCurrent --buildNumber=1 --configuration=debug_sim_arm64 --continueOnError -``` - -Expected: build succeeds. - -Common likely errors and fixes: -- "value of type 'ChatMessageItemAssociatedData' has no member 'isCopyProtectionEnabled'" → property name has changed; grep `submodules/TelegramUI/Components/Chat/ChatMessageItemCommon/Sources/` for the canonical name and substitute. -- "value of type 'PeerId' has no member 'isVerificationCodes'" → grep `submodules/TelegramCore/Sources/` for `isVerificationCodes` and import the right module if missing. -- "instance method 'presentControllerInCurrent' requires…" / similar — both `presentControllerInCurrent` and `presentGlobalOverlayController` exist on `ChatControllerInteraction` (lines 219 and 222 of `ChatControllerInteraction.swift`); their signatures take `(ViewController, Any?)`. -- Missing pre-existing failures from the user's `sideInset` migration are NOT from this task — see Task 1 Step 4's note. - -- [ ] **Step 3: Commit** - -```sh -git add submodules/TelegramUI/Components/Chat/ChatMessageRichDataBubbleContentNode/Sources/ChatMessageRichDataBubbleContentNode.swift -git commit -m "Rich bubble: drag-handle text selection in context-preview mode" -``` - ---- - -### Task 5: Manual smoke verification - -There are no automated tests for chat UI. Final task is a hands-on smoke test in the simulator. - -**Files:** none modified. Verification only. - -- [ ] **Step 1: Launch the app in the simulator** - -The build command run in earlier tasks produces the app binary; launch via Xcode (open `Telegram-iOS.xcworkspace` if the workspace exists locally) or run the Bazel-produced target. Sign in to a real test account. - -- [ ] **Step 2: Find or send a message with a rich-data IV preview** - -Send a Telegraph or t.me URL that produces an instant-view preview. The `debugRichText` experimental setting must be enabled for the preview to render via `ChatMessageRichDataBubbleContentNode` instead of the standard webpage card. (`ChatMessageBubbleItemNode.swift:386-387` is the gate.) - -- [ ] **Step 3: Long-press the bubble** - -Long-press the rich-data bubble. The framework lifts it into the context-preview popover, the message context menu appears alongside. - -- [ ] **Step 4: Drag-select text** - -Tap and drag inside the lifted preview. Drag-handles (knobs) should appear; the selection should extend across paragraphs as you drag. The selection background uses the incoming/outgoing `textSelectionColor` from the current theme. - -- [ ] **Step 5: Verify the action menu** - -The action menu (Copy / Translate / Share / Speak / Look Up) should appear anchored on the selection. Verify: -- Copy: places the selected text on the pasteboard. Multi-paragraph selections include `\n\n` between paragraphs. -- Quote menu item is **not** present (we explicitly disabled it). -- Translate / Share / Speak / Look Up route through the standard chat flow and behave normally. - -- [ ] **Step 6: Dismiss the context preview** - -Tap outside the preview or scroll away. The selection overlay and knobs fade out cleanly (alpha 1→0 over 0.2s), and the bubble returns to its normal state. Re-opening the context preview should re-create the selection nodes from scratch. - -- [ ] **Step 7: Sign-off** - -If steps 4–6 behave as described, the change is complete. If any step fails, capture: which step, observed vs. expected, any console output. Common deviations: -- Knobs never appear → confirm `textSelectionNode.frame` and `textSelectionNode.highlightAreaNode.frame` are both `containerNode.bounds`. If `containerNode.bounds.size` is zero at the moment of preview entry, the selection node has nothing to draw on. -- Selection rects don't line up with text → confirm `adapter.frame.origin` is `.zero` and item frames in the layout are in `containerNode`-local coords (the layout origin is `(0, 0)` inside `containerNode`; the `(1, 1)` outer offset doesn't apply here because the selection nodes live INSIDE `containerNode`). -- Cross-paragraph drag stops at paragraph boundaries → confirm `attributesAtPoint` falls through to the nearest-entry branch when `orNearest == true`. -- Copy includes wrong text → confirm `combinedString` interleaves `"\n\n"` separators between items. - ---- - -## Self-review - -**Spec coverage:** -- Spec §"API exposure on `InstantPageTextItem`" → Task 1 (all three accessors). -- Spec §"`InstantPageMultiTextAdapter`" → Task 2 (full adapter). -- Spec §"Rich-bubble lifecycle wiring" — ivars/import/BUILD dep → Task 3; `updateIsExtractedToContextPreview` / `willUpdateIsExtractedToContextPreview` → Task 4. -- Spec §"Verification" → Task 5 (manual smoke). -- Spec §"Out of scope" stays out of scope; no tasks added. - -All spec sections covered. - -**Placeholder scan:** None of the "TBD" / "TODO" / "implement later" / "similar to Task N" patterns are present. Each step shows the actual code or command. - -**Type consistency:** -- `InstantPageMultiTextAdapter` is named the same in Task 2 (definition) and Tasks 3–4 (consumers). -- `Entry` struct is internal to the adapter and not referenced externally. -- `InstantPageTextItem.attributesAtPoint(_:orNearest:)` and `textRangeRects(in:)` are defined in Task 1 with the same signatures the adapter calls in Task 2. -- `TextSelectionNode` initializer parameters in Task 4 match the verified signature from `submodules/TextSelectionNode/Sources/TextSelectionNode.swift:296` (`theme`, `strings`, `textNodeOrView`, `updateIsActive`, `present`, `rootView`, `performAction` — no `externalKnobSurface`). -- `TextSelectionTheme(selection:knob:isDark:)` matches the verified init at line 66 of the same file. -- `controllerInteraction.performTextSelectionAction` invocation matches `(Message?, Bool, NSAttributedString, [MessageTextEntity]?, TextSelectionAction)` from line 263 of `ChatControllerInteraction.swift`. -- `subject` pattern `.messageOptions(_, _, info)` with `case .reply = info` mirrors text-bubble exactly. diff --git a/docs/superpowers/plans/2026-05-01-rich-data-bubble-scroll-to-anchor.md b/docs/superpowers/plans/2026-05-01-rich-data-bubble-scroll-to-anchor.md deleted file mode 100644 index bcdfa83373..0000000000 --- a/docs/superpowers/plans/2026-05-01-rich-data-bubble-scroll-to-anchor.md +++ /dev/null @@ -1,504 +0,0 @@ -# Rich-Data Bubble scrollToAnchor Implementation Plan - -> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. - -**Goal:** Make `ChatMessageRichDataBubbleContentNode.scrollToAnchor` actually scroll the chat history so that an in-page anchor's line lands at the top of the visible content area. - -**Architecture:** Mirror the existing `getQuoteRect` mechanism. The rich-data bubble exposes `getAnchorRect(anchor:)`, the bubble item node forwards to it. A new `ChatControllerInteraction.scrollToMessageIdWithAnchor` closure walks visible items via `forEachVisibleItemNode` (the bubble is necessarily at least partially visible because the user tapped a link in it), reads the anchor's item-local y, and routes through `ChatHistoryListNode.scrollToMessage(... scrollPosition: .bottom(anchorY))`. `.bottom` places the item so the anchor lands at the visual top of the content area; it works uniformly for short and tall items, where `.center(.custom)` is bypassed for items that fit in the content area. - -**Tech Stack:** Swift, Bazel build, AsyncDisplayKit. No unit tests in this project — verification is a full Bazel build. - -**Spec:** [docs/superpowers/specs/2026-05-01-rich-data-bubble-scroll-to-anchor-design.md](../specs/2026-05-01-rich-data-bubble-scroll-to-anchor-design.md) - -**Build command (run after each task):** - -```sh -source ~/.zshrc 2>/dev/null; \ -python3 build-system/Make/Make.py --overrideXcodeVersion --cacheDir ~/telegram-bazel-cache build \ - --configurationPath build-system/appstore-configuration.json \ - --gitCodesigningRepository git@gitlab.com:peter-iakovlev/fastlanematch.git \ - --gitCodesigningType development --gitCodesigningUseCurrent \ - --buildNumber=1 --configuration=debug_sim_arm64 -``` - -After Tasks 1–3 the build must be green; the feature is not yet live (no callers use the new methods). After Task 4 the new closure exists and is implemented but the bubble still routes through the old stub. After Task 5 the feature is live. - ---- - -## Task 1: Add base `getAnchorRect` to `ChatMessageBubbleContentNode` - -This makes `getAnchorRect(anchor:)` callable on every content node (returns `nil` by default) so the iteration in `ChatMessageBubbleItemNode` doesn't need a type-test. - -**Files:** -- Modify: `submodules/TelegramUI/Components/Chat/ChatMessageBubbleContentNode/Sources/ChatMessageBubbleContentNode.swift` - -- [ ] **Step 1: Add the base method** - -Open the file. Find the existing `open func transitionNode(messageId:media:adjustRect:) -> (...)` definition (around line 261). Add a new method directly after its closing brace: - -```swift -open func getAnchorRect(anchor: String) -> CGRect? { - return nil -} -``` - -The result is that the file should contain, contiguously: - -```swift -open func transitionNode(messageId: MessageId, media: Media, adjustRect: Bool) -> (ASDisplayNode, CGRect, () -> (UIView?, UIView?))? { - return nil -} - -open func getAnchorRect(anchor: String) -> CGRect? { - return nil -} - -open func updateHiddenMedia(_ media: [Media]?) -> Bool { - return false -} -``` - -- [ ] **Step 2: Build** - -Run the build command at the top of this plan. -Expected: build succeeds. - -- [ ] **Step 3: Commit** - -```sh -git add submodules/TelegramUI/Components/Chat/ChatMessageBubbleContentNode/Sources/ChatMessageBubbleContentNode.swift -git commit -m "$(cat <<'EOF' -ChatMessageBubbleContentNode: add base getAnchorRect - -Co-Authored-By: Claude Opus 4.7 (1M context) -EOF -)" -``` - ---- - -## Task 2: Override `getAnchorRect` in `ChatMessageRichDataBubbleContentNode` - -Walks the cached instant-page layout and returns the rect of an anchor (in the bubble content node's coordinate space) without triggering any side-effects. - -**Files:** -- Modify: `submodules/TelegramUI/Components/Chat/ChatMessageRichDataBubbleContentNode/Sources/ChatMessageRichDataBubbleContentNode.swift` - -- [ ] **Step 1: Add the override and recursive helper** - -Open the file. Find the existing `private func splitAnchor(_ url: String)` (around line 774). Insert two new methods directly above it (so the new public override comes before the private string helpers but after `findInstantPageMedia`): - -```swift -override public func getAnchorRect(anchor: String) -> CGRect? { - guard let layout = self.currentPageLayout?.layout else { - return nil - } - if let rect = self.anchorRect(in: layout.items, anchor: anchor, baseY: 0.0) { - // Translate from layout/containerNode coords to bubble-content-node coords. - // containerNode is offset by (1, 1) from the bubble content node. - return rect.offsetBy(dx: 1.0, dy: 1.0) - } - return nil -} - -private func anchorRect(in items: [InstantPageItem], anchor: String, baseY: CGFloat) -> CGRect? { - for item in items { - if let item = item as? InstantPageAnchorItem, item.anchor == anchor { - return CGRect(x: item.frame.minX, y: baseY + item.frame.minY, width: 1.0, height: 1.0) - } else if let item = item as? InstantPageTextItem { - if let (lineIndex, _) = item.anchors[anchor] { - let lineFrame = item.lines[lineIndex].frame - return CGRect(x: item.frame.minX + lineFrame.minX, y: baseY + item.frame.minY + lineFrame.minY, width: lineFrame.width, height: lineFrame.height) - } - } else if let item = item as? InstantPageTableItem { - if let (offset, _) = item.anchors[anchor] { - return CGRect(x: item.frame.minX, y: baseY + item.frame.minY + offset, width: item.frame.width, height: 1.0) - } - } else if let item = item as? InstantPageDetailsItem { - // Inner items are laid out below the title bar, so the recursive base - // must include titleHeight (mirrors InstantPageDetailsNode.linkSelectionRects). - if let rect = self.anchorRect(in: item.items, anchor: anchor, baseY: baseY + item.frame.minY + item.titleHeight) { - return rect - } - } - } - return nil -} -``` - -Note: the existing file already imports `InstantPageUI`, so `InstantPageItem`, `InstantPageAnchorItem`, `InstantPageTextItem`, `InstantPageTableItem`, and `InstantPageDetailsItem` resolve. `InstantPageTextItem.anchors` is typed `[String: (Int, Bool)]`, `InstantPageTableItem.anchors` is `[String: (CGFloat, Bool)]` — destructure accordingly. - -- [ ] **Step 2: Build** - -Run the build command. -Expected: build succeeds. - -- [ ] **Step 3: Commit** - -```sh -git add submodules/TelegramUI/Components/Chat/ChatMessageRichDataBubbleContentNode/Sources/ChatMessageRichDataBubbleContentNode.swift -git commit -m "$(cat <<'EOF' -Rich bubble: add getAnchorRect override - -Co-Authored-By: Claude Opus 4.7 (1M context) -EOF -)" -``` - ---- - -## Task 3: Forward `getAnchorRect` from `ChatMessageBubbleItemNode` - -Iterates content nodes and converts the rect to the bubble item node's coordinate space. Mirrors the existing `getQuoteRect` shape exactly. - -**Files:** -- Modify: `submodules/TelegramUI/Components/Chat/ChatMessageBubbleItemNode/Sources/ChatMessageBubbleItemNode.swift` - -- [ ] **Step 1: Add the public forwarder** - -Open the file. Find the existing `public func getQuoteRect(quote: String, offset: Int?) -> CGRect?` (around line 7237). Insert a new method directly after its closing brace, before `public func getInnerReplySubjectRect(...)`: - -```swift -public func getAnchorRect(anchor: String) -> CGRect? { - for contentNode in self.contentNodes { - if let result = contentNode.getAnchorRect(anchor: anchor) { - return contentNode.view.convert(result, to: self.view) - } - } - return nil -} -``` - -- [ ] **Step 2: Build** - -Run the build command. -Expected: build succeeds. - -- [ ] **Step 3: Commit** - -```sh -git add submodules/TelegramUI/Components/Chat/ChatMessageBubbleItemNode/Sources/ChatMessageBubbleItemNode.swift -git commit -m "$(cat <<'EOF' -Bubble item: forward getAnchorRect to content nodes - -Co-Authored-By: Claude Opus 4.7 (1M context) -EOF -)" -``` - ---- - -## Task 4: Add `scrollToMessageIdWithAnchor` closure (declaration + 7 sites) - -Adds the new `(MessageIndex, String) -> Void` closure to `ChatControllerInteraction`, the real implementation in `ChatController.swift`, and no-op stubs at the six other call sites. After this task the build is green and the closure works end-to-end on the chat-controller side; the rich-data bubble still routes through the old stub so the feature is not yet live. - -**Files (8 edits):** -- Modify: `submodules/TelegramUI/Components/ChatControllerInteraction/Sources/ChatControllerInteraction.swift` (3 edits: field, init param, assignment) -- Modify: `submodules/TelegramUI/Sources/ChatController.swift` (real implementation) -- Modify: `submodules/BrowserUI/Sources/BrowserBookmarksScreen.swift` (no-op stub) -- Modify: `submodules/TelegramUI/Components/Chat/ChatRecentActionsController/Sources/ChatRecentActionsControllerNode.swift` (no-op stub) -- Modify: `submodules/TelegramUI/Components/Chat/ChatSendAudioMessageContextPreview/Sources/ChatSendAudioMessageContextPreview.swift` (no-op stub) -- Modify: `submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoScreen.swift` (no-op stub) -- Modify: `submodules/TelegramUI/Sources/OverlayAudioPlayerControllerNode.swift` (no-op stub) -- Modify: `submodules/TelegramUI/Sources/SharedAccountContext.swift` (no-op stub) - -- [ ] **Step 1: Add the field on `ChatControllerInteraction`** - -In `submodules/TelegramUI/Components/ChatControllerInteraction/Sources/ChatControllerInteraction.swift`, find: - -```swift -public let scrollToMessageId: (MessageIndex, CGFloat) -> Void -``` - -(around line 311). Insert directly after it: - -```swift -public let scrollToMessageIdWithAnchor: (MessageIndex, String) -> Void -``` - -- [ ] **Step 2: Add the init parameter** - -In the same file, find the init parameter list (around line 490): - -```swift -scrollToMessageId: @escaping (MessageIndex, CGFloat) -> Void, -``` - -Insert directly after it: - -```swift -scrollToMessageIdWithAnchor: @escaping (MessageIndex, String) -> Void, -``` - -- [ ] **Step 3: Add the init assignment** - -In the same file, find (around line 622): - -```swift -self.scrollToMessageId = scrollToMessageId -``` - -Insert directly after it: - -```swift -self.scrollToMessageIdWithAnchor = scrollToMessageIdWithAnchor -``` - -- [ ] **Step 4: Add real implementation in `ChatController.swift`** - -In `submodules/TelegramUI/Sources/ChatController.swift`, find (around line 5397): - -```swift -}, scrollToMessageId: { [weak self] index, offset in - self?.chatDisplayNode.historyNode.scrollToMessage(index: index, offset: offset) -}, navigateToStory: { [weak self] message, storyId in -``` - -Insert a new closure between `scrollToMessageId` and `navigateToStory`: - -```swift -}, scrollToMessageId: { [weak self] index, offset in - self?.chatDisplayNode.historyNode.scrollToMessage(index: index, offset: offset) -}, scrollToMessageIdWithAnchor: { [weak self] index, anchor in - guard let self else { - return - } - var anchorY: CGFloat? - self.chatDisplayNode.historyNode.forEachVisibleItemNode { itemNode in - guard anchorY == nil else { - return - } - if let itemNode = itemNode as? ChatMessageBubbleItemNode, - itemNode.item?.message.id == index.id, - let rect = itemNode.getAnchorRect(anchor: anchor) { - anchorY = rect.minY - } - } - if let anchorY { - self.chatDisplayNode.historyNode.scrollToMessage( - from: index, to: index, - animated: true, highlight: false, - scrollPosition: .bottom(anchorY) - ) - } else { - self.chatDisplayNode.historyNode.scrollToMessage(index: index) - } -}, navigateToStory: { [weak self] message, storyId in -``` - -`scrollToMessage(from:to:animated:highlight:scrollPosition:)` is the existing public method on `ChatHistoryListNode` (declared at line 3585 in `ChatHistoryListNode.swift`); `quote`, `subject`, and `setupReply` use their default values. `ChatMessageBubbleItemNode` is already imported at the top of `ChatController.swift`. The `forEachVisibleItemNode` walk is sound because tapping the in-page anchor link requires the bubble to be at least partially visible. - -- [ ] **Step 5: Add no-op stub in `BrowserBookmarksScreen.swift`** - -In `submodules/BrowserUI/Sources/BrowserBookmarksScreen.swift`, find (around line 183): - -```swift -}, scrollToMessageId: { _, _ in -``` - -Replace with: - -```swift -}, scrollToMessageId: { _, _ in -}, scrollToMessageIdWithAnchor: { _, _ in -``` - -- [ ] **Step 6: Add no-op stub in `ChatRecentActionsControllerNode.swift`** - -In `submodules/TelegramUI/Components/Chat/ChatRecentActionsController/Sources/ChatRecentActionsControllerNode.swift`, find (around line 660): - -```swift -}, scrollToMessageId: { _, _ in -``` - -Replace with: - -```swift -}, scrollToMessageId: { _, _ in -}, scrollToMessageIdWithAnchor: { _, _ in -``` - -- [ ] **Step 7: Add no-op stub in `ChatSendAudioMessageContextPreview.swift`** - -In `submodules/TelegramUI/Components/Chat/ChatSendAudioMessageContextPreview/Sources/ChatSendAudioMessageContextPreview.swift`, find (around line 507): - -```swift -}, scrollToMessageId: { _, _ in -``` - -Replace with: - -```swift -}, scrollToMessageId: { _, _ in -}, scrollToMessageIdWithAnchor: { _, _ in -``` - -- [ ] **Step 8: Add no-op stub in `PeerInfoScreen.swift`** - -In `submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoScreen.swift`, find (around line 1278): - -```swift -}, scrollToMessageId: { _, _ in -``` - -Replace with: - -```swift -}, scrollToMessageId: { _, _ in -}, scrollToMessageIdWithAnchor: { _, _ in -``` - -- [ ] **Step 9: Add no-op stub in `OverlayAudioPlayerControllerNode.swift`** - -In `submodules/TelegramUI/Sources/OverlayAudioPlayerControllerNode.swift`, find (around line 252): - -```swift -}, scrollToMessageId: { _, _ in -``` - -Replace with: - -```swift -}, scrollToMessageId: { _, _ in -}, scrollToMessageIdWithAnchor: { _, _ in -``` - -- [ ] **Step 10: Add no-op stub in `SharedAccountContext.swift`** - -In `submodules/TelegramUI/Sources/SharedAccountContext.swift`, find (around line 2565): - -```swift -scrollToMessageId: { _, _ in -``` - -(Note: this site has no leading `}, ` because it is the first argument on its line — verify with `grep -n "scrollToMessageId:" submodules/TelegramUI/Sources/SharedAccountContext.swift`.) - -Insert a new closure directly after the closing `}` of the `scrollToMessageId` stub. If the original looks like: - -```swift -scrollToMessageId: { _, _ in -}, -navigateToStory: { _, _ in -``` - -it should become: - -```swift -scrollToMessageId: { _, _ in -}, -scrollToMessageIdWithAnchor: { _, _ in -}, -navigateToStory: { _, _ in -``` - -Match the surrounding indentation and trailing-comma style of the file. - -- [ ] **Step 11: Build** - -Run the build command. -Expected: build succeeds. Any compile error in this task means a stub site was missed or the closure type was mismatched — search for `scrollToMessageId:` again and confirm every site has a corresponding `scrollToMessageIdWithAnchor:`. - -- [ ] **Step 12: Commit** - -```sh -git add \ - submodules/TelegramUI/Components/ChatControllerInteraction/Sources/ChatControllerInteraction.swift \ - submodules/TelegramUI/Sources/ChatController.swift \ - submodules/BrowserUI/Sources/BrowserBookmarksScreen.swift \ - submodules/TelegramUI/Components/Chat/ChatRecentActionsController/Sources/ChatRecentActionsControllerNode.swift \ - submodules/TelegramUI/Components/Chat/ChatSendAudioMessageContextPreview/Sources/ChatSendAudioMessageContextPreview.swift \ - submodules/TelegramUI/Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoScreen.swift \ - submodules/TelegramUI/Sources/OverlayAudioPlayerControllerNode.swift \ - submodules/TelegramUI/Sources/SharedAccountContext.swift -git commit -m "$(cat <<'EOF' -ChatControllerInteraction: add scrollToMessageIdWithAnchor closure - -Routes through ChatHistoryListNode.scrollToMessage with a custom -.center(.custom) callback that asks the bubble item for the anchor -rect's midY. Six existing no-op interaction sites get matching -no-op stubs. - -Co-Authored-By: Claude Opus 4.7 (1M context) -EOF -)" -``` - ---- - -## Task 5: Wire up `scrollToAnchor` in the rich-data bubble - -Replace the stub body so that taps on in-page anchor links actually scroll. After this task the feature is live end-to-end. - -**Files:** -- Modify: `submodules/TelegramUI/Components/Chat/ChatMessageRichDataBubbleContentNode/Sources/ChatMessageRichDataBubbleContentNode.swift` - -- [ ] **Step 1: Replace `scrollToAnchor` body** - -In `ChatMessageRichDataBubbleContentNode.swift`, find (around line 796): - -```swift -private func scrollToAnchor(_ anchor: String) { - guard let item = self.item else { - return - } - // 0.0 is offset - item.controllerInteraction.scrollToMessageId(item.message.index, 0.0) -} -``` - -Replace with: - -```swift -private func scrollToAnchor(_ anchor: String) { - guard let item = self.item else { - return - } - if anchor.isEmpty { - item.controllerInteraction.scrollToMessageId(item.message.index, 0.0) - } else { - item.controllerInteraction.scrollToMessageIdWithAnchor(item.message.index, anchor) - } -} -``` - -The empty-anchor branch keeps the existing "scroll to message top" behavior for `#` URLs with no fragment. - -- [ ] **Step 2: Build** - -Run the build command. -Expected: build succeeds. - -- [ ] **Step 3: Manual smoke test** - -This project has no unit tests. Smoke-test in the simulator: - -1. Launch the app on the iOS simulator. -2. Open a chat that contains a webpage message rendered as a rich-data bubble. Good source: a Wikipedia article URL whose Telegram instant-page render contains in-page section/footnote links (e.g., the "Contents" section or the `[1]`-style citation links). -3. Tap a section/footnote link inside the bubble. -4. Expected: the chat scrolls so that the target line of the bubble is centered in the visible area. If the bubble is partially off-screen, the chat scrolls to bring the line into view. -5. Tap a `#`-only link (no fragment) if you can find one. Expected: chat scrolls to the message top (existing pre-task behavior preserved). - -If the scroll doesn't land where expected, double-check the coord conversions in Task 2 (`+1, +1` for `containerNode` inset) and Task 3 (`contentNode.view.convert(rect, to: self.view)`). - -- [ ] **Step 4: Commit** - -```sh -git add submodules/TelegramUI/Components/Chat/ChatMessageRichDataBubbleContentNode/Sources/ChatMessageRichDataBubbleContentNode.swift -git commit -m "$(cat <<'EOF' -Rich bubble: scrollToAnchor scrolls to anchor's line - -Empty anchor keeps the previous scroll-to-message-top behavior. - -Co-Authored-By: Claude Opus 4.7 (1M context) -EOF -)" -``` - ---- - -## Done - -All five tasks complete leaves: -- Each commit independently builds. -- The feature is live: tapping an in-page anchor link inside a rich-data bubble scrolls the chat to center the target line. -- Reference popups and details expansion are deferred (per spec). diff --git a/docs/superpowers/specs/2026-04-30-typing-draft-send-delay-design.md b/docs/superpowers/specs/2026-04-30-typing-draft-send-delay-design.md deleted file mode 100644 index 09952f55d1..0000000000 --- a/docs/superpowers/specs/2026-04-30-typing-draft-send-delay-design.md +++ /dev/null @@ -1,178 +0,0 @@ -# Typing-Draft Send Delay — Design - -**Date:** 2026-04-30 -**Component:** `submodules/TelegramCore/Sources/State/PendingMessageManager.swift` (+ minimal Postbox additions) - -## Goal - -Delay outgoing messages while the peer in the same `(peerId, threadId)` is "live-typing" an incoming message (i.e. `Postbox.combinedView(keys: [.typingDrafts(...)])` reports a non-nil draft for that key). Messages park after their content is fully uploaded, then drain in `messageId.id` order once the typing-draft for that key clears. - -## Behavior summary - -- **Scope.** All "deliver-now" outgoing message types: regular text/media single sends, grouped media albums, and forwards. Excluded: scheduled messages, secret-chat messages, and Saved Messages (account-self peer). -- **Pipeline.** Uploads run in parallel as they do today. The gate sits between "upload complete" and the actual MTProto send call. -- **Release.** As soon as the typing-draft for the message's `(peerId, threadId)` clears (the view's set no longer contains that key) — no extra grace delay, no upper-bound timeout. -- **Keying.** Strictly per-thread. `threadId == nil` is the normal value for non-threaded chats and gates with `PeerAndThreadId(peerId: ..., threadId: nil)`. The `Message.newTopicThreadId` sentinel does not gate (already handled by `.waitingForNewTopic`). -- **Always-on.** No preference toggle. -- **Composes with paid-message postpone.** Paid postpone gates upload-start; typing-draft gate gates post-upload send. Both must be clear before send. - -## Architecture - -All logic lives in `PendingMessageManager`. Postbox gains one new public view; no other Postbox API changes. - -### Postbox additions - -1. New file `submodules/Postbox/Sources/AllTypingDraftsView.swift`: - - `MutableAllTypingDraftsView: MutablePostboxView` - - `init(postbox:)` seeds `keys` from `postbox.currentTypingDrafts.keys`. - - `replay(postbox:transaction:)` diffs against `transaction.updatedTypingDrafts`: insert key when `update.value != nil`, remove when nil. Returns `true` if the set changed. - - `refreshDueToExternalTransaction(postbox:)` reloads from `postbox.currentTypingDrafts.keys` and returns `true`. - - `immutableView()` returns an `AllTypingDraftsView`. - - `public final class AllTypingDraftsView: PostboxView` exposes `public let keys: Set`. -2. `submodules/Postbox/Sources/Views.swift`: - - Add `case allTypingDrafts` to `PostboxViewKey` (no associated payload). - - Wire constant `Hashable` combine and `==` matching for the new case. - - Add the `case .allTypingDrafts` arm to `postboxViewForKey` returning `MutableAllTypingDraftsView(postbox:)`. -3. `PostboxImpl.currentTypingDrafts` is `fileprivate(set)`, accessible from view files in the same module. No new accessor needed. - -### PendingMessageManager additions - -New `PendingMessageState` case: - -```swift -case waitingForSendGate(groupId: Int64?, content: PendingMessageUploadedContentAndReuploadInfo) -``` - -Added to `PendingMessageState.groupId`'s switch. Excluded from `updatePendingMediaUploads`'s upload-progress aggregation. - -New stored state on the manager: - -```swift -private var liveTypingDraftKeys: Set = [] -private let allTypingDraftsDisposable = MetaDisposable() -private var forwardSendGateGroups: [PeerAndThreadId: [[(PendingMessageContext, Message, ForwardSourceInfoAttribute)]]] = [:] -``` - -In `init`, subscribe once: - -```swift -self.allTypingDraftsDisposable.set( - (postbox.combinedView(keys: [.allTypingDrafts]) - |> deliverOn(self.queue)).start(next: { [weak self] view in - self?.handleLiveTypingDraftsUpdate(view) - }) -) -``` - -Dispose in `deinit`. - -## Gate predicate - -```swift -private func isSendGateOpen(for key: PeerAndThreadId) -> Bool { - return !self.liveTypingDraftKeys.contains(key) -} - -private func shouldGateSend(messageId: MessageId, threadId: Int64?) -> Bool { - if messageId.namespace == Namespaces.Message.ScheduledCloud { return false } - if messageId.peerId.namespace == Namespaces.Peer.SecretChat { return false } - if messageId.peerId == self.accountPeerId { return false } - if threadId == Message.newTopicThreadId { return false } - return true -} -``` - -A pending context is gate-applicable if `shouldGateSend(...)` returns true. The gate is open if `isSendGateOpen(...)` returns true. Sites delay the send only when `shouldGateSend && !isSendGateOpen`. - -## Gate insertion points - -### (a) Single-message — `beginSendingMessage(messageContext:messageId:groupId:content:)` - -Today: `groupId == nil → commitSendingSingleMessage`; otherwise `state = .waitingToBeSent(groupId: ..., content: ...)`. - -New: when `groupId == nil`, additionally check the gate: - -```swift -let key = PeerAndThreadId(peerId: messageId.peerId, threadId: messageContext.threadId) -if shouldGateSend(messageId: messageId, threadId: messageContext.threadId) && !isSendGateOpen(for: key) { - messageContext.state = .waitingForSendGate(groupId: nil, content: content) -} else { - self.commitSendingSingleMessage(messageContext: messageContext, messageId: messageId, content: content) -} -``` - -The grouped path (`groupId != nil`) is unchanged here; gating for albums happens in (b). - -### (b) Grouped-album — `commitSendingMessageGroup(groupId:messages:)` - -Today: flips every group context to `.sending(groupId:)`, fires `sendGroupMessagesContent`. - -New: derive a representative key from the first message's `(peerId, threadId)`. (Group members share both by construction.) If `shouldGateSend && !isSendGateOpen`, flip every group context to `.waitingForSendGate(groupId: groupId, content: )` and return. Otherwise unchanged. - -`dataForPendingMessageGroup(_ groupId:)` is updated to recognize `.waitingForSendGate(groupId: contextGroupId, ...)` the same way it recognizes `.waitingToBeSent` — i.e. a group becomes "ready" when every member is in `.waitingToBeSent` OR `.waitingForSendGate`. This prevents partial-park deadlocks. - -### (c) Forwards — inside `beginSendingMessages`, lines 714–733 - -Today: builds `countedMessageGroups` and immediately fires `sendGroupMessagesContent` per group. - -The pre-existing `messagesToForward` bucketing is by `PeerIdAndNamespace` only — not by `threadId`. The downstream `sendGroupMessagesContent` network call requires thread homogeneity (a forward dispatch targets a single destination thread), so in practice every group already shares `threadId`. The gate uses this assumption: derive the key from `messages[0].1.threadId` of each `countedMessageGroup`. If a future caller violates the assumption, the existing dispatch path is already broken. - -New: per group, derive `key = PeerAndThreadId(peerId: messages[0].1.id.peerId, threadId: messages[0].1.threadId)`. If `shouldGateSend && !isSendGateOpen`, flip every context in the group to `.waitingForSendGate(groupId: nil, content: PendingMessageUploadedContentAndReuploadInfo(content: .forward(forwardInfo), reuploadInfo: nil, cacheReferenceKey: nil))` and append the entire `[(PendingMessageContext, Message, ForwardSourceInfoAttribute)]` group to `forwardSendGateGroups[key]`. Otherwise fire as today. - -Forward groups within a key drain in FIFO order. - -## Drain logic - -`drainSendGate(key: PeerAndThreadId)` runs on `self.queue`. Idempotent. - -1. **Single-message drain.** Snapshot `messageContexts` filtering on `state == .waitingForSendGate(groupId: nil, ...)` AND `PeerAndThreadId(peerId: contextId.peerId, threadId: context.threadId) == key`. Sort by `messageId.id` ascending. For each, extract the parked `content`, call `commitSendingSingleMessage(messageContext:messageId:content:)`. -2. **Grouped-album drain.** Collect distinct `groupId`s among `.waitingForSendGate(groupId: , ...)` contexts whose key matches. Iterate in ascending min-`messageId.id`-in-group order. For each, call `dataForPendingMessageGroup(groupId)` (which now sees the parked members as ready) and pass the result to `commitSendingMessageGroup(groupId:messages:)`. -3. **Forward drain.** Pop `forwardSendGateGroups.removeValue(forKey: key)`. For each parked group (FIFO): flip every context to `.sending(groupId: nil)`, build the `[(MessageId, PendingMessageUploadedContentAndReuploadInfo)]` array, fire `sendGroupMessagesContent` exactly mirroring the existing forward-fire code (lines 719–731). -4. After (1)–(3), call `updateWaitingUploads(peerId: key.peerId)` and `updatePendingMediaUploads()` once. - -`handleLiveTypingDraftsUpdate(_ view: CombinedView)`: - -```swift -let view = (view.views[.allTypingDrafts] as? AllTypingDraftsView) -let new = view?.keys ?? [] -let cleared = self.liveTypingDraftKeys.subtracting(new) -self.liveTypingDraftKeys = new -for key in cleared { - self.drainSendGate(key: key) -} -``` - -Single-emission semantics: a `(false → true)` transition (key newly populated) parks future arrivals only; in-flight `.sending` continues. A `(true → false)` transition fires drain. - -## Side effects on existing helpers - -- `PendingMessageState.groupId` switch (line 37): add `.waitingForSendGate` case returning the case's `groupId` (forward parking uses `groupId == nil`; grouped-album parking uses the real groupId). -- `updatePendingMediaUploads()` (line 262): `.waitingForSendGate` is **not** treated as uploading. Excluded from the switch (or explicitly returns `default` early). -- `dataForPendingMessageGroup(_ groupId:)` (line 753): add `.waitingForSendGate(contextGroupId, content)` arm — if `contextGroupId == groupId`, append `(context, id, content)` to result, same as the existing `.waitingToBeSent` arm. -- `updatePendingMessageIds(_:)` (line 284): in the existing `for id in removedMessageIds` loop, additionally drop `forwardSendGateGroups[*]` entries whose contained context matches `id`. (Single/album parking is auto-cleaned because parked state lives on the context, which gets `state = .none`.) Implementation: walk the dict, filter out the removed context from each parked group, drop any group that empties out, drop any key whose value-array empties out. - -## Edge cases - -- **First-emit race.** `liveTypingDraftKeys` initializes to `[]`. If a send is attempted before the first view emit and a draft is actually active, that single message slips through. Tolerated. -- **Saved Messages / secret chats / scheduled / new-topic sentinel.** All explicit skip-cases in `shouldGateSend`. -- **Self-typing on another device.** A draft we authored on another device is treated like any other — our outgoing send to that chat parks until it clears. This is consistent with the design intent (drafts visibly commit before subsequent sends arrive). No author filter. -- **Removed-while-parked.** Handled by `updatePendingMessageIds(_:)` extension above. -- **Re-entrancy.** Drain helpers snapshot work-lists before iterating, so mid-iteration mutations to `messageContexts` (e.g. a fired send completes synchronously) don't corrupt the loop. -- **Paid postpone composition.** Paid postpone gates upload-start; once paid commit fires, upload runs; once upload completes, the typing-draft gate parks at `.waitingForSendGate`; once the draft clears, send fires. Stacked sequentially without interaction. -- **Subscription teardown.** `allTypingDraftsDisposable.dispose()` in `deinit`. - -## Testing - -This codebase has no unit tests. Verification is via full build + manual exercise: - -- Build: `python3 build-system/Make/Make.py --overrideXcodeVersion --cacheDir ~/telegram-bazel-cache build --configurationPath build-system/appstore-configuration.json --gitCodesigningRepository git@gitlab.com:peter-iakovlev/fastlanematch.git --gitCodesigningType development --gitCodesigningUseCurrent --buildNumber=1 --configuration=debug_sim_arm64 --continueOnError` (prefixed with `source ~/.zshrc 2>/dev/null;`). -- Manual: in a 1:1 chat with another device, induce a live-typing draft on the peer side and confirm an outgoing text send parks (chat shows "sending" status held until draft clears or commits). Repeat for: media single send, grouped media album, forward. -- Negative manual: scheduled message — confirm not gated. Saved Messages — confirm not gated. Secret chat — confirm not gated. - -## Out of scope - -- Per-chat opt-in toggle. -- Upper-bound timeout / fallback send. -- Grace-delay after draft clears. -- UI affordance ("waiting for X to finish typing…"). -- Filtering self-authored drafts. diff --git a/docs/superpowers/specs/2026-05-01-groupref-ssrc-discovery-design.md b/docs/superpowers/specs/2026-05-01-groupref-ssrc-discovery-design.md deleted file mode 100644 index 1ee706a42a..0000000000 --- a/docs/superpowers/specs/2026-05-01-groupref-ssrc-discovery-design.md +++ /dev/null @@ -1,354 +0,0 @@ -# GroupInstanceReferenceImpl: Reactive Remote-Audio-SSRC Discovery - -**Date:** 2026-05-01 -**Status:** Approved (design only — no implementation yet) -**Scope:** `submodules/TgVoipWebrtc/tgcalls/tgcalls/group/GroupInstanceReferenceImpl.cpp` and adjacent test wiring. - -## Problem - -`GroupInstanceReferenceImpl` (PeerConnection-based group call client) currently learns about remote audio SSRCs **only** from a `colibriClass=ActiveAudioSsrcs` data-channel message broadcast by the test-bench Pion SFU (`tgcalls/tools/go_sfu/sfu.go`). The real Telegram SFU does not send that message — `GroupInstanceCustomImpl::receiveDataChannelMessage` only handles `SenderVideoConstraints` and `DebugMessage`. CustomImpl discovers SSRCs reactively from raw RTP via `GroupNetworkManager` → `receiveUnknownSsrcPacket` → `maybeRequestUnknownSsrc` → `_requestMediaChannelDescriptions`. ReferenceImpl has no equivalent path; in real calls every remote audio packet is silently dropped (or routed to mid=0's unsignaled handler with no application visibility). - -The fix must: -- Surface every previously-unseen remote audio SSRC to ReferenceImpl's internal logic, ideally on the first frame. -- Drive the addition of a recvonly audio transceiver for that SSRC. -- Match CustomImpl's app-facing contract — the application sees the same `_requestMediaChannelDescriptions(ssrcs, completion)` callback it already implements. -- Use a single discovery mechanism in both real and test environments (the test SFU's `ActiveAudioSsrcs` broadcast becomes obsolete and is removed; see "Removing `ActiveAudioSsrcs`" below). - -## Approach: one `GRAudioFrameTransformer` installed on every audio receiver - -WebRTC exposes `RtpReceiverInterface::SetDepacketizerToDecoderFrameTransformer(FrameTransformerInterface*)`. The transformer's `Transform(frame)` takes ownership of a `std::unique_ptr` and there is **no requirement that it call `OnTransformedFrame` synchronously** — the design is explicitly async. The transformer can hold the frame for arbitrarily long; the audio pipeline simply waits. - -We install **the same `GRAudioFrameTransformer` instance on every audio receiver** in this `GroupInstanceReferenceInternal`: - -- **mid=0 (sendrecv outgoing audio)** — explicitly via `_outgoingAudioTransceiver->receiver()->SetDepacketizerToDecoderFrameTransformer(_audioFrameTransformer)` in `start()`. This lands as both the per-receiver transformer and (because mid=0's receive side has `signaled_ssrc=nullopt`) the channel's `unsignaled_frame_transformer_` — meaning any unsignaled stream created later for an unknown SSRC also gets it. -- **Each recvonly audio transceiver** (added by the discovery flow) — explicitly via the same call when the transceiver is added in `renegotiate()`. This is structurally required for the upcoming e2e-decrypt fix (every receiver needs the decrypt hook); attaching it now too is free and removes our reliance on stream-promotion implicitly carrying the transformer along. - -The transformer carries the per-SSRC state machine (described below). It also carries a `decryptHook` callable (initially null) that the e2e PR will wire to `descriptor.e2eEncryptDecrypt`. Today the hook just passes the frame through unchanged; tomorrow it decrypts before `OnTransformedFrame`. - -### Why install on every receiver explicitly - -If we relied solely on `unsignaled_frame_transformer_`, the transformer would be carried onto a recvonly transceiver only via the stream-promotion path (`webrtc_voice_engine.cc:2258-2266`: `MaybeDeregisterUnsignaledRecvStream` keeps the stream object intact, transformer attached). That's correct *today* but it's an internal-WebRTC behavior we'd be pinning to. Once we explicitly attach to each recvonly receiver we own the lifecycle: the transformer is on the stream because we put it there, regardless of how WebRTC's voice engine handles the unsignaled→signaled transition. - -For the buffer flush specifically: the buffered frames were captured while the SSRC was on mid=0's unsignaled-fallback path. When we later install the transformer on the recvonly receiver R' for the same SSRC, the channel's stream (now promoted in place) keeps the same transformer reference (same instance, same pointer) — so `releaseSsrc` flushes through `_perSsrcSinks[ssrc]` (the sink callback WebRTC registered when the stream first appeared) and frames land in that one stream's decoder. - -### Tap behavior - -For each SSRC the transformer maintains an `Entry { state, buffer, firstFrameTimeMs }` with `state ∈ { kBuffering, kDrained }`. - -`Transform(frame)` (worker thread): -1. Acquire the mutex. -2. Look up the entry for `frame->GetSsrc()`. -3. If absent and we're below `kMaxConcurrentBufferedSsrcs`: insert with `kBuffering` state, post `_onNewSsrc(ssrc)` to the media thread (outside the lock), buffer the frame. -4. If `kBuffering`: append to buffer (drop oldest if `buffer.size() >= kMaxBufferedFramesPerSsrc`). -5. If `kDrained`: release the lock, then call `OnTransformedFrame(std::move(frame))`. Live audio flows through. - -`releaseSsrc(uint32_t ssrc)` (media thread, called from `onRenegotiationComplete`): -1. Acquire the mutex. -2. Locate the entry; if absent or already `kDrained`, return. -3. Move the deque out, mark `state = kDrained`, release the mutex. -4. Iterate the moved deque calling `OnTransformedFrame(std::move(frame))` on each. Performed outside the lock to avoid re-entrant deadlocks. - -The order of operations matters: marking `kDrained` *before* releasing the lock guarantees that any concurrent `Transform()` either (a) sees `kBuffering` and buffers — but its frame is lost because we already drained the FIFO, or (b) sees `kDrained` and passes through. Case (a) is a real one-frame-loss race window. We accept it: at 20 ms Opus that's a single packet of audio, inaudible, and overwhelmingly unlikely (the window is the few microseconds between unlocking and starting the drain loop). - -### Failure mode - -If `releaseSsrc(X)` is not called within `kSsrcDiscoveryTimeoutMs = 1000` ms (renegotiation failed or app declined the SSRC), an in-line eviction inside `Transform()` drops the buffer and **leaves the entry in `kBuffering` with empty FIFO**. Subsequent frames continue to attempt to buffer (and immediately drop on the FIFO cap = 0 / re-eviction), so the participant remains silent until the entry is cleared. Acceptable — the same outcome as the pure-drop alternative would have produced. - -### Net behavior - -- **Audible continuity for new participants.** Buffered frames flush into the same stream that carries future audio. NetEQ sees the buffered burst as one large jitter-buffer fill followed by normal-paced packets — same shape as recovering from a network glitch. May produce a brief audible artifact during the burst (NetEQ may accelerate or reorder) but no silence. -- **No orphaned `AudioReceiveStream`.** Stream is promoted in place; one stream per SSRC. -- **Tap stays in the live path.** Per-frame: one mutex, one map lookup, one `OnTransformedFrame`. Hot but cheap. - -CustomImpl already uses `FrameTransformer` (for E2E encryption) — the pattern is established in this codebase. Pass-through transformers also work in WebRTC (the `OnTransformedFrame` callback is the only contract). - -### Why not the alternatives - -- **`OnTrack` for unsignaled audio:** PeerConnection's "default" handler creates one default track. Multi-SSRC behavior is murky; fragile. -- **`PeerConnection::GetStats()` polling:** Works but adds 100–250 ms of discovery latency per new participant (audio drops during the window) and the stats walk is non-trivial. -- **Tap on a custom socket factory:** Requires re-implementing SRTP decrypt and RTP parsing. Too invasive. - -## Components - -``` - ┌────────────────────────────┐ - incoming RTP (any SSRC) ───▶ │ PeerConnection BUNDLE │ - │ demuxer (SSRC-keyed) │ - └─────────────┬──────────────┘ - │ - ┌───────────────────┼─────────────────────┐ - │ │ │ - signaled SSRC X signaled SSRC Y unknown / catch-all - (recvonly mid=N1) (recvonly mid=N2) (sendrecv mid=0) - │ │ │ - ▼ ▼ ▼ - ┌──────────────┐ ┌──────────────┐ ┌──────────────────────┐ - │ AudioTrack │ │ AudioTrack │ │ GRSsrcTapTransformer │ - │ + level sink │ │ + level sink │ │ (Transform → notify │ - └──────────────┘ └──────────────┘ │ + OnTransformedFrame)│ - └──────────┬───────────┘ - │ (worker thread) - │ - ▼ - PostTask to media thread - │ - ▼ - handleDiscoveredAudioSsrc(ssrc) - │ - ▼ - (existing) renegotiate() + - _requestMediaChannelDescriptions -``` - -### `GRAudioFrameTransformer` (new, anonymous-namespace class in `GroupInstanceReferenceImpl.cpp`) - -```cpp -class GRAudioFrameTransformer : public webrtc::FrameTransformerInterface { -public: - using SsrcCallback = std::function; - // Hook for the future e2e-decrypt fix. Called per frame on the worker - // thread before OnTransformedFrame. Today: identity (passes the frame - // through unchanged). The e2e PR will assign it to a closure that - // unwraps the descriptor.e2eEncryptDecrypt envelope. - using DecryptHook = std::function; - - GRAudioFrameTransformer(SsrcCallback onNewSsrc, - DecryptHook decrypt, // may be nullptr - rtc::Thread* mediaThread); - - // Called from ReferenceImpl on the media thread after onRenegotiationComplete - // confirms a recvonly transceiver now owns `ssrc`. Drains the per-SSRC - // FIFO into OnTransformedFrame in arrival order; subsequent frames for - // `ssrc` flow through unchanged (kDrained = live passthrough). - void releaseSsrc(uint32_t ssrc); - - // FrameTransformerInterface - void Transform(std::unique_ptr frame) override; - void RegisterTransformedFrameCallback(rtc::scoped_refptr) override; - void RegisterTransformedFrameSinkCallback(rtc::scoped_refptr, uint32_t ssrc) override; - void UnregisterTransformedFrameCallback() override; - void UnregisterTransformedFrameSinkCallback(uint32_t ssrc) override; - -private: - enum class SsrcState { kBuffering, kDrained }; - - struct Entry { - SsrcState state = SsrcState::kBuffering; - std::deque> buffer; - int64_t firstFrameTimeMs = 0; // for timeout eviction - }; - - void evictExpired_n() RTC_EXCLUSIVE_LOCKS_REQUIRED(_mu); // called inside Transform - - SsrcCallback _onNewSsrc; - rtc::Thread* _mediaThread; // used only as identity for assertions - - webrtc::Mutex _mu; - rtc::scoped_refptr _broadcastSink RTC_GUARDED_BY(_mu); - std::map> _perSsrcSinks RTC_GUARDED_BY(_mu); - std::map _entries RTC_GUARDED_BY(_mu); - - static constexpr int64_t kSsrcDiscoveryTimeoutMs = 1000; - static constexpr size_t kMaxBufferedFramesPerSsrc = 60; // ~1.2s at 20ms Opus - static constexpr size_t kMaxConcurrentBufferedSsrcs = 64; // upper bound on memory -}; -``` - -#### `Transform` (worker thread) - -1. `ssrc = frame->GetSsrc()`. Acquire `_mu`. -2. `evictExpired_n()` — walk `_entries`; for any whose `firstFrameTimeMs` is older than `kSsrcDiscoveryTimeoutMs` and still `kBuffering`, clear the buffer (entry stays so we don't re-notify; subsequent frames re-evict and stay silent until the entry is removed by an explicit application action — acceptable failure mode). -3. Look up the entry for `ssrc`: - - **Not present and `_entries.size() >= kMaxConcurrentBufferedSsrcs`** → drop frame, no notify (overflow protection against pathological SFU behavior). - - **Not present otherwise** → insert `Entry{ kBuffering, {}, now() }`, push frame, **release lock**, invoke `_onNewSsrc(ssrc)` (which posts to media thread → `handleDiscoveredAudioSsrc(ssrc)`). - - **Present and `kBuffering`**: - - If `entry.buffer.size() >= kMaxBufferedFramesPerSsrc` → drop the oldest buffered frame (FIFO bounded). - - Push `std::move(frame)` to the back of `entry.buffer`. - - **Present and `kDrained`** → take a local copy of the appropriate sink callback (per-SSRC if registered, else broadcast), **release lock**, call `sink->OnTransformedFrame(std::move(frame))`. This is the live-audio path after `releaseSsrc` has fired. - -The mutex is held only across the lookup and entry/buffer mutation. Both branches that emit through `OnTransformedFrame` (`kDrained` in `Transform`, and `releaseSsrc`) drop the lock before the call to avoid re-entrant deadlocks — WebRTC may synchronously schedule decoder work in `OnTransformedFrame` that calls back into related machinery. - -#### `releaseSsrc(uint32_t ssrc)` (media thread) - -1. Acquire `_mu`. Locate the entry; if missing or already `kDrained`, return. -2. Find the appropriate sink callback: per-SSRC if registered, else broadcast. -3. Mark `entry.state = kDrained` and `std::move` the deque out. **Marking `kDrained` before releasing the lock** is what guarantees no concurrent `Transform()` can buffer a frame that we then fail to flush. -4. Release `_mu`. Iterate the moved deque calling `sink->OnTransformedFrame(std::move(frame))` on each. - -#### `Register*` / `Unregister*` - -Store the callbacks under `_mu`. The per-SSRC `RegisterTransformedFrameSinkCallback` is invoked by WebRTC the first time a new SSRC arrives at this transformer; we hold it so `releaseSsrc` can dispatch through it. `Unregister*` clears. - -### Hook points in `GroupInstanceReferenceInternal` - -In `start()`, after `_outgoingAudioTransceiver` is created (mid=0): - -```cpp -auto weak = std::weak_ptr(shared_from_this()); -auto threads = _threads; -_audioFrameTransformer = rtc::make_ref_counted( - /*onNewSsrc=*/[weak, threads](uint32_t ssrc) { - threads->getMediaThread()->PostTask([weak, ssrc]() { - if (auto strong = weak.lock()) { - strong->handleDiscoveredAudioSsrc(ssrc); - } - }); - }, - /*decrypt=*/nullptr, // wired in the e2e PR - /*mediaThread=*/_threads->getMediaThread()); -_outgoingAudioTransceiver->receiver()->SetDepacketizerToDecoderFrameTransformer( - _audioFrameTransformer); -``` - -In `renegotiate()`, immediately after `_peerConnection->AddTransceiver(MEDIA_TYPE_AUDIO, recvonly)` succeeds for an SSRC discovered through the tap, attach the same transformer to the new receiver: - -```cpp -auto result = _peerConnection->AddTransceiver(cricket::MEDIA_TYPE_AUDIO, init); -if (result.ok()) { - info.transceiver = result.value(); - info.transceiver->receiver() - ->SetDepacketizerToDecoderFrameTransformer(_audioFrameTransformer); -} -``` - -In `onRenegotiationComplete()`, after `wireRemoteAudioLevelSinks()` runs, release any SSRCs whose recvonly transceiver just became active: - -```cpp -if (_audioFrameTransformer) { - for (auto& [ssrc, info] : _remoteSsrcs) { - if (info.transceiver && info.transceiver->mid().has_value()) { - // Idempotent: releaseSsrc no-ops on entries already drained. - _audioFrameTransformer->releaseSsrc(ssrc); - } - } -} -``` - -### `handleDiscoveredAudioSsrc(uint32_t ssrc)` (new, on media thread) - -This is the **only** entry point for adding a remote audio SSRC. It accumulates the SSRC into `_remoteSsrcs` and **schedules** a single coalesced renegotiation rather than firing one immediately: - -```cpp -void handleDiscoveredAudioSsrc(uint32_t ssrc) { - if (ssrc == 0) return; - if (ssrc == _outgoingSsrc) return; // our own - if (_remoteSsrcs.count(ssrc) > 0) return; // already known - - std::string mid = std::to_string(_nextMid++); - RemoteSsrcInfo info; - info.mid = mid; - _remoteSsrcs.emplace(ssrc, std::move(info)); - - if (_requestMediaChannelDescriptions) { - _requestMediaChannelDescriptions({ssrc}, [](auto&&) { /* fire-and-forget */ }); - } - scheduleDiscoveryRenegotiation(); -} -``` - -### Removing `ActiveAudioSsrcs` - -With the tap as the canonical discovery path, the test SFU's `ActiveAudioSsrcs` broadcast becomes redundant — and continuing to ship it would mean test runs exercise a code path that doesn't exist in production. Three deletions: - -1. `tools/go_sfu/sfu.go` — remove the `colibriClass=ActiveAudioSsrcs` broadcast (the message construction at `sfu.go:987` and any per-participant-join trigger that emits it). Remove the `ColibriClass`/`Ssrcs` JSON struct used solely for this purpose. -2. `GroupInstanceReferenceImpl.cpp` — delete `handleActiveAudioSsrcs(json)` and the `if (colibriClass == "ActiveAudioSsrcs") { ... }` dispatch in `onDataChannelMessage`. The dispatch becomes "forward to app callback if set" only (currently forwards regardless, so just drop the colibri branch). -3. `tools/cli/group_participant.cpp` — no change required. The CLI already only reacts to `ActiveVideoSsrcs` in its `dataChannelMessageReceived`; `ActiveAudioSsrcs` was never observed by the test app, only consumed internally by ReferenceImpl. - -Verification that removal is safe: `grep -r ActiveAudioSsrcs` across the repo currently returns hits only in (1) the SFU emitter, (2) the ReferenceImpl handler we're deleting, and (3) documentation/CLAUDE.md files (which we update as part of the change). CustomImpl never references it; iOS app code never references it; the test CLI never references it. - -Removed-SSRC handling: the deleted `handleActiveAudioSsrcs` also processed *removals* (SFU told us a participant left). After deletion, ReferenceImpl no longer reacts to participant departures via the data channel. This matches CustomImpl's behavior — CustomImpl also has no remove path; SSRCs simply go silent and the application removes them from the participant list via MTProto. Recvonly transceivers stay in the SDP indefinitely, which is a small per-call leak but not a correctness issue. (If this proves to be a problem in long-running calls, a future change can add a "remove if no audio for N seconds" sweep.) - -### `scheduleDiscoveryRenegotiation()` — debounce window - -A 250 ms delayed task on the media thread coalesces a burst of discoveries into one renegotiation. The existing `renegotiate()` already iterates `_remoteSsrcs` and adds a recvonly transceiver for any entry that doesn't have one yet, so all SSRCs accumulated during the delay window are picked up in a single offer/answer cycle. - -```cpp -static constexpr int kDiscoveryRenegotiationDelayMs = 250; - -void scheduleDiscoveryRenegotiation() { - if (_discoveryRenegotiationScheduled) return; - _discoveryRenegotiationScheduled = true; - auto weak = std::weak_ptr(shared_from_this()); - _threads->getMediaThread()->PostDelayedTask( - [weak]() { - auto strong = weak.lock(); - if (!strong) return; - strong->_discoveryRenegotiationScheduled = false; - strong->renegotiate(); - }, - webrtc::TimeDelta::Millis(kDiscoveryRenegotiationDelayMs)); -} -``` - -**Layering with existing serialization.** The debounce sits on top of `renegotiate()`'s existing `_isRenegotiating` / `_pendingRenegotiation` guard. Three regimes: - -1. **No renegotiation in flight when the timer fires:** `renegotiate()` runs immediately, picks up all queued SSRCs. -2. **A renegotiation is already in flight (e.g., from `setRequestedVideoChannels`):** the queued `renegotiate()` sets `_pendingRenegotiation`, runs after the in-flight cycle completes — picks up everything including the new SSRCs. -3. **More SSRCs discovered while the timer is pending:** `_discoveryRenegotiationScheduled == true` → no new task scheduled, the SSRC just lands in `_remoteSsrcs` and joins the upcoming batch. - -Result: at most one discovery-sourced renegotiation per 250 ms, regardless of arrival burst size. - -**Audible-gap implication.** New joiners are silent during the debounce window because their packets land in mid=0's catch-all (which still decodes them and feeds the AudioMixer for playback) but their per-receiver `GRAudioLevelSink` doesn't exist yet, so the speaking-indicator UI shows no level until the renegotiation completes (~250 ms + offer/answer round-trip). Audio is heard, the indicator just lags. Acceptable. - -**Stop semantics.** On `stop()`, the queued task may still fire. The `weak_ptr` guard makes the lambda a no-op if the internal has been destroyed. The `_isRenegotiating` flag inside `renegotiate()` also bails if `_peerConnection` has been closed. - -**Behavior change in test mode:** the existing `handleActiveAudioSsrcs` calls `_requestMediaChannelDescriptions` once per batch with all new SSRCs. After refactor, it issues N single-SSRC calls. This is acceptable: requests are local fire-and-forget callbacks into the app and bear no network cost in the CLI test bench. If the iOS app's implementation later turns out to be sensitive to call frequency, `handleActiveAudioSsrcs` can re-aggregate by collecting the SSRCs first and issuing one batched request after the per-SSRC `handleDiscoveredAudioSsrc` calls — but the simpler version is the starting point. - -## Data flow - -1. SFU starts forwarding remote audio for SSRC X (no signaling messages). -2. PeerConnection demuxes the first packet for SSRC X — no recvonly transceiver matches → routed to mid=0's catch-all receiver. The voice channel creates an unsignaled `WebRtcAudioReceiveStream` for X with our tap as the depacketizer-to-decoder transformer. `Transform(frame1)` is called. -3. Tap finds no entry for X → inserts `{ kBuffering, [frame1], now() }` → posts `_onNewSsrc(X)` to the media thread → `handleDiscoveredAudioSsrc(X)`. -4. `handleDiscoveredAudioSsrc` adds X to `_remoteSsrcs`, fires `_requestMediaChannelDescriptions({X}, ...)`, calls `scheduleDiscoveryRenegotiation()` (debounce 250 ms). -5. Subsequent packets for X arrive at the tap (state still `kBuffering`) → appended to the same FIFO (oldest dropped if `>= kMaxBufferedFramesPerSsrc`). -6. After 250 ms the debounce timer fires `renegotiate()`, which adds a recvonly transceiver bound to mid=`_nextMid++` for every entry in `_remoteSsrcs` that lacks one. `SetRemoteDescription` propagates SSRC X into the recvonly m-line; `WebRtcVoiceReceiveChannel::AddRecvStream(X)` finds X in `unsignaled_recv_ssrcs_` and **promotes** the existing stream in place (no new stream created; tap transformer remains attached). -7. `onRenegotiationComplete` runs: `wireRemoteAudioLevelSinks()` attaches a `GRAudioLevelSink` to the new recvonly receiver's track; for each SSRC whose transceiver now has a mid, ReferenceImpl calls `_ssrcTapTransformer->releaseSsrc(ssrc)`. -8. `releaseSsrc(X)` marks the entry `kDrained` under the lock, moves the FIFO out, releases the lock, and calls `OnTransformedFrame` for each buffered frame in arrival order. The promoted stream's decoder receives the burst; NetEQ buffers and plays out at natural rate. -9. Subsequent packets for X reach `Transform()`; the entry is `kDrained` → tap calls `OnTransformedFrame` directly. Live audio flows. The per-receiver `GRAudioLevelSink` (attached in step 7) reads real levels from the post-decode PCM stream. - -**Failure mode (timeout).** If `releaseSsrc(X)` is not called within `kSsrcDiscoveryTimeoutMs = 1000` ms (renegotiation failed or app declined the SSRC), the in-line eviction in `Transform` clears the buffer for X. The entry stays in `kBuffering` so we don't re-notify, but no future frames are forwarded — the participant goes silent. Same outcome as the pure-drop alternative. - -## Threading - -- `Transform` runs on PeerConnection's worker thread. Hot path — must be cheap. Per call: one mutex acquisition, a deque push (or drop), an O(N_active_SSRCs) eviction walk that is cheap (typically 0–2 items per call). On first-sight SSRC the worker thread also posts to the media thread. -- `releaseSsrc` runs on the media thread (called from `onRenegotiationComplete`). Acquires the same mutex, moves the FIFO out under lock, then releases the lock and calls `OnTransformedFrame` outside the lock to avoid re-entrant deadlocks (WebRTC's `OnTransformedFrame` may call back into the transformer infrastructure). -- `OnTransformedFrame` itself: WebRTC's contract does not pin it to a specific thread; calling from the media thread is legal. WebRTC dispatches the actual depacketize/decode onto the worker thread internally. -- `handleDiscoveredAudioSsrc` runs on the media thread. Existing renegotiation machinery is media-thread-safe. -- Lifetime: the transformer is owned by `_ssrcTapTransformer` (member, `scoped_refptr`). `weak_ptr` capture in the SSRC callback prevents use-after-free during teardown. WebRTC clears the transformer when the receiver is destroyed (PeerConnection close); any frames still in the FIFO at that point are released by the deque destructor (the underlying `TransformableFrameInterface` instances are owned `unique_ptr`s and clean up automatically). - -## Testing - -After removing `ActiveAudioSsrcs`, the tap is the only discovery path in every mode — test and real. The existing CLI test bench validates it without modification: - -- All-Reference, no mute: each ReferenceImpl peer must discover the others via the tap, add recvonly transceivers, and report `level ≥ 0.05` (current invariant in `validateGroupState`). -- Mixed (CustomImpl + ReferenceImpl), no mute: same invariant from both sides. -- Mute scenarios: muted peers must still be discovered (their packets carry encoded silence; the tap fires on first packet) and their `level` must read 0 (existing muted-peer invariant from the previous fix). - -If any of these regress, the tap is broken — which is exactly the coverage we want. - -No new CLI flags or SFU exports needed; the previous draft's `--suppress-active-audio-ssrcs` is moot. - -## Out of scope (this design) - -- **E2E `e2eEncryptDecrypt` wiring** is a separate fix, but this design pre-installs the surface it needs: `GRAudioFrameTransformer::DecryptHook` is a constructor parameter (nullptr today). The e2e PR captures `descriptor.e2eEncryptDecrypt` and passes a closure that decrypts the frame's `GetData()` and writes back via `SetData()` before the transformer calls `OnTransformedFrame`. No further structural changes — the transformer is already attached to every audio receiver. -- SSRC>int31 join-payload masking (separate fix). -- Push-style discovery via a new `GroupInstanceInterface::addIncomingAudioSsrcs(...)` method. May be added later but is not needed to fix the immediate problem. -- Video SSRC discovery — handled by the existing app-facing `dataChannelMessageReceived` callback for `ActiveVideoSsrcs` (and via `setRequestedVideoChannels` from MTProto data on iOS). The same per-receiver transformer pattern would extend to incoming video for video e2e, but that's outside the audio scope here. - -## Risks - -- **Buffer-flush correctness.** The tap holds frames until `releaseSsrc` fires. If the call is missed (bug in `onRenegotiationComplete`, race with `stop()`), the timeout clears the buffer at 1 s and the participant goes silent. The CLI integration tests catch this end-to-end: with `ActiveAudioSsrcs` removed, the tap is the *only* discovery path, so the existing `receivedAudio ≥ 0.05` invariant validates the full chain. -- **Tap-passthrough correctness.** Because the tap transformer remains attached after stream promotion, *every* live frame for an SSRC also passes through `Transform()` → `kDrained` branch → `OnTransformedFrame`. If the `kDrained` branch is broken or skipped, every audio frame for every promoted SSRC is silently dropped. Same CLI test coverage applies: the moment passthrough breaks, no peer hears anyone. -- **NetEQ jitter-buffer burst on flush.** `releaseSsrc` flushes up to ~1 s of audio (`kMaxBufferedFramesPerSsrc` × 20 ms = 1.2 s) into the receive stream in one tight loop. NetEQ sees this as a jitter-buffer fill spike. It will normally play out at the natural 50 fps rate, but the burst may exceed `audio_jitter_buffer_max_packets_` and trigger acceleration, deletion, or PLC artifacts. Worst case: a brief audio glitch when a new participant first speaks. Acceptable; mitigated by setting `kMaxBufferedFramesPerSsrc` aggressively low (e.g., 30 frames = 600 ms) if the artifact proves audible. -- **Race window during release.** Marking `kDrained` while still holding the lock prevents concurrent `Transform()` from buffering a doomed frame. There is still a microsecond between unlock and the start of the drain loop where a `Transform()` could beat `releaseSsrc` to the live-passthrough path — but the result is just the new frame arriving at the decoder *before* the buffered backlog. NetEQ reorders by RTP timestamp; harmless. -- **Renegotiation storm.** Mitigated by the 250 ms debounce in `scheduleDiscoveryRenegotiation()`: a burst of N SSRCs in the window collapses to one renegotiation. The existing `_isRenegotiating` / `_pendingRenegotiation` flags handle the case where another renegotiation source (e.g., `setRequestedVideoChannels`) is concurrently in flight. The first-sight check in the tap prevents duplicate per-SSRC scheduling. -- **Memory-pressure cap.** Worst-case buffered audio: `kMaxConcurrentBufferedSsrcs` × `kMaxBufferedFramesPerSsrc` × ~80 bytes/frame ≈ 64 × 60 × 80 = 308 KB. Both bounds are deliberately conservative — a misbehaving SFU sending unique SSRCs per packet hits the SSRC cap and drops further new ones rather than allocating unbounded memory. -- **Stream promotion is still load-bearing for buffered audio.** Live frames flow correctly because we explicitly install the transformer on each recvonly receiver — that path is no longer dependent on internal WebRTC behavior. *Buffered frames* still rely on the unsignaled→signaled stream promotion: the per-SSRC `TransformedFrameCallback` we got at first-sight is the one we replay through. If a future WebRTC update breaks promotion (constructs a new signaled stream and orphans the unsignaled one), `releaseSsrc` would dispatch frames into the orphan and they'd never decode. The CLI tests catch this — buffered audio would be silent during the first 250–500 ms of every new participant, which the audio-level invariant will flag in mute-style tests if extended to assert on first-second levels. - -## Files touched (anticipated) - -- `submodules/TgVoipWebrtc/tgcalls/tgcalls/group/GroupInstanceReferenceImpl.cpp` — add `GRAudioFrameTransformer` (per-SSRC FIFO + `releaseSsrc` + `decryptHook` callable initialized to nullptr); construct + install on mid=0's receiver in `start()`; install on each new recvonly receiver in `renegotiate()`; add `handleDiscoveredAudioSsrc` and `scheduleDiscoveryRenegotiation`; **delete `handleActiveAudioSsrcs` and its dispatch in `onDataChannelMessage`**; call `releaseSsrc` from `onRenegotiationComplete` for each newly-mid-assigned SSRC; add `_audioFrameTransformer` (`scoped_refptr`) and `_discoveryRenegotiationScheduled` members. -- `submodules/TgVoipWebrtc/tgcalls/tools/go_sfu/sfu.go` — **delete `ActiveAudioSsrcs` broadcast** (message construction at `sfu.go:987` and any per-join trigger). -- `submodules/TgVoipWebrtc/CLAUDE.md` and `submodules/TgVoipWebrtc/tgcalls/tools/cli/CLAUDE.md` — update to reflect that ReferenceImpl discovers SSRCs via a `FrameTransformer` tap on mid=0; remove `ActiveAudioSsrcs`/`SetDefaultRawAudioSink` references. -- No iOS-side changes (`OngoingCallThreadLocalContext.mm` etc.) — the existing `requestMediaChannelDescriptions` callback already supports the discovery path. -- No CLI changes (`tools/cli/main.cpp`, `group_mode.cpp/.h`) — the existing tests validate the tap directly. diff --git a/docs/superpowers/specs/2026-05-01-instant-page-underline-rendering-design.md b/docs/superpowers/specs/2026-05-01-instant-page-underline-rendering-design.md deleted file mode 100644 index cd87db6704..0000000000 --- a/docs/superpowers/specs/2026-05-01-instant-page-underline-rendering-design.md +++ /dev/null @@ -1,101 +0,0 @@ -# InstantPage underline rendering - -## Problem - -`layoutTextItemWithString` in `submodules/InstantPageUI/Sources/InstantPageTextItem.swift` does not handle the `NSAttributedString.Key.underlineStyle` attribute. Underline runs are produced upstream by `InstantPageTextStyleStack.textAttributes()` (`InstantPageTextStyleStack.swift:194-202`) for two distinct sources: - -1. Explicit `RichText.underline` runs (push at `InstantPageTextItem.swift:607`, plus `:628` and `:657` for related cases). -2. Links whose computed foreground color matches the body-text color — the styleStack falls back to underlining them so they remain distinguishable (`InstantPageTextStyleStack.swift:200-201`). - -The attribute lands on the attributed string in both cases, but the per-line attribute enumerator at `InstantPageTextItem.swift:915-938` only branches on `strikethroughStyle`, `InstantPageMarkerColorAttribute`, and `InstantPageAnchorAttribute`. Underline runs are silently dropped during layout, so they never get drawn. - -The canonical handling pattern lives in `submodules/Display/Source/TextNode.swift:2061-2066` (collection during layout) and `:2619-2638` (manual draw at draw time). `TextNode` deliberately draws underlines manually (`drawUnderlinesManually = true` at `:216`) rather than letting Core Text render them, because CT's underline rendering has historic positioning, color, and clipping issues across glyph clusters and emoji. - -## Goal - -Render underlines in InstantPage articles wherever the styleStack emits `underlineStyle`, matching `TextNode.swift` line-for-line so a future reader sees the same shape in both files. - -## Non-goals - -- Wavy or double underline support — the InstantPage styleStack only emits `NSUnderlineStyle.single`. -- Changes to `InstantPageTextStyleStack` — the attribute it produces is already correct. -- Changes to the existing strikethrough draw's reliance on the context's residual fill color — out of scope, not regressed. -- Changes to `attributesAtPoint` or selection-rect logic — these read attributes directly off `attributedString`, so they already work for underlined ranges. - -## Design - -### New type - -In `InstantPageTextItem.swift`, alongside `InstantPageTextStrikethroughItem`: - -```swift -struct InstantPageTextUnderlineItem { - let frame: CGRect - let range: NSRange - let color: UIColor? -} -``` - -`color` carries an optional `NSAttributedString.Key.underlineColor`. There is no `style` field — `.single` is the only value the styleStack emits. `range` is needed at draw time to look up `foregroundColor` per-range when `underlineColor` is absent. - -### Line storage - -Add `let underlineItems: [InstantPageTextUnderlineItem]` to `InstantPageTextLine`, with a matching init parameter alongside `strikethroughItems`. There is exactly one construction site for `InstantPageTextLine` (`InstantPageTextItem.swift:970`), so updating the initializer is local. - -### Collection (layoutTextItemWithString) - -In the `enumerateAttributes` loop currently at `InstantPageTextItem.swift:915-938`, add a parallel branch that mirrors `TextNode.swift:2061-2066`: - -```swift -if let _ = attributes[NSAttributedString.Key.underlineStyle] { - let lowerX = floor(CTLineGetOffsetForStringIndex(line, range.location, nil)) - let upperX = ceil(CTLineGetOffsetForStringIndex(line, range.location + range.length, nil)) - let x = lowerX < upperX ? lowerX : upperX - underlineItems.append(InstantPageTextUnderlineItem( - frame: CGRect(x: workingLineOrigin.x + x, y: workingLineOrigin.y, width: abs(upperX - lowerX), height: fontLineHeight), - range: range, - color: attributes[NSAttributedString.Key.underlineColor] as? UIColor - )) -} -``` - -Geometry is verbatim the strikethrough branch's — same `lowerX`/`upperX` clamp and the same `workingLineOrigin.x + x` offset. The collection is independent of strikethrough; both branches can fire on the same range. - -### Draw (drawInTile) - -After the strikethrough draw block at `InstantPageTextItem.swift:261-266`, add: - -```swift -if !line.underlineItems.isEmpty { - for item in line.underlineItems { - var color: UIColor? = item.color - if color == nil { - self.attributedString.enumerateAttributes(in: item.range, options: []) { attributes, _, _ in - if let foreground = attributes[NSAttributedString.Key.foregroundColor] as? UIColor { - color = foreground - } - } - } - if let color { - context.setFillColor(color.cgColor) - } - let itemFrame = item.frame.offsetBy(dx: lineFrame.minX, dy: 0.0) - context.fill(CGRect(x: itemFrame.minX, y: itemFrame.minY + 1.0, width: itemFrame.size.width, height: 1.0)) - } -} -``` - -Color resolution order (`underlineColor` → per-range `foregroundColor`) and position rule (`y: minY + 1.0`, `height: 1.0`) match `TextNode.swift:2624-2638` exactly. - -The `setFillColor` call is gated on a non-nil resolved color so we do not silently flip an unrelated drawing's fill color if no foreground attribute is found in the range. In practice the attributed string always carries a `foregroundColor` (set unconditionally by the styleStack at `InstantPageTextStyleStack.swift:198-211`), so the gate is defense-in-depth, not a hot path. - -## Verification - -- Full Bazel build via `Make.py … --configuration=debug_sim_arm64`. -- Manual smoke against an article whose body contains an explicit `` block, and a separate article whose link color matches the body color (the styleStack's link-fallback case). - -No unit tests exist in this project (per `CLAUDE.md`). - -## Risk - -Additive: a new struct, a new optional field on `InstantPageTextLine`, one new branch in the layout enumerator, one new draw block. No public API changes, no signature changes outside `InstantPageTextItem.swift`. Runs without `underlineStyle` are unaffected. diff --git a/docs/superpowers/specs/2026-05-01-rich-bubble-instant-page-link-handling-design.md b/docs/superpowers/specs/2026-05-01-rich-bubble-instant-page-link-handling-design.md deleted file mode 100644 index 5e946f94ac..0000000000 --- a/docs/superpowers/specs/2026-05-01-rich-bubble-instant-page-link-handling-design.md +++ /dev/null @@ -1,180 +0,0 @@ -# Instant-page link handling in `ChatMessageRichDataBubbleContentNode` - -## Context - -`ChatMessageRichDataBubbleContentNode` renders a webpage's `instantPage` inline inside a chat bubble, by reusing the same `InstantPageLayout`/`InstantPageTile`/`InstantPageNode` machinery the full-screen instant view uses. Today the layout, tiles, and item nodes are wired up correctly, but every interactive callback (`openUrl`, `openPeer`, `openMedia`, …) on the realized item nodes is a commented stub, and `tapActionAtPoint` always returns `.none`. As a result, taps on URLs inside the inline preview do nothing. - -The full-screen instant view (`submodules/InstantPageUI/Sources/InstantPageControllerNode.swift`) handles URL taps by walking the layout to find the `InstantPageTextItem` under the tap location, asking it for `urlAttribute(at:)`, and then routing the resulting `InstantPageUrlItem` through its own `openUrl(_:)` resolver. Same-page anchors are handled inline via `scrollToAnchor(_:)`. - -Chat text bubbles handle URL taps via `ChatMessageBubbleContentTapAction(content: .url(...), rects:, activate:)`. The `activate` closure returns a `Promise` driven by upstream URL resolution; while it's `true` the bubble shows a `LinkHighlightingNode` overlay so users get press-feedback. - -## Goal - -Wire URL tap handling and link-highlight feedback into `ChatMessageRichDataBubbleContentNode`, plus stubbed handlers for intra-page anchor scrolling. Item-level `openUrl`/`openPeer` callbacks emitted by realized `InstantPageNode`s also route to the chat's `controllerInteraction`. - -Out of scope: media taps, pinch preview, embed height updates, details expansion, long-press action-sheet (Open / Copy / Add to Reading List), and the actual implementation of intra-page anchor scrolling — these stay as no-op stubs and can land as follow-ups. - -## Design - -### File touched - -`submodules/TelegramUI/Components/Chat/ChatMessageRichDataBubbleContentNode/Sources/ChatMessageRichDataBubbleContentNode.swift` (only). - -### New private state - -``` -private var linkProgressDisposable: Disposable? -private var linkProgressRects: [CGRect]? -private var linkHighlightingNode: LinkHighlightingNode? -``` - -`deinit` disposes `linkProgressDisposable`. - -### Tap detection - -Two private helpers, modelled on `InstantPageControllerNode`: - -``` -private func textItemAtLocation(_ point: CGPoint) -> (InstantPageTextItem, CGPoint)? -private func urlForTapLocation(_ point: CGPoint) - -> (item: InstantPageTextItem, urlItem: InstantPageUrlItem, localPoint: CGPoint)? -``` - -- The incoming `point` is in the bubble-content-node coordinate system. The helpers subtract the `containerNode` offset `(1.0, 1.0)` once on entry, then walk `currentPageLayout?.layout.items`. -- Top-level `InstantPageTextItem`s, `InstantPageScrollableItem` (delegates to its own `textItemAtLocation` accounting for content offset), and `InstantPageDetailsItem` (looks up the realized `InstantPageDetailsNode` via `visibleItemsWithNodes` and queries its nested layout) are all supported — same coverage as the IV. -- `urlForTapLocation` calls `item.urlAttribute(at:)`. Returns the matched item, the `InstantPageUrlItem`, and the item-local point. The local point is what `linkSelectionRects(at:)` consumes when computing highlight rects. - -### `tapActionAtPoint` body - -Skeleton (existing `messageOptions` early-return is preserved): - -``` -override public func tapActionAtPoint(...) -> ChatMessageBubbleContentTapAction { - if case .tap = gesture { - } else { - if let item = self.item, let subject = item.associatedData.subject, case .messageOptions = subject { - return ChatMessageBubbleContentTapAction(content: .none) - } - } - - guard let urlHit = self.urlForTapLocation(point) else { - return ChatMessageBubbleContentTapAction(content: .none) - } - - let (baseUrl, anchor) = splitAnchor(urlHit.urlItem.url) - if let webpage = self.currentLoadedWebpage(), webpage.url == baseUrl, let anchor { - return ChatMessageBubbleContentTapAction(content: .custom({ [weak self] in - self?.scrollToAnchor(anchor) - })) - } - - let concealed = true // see "Concealed flag" note below - let url = ChatMessageBubbleContentTapAction.Url(url: urlHit.urlItem.url, concealed: concealed) - let rects = self.computeHighlightRects(item: urlHit.item, localPoint: urlHit.localPoint) - return ChatMessageBubbleContentTapAction( - content: .url(url), - rects: rects, - activate: self.makeActivate(item: urlHit.item, localPoint: urlHit.localPoint) - ) -} -``` - -**Concealed flag**: default to `concealed = true` for v1. Reason: `InstantPageTextItem` does not expose a clean "attribute substring with range" API the way the chat text node does, so we cannot easily compare displayed link text to its target URL. `true` is the safer (more disclosure) default — chat will show a confirmation if the visible text and resolved URL differ. If during implementation a clean substring path emerges, switch to `doesUrlMatchText(url:text:fullText:)` analogously to text-bubble. - -### Highlight feedback - -`makeActivate(item:localPoint:)` mirrors the text-bubble pattern: - -``` -private func makeActivate(item: InstantPageTextItem, localPoint: CGPoint) -> (() -> Promise?)? { - return { [weak self] in - guard let self else { return nil } - let promise = Promise() - self.linkProgressDisposable?.dispose() - if self.linkProgressRects != nil { - self.linkProgressRects = nil - self.updateLinkProgressState() - } - self.linkProgressDisposable = (promise.get() |> deliverOnMainQueue).startStrict(next: { [weak self] value in - guard let self else { return } - let updated: [CGRect]? = value - ? self.computeHighlightRects(item: item, localPoint: localPoint) - : nil - if self.linkProgressRects != updated { - self.linkProgressRects = updated - self.updateLinkProgressState() - } - }) - return promise - } -} -``` - -`computeHighlightRects(item:localPoint:)`: -- Calls `item.linkSelectionRects(at: localPoint)` — already public on `InstantPageTextItem`, returns the URL run's line rects in item-local coords. -- Translates each rect into `containerNode`-local coords by adding `item.frame.origin` plus any parent offset captured at hit-test time (zero for top-level items; the offset returned by `textItemAtLocation` for items nested under scrollables/details). - -`updateLinkProgressState()`: -- If `linkProgressRects` is non-nil and non-empty: lazily create `linkHighlightingNode` (`LinkHighlightingNode(color: incoming-or-outgoing linkHighlightColor)` derived from `self.item?.message.effectivelyIncoming(...)`), inserted into `containerNode` at index 0 (below all tiles). Set its frame to `containerNode.bounds`. Call `updateRects(rects)`. -- Otherwise: fade out the existing `linkHighlightingNode` (alpha 1→0 over 0.18s, remove on completion) and clear the field. - -Insertion order: rich-bubble tiles use `backgroundColor: .clear`, so a highlighting node positioned below them is visible through. Tiles are added with `insertSubnode(_, at: 0)` / `aboveSubnode:` — inserting the highlight at index 0 keeps it underneath every tile but inside the same `containerNode` clip region. - -### Item-callback wiring (inside `item.node(...)`) - -The currently stubbed callbacks become: - -``` -openMedia: { _ in /* TODO */ }, -longPressMedia: { _ in /* TODO */ }, -activatePinchPreview: { _ in /* TODO */ }, -pinchPreviewFinished: { _ in /* TODO */ }, -openPeer: { [weak self] peer in - guard let self, let item = self.item else { return } - item.controllerInteraction.openPeer(peer, .chat(textInputState: nil, subject: nil, peekData: nil), nil, .default) -}, -openUrl: { [weak self] urlItem in - guard let self, let item = self.item else { return } - let (baseUrl, anchor) = splitAnchor(urlItem.url) - if let webpage = self.currentLoadedWebpage(), webpage.url == baseUrl, let anchor { - self.scrollToAnchor(anchor) - return - } - item.controllerInteraction.openUrl(ChatControllerInteraction.OpenUrl( - url: urlItem.url, - concealed: false, - message: item.message, - allowInlineWebpageResolution: urlItem.webpageId != nil - )) -}, -updateWebEmbedHeight: { _ in }, -updateDetailsExpanded: { _ in }, -``` - -- `openPeer` matches the IV's default routing — open the chat for the peer. -- `openUrl` honors the same-page-anchor stub, so item-emitted URL taps share the placeholder hook with text-tap routing. -- `urlItem.webpageId != nil` is mapped to `allowInlineWebpageResolution`. `InstantPageUrlItem.webpageId` is the IV's hint that the URL was authored as a referenced webpage, which is the same intent the chat flag captures. - -### Helpers - -``` -private func splitAnchor(_ url: String) -> (base: String, anchor: String?) -private func currentLoadedWebpage() -> TelegramMediaWebpageLoadedContent? -private func scrollToAnchor(_ anchor: String) { - // TODO: implement intra-page anchor scrolling -} -``` - -`splitAnchor` extracts the `#fragment` from a URL using the same approach as `InstantPageControllerNode.openUrl` (find `#`, percent-decode the suffix, slice the prefix). `currentLoadedWebpage` pulls `case .Loaded(content)` out of the first `TelegramMediaWebpage` on `self.item?.message.media`. - -## Verification - -- Build the app with `python3 build-system/Make/Make.py … build … --configuration=debug_sim_arm64` (no unit tests in this project). -- Manual test: send a message containing a t.me link with an instant-view preview. Tap a URL inside the rich-data preview bubble — it should route to the chat's URL handler (open inline webview / external browser / peer chat as appropriate). Long-press should fall through to the existing chat URL long-press menu (the bubble framework provides this for `.url` taps with `hasLongTapAction: true`, the default). Tapping a same-page anchor in the preview should hit the empty `scrollToAnchor` stub (no-op for now). -- Visual: while a URL is resolving, the URL run should be highlighted with a `LinkHighlightingNode` rectangle in the bubble's link-highlight color. The highlight should fade out on completion or cancellation. - -## Open follow-ups (not in this spec) - -- Implement `scrollToAnchor` (likely "open the full instant view at this anchor", since the inline rich bubble has no scroll view). -- Wire `openMedia` / `longPressMedia` / `activatePinchPreview` / `updateDetailsExpanded` / `updateWebEmbedHeight`. -- Long-press action sheet (Open / Copy / Add to Reading List) for URLs inside the inline preview, mirroring the IV. diff --git a/docs/superpowers/specs/2026-05-01-rich-bubble-text-selection-design.md b/docs/superpowers/specs/2026-05-01-rich-bubble-text-selection-design.md deleted file mode 100644 index 0dbdf584e9..0000000000 --- a/docs/superpowers/specs/2026-05-01-rich-bubble-text-selection-design.md +++ /dev/null @@ -1,145 +0,0 @@ -# Text selection in `ChatMessageRichDataBubbleContentNode` - -## Context - -`ChatMessageRichDataBubbleContentNode` renders an instant-page preview inline inside a chat bubble using `InstantPageLayout`/`InstantPageTile`/`InstantPageNode`. Users can already tap URLs and tap media (gallery), but cannot select any of the article text inside the preview. - -Two reference implementations exist: - -- `ChatMessageTextBubbleContentNode` (`submodules/TelegramUI/Components/Chat/ChatMessageTextBubbleContentNode/Sources/...`) — uses `TextSelectionNode` (drag-handle / knob style, action menu via `controllerInteraction.performTextSelectionAction`). Selection is gated on the bubble entering context-preview mode (`updateIsExtractedToContextPreview(true)`). The text-bubble has a single `textNode` so `TextSelectionNode` wraps it directly. -- `InstantPageControllerNode` (`submodules/InstantPageUI/Sources/...`) — paragraph-granularity highlight + `ContextMenuController`. Long-tap on a paragraph selects the whole paragraph; no drag-handles. - -The user picked the chat text-bubble model, gated only on context-preview mode. The structural challenge: rich-bubble has **many** `InstantPageTextItem`s spread across tiles, with no per-item rendering node — text is drawn directly into tile contexts via `CTLine`. - -## Goal - -Wire drag-handle text selection inside `ChatMessageRichDataBubbleContentNode`, available only in context-preview mode, with cross-paragraph selection across all `InstantPageTextItem`s in the visible layout. Action menu integrates Copy / Translate / Share / Speak / Look Up via `controllerInteraction.performTextSelectionAction`. Quote is disabled (the IV preview text is not part of `item.message.text`, which the quote feature references). - -Out of scope: nested selection inside `InstantPageDetailsItem` / `InstantPageScrollableItem` (rich-bubble does not expand details or scroll inner content); selection during normal (non-preview) interaction; per-paragraph selection-only mode. - -## Design - -### Files touched - -- **Modify:** `submodules/InstantPageUI/Sources/InstantPageTextItem.swift` — promote three accessors to public so a `TextNodeProtocol` adapter can build on top. -- **Create:** `submodules/InstantPageUI/Sources/InstantPageMultiTextAdapter.swift` — a `TextNodeProtocol`-conforming `ASDisplayNode` that aggregates multiple `InstantPageTextItem`s into a single character-indexed text view. -- **Modify:** `submodules/TelegramUI/Components/Chat/ChatMessageRichDataBubbleContentNode/BUILD` — add `//submodules/TextSelectionNode`. -- **Modify:** `submodules/TelegramUI/Components/Chat/ChatMessageRichDataBubbleContentNode/Sources/ChatMessageRichDataBubbleContentNode.swift` — add the `import`, two new ivars, and lifecycle hooks for entering / leaving context preview. - -### API exposure on `InstantPageTextItem` - -Three accessors become public: - -```swift -public final class InstantPageTextItem: InstantPageItem { - public let attributedString: NSAttributedString // was `let` (package-private) - // ... - - public func attributesAtPoint(_ point: CGPoint, orNearest: Bool) -> (Int, [NSAttributedString.Key: Any])? - public func textRangeRects(in range: NSRange) -> (rects: [CGRect], start: TextRangeRectEdge, end: TextRangeRectEdge)? -} -``` - -- The new `attributesAtPoint(_:orNearest:)` extends the existing internal `attributesAtPoint(_:)`. When `orNearest == true` and no line directly contains the point, it picks the line with the smallest vertical distance to the point and runs `CTLineGetStringIndexForPosition` with the X clamped to that line's horizontal range. Mirrors what `TextNode.attributesAtPoint(orNearest:)` does. The existing internal `attributesAtPoint(_:)` is preserved (still used by `urlAttribute(at:)` and `linkSelectionRects(at:)`). -- The new `textRangeRects(in:)` wraps the existing internal `rangeRects(in:)`. It returns `Display.TextRangeRectEdge` (same `(x, y, height: CGFloat)` shape as the IV's local `InstantPageTextRangeRectEdge`). When the inner result has no edges (range maps to no rects), the public version returns `nil`. - -The existing internal members are not renamed — only new public surface is added. - -### `InstantPageMultiTextAdapter` - -A `TextNodeProtocol`-conforming `ASDisplayNode` that aggregates multiple `InstantPageTextItem`s into a single character-indexed text view: - -```swift -public final class InstantPageMultiTextAdapter: ASDisplayNode, TextNodeProtocol { - private struct Entry { - let item: InstantPageTextItem - let charOffset: Int // global char index where this item's text starts - let frameOrigin: CGPoint // item.frame.origin, in adapter-local coords - } - - private let entries: [Entry] - private let combinedString: NSAttributedString - - public init(items: [InstantPageTextItem]) - - // TextNodeProtocol - public var currentText: NSAttributedString? { combinedString } - public func attributesAtPoint(_ point: CGPoint, orNearest: Bool) -> (Int, [NSAttributedString.Key: Any])? - public func textRangeRects(in range: NSRange) -> (rects: [CGRect], start: TextRangeRectEdge, end: TextRangeRectEdge)? -} -``` - -**Construction.** `init(items:)` walks the list in document order. For each item: -1. Append `item.attributedString` to the running combined string. -2. Record `Entry(item, charOffset: combined.length-before-append, frameOrigin: item.frame.origin)`. -3. Append `"\n\n"` (plain) as a separator between entries (no separator after the last). - -The separator chars sit in the global string with no rects in `textRangeRects` (no entry contains them), so visual selection cleanly skips inter-paragraph gaps. They also keep paragraph breaks in the copied text. - -**`attributesAtPoint(_:orNearest:)`.** -1. Direct pass: for each entry, compute `localPoint = point - entry.frameOrigin`. If `entry.item.attributesAtPoint(localPoint, orNearest: false)` returns a hit, return `(entry.charOffset + localIndex, attrs)`. -2. Fallback (only when `orNearest == true`): pick the entry whose frame has the smallest vertical distance to `point.y` (zero if `point.y` is in the y-range, otherwise `min(|p.y - frame.minY|, |p.y - frame.maxY|)`), then call its `attributesAtPoint(localPoint, orNearest: true)`. Return `(entry.charOffset + localIndex, attrs)` or `nil` if even the nearest item returns nil. -3. Otherwise return `nil`. - -**`textRangeRects(in:)`.** Splits the global range across entries: -1. For each entry whose `[charOffset, charOffset + item.attributedString.length)` intersects the requested range: - - Compute the local sub-range within the entry. - - Call `entry.item.textRangeRects(in: localRange)`. - - Translate each rect by `entry.frameOrigin`. - - First contributing entry: take its `start` edge translated by `frameOrigin`. - - Each contributing entry updates `end` to its translated `end` edge. -2. If no entry contributed any rects, return `nil`. -3. Otherwise return `(allRects, start, end)`. - -The adapter is invisible — it has no contents and is purely a `TextNodeProtocol` provider. It exists as an `ASDisplayNode` only because the protocol requires it. - -### Rich-bubble lifecycle wiring - -**New ivars:** - -```swift -private var textSelectionAdapter: InstantPageMultiTextAdapter? -private var textSelectionNode: TextSelectionNode? -``` - -**Imports / BUILD:** add `import TextSelectionNode` and `//submodules/TextSelectionNode` to the rich-bubble's BUILD deps. `TextRangeRectEdge` lives in `Display`, already imported. - -**Entering preview** (`updateIsExtractedToContextPreview(true)`): -1. Bail out if `textSelectionNode != nil`, no `item`, no `currentPageLayout`, or no `chatControllerNode`. -2. Filter `currentPageLayout.layout.items` to selectable, non-empty `InstantPageTextItem`s. -3. Construct `InstantPageMultiTextAdapter(items:)`, set its frame to `containerNode.bounds`, add it to `containerNode`. -4. Pick incoming/outgoing `textSelectionColor` and `textSelectionKnobColor` from the presentation theme. -5. Construct `TextSelectionNode` with: - - `textNodeOrView: .node(adapter)` - - `present`: routes to `controllerInteraction.presentControllerInCurrent` when `item.associatedData.subject` matches `.messageOptions(_, _, info)` with `case .reply = info`, else `presentGlobalOverlayController` — same branch the text-bubble uses (see `ChatMessageTextBubbleContentNode.swift:1651-1654`). - - `rootView`: returns the `chatControllerNode` view. - - `performAction`: routes to `controllerInteraction.performTextSelectionAction(item.message, true, text, nil, action)`. -6. Set flags: - - `enableCopy = (!associatedData.isCopyProtectionEnabled && !message.isCopyProtected()) || message.id.peerId.isVerificationCodes` — same rule as text-bubble. - - `enableQuote = false` — quote-replies reference `item.message.text`; IV preview text isn't in there. - - `enableTranslate = true`, `enableShare = true`, `enableLookup = true`. -7. Set `textSelectionNode.frame` and `textSelectionNode.highlightAreaNode.frame` to `containerNode.bounds`. -8. Add `highlightAreaNode` then `textSelectionNode` to `containerNode`. - -**Leaving preview** (`willUpdateIsExtractedToContextPreview(false)`): mirror text-bubble's tear-down — animate alpha 1→0 over 0.2s on both `highlightAreaNode` and the `textSelectionNode` itself, remove from supernode in the completion, clear both ivars synchronously so a subsequent re-entry creates fresh nodes. - -**Subnode ordering** inside `containerNode` (bottom → top): tiles → `linkHighlightingNode` (touch state, from earlier task) → `linkProgressView` (in-flight URL shimmer) → adapter (invisible) → `textSelectionNode.highlightAreaNode` → `textSelectionNode`. Order preserved by insertion sequence. - -**Coordinate strategy.** Both adapter and `textSelectionNode` use `containerNode.bounds`. The IV layout origin is `(0, 0)` inside `containerNode`, and `InstantPageTextItem.frame` is in that space — so the adapter's local coords line up with item frames directly without a `(1, 1)` translation. (The `(1, 1)` translation only applies to points coming from the bubble-content-node coord space, e.g., in `tapActionAtPoint`.) - -## Verification - -- Build green: `python3 build-system/Make/Make.py … build … --configuration=debug_sim_arm64`. No automated tests in this project. -- Manual test in simulator: - 1. Find or send a message with a rich-data IV preview (`debugRichText` setting must be on). - 2. Long-press the bubble — it lifts into the context-preview popover, the message context menu appears alongside. - 3. In the lifted preview, select text by tapping and dragging knobs. Selection extends across paragraphs. - 4. Action menu (Copy / Translate / Share / Speak / Look Up) appears anchored on the selection. Confirm Copy puts the selected text on the pasteboard, with `\n\n` between paragraphs. - 5. Quote menu item is **not** present. - 6. Dismiss the context preview — selection overlay and knobs fade out cleanly. - -## Open follow-ups (not in this spec) - -- Cross-paragraph selection inside expanded `InstantPageDetailsItem` / scrollable `InstantPageScrollableItem` content (rich-bubble doesn't currently expand or scroll those). -- Spoiler awareness on selection (text-bubble has spoiler-aware selection that triggers reveal). IV text items currently don't carry spoiler attributes through `attributedString` in a way that's symmetric with chat text, so deferred. -- Search-text highlighting within the IV preview (`updateSearchTextHighlightState`). diff --git a/docs/superpowers/specs/2026-05-01-rich-data-bubble-scroll-to-anchor-design.md b/docs/superpowers/specs/2026-05-01-rich-data-bubble-scroll-to-anchor-design.md deleted file mode 100644 index bdd859d8a0..0000000000 --- a/docs/superpowers/specs/2026-05-01-rich-data-bubble-scroll-to-anchor-design.md +++ /dev/null @@ -1,149 +0,0 @@ -# ChatMessageRichDataBubbleContentNode.scrollToAnchor - -## Background - -`ChatMessageRichDataBubbleContentNode` renders a webpage's `instantPage` inline inside a chat message bubble (the same layout/tile machinery as `InstantPageControllerNode`, but embedded as a content node of `ChatMessageBubbleItemNode`). - -The bubble already detects in-page anchor links (URL with a `#fragment`) when its base URL matches the current loaded webpage and routes them to a private `scrollToAnchor(_ anchor: String)`. That method is a stub today: - -```swift -private func scrollToAnchor(_ anchor: String) { - guard let item = self.item else { return } - item.controllerInteraction.scrollToMessageId(item.message.index, 0.0) -} -``` - -`ChatHistoryListNode.scrollToMessage(index:offset:)` ignores the offset, so the anchor name is dropped and the bubble simply scrolls to the message top. Tapping a footnote / section link inside a long instant-page bubble does nothing useful when the target is below the fold. - -## Goal - -When an in-page anchor inside a rich-data bubble is tapped, scroll the chat history so the anchor's line lands at the top of the visible content area. - -## Non-goals (explicitly deferred) - -- **Reference popup**: `InstantPageControllerNode.scrollToAnchor` shows `InstantPageReferenceController` as an overlay when the anchor is a footnote-style "reference" (text item, non-empty anchor text). We will simply scroll to the line containing the reference instead. No popup. -- **Collapsed details expansion**: The bubble already no-ops `updateDetailsExpanded`, so the runtime never toggles `InstantPageDetailsItem` state. We compute the rect for anchors inside details items as if they were expanded; no expansion side-effect is performed. Worst case for a layout-collapsed details anchor is a slightly-off scroll target — acceptable for v1. - -## Approach - -Add a `getAnchorRect(anchor:)` resolver on the bubble (mirrors `getQuoteRect`'s shape: base no-op, rich-data override walks the layout, bubble item forwards to content nodes). The chat controller then uses `forEachVisibleItemNode` to find the bubble being scrolled to (it is by definition partially visible — the user tapped a link in it), reads the anchor's item-local y, and dispatches `historyNode.scrollToMessage(... scrollPosition: .bottom(anchorY))`. `.bottom(additionalOffset)` places the item so its frame.maxY lands at `(visibleSize.height - insets.bottom) + additionalOffset`; with `additionalOffset = anchorY` (item-local-y of the anchor's top edge), the anchor renders at the visual top of the chat's content area regardless of whether the item is short or tall. (`.center(.custom)` was the original pick but is bypassed for items that fit in the content area, and the rotation maps "list-coord low" to "visual bottom" in chat lists, so `.bottom` is the more uniform primitive here.) - -### Components - -#### 1. `ChatMessageBubbleContentNode.getAnchorRect(anchor:)` — base, default `nil` - -Add an `open func getAnchorRect(anchor: String) -> CGRect? { return nil }` to the base class so callers don't need to type-test every content node. - -#### 2. `ChatMessageRichDataBubbleContentNode.getAnchorRect(anchor:)` — override - -Walk `self.currentPageLayout?.layout.items`, mirroring the cases in `InstantPageControllerNode.findAnchorItem`: -- `InstantPageAnchorItem` with matching `anchor` → return a 1pt rect at the item's `frame.origin`. -- `InstantPageTextItem`, `item.anchors[anchor] == (lineIndex, _)` → return the rect of `item.lines[lineIndex].frame`, offset by `item.frame.origin`. -- `InstantPageTableItem`, `item.anchors[anchor] == (offset, _)` → return a 1pt-tall row-width rect at `item.frame.origin + (0, offset)`. -- `InstantPageDetailsItem` → recurse into `item.items` with `baseY` increased by `item.frame.minY + item.titleHeight` (inner items live below the title bar; mirrors `InstantPageDetailsNode.linkSelectionRects`). Per non-goal #2, no expand side-effect. - -The walk returns coordinates in *layout space* (= `containerNode`-local). The bubble's `containerNode` is offset `(1, 1)` from the bubble content node, so add `(1, 1)` before returning. The returned rect is in `ChatMessageRichDataBubbleContentNode`'s own coordinate space (its `view`). - -If no anchor matches anywhere in the tree, return `nil`. - -#### 3. `ChatMessageBubbleItemNode.getAnchorRect(anchor:)` — public - -Add next to the existing `getQuoteRect(quote:offset:)`. Iterate `self.contentNodes`; for each, call `contentNode.getAnchorRect(anchor:)` and, if non-nil, return `contentNode.view.convert(rect, to: self.view)`. Return `nil` if no content node knows the anchor. - -#### 4. `ChatControllerInteraction.scrollToMessageIdWithAnchor` — new closure - -Add a new public closure on `ChatControllerInteraction`: - -```swift -public let scrollToMessageIdWithAnchor: (MessageIndex, String) -> Void -``` - -Wire through the initializer (parameter, assignment) alongside the existing `scrollToMessageId`. The existing `scrollToMessageId(MessageIndex, CGFloat)` closure stays untouched — its 7 callers (incl. 6 no-op stubs) need no signature change. - -Add no-op stubs `scrollToMessageIdWithAnchor: { _, _ in }` at the six existing no-op sites: -- `BrowserUI/Sources/BrowserBookmarksScreen.swift` -- `Components/Chat/ChatRecentActionsController/Sources/ChatRecentActionsControllerNode.swift` -- `Components/Chat/ChatSendAudioMessageContextPreview/Sources/ChatSendAudioMessageContextPreview.swift` -- `Components/PeerInfo/PeerInfoScreen/Sources/PeerInfoScreen.swift` -- `TelegramUI/Sources/OverlayAudioPlayerControllerNode.swift` -- `TelegramUI/Sources/SharedAccountContext.swift` - -#### 5. Real implementation in `ChatController.swift` - -Next to the existing `scrollToMessageId:` argument in the `ChatControllerInteraction(...)` construction, add: - -```swift -scrollToMessageIdWithAnchor: { [weak self] index, anchor in - guard let self else { return } - var anchorY: CGFloat? - self.chatDisplayNode.historyNode.forEachVisibleItemNode { itemNode in - guard anchorY == nil else { return } - if let itemNode = itemNode as? ChatMessageBubbleItemNode, - itemNode.item?.message.id == index.id, - let rect = itemNode.getAnchorRect(anchor: anchor) { - anchorY = rect.minY - } - } - if let anchorY { - self.chatDisplayNode.historyNode.scrollToMessage( - from: index, to: index, - animated: true, highlight: false, - scrollPosition: .bottom(anchorY) - ) - } else { - self.chatDisplayNode.historyNode.scrollToMessage(index: index) - } -} -``` - -`ChatHistoryListNode.scrollToMessage(from:to:animated:highlight:quote:subject:scrollPosition:setupReply:)` already accepts `scrollPosition` and routes it through `MessageHistoryScrollToSubject` → `ListViewScrollToItem.position`. The `.bottom(additionalOffset)` formula sets `frame.maxY' = (visibleSize.height - insets.bottom) + additionalOffset`; with `additionalOffset = anchorY` (the anchor's item-local y in pre-transform coords), the chat list — rotated 180° at the layer — renders the anchor at the visual top of the content area. The `forEachVisibleItemNode` walk is safe because tapping the in-page anchor link requires the bubble to be at least partially visible. - -#### 6. Replace the `scrollToAnchor` stub - -In `ChatMessageRichDataBubbleContentNode.swift`: - -```swift -private func scrollToAnchor(_ anchor: String) { - guard let item = self.item else { return } - if anchor.isEmpty { - item.controllerInteraction.scrollToMessageId(item.message.index, 0.0) - } else { - item.controllerInteraction.scrollToMessageIdWithAnchor(item.message.index, anchor) - } -} -``` - -Empty anchor (the `#` with no fragment case) keeps the existing "scroll to message top" behavior. - -## Files touched - -| File | Change | -|---|---| -| `submodules/TelegramUI/Components/Chat/ChatMessageBubbleContentNode/Sources/ChatMessageBubbleContentNode.swift` | Add `open func getAnchorRect(anchor:) -> CGRect?` returning `nil`. | -| `submodules/TelegramUI/Components/Chat/ChatMessageRichDataBubbleContentNode/Sources/ChatMessageRichDataBubbleContentNode.swift` | Override `getAnchorRect`; rewrite `scrollToAnchor` body. | -| `submodules/TelegramUI/Components/Chat/ChatMessageBubbleItemNode/Sources/ChatMessageBubbleItemNode.swift` | Add public `getAnchorRect(anchor:)`. | -| `submodules/TelegramUI/Components/ChatControllerInteraction/Sources/ChatControllerInteraction.swift` | New `scrollToMessageIdWithAnchor` field + init param + assignment. | -| `submodules/TelegramUI/Sources/ChatController.swift` | Real implementation of the closure. | -| 6 no-op stub sites | Add `scrollToMessageIdWithAnchor: { _, _ in }` next to existing stub. | - -## What is *not* changed - -- No new types in `Display/`, `AccountContext/`, or `TelegramCore/`. -- No changes to `MessageHistoryScrollToSubject` or `ChatHistoryLocation`. -- No changes to `InstantPageUI/` (the layout-walking logic is replicated in the rich-data bubble file rather than exported, since it's both small and specialized for the embedded layout). -- No changes to the existing `scrollToMessageId(_, CGFloat)` closure or its 7 call sites' signatures. - -## Verification - -There are no unit tests in this project. Verification is a full Bazel build: - -```sh -source ~/.zshrc 2>/dev/null; \ -python3 build-system/Make/Make.py --overrideXcodeVersion --cacheDir ~/telegram-bazel-cache build \ - --configurationPath build-system/appstore-configuration.json \ - --gitCodesigningRepository git@gitlab.com:peter-iakovlev/fastlanematch.git \ - --gitCodesigningType development --gitCodesigningUseCurrent \ - --buildNumber=1 --configuration=debug_sim_arm64 -``` - -Manual smoke test in the simulator: open a chat that contains a webpage message rendered as a rich-data bubble with an instant page that has internal anchors (e.g., a Wikipedia article with section links or footnote references). Tap a section link or footnote link; the chat should scroll so that the target line lands at the top of the visible content area.