Skip to content
Source
Sign inSign up
pingdotgg/t3code

fix(threads): stop missing-thread subscription retries #12711

ClosedQuicksaver(GitHub profile, opens in a new tab)wants to merge 1 commit intomain fromrefs/pull/12711/headopened View on GitHub

Summary

Deleted threads could trigger a subscription retry every 250 ms. The client treated an authoritative HTTP thread_not_found response as temporary, fell back to WebSocket, and retried when that snapshot failed too.

Missing-thread responses now clear cached detail, mark the thread deleted, and stop subscription retries, including after reconnecting or foregrounding the app. Other snapshot failures retain their fallback and retry behavior. Local web drafts wait for their server thread to exist before subscribing, so an expected pre-creation 404 cannot delete a valid draft.

What changed

  • Recognize terminal missing-thread errors across HTTP and WebSocket snapshot loading.
  • Negotiate the dedicated WebSocket error through a versioned capability and legacy opt-in, preserving compatibility with older clients and servers.
  • Serialize cache removal with persistence across disposal and remount, preventing an in-flight save from restoring deleted detail.
  • Share draft readiness classification between web detail and status consumers, including drafts whose workspace mode changes before the first send.

Validation

444 focused tests passed; four package typechecks and targeted lint passed.
  • 444 tests passed across 10 client-runtime, contracts, web, and server test files, covering missing-thread classification, cache persistence, subscription lifecycle, protocol compatibility, draft readiness, and server behavior.
  • Contracts, client-runtime, web, and server typechecks passed.
  • Targeted lint passed with existing test warnings.
  • The branch diff whitespace check passed.

🤖 Generated by GPT-6 in Codex via T3 Code

    1. github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched

    2. Approvability

      Verdict: Not approved

      Macroscope's review found this PR not approvable — This is a cross-package runtime change that alters WebSocket/HTTP error contracts, subscription retry behavior, cache deletion ordering, and draft readiness across existing paths. An unresolved medium-severity concurrency finding also concerns an old scope deleting a successor's cached thread after an ownership handoff.

      Not approved because:

      • 1 blocking correctness issue found at or above your repo's Minimum Blocking Severity
      Adjust the Minimum Blocking Severity for this repo — including turning it Off — in [Settings](https://app.macroscope.com/pingdotgg/settings#Repos). You can add or adjust custom eligibility rules. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).
    3. coderabbitai[bot](GitHub profile, opens in a new tab)commented
      Review in Change Stack →

      Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

      Note

      Reviews paused

      It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

      Use the following commands to manage reviews:

      • @coderabbitai resume to resume automatic reviews.
      • @coderabbitai review to trigger a single review.

      Use the checkboxes below for quick actions:

      • ▶️ Resume reviews
      • 🔍 Trigger review

      No actionable comments were generated in the recent review. 🎉

      ℹ️ Recent review info
      ⚙️ Run configuration

      Configuration used: Repository: pingdotgg/t3code/.coderabbit.yaml

      Review profile: CHILL

      Plan: Advanced

      Run ID: 3109f81c-198b-43dd-86ad-0647e923b1ff

      📥 Commits

      Reviewing files that changed from the base of the PR and between 0948213c0df4da21be17e41203ff0aaafd7babd3 and 052d59ba4336efa1af37f13bcef5b831fb3832ca.

      📒 Files selected for processing (3)
      • apps/server/src/server.test.ts
      • apps/server/src/ws.ts
      • packages/contracts/src/rpc.ts

      Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 4 remain after this review.


      📝 Walkthrough

      Walkthrough

      The change adds negotiated thread-not-found errors, preserves authoritative HTTP not-found failures, terminates missing-thread state, serializes cache deletion, and delays web subscriptions for local drafts until their server shells exist.

      Changes

      Thread synchronization reliability

      Layer / File(s)Summary
      Protocol negotiation and server errors
      packages/contracts/src/orchestration.ts, packages/contracts/src/rpc.ts, packages/contracts/src/rpc.test.ts, apps/server/src/ws.ts, apps/server/src/server.test.ts, BRANCH_DETAILS.md
      Subscribe-thread requests support versioned and legacy opt-in fields. Supported clients receive OrchestrationThreadNotFoundError; other clients retain OrchestrationGetSnapshotError. Contract and server tests cover payload and error compatibility.
      Terminal error classification and HTTP loading
      packages/client-runtime/src/errors/orchestration.ts, packages/client-runtime/src/errors/orchestration.test.ts, packages/client-runtime/src/state/threadSnapshotHttp.ts, packages/client-runtime/src/state/threadSnapshotHttp.test.ts
      The client identifies terminal HTTP and WebSocket thread-not-found failures. The HTTP snapshot loader preserves authoritative not-found errors, while other failures use socket fallback.
      Terminal deletion and cache persistence
      packages/client-runtime/src/state/threads.ts, packages/client-runtime/src/state/threads-sync.test.ts, packages/client-runtime/src/state/threads-atoms.test.ts, packages/client-runtime/src/state/threads-pagination.test.ts
      Missing threads become deleted, subscriptions stop, later events do not restore state, and cache removal is serialized with pending saves and resumed state owners. Tests cover deletion, pagination, and persistence races.
      Draft-thread subscription readiness
      apps/web/src/state/entities.ts, apps/web/src/components/ThreadRouteView.tsx, apps/web/src/state/entities.test.ts, apps/web/src/newThreadSubscriptionGate.test.ts, apps/web/src/composerDraftStore.test.ts
      Local drafts are classified separately from server threads. Detail and status subscriptions wait for a server shell when required. Tests cover remote new-thread references and draft lookup across environment modes.

      Priority: ⬇️ Low

      Estimated code review effort: 3 (Moderate) | ~25 minutes

      Change: Bug fix

      Sequence Diagram(s)

      sequenceDiagram
        participant ThreadState
        participant ThreadSnapshotLoader
        participant WebSocketServer
        participant CacheStore
        ThreadState->>ThreadSnapshotLoader: load thread snapshot
        ThreadSnapshotLoader->>WebSocketServer: request snapshot
        WebSocketServer-->>ThreadSnapshotLoader: thread_not_found failure
        ThreadSnapshotLoader-->>ThreadState: terminal not-found error
        ThreadState->>CacheStore: remove cached thread
        ThreadState-->>WebSocketServer: interrupt subscription

      Suggested reviewers: chrisdeeming, bil0000, juliusmarminge

      Merge Risk: ⚪ Minimal · up to 052d5

      No actionable blocker remains. Missing-thread handling preserves legacy compatibility while stopping terminal retries and delaying draft subscriptions until server readiness; merge after normal checks pass.

      Security Architecture Review

      Security architecture risk: 🔵 Low · up to 052d5

      The change contains missing-thread retry loops without an identified authorization bypass or new attack path. Compatibility and deletion ordering have supporting checks, but deployment-wide isolation and mixed-version operation were not independently established.

      Retained concerns No architecture-level concerns identified.

      Security review details

      Security Blast Radius

      • inferred — The inspected effect is scoped to a requested thread snapshot and its environment/thread client cache entry. Capability negotiation does not add a mutation operation or broader authority. This assessment does not establish deployment-wide tenant isolation.

      Trust Boundaries and Controls

      • observed — The subscription remains subject to the session's orchestration-read scope through the existing RPC authorization wrapper. Client-supplied thread IDs and negotiation fields do not bypass that check in the inspected path.

      Resilience and Maintainability Implications

      • inferred — Typed failure classification, deleted-state guards, and shared save/removal ordering contain repeated requests and stale-detail restoration races. Repository tests exercise foregrounding, replacement sessions, deletion ordering, and ordinary failure recovery rather than treating every snapshot failure as terminal.
      🚥 Pre-merge checks | ✅ 4 | ❌ 1

      ❌ Failed checks (1 warning)

      Check nameStatusExplanationResolution
      Docstring Coverage⚠️ WarningDocstring coverage is 12.50% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 24 functions across 18 files.Write docstrings for the functions missing them to satisfy the coverage threshold.
      ✅ Passed checks (4 passed)
      Check nameStatusExplanation
      Title check✅ PassedThe title clearly and concisely describes the primary change: stopping repeated subscription retries for missing threads.
      Description check✅ PassedThe description clearly explains the problem, the solution, compatibility changes, draft readiness behavior, and validation results. It is focused and mostly complete. It does not use the exact templa…
      Linked Issues check✅ PassedCheck skipped because no linked issues were found for this pull request.
      Out of Scope Changes check✅ PassedCheck skipped because no linked issues were found for this pull request.
      • Fix all pre-merge checks with AI
      ✨ Finishing Touches
      🧪 Generate unit tests (beta)
      • Create a new PR

      Comment `@coderabbitai help` to get the list of available commands.
    4. One small repo-hygiene note: BRANCH_DETAILS.md reads like implementation / merge notes for this PR rather than durable project documentation.

      The root AGENTS.md explicitly says not to commit implementation plans, research notes, or PR summaries, and to let the merged PR be the implementation record.

      Would it make sense to drop this file from the PR? The code and tests already capture the compatibility seams it describes.

    5. @coderabbitai The retained ownership concern in your updated review is the same concern already assessed and resolved here.

      I rechecked the current head, d1cf1f9ecb. setDeletedLocked publishes deleted state through remember before waiting for persistenceLock. A successor inherits that deleted state, and persistence checks it inside the lock. It cannot save fresh detail in the proposed interleaving. Rechecking ownership before removal would instead let stale disk detail survive when the successor has already inherited deleted state.

      All 70 tests in threads-atoms.test.ts, threads-sync.test.ts, and threads-pagination.test.ts pass on this head, including pending finalizer saves overlapping terminal deletion. No implementation change is needed for the repeated finding.

      The generic docstring coverage warning also remains unchanged. It identifies no missing explanation, and the repository documentation policy asks us to document non-obvious constraints rather than add per-function narration. No documentation change is needed.

      🤖 Generated by GPT-6 in Codex via T3 Code

    6. Tip

      For best results, initiate chat on the files or code changes.

      🧩 Analysis chain

      🏁 Script executed:

      #!/bin/bash
      set -euo pipefail
      printf 'HEAD: '; git rev-parse --short HEAD
      printf '\nFiles:\n'; fd -a '^(threads\.ts|AGENTS\.md)$' | head -60
      printf '\nThread symbols:\n'; ast-grep outline packages/client-runtime/src/state/threads.ts --items all --match 'setDeletedLocked|remember|persistenceLock|persist|save|resume' | head -160
      printf '\nRelevant source lines:\n'; rg -n -C 7 'setDeletedLocked|persistenceLock|remember\(|saveThread\(|removeThread\(|resum(e|ed)' packages/client-runtime/src/state/threads.ts | head -340
      printf '\nPolicy matches:\n'; rg -n -C 4 'implementation plans|research notes|PR summaries|non-obvious|docstring|document' AGENTS.md | head -160

      Length of output: 20223


      🏁 Script executed:

      #!/bin/bash
      set -euo pipefail
      printf 'State initialization, handoff and persistence:\n'
      sed -n '185,335p' packages/client-runtime/src/state/threads.ts
      printf '\nDeletion and stream gate:\n'
      sed -n '390,475p' packages/client-runtime/src/state/threads.ts
      printf '\nRegression test locations:\n'
      rg -n -C 5 'pending finalizer|disposed successor|mounted successor|removeThread|persistenceLock' packages/client-runtime/src/state/threads-atoms.test.ts | tail -180
      printf '\nRelated review text (if accessible):\n'
      gh api repos/pingdotgg/t3code/issues/comments/5748829793 --jq '.body' 2>/dev/null | head -130 || true
      gh api repos/pingdotgg/t3code/pulls/comments/4056962476 --jq '.body' 2>/dev/null | head -100 || true

      Length of output: 19006


      @Quicksaver, you are right. I checked the current head. setDeletedLocked publishes deleted state through remember before it waits for persistenceLock. A successor inherits that state, and persist checks it inside the lock before saving. My retained ownership concern was incorrect. A second ownership check before removal could leave stale cached detail on disk.

      The generic docstring warning was also not actionable under the repository’s documentation policy. No code or documentation change is needed for either finding. I did not rerun the 70 tests you reported.

      Thanks for the careful correction.


      ✏️ Learnings added
      Learnt from: Quicksaver
      URL: https://github.com/pingdotgg/t3code/pull/12711
      
      Timestamp: 2026-09-27T17:25:43.708Z
      Learning: In `packages/client-runtime/src/state/threads.ts`, `setDeletedLocked` publishes deleted state via `remember` before waiting for the shared `persistenceLock`. A successor owner inherits the deleted state, and `persist` checks that state inside the lock before saving. Do not flag removal by the previous owner after the lock wait as a successor-detail deletion race without a separate path that can persist successor detail. Rechecking ownership after the lock wait could leave stale cached detail on disk.

      Learnt from: Quicksaver
      URL: https://github.com/pingdotgg/t3code/pull/12711
      
      Timestamp: 2026-09-27T17:25:43.708Z
      Learning: The root `AGENTS.md` in pingdotgg/t3code directs contributors to document non-obvious constraints rather than narrate code or add per-function docstrings. Do not raise a generic docstring-coverage warning without identifying a specific missing explanation.

      Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

      You are interacting with an AI system.

    7. @kvnloo In response to your note, this fork requires BRANCH_DETAILS.md as its per-branch customization contract. The fork's agent tooling reads it before working on the branch, so I am keeping it here as required branch documentation.

      🤖 Generated by GPT-6 in Codex via T3 Code

    8. Note

      This comment is posted by Julius' dot

      Closing under the contribution documentation requirement and AGENTS.md’s work-artifact rule. BRANCH_DETAILS.md commits a per-branch implementation account, merge checklist/file catalog and local development ports. Your reply confirms it is retained for the fork’s agent tooling; that requirement does not override upstream’s rule against committed implementation notes.

      The missing-thread retry problem and focused regression evidence remain useful. Please remove this branch artifact from the upstream diff, keep fork-specific tooling notes outside it, and retain only genuinely hard-to-discover constraints in nearby code or appropriate existing documentation. Then request reconsideration.

    9. juliusmarminge closed this

Sign in to join this conversation.