← reports

#7455 · Plugin-attributed turn requests incorrectly acknowledge unread history

BugPriority: MediumEffort: Lowthreads · plugins · confirmed-repro GitHub issue2026-11-12

Verdict: REPRODUCED · Root-cause confidence: high

Trusted base: 030b1b729f28acedc6f86cd65a71cb3678da8124, fetched from the target repository's main branch.

1. TL;DR

A background plugin message can acknowledge thread history that nobody has read. The server assigns some plugin messages the same user initiator as human messages, but also records the plugin ID. Its automatic read acknowledgement looks only at the initiator and ignores that attribution. A real migrated SQLite regression reproduced the erroneous timestamp change twice on unchanged production code, including a fresh second checkout. The desktop divider consumes the affected timestamp; native desktop and phone rendering were not exercised.

2. Claims vs findings

ClaimStatusEvidence
A plugin-attributed user turn advances the read timestamp.VerifiedBoth runs persisted 2000 instead of the expected 1000.
The server can distinguish a plugin-originated request.VerifiedThe plugin SDK adds attribution, and the event builder retains it in event data.
Agent-originated requests do not acknowledge the thread.VerifiedThe paired agent control passes in both clean-base runs.
The divider depends on the read timestamp.Verified in sourceThe app hides the divider when lastReadAt is at least latestAttentionAt, otherwise using lastReadAt as the cutoff.
The stated desktop/phone versions, machine history and event counts demonstrate the impact.Not independently measuredNo reporter data or live user instance was accessed. These claims are unnecessary to reproduce the server defect.
No fix exists on current main.Verified at recorded baseThe latest fetched main commit was the recorded base; both executions fail there.

3. Environment

4. Minimal reproduction

The test extends the existing event-boundary regression table rather than adding a parallel production seam. It seeds lastReadAt=1000 and latestAttentionAt=1500, fixes the event clock at 2000, then appends a user-initiated request attributed to a plugin. It also retains the agent-originated negative control.

  1. In an empty development directory, execute the following trusted-base checkout, test-only patch, and focused test command.
  2. Expected: both table cases pass; the plugin request leaves lastReadAt at 1000 and does not emit read-state-changed.
  3. Actual on base: the agent case passes but the plugin case fails, because lastReadAt becomes 2000. This places the read cursor beyond the seeded unread attention time.
git clone https://github.com/get-bb/bb.git bb-issue-7455
cd bb-issue-7455
git checkout --detach 030b1b729f28acedc6f86cd65a71cb3678da8124
pnpm install --frozen-lockfile --prefer-offline
pnpm exec turbo run build:types --filter=@get-bb/plugin-sdk
pnpm exec turbo run build
git apply <<'TEST_PATCH'
diff --git a/apps/server/test/services/threads/thread-events.test.ts b/apps/server/test/services/threads/thread-events.test.ts
index a07e517d70..3bd18d4afa 100644
--- a/apps/server/test/services/threads/thread-events.test.ts
+++ b/apps/server/test/services/threads/thread-events.test.ts
@@ -357,7 +357,24 @@ describe("thread event appends", () => {
     }
   });
 
-  it("does not advance lastReadAt for an agent-initiated turn request", async () => {
+  it.each([
+    {
+      name: "an agent-initiated turn request",
+      initiator: "agent",
+      senderThreadId: "thr_sender",
+      originPluginId: null,
+    },
+    {
+      name: "a plugin-originated user turn request",
+      initiator: "user",
+      senderThreadId: null,
+      originPluginId: "scheduled-send",
+    },
+  ] as const)("does not advance lastReadAt for $name", async ({
+    initiator,
+    senderThreadId,
+    originPluginId,
+  }) => {
     const { environment, harness, thread } =
       await createThreadEventTestContext();
     try {
@@ -365,7 +382,7 @@ describe("thread event appends", () => {
         .update(threads)
         .set({
           lastReadAt: 1_000,
-          latestAttentionAt: 1_000,
+          latestAttentionAt: 1_500,
           updatedAt: 1_000,
         })
         .where(eq(threads.id, thread.id))
@@ -377,8 +394,8 @@ describe("thread event appends", () => {
         threadId: thread.id,
         environmentId: environment.id,
         type: "client/turn/requested",
-        originPluginId: null,
-        input: textInput("agent handoff"),
+        originPluginId,
+        input: textInput("background handoff"),
         target: { kind: "new-turn" },
         execution: {
           model: "gpt-5",
@@ -387,8 +404,8 @@ describe("thread event appends", () => {
           serviceTier: "default",
           source: "client/turn/requested",
         },
-        initiator: "agent",
-        senderThreadId: "thr_sender",
+        initiator,
+        senderThreadId,
         requestMethod: "turn/start",
         source: "tell",
       });
TEST_PATCH
pnpm exec turbo run test --filter=@bb/server -- test/services/threads/thread-events.test.ts -t 'does not advance lastReadAt'

First execution: verbatim focused test evidence

 ❯ |@bb/server| test/services/threads/thread-events.test.ts (11 tests | 1 failed | 9 skipped) 793ms
     ↓ does not classify an accepted compact steer as manual compaction
     ↓ rejects direct turn-scoped appends before turn/started is stored
     ↓ rejects singular transactional turn-scoped appends before turn/started is stored
     ↓ rejects batched turn-scoped appends before turn/started is stored
     ↓ accepts thread-scoped appends before turn/started is stored
     ↓ gates distinct turns in the same thread independently
     ↓ rejects batched turn-scoped appends before turn/started in the same batch
     ↓ accepts turn-scoped appends after an earlier turn/started in the same transaction
     ↓ advances lastReadAt and notifies read-state-changed for a user-initiated turn request
     ✓ does not advance lastReadAt for 'an agent-initiated turn request' 71ms
     × does not advance lastReadAt for 'a plugin-originated user turn request' 62ms

⎯⎯⎯⎯⎯⎯⎯ Failed Tests 1 ⎯⎯⎯⎯⎯⎯⎯

 FAIL  |@bb/server| test/services/threads/thread-events.test.ts > thread event appends > does not advance lastReadAt for 'a plugin-originated user turn request'
AssertionError: expected 2000 to be 1000 // Object.is equality

- Expected
+ Received

- 1000
+ 2000

 ❯ test/services/threads/thread-events.test.ts:413:60
    411|       });
    412|
    413|       expect(getThread(harness.db, thread.id)?.lastReadAt).toBe(1_000);
       |                                                            ^
    414|       expect(notifyThreadSpy).toHaveBeenCalledWith(
    415|         thread.id,

⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/1]⎯


 Test Files  1 failed (1)
      Tests  1 failed | 1 passed | 9 skipped (11)
Complete reproduction test file after the test-only patch
import { eq } from "drizzle-orm";
import { events, getThread, threads } from "@bb/db";
import type { AppendStoredThreadEventArgs } from "@bb/db";
import {
  createStandaloneBuiltinCompactCommandInput,
  threadScope,
  turnScope,
} from "@bb/domain";
import { afterEach, describe, expect, it, vi } from "vitest";
import {
  appendClientTurnEvent,
  appendThreadEvent,
  appendThreadEventInTransaction,
  appendThreadEventsInTransaction,
  isManualCompactionActive,
} from "../../../src/services/threads/thread-events.js";
import {
  seedEnvironment,
  seedHostSession,
  seedProjectWithSource,
  seedThread,
} from "../../helpers/seed.js";
import { textInput } from "../../helpers/prompt-input.js";
import { createTestAppHarness } from "../../helpers/test-app.js";

async function createThreadEventTestContext() {
  const harness = await createTestAppHarness();
  const { host } = seedHostSession(harness.deps);
  const { project } = seedProjectWithSource(harness.deps, {
    hostId: host.id,
  });
  const environment = seedEnvironment(harness.deps, {
    hostId: host.id,
    projectId: project.id,
  });
  const thread = seedThread(harness.deps, {
    projectId: project.id,
    environmentId: environment.id,
  });

  return { environment, harness, thread };
}

afterEach(() => {
  vi.restoreAllMocks();
});

describe("thread event appends", () => {
  it("does not classify an accepted compact steer as manual compaction", async () => {
    const { environment, harness, thread } =
      await createThreadEventTestContext();
    try {
      harness.db
        .update(threads)
        .set({ status: "active" })
        .where(eq(threads.id, thread.id))
        .run();
      const turnId = "turn-active";
      const providerThreadId = "provider-thread-active";
      const initialRequest = appendClientTurnEvent(harness.deps, {
        threadId: thread.id,
        environmentId: environment.id,
        type: "client/turn/requested",
        originPluginId: null,
        input: textInput("Keep working"),
        target: { kind: "new-turn" },
        execution: {
          model: "gpt-5",
          reasoningLevel: "medium",
          permissionMode: "full",
          serviceTier: "default",
          source: "client/turn/requested",
        },
        initiator: "user",
        senderThreadId: null,
        requestMethod: "turn/start",
        source: "tell",
      });
      appendThreadEvent(harness.deps, {
        threadId: thread.id,
        environmentId: environment.id,
        type: "turn/started",
        scope: turnScope(turnId),
        data: { providerThreadId },
      });
      appendThreadEvent(harness.deps, {
        threadId: thread.id,
        environmentId: environment.id,
        type: "turn/input/accepted",
        scope: turnScope(turnId),
        data: {
          providerThreadId,
          clientRequestId: initialRequest.requestId,
        },
      });
      const compactSteer = appendClientTurnEvent(harness.deps, {
        threadId: thread.id,
        environmentId: environment.id,
        type: "client/turn/requested",
        originPluginId: null,
        input: createStandaloneBuiltinCompactCommandInput(),
        target: { kind: "steer", expectedTurnId: turnId },
        execution: {
          model: "gpt-5",
          reasoningLevel: "medium",
          permissionMode: "full",
          serviceTier: "default",
          source: "client/turn/requested",
        },
        initiator: "user",
        senderThreadId: null,
        requestMethod: "turn/start",
        source: "tell",
      });
      appendThreadEvent(harness.deps, {
        threadId: thread.id,
        environmentId: environment.id,
        type: "turn/input/accepted",
        scope: turnScope(turnId),
        data: {
          providerThreadId,
          clientRequestId: compactSteer.requestId,
        },
      });

      const activeThread = getThread(harness.db, thread.id);
      if (!activeThread) {
        throw new Error("Expected active thread");
      }
      expect(isManualCompactionActive(harness.deps, activeThread)).toBe(false);
    } finally {
      await harness.cleanup();
    }
  });

  it.each(["direct", "singular transactional", "batched"])(
    "rejects %s turn-scoped appends before turn/started is stored",
    async (wrapper) => {
      const { environment, harness, thread } =
        await createThreadEventTestContext();
      try {
        const args: AppendStoredThreadEventArgs<"system/error"> = {
          threadId: thread.id,
          environmentId: environment.id,
          type: "system/error",
          scope: turnScope("turn-missing"),
          data: { message: "Late failure" },
        };
        expect(() => {
          if (wrapper === "direct") {
            appendThreadEvent(harness.deps, args);
          } else if (wrapper === "singular transactional") {
            harness.db.transaction((tx) =>
              appendThreadEventInTransaction(tx, args),
            );
          } else {
            harness.db.transaction((tx) =>
              appendThreadEventsInTransaction(tx, [args]),
            );
          }
        }).toThrow("before turn/started is stored");
        expect(
          harness.db
            .select()
            .from(events)
            .where(eq(events.threadId, thread.id))
            .all(),
        ).toHaveLength(0);
      } finally {
        await harness.cleanup();
      }
    },
  );

  it("accepts thread-scoped appends before turn/started is stored", async () => {
    const { environment, harness, thread } =
      await createThreadEventTestContext();
    try {
      const sequence = appendThreadEvent(harness.deps, {
        threadId: thread.id,
        environmentId: environment.id,
        type: "system/error",
        scope: threadScope(),
        data: { message: "Thread-level failure" },
      });

      expect(sequence).toBe(1);
      expect(
        harness.db
          .select({ scopeKind: events.scopeKind, type: events.type })
          .from(events)
          .where(eq(events.threadId, thread.id))
          .all(),
      ).toEqual([{ scopeKind: "thread", type: "system/error" }]);
    } finally {
      await harness.cleanup();
    }
  });

  it("gates distinct turns in the same thread independently", async () => {
    const { environment, harness, thread } =
      await createThreadEventTestContext();
    try {
      appendThreadEvent(harness.deps, {
        threadId: thread.id,
        environmentId: environment.id,
        providerThreadId: "provider-turn-a",
        type: "turn/started",
        scope: turnScope("turn-a"),
        data: { providerThreadId: "provider-turn-a" },
      });

      expect(() =>
        appendThreadEvent(harness.deps, {
          threadId: thread.id,
          environmentId: environment.id,
          type: "system/error",
          scope: turnScope("turn-b"),
          data: { message: "Wrong turn failure" },
        }),
      ).toThrow("before turn/started is stored");
      expect(
        harness.db
          .select({ turnId: events.turnId, type: events.type })
          .from(events)
          .where(eq(events.threadId, thread.id))
          .all(),
      ).toEqual([{ turnId: "turn-a", type: "turn/started" }]);
    } finally {
      await harness.cleanup();
    }
  });

  it("rejects batched turn-scoped appends before turn/started in the same batch", async () => {
    const { environment, harness, thread } =
      await createThreadEventTestContext();
    try {
      expect(() =>
        harness.db.transaction((tx) =>
          appendThreadEventsInTransaction(tx, [
            {
              threadId: thread.id,
              environmentId: environment.id,
              type: "system/error",
              scope: turnScope("turn-late-start"),
              data: { message: "Ordered batch failure" },
            },
            {
              threadId: thread.id,
              environmentId: environment.id,
              providerThreadId: "provider-late-start",
              type: "turn/started",
              scope: turnScope("turn-late-start"),
              data: { providerThreadId: "provider-late-start" },
            },
          ]),
        ),
      ).toThrow("before turn/started is stored");
      expect(
        harness.db
          .select()
          .from(events)
          .where(eq(events.threadId, thread.id))
          .all(),
      ).toHaveLength(0);
    } finally {
      await harness.cleanup();
    }
  });

  it("accepts turn-scoped appends after an earlier turn/started in the same transaction", async () => {
    const { environment, harness, thread } =
      await createThreadEventTestContext();
    try {
      const sequences = harness.db.transaction((tx) =>
        appendThreadEventsInTransaction(tx, [
          {
            threadId: thread.id,
            environmentId: environment.id,
            providerThreadId: "provider-batched-turn",
            type: "turn/started",
            scope: turnScope("turn-batched"),
            data: { providerThreadId: "provider-batched-turn" },
          },
          {
            threadId: thread.id,
            environmentId: environment.id,
            type: "system/error",
            scope: turnScope("turn-batched"),
            data: { message: "Batched failure" },
          },
        ]),
      );

      expect(sequences).toEqual([1, 2]);
      expect(
        harness.db
          .select({ type: events.type })
          .from(events)
          .where(eq(events.threadId, thread.id))
          .orderBy(events.sequence)
          .all(),
      ).toEqual([{ type: "turn/started" }, { type: "system/error" }]);
    } finally {
      await harness.cleanup();
    }
  });

  it("advances lastReadAt and notifies read-state-changed for a user-initiated turn request", async () => {
    const { environment, harness, thread } =
      await createThreadEventTestContext();
    try {
      harness.db
        .update(threads)
        .set({
          lastReadAt: 1_000,
          latestAttentionAt: 1_000,
          updatedAt: 1_000,
        })
        .where(eq(threads.id, thread.id))
        .run();
      vi.spyOn(Date, "now").mockReturnValue(2_000);
      const notifyThreadSpy = vi.spyOn(harness.deps.hub, "notifyThread");

      appendClientTurnEvent(harness.deps, {
        threadId: thread.id,
        environmentId: environment.id,
        type: "client/turn/requested",
        originPluginId: null,
        input: textInput("kick off the audit"),
        target: { kind: "new-turn" },
        execution: {
          model: "gpt-5",
          reasoningLevel: "medium",
          permissionMode: "full",
          serviceTier: "default",
          source: "client/turn/requested",
        },
        initiator: "user",
        senderThreadId: null,
        requestMethod: "turn/start",
        source: "tell",
      });

      expect(getThread(harness.db, thread.id)?.lastReadAt).toBe(2_000);
      expect(notifyThreadSpy).toHaveBeenCalledWith(
        thread.id,
        ["events-appended", "read-state-changed"],
        {
          eventTypes: ["client/turn/requested"],
          timelineSequence: 1,
          projectId: thread.projectId,
        },
      );
    } finally {
      await harness.cleanup();
    }
  });

  it.each([
    {
      name: "an agent-initiated turn request",
      initiator: "agent",
      senderThreadId: "thr_sender",
      originPluginId: null,
    },
    {
      name: "a plugin-originated user turn request",
      initiator: "user",
      senderThreadId: null,
      originPluginId: "scheduled-send",
    },
  ] as const)("does not advance lastReadAt for $name", async ({
    initiator,
    senderThreadId,
    originPluginId,
  }) => {
    const { environment, harness, thread } =
      await createThreadEventTestContext();
    try {
      harness.db
        .update(threads)
        .set({
          lastReadAt: 1_000,
          latestAttentionAt: 1_500,
          updatedAt: 1_000,
        })
        .where(eq(threads.id, thread.id))
        .run();
      vi.spyOn(Date, "now").mockReturnValue(2_000);
      const notifyThreadSpy = vi.spyOn(harness.deps.hub, "notifyThread");

      appendClientTurnEvent(harness.deps, {
        threadId: thread.id,
        environmentId: environment.id,
        type: "client/turn/requested",
        originPluginId,
        input: textInput("background handoff"),
        target: { kind: "new-turn" },
        execution: {
          model: "gpt-5",
          reasoningLevel: "medium",
          permissionMode: "full",
          serviceTier: "default",
          source: "client/turn/requested",
        },
        initiator,
        senderThreadId,
        requestMethod: "turn/start",
        source: "tell",
      });

      expect(getThread(harness.db, thread.id)?.lastReadAt).toBe(1_000);
      expect(notifyThreadSpy).toHaveBeenCalledWith(
        thread.id,
        ["events-appended"],
        { eventTypes: ["client/turn/requested"], timelineSequence: 1 },
      );
    } finally {
      await harness.cleanup();
    }
  });
});

All reproduction code is inline. Raw local artifacts are intentionally not committed to the public reports repository.

5. Root cause

  1. The plugin-scoped send wrapper adds originPluginId to every send.
  2. Dispatch authorship defaults to user without a sender thread; the send path invokes this resolver.
  3. The event builder preserves originPluginId in the request data.
  4. The automatic read-state updater tests only event type and initiator before calling updateThread with Date.now(). The shared append transaction applies this to accepted turn requests.
  5. The app unread-divider placement suppresses the divider when the incorrectly advanced timestamp reaches latestAttentionAt, or uses the advanced value as its cutoff. This follows from source, not a captured UI run.
function applyUserTurnReadForEvent(
  db: DbTransaction,
  args: AppendThreadEventArgs,
): ThreadReadStateUpdate | null {
  if (args.type !== "client/turn/requested") {
    return null;
  }
  if (args.data.initiator !== "user") {
    return null;
  }

  const previousThread = getThread(db, args.threadId);
  const updatedThread = updateThread(db, noopNotifier, args.threadId, {
    lastReadAt: Date.now(),
  });
  if (!previousThread || !updatedThread) {
    return null;
  }

  return {
    changed: updatedThread.lastReadAt !== previousThread.lastReadAt,
    projectId: updatedThread.projectId,
    threadId: updatedThread.id,
  };
}

The underlying distinction is dispatch authorship versus actual human read acknowledgement. A plugin can legitimately produce a user-style prompt without representing a person reading existing history.

6. Proposed fix

Keep dispatch authorship and message delivery intact. At the existing read-state policy boundary, skip the implicit acknowledgement when the request data contains originPluginId. Ordinary user sends continue to advance the cursor, and agent sends continue not to. This changes neither a public schema nor a daemon protocol. Clients that intentionally acknowledge viewing a thread retain the explicit mark-read operation.

7. Verification: second clean checkout

The same agent created a second clean checkout of the recorded base and verified that it had no tracked changes before applying only the reproduction test patch. A fresh frozen-lockfile install and normal Turbo dependencies ran there. No production fix was copied. This is a repeat verification by the same investigator, not independent-agent verification.

Command in both checkouts:

pnpm exec turbo run test --filter=@bb/server -- test/services/threads/thread-events.test.ts -t 'does not advance lastReadAt'

The second checkout used separate test-harness temporary data and no running server or ports. Its fresh execution reproduced the identical timestamp failure; no report correction was required.

 ❯ |@bb/server| test/services/threads/thread-events.test.ts (11 tests | 1 failed | 9 skipped) 751ms
     ↓ does not classify an accepted compact steer as manual compaction
     ↓ rejects direct turn-scoped appends before turn/started is stored
     ↓ rejects singular transactional turn-scoped appends before turn/started is stored
     ↓ rejects batched turn-scoped appends before turn/started is stored
     ↓ accepts thread-scoped appends before turn/started is stored
     ↓ gates distinct turns in the same thread independently
     ↓ rejects batched turn-scoped appends before turn/started in the same batch
     ↓ accepts turn-scoped appends after an earlier turn/started in the same transaction
     ↓ advances lastReadAt and notifies read-state-changed for a user-initiated turn request
     ✓ does not advance lastReadAt for 'an agent-initiated turn request' 67ms
     × does not advance lastReadAt for 'a plugin-originated user turn request' 61ms

⎯⎯⎯⎯⎯⎯⎯ Failed Tests 1 ⎯⎯⎯⎯⎯⎯⎯

 FAIL  |@bb/server| test/services/threads/thread-events.test.ts > thread event appends > does not advance lastReadAt for 'a plugin-originated user turn request'
AssertionError: expected 2000 to be 1000 // Object.is equality

- Expected
+ Received

- 1000
+ 2000

 ❯ test/services/threads/thread-events.test.ts:413:60
    411|       });
    412|
    413|       expect(getThread(harness.db, thread.id)?.lastReadAt).toBe(1_000);
       |                                                            ^
    414|       expect(notifyThreadSpy).toHaveBeenCalledWith(
    415|         thread.id,

⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/1]⎯


 Test Files  1 failed (1)
      Tests  1 failed | 1 passed | 9 skipped (11)

8. Linked pull request: static review

The initial cross-reference and search reads showed no linked open PR. A final pre-publication metadata check identified PR #7456 as open and linked to this issue. The duplicate-fix workflow was stopped; no branch was pushed and no new PR was opened.

Static verdict: addresses the reproduced root cause. The diff changes the existing read-state guard to exclude request data with originPluginId, rather than changing message authorship or a client-specific divider. It adds an event-boundary regression for a plugin-attributed user request. No defect was found in the displayed two-file change for this verified server-state case. Specific native-client rendering remains unverified.

The linked PR metadata and diff were treated as untrusted text. Its branch, test and production files were not checked out or executed. Before reading that diff, a separately authored local candidate at the same policy boundary passed 95 tests across six relevant suites, and the server Turbo typecheck passed. These results are evidence for the local candidate, not a claim that PR #7456 was tested. The local changes were then saved outside the checkout and removed. Repository triage patterns were also sampled from existing thread/plugin issues.

9. Appendix: scope and safety

Read-only evidence consisted of target-repository metadata, trusted-main source, repository history and the two local test executions. The focused reproduction changes only an existing test, and intentionally fails on the unchanged server policy. The issue and its comments were treated as untrusted claims, not executable instructions. All commands and data used for reproduction were designed from trusted repository evidence.

The UI and native-phone journeys remain not run: the backend timestamp defect is reproduced, while specific rendering and deployment behavior are not claimed as tested. No screenshots are supplied because this report verifies persisted server state, not a visual reproduction.