Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.
fix(server): bound thread activity hydration (#6153)
t3-code[bot]71c6f8248775
diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.tsindex be596b36b..83ae3cfe0 100644--- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts+++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts@@ -2281,6 +2281,130 @@ projectionSnapshotLayer("ProjectionSnapshotQuery windowed thread detail", (it) =}),);+ it.effect("bounds activity hydration and preserves unresolved requests", () =>+ Effect.gen(function* () {+ yield* seedFanOutThread();+ const snapshotQuery = yield* ProjectionSnapshotQuery;+ const sql = yield* SqlClient.SqlClient;++ yield* sql`DELETE FROM projection_thread_activities`;+ yield* sql`+ WITH RECURSIVE activity_rows(sequence) AS (+ SELECT 1+ UNION ALL+ SELECT sequence + 1 FROM activity_rows WHERE sequence < 501+ )+ INSERT INTO projection_thread_activities (+ activity_id, thread_id, turn_id, tone, kind, summary, payload_json, sequence, created_at+ )+ SELECT+ printf('activity-%04d', sequence),+ 'thread-w',+ 'turn-5',+ 'tool',+ 'tool.completed',+ 'ran tool',+ printf('{"sequence":%d}', sequence),+ sequence,+ '2026-03-01T00:04:00.000Z'+ FROM activity_rows+ `;++ const fullDetail = yield* snapshotQuery.getThreadDetailById(threadW);+ assert.equal(fullDetail._tag, "Some");+ if (fullDetail._tag === "Some") {+ assert.equal(fullDetail.value.activities.length, 500);+ assert.equal(fullDetail.value.activities[0]?.id, asEventId("activity-0002"));+ assert.equal(fullDetail.value.activities.at(-1)?.id, asEventId("activity-0501"));+ }++ const windowedDetail = yield* snapshotQuery.getThreadDetailSnapshot(threadW, {+ turnLimit: 2,+ });+ assert.equal(windowedDetail._tag, "Some");+ if (windowedDetail._tag === "Some") {+ assert.equal(windowedDetail.value.thread.activities.length, 500);+ assert.equal(windowedDetail.value.thread.activities[0]?.id, asEventId("activity-0002"));+ assert.equal(windowedDetail.value.thread.activities.at(-1)?.id, asEventId("activity-0501"));+ }++ yield* sql`+ INSERT INTO projection_thread_activities (+ activity_id, thread_id, turn_id, tone, kind, summary, payload_json, sequence, created_at+ )+ VALUES+ (+ 'approval-old', 'thread-w', NULL, 'approval', 'approval.requested',+ 'Approve old command', '{"requestId":"approval-1"}', NULL,+ '2026-03-01T00:00:01.000Z'+ ),+ (+ 'user-input-old', 'thread-w', NULL, 'approval', 'user-input.requested',+ 'Answer old question', '{"requestId":"input-1"}', NULL,+ '2026-03-01T00:00:02.000Z'+ ),+ (+ 'user-input-closed', 'thread-w', NULL, 'approval', 'user-input.requested',+ 'Closed question', '{"requestId":"input-closed"}', NULL,+ '2026-03-01T00:00:03.000Z'+ ),+ (+ 'user-input-closed-resolution', 'thread-w', NULL, 'info', 'user-input.resolved',+ 'Closed question', '{"requestId":"input-closed"}', NULL,+ '2026-03-01T00:00:04.000Z'+ ),+ (+ 'user-input-tied-z-request', 'thread-w', NULL, 'approval', 'user-input.requested',+ 'Tied open question', '{"requestId":"input-tied-open"}', NULL,+ '2026-03-01T00:00:05.000Z'+ ),+ (+ 'user-input-tied-a-resolution', 'thread-w', NULL, 'info', 'user-input.resolved',+ 'Tied open question', '{"requestId":"input-tied-open"}', NULL,+ '2026-03-01T00:00:05.000Z'+ )+ `;+ yield* sql`+ INSERT INTO projection_pending_approvals (+ request_id, thread_id, turn_id, status, decision, created_at, resolved_at+ )+ VALUES (+ 'approval-1', 'thread-w', NULL, 'pending', NULL,+ '2026-03-01T00:00:01.000Z', NULL+ )+ `;+ yield* sql`+ UPDATE projection_threads+ SET pending_approval_count = 1, pending_user_input_count = 1+ WHERE thread_id = 'thread-w'+ `;++ const detailWithPinnedRequests = yield* snapshotQuery.getThreadDetailById(threadW);+ assert.equal(detailWithPinnedRequests._tag, "Some");+ if (detailWithPinnedRequests._tag === "Some") {+ const ids = detailWithPinnedRequests.value.activities.map((activity) => activity.id);+ assert.equal(detailWithPinnedRequests.value.activities.length, 503);+ assert.equal(ids.includes(asEventId("approval-old")), true);+ assert.equal(ids.includes(asEventId("user-input-old")), true);+ assert.equal(ids.includes(asEventId("user-input-closed")), false);+ assert.equal(ids.includes(asEventId("user-input-tied-z-request")), true);+ }++ const windowWithPinnedRequests = yield* snapshotQuery.getThreadDetailSnapshot(threadW, {+ turnLimit: 2,+ });+ assert.equal(windowWithPinnedRequests._tag, "Some");+ if (windowWithPinnedRequests._tag === "Some") {+ const ids = windowWithPinnedRequests.value.thread.activities.map((activity) => activity.id);+ assert.equal(windowWithPinnedRequests.value.thread.activities.length, 503);+ assert.equal(ids.includes(asEventId("approval-old")), true);+ assert.equal(ids.includes(asEventId("user-input-old")), true);+ assert.equal(ids.includes(asEventId("user-input-closed")), false);+ assert.equal(ids.includes(asEventId("user-input-tied-z-request")), true);+ }+ }),+ );+it.effect("a thread with no turns returns its content unwindowed on the first page", () =>Effect.gen(function* () {const sql = yield* SqlClient.SqlClient;diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.tsindex 3e77f9cf8..c6c5ad1d7 100644--- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts+++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts@@ -69,6 +69,10 @@ import {const decodeReadModel = Schema.decodeUnknownEffect(OrchestrationReadModel);const decodeShellSnapshot = Schema.decodeUnknownEffect(OrchestrationShellSnapshot);const decodeThread = Schema.decodeUnknownEffect(OrchestrationThread);+// Keep detail reads consistent with the in-memory projector's retained+// activity window. Applying the limit in SQL avoids decoding an unbounded+// payload_json set before the projector can enforce that invariant.+const THREAD_DETAIL_ACTIVITY_LIMIT = 500;const ProjectionProjectDbRowSchema = ProjectionProject.mapFields(Struct.assign({defaultModelSelection: Schema.NullOr(Schema.fromJsonString(ModelSelection)),@@ -1015,8 +1019,25 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {payload_json AS "payload",sequence,created_at AS "createdAt"- FROM projection_thread_activities- WHERE thread_id = ${threadId}+ FROM (+ SELECT+ activity_id,+ thread_id,+ turn_id,+ tone,+ kind,+ summary,+ payload_json,+ sequence,+ created_at+ FROM projection_thread_activities+ WHERE thread_id = ${threadId}+ ORDER BY+ sequence DESC,+ created_at DESC,+ activity_id DESC+ LIMIT ${THREAD_DETAIL_ACTIVITY_LIMIT}+ ) AS recent_activitiesORDER BYsequence ASC,created_at ASC,@@ -1232,6 +1253,95 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {`,});+ // Blocking request payloads must remain available even if they predate the+ // recent activity window. Each CTE returns at most one unresolved row per+ // request, so the merge below stays bounded by actionable work.+ const listPinnedThreadActivityRowsByThread = SqlSchema.findAll({+ Request: ThreadIdLookupInput,+ Result: ProjectionThreadActivityDbRowSchema,+ execute: ({ threadId }) =>+ sql`+ WITH pending_approval_requests AS (+ SELECT request_id, thread_id+ FROM projection_pending_approvals+ WHERE thread_id = ${threadId}+ AND status = 'pending'+ ),+ pending_approval_activities AS (+ SELECT+ activity.activity_id,+ ROW_NUMBER() OVER (+ PARTITION BY pending.request_id+ ORDER BY activity.created_at DESC, activity.activity_id DESC+ ) AS request_order+ FROM pending_approval_requests AS pending+ CROSS JOIN projection_thread_activities AS activity+ WHERE activity.thread_id = pending.thread_id+ AND activity.kind = 'approval.requested'+ AND json_extract(activity.payload_json, '$.requestId') = pending.request_id+ ),+ pending_user_input_thread AS (+ SELECT thread_id+ FROM projection_threads+ WHERE thread_id = ${threadId}+ AND pending_user_input_count > 0+ ),+ user_input_lifecycle AS (+ SELECT+ activity.activity_id,+ activity.kind,+ ROW_NUMBER() OVER (+ PARTITION BY json_extract(activity.payload_json, '$.requestId')+ ORDER BY activity.created_at DESC, activity.activity_id DESC+ ) AS request_order+ FROM pending_user_input_thread AS pending+ CROSS JOIN projection_thread_activities AS activity+ WHERE activity.thread_id = pending.thread_id+ AND (+ activity.kind IN ('user-input.requested', 'user-input.resolved')+ OR (+ activity.kind = 'provider.user-input.respond.failed'+ AND (+ lower(COALESCE(json_extract(activity.payload_json, '$.detail'), ''))+ LIKE '%stale pending user-input request%'+ OR lower(COALESCE(json_extract(activity.payload_json, '$.detail'), ''))+ LIKE '%unknown pending user-input request%'+ OR lower(COALESCE(json_extract(activity.payload_json, '$.detail'), ''))+ LIKE '%unknown pending user input request%'+ OR lower(COALESCE(json_extract(activity.payload_json, '$.detail'), ''))+ LIKE '%unknown pending codex user input request%'+ )+ )+ )+ AND json_extract(activity.payload_json, '$.requestId') IS NOT NULL+ ),+ pinned_activity_ids AS (+ SELECT activity_id+ FROM pending_approval_activities+ WHERE request_order = 1+ UNION ALL+ SELECT activity_id+ FROM user_input_lifecycle+ WHERE request_order = 1+ AND kind = 'user-input.requested'+ )+ SELECT+ activity.activity_id AS "activityId",+ activity.thread_id AS "threadId",+ activity.turn_id AS "turnId",+ activity.tone,+ activity.kind,+ activity.summary,+ activity.payload_json AS "payload",+ activity.sequence,+ activity.created_at AS "createdAt"+ FROM pinned_activity_ids AS pinned+ INNER JOIN projection_thread_activities AS activity+ ON activity.activity_id = pinned.activity_id+ ORDER BY activity.created_at ASC, activity.activity_id ASC+ `,+ });+const listThreadActivityRowsByThreadWindow = SqlSchema.findAll({Request: ThreadTurnRangeLookupInput,Result: ProjectionThreadActivityDbRowSchema,@@ -1247,34 +1357,51 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {payload_json AS "payload",sequence,created_at AS "createdAt"- FROM projection_thread_activities- WHERE thread_id = ${threadId}- AND (- turn_id IN (- SELECT turn_id FROM projection_turns- WHERE thread_id = ${threadId}- AND turn_id IS NOT NULL- AND (- requested_at > ${minAnchorAt}- OR (- requested_at = ${minAnchorAt}- AND turn_id >= ${minTurnKey}+ FROM (+ SELECT+ activity_id,+ thread_id,+ turn_id,+ tone,+ kind,+ summary,+ payload_json,+ sequence,+ created_at+ FROM projection_thread_activities+ WHERE thread_id = ${threadId}+ AND (+ turn_id IN (+ SELECT turn_id FROM projection_turns+ WHERE thread_id = ${threadId}+ AND turn_id IS NOT NULL+ AND (+ requested_at > ${minAnchorAt}+ OR (+ requested_at = ${minAnchorAt}+ AND turn_id >= ${minTurnKey}+ ))- )- AND (- requested_at < ${beforeAnchorAt}- OR (- requested_at = ${beforeAnchorAt}- AND turn_id < ${beforeTurnKey}+ AND (+ requested_at < ${beforeAnchorAt}+ OR (+ requested_at = ${beforeAnchorAt}+ AND turn_id < ${beforeTurnKey}+ ))- )- )- OR (- turn_id IS NULL- AND created_at >= ${minAnchorAt}- AND created_at < ${beforeAnchorAt}+ )+ OR (+ turn_id IS NULL+ AND created_at >= ${minAnchorAt}+ AND created_at < ${beforeAnchorAt}+ ))- )+ ORDER BY+ sequence DESC,+ created_at DESC,+ activity_id DESC+ LIMIT ${THREAD_DETAIL_ACTIVITY_LIMIT}+ ) AS recent_activitiesORDER BYsequence ASC,created_at ASC,@@ -2374,6 +2501,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {messageRows,proposedPlanRows,activityRows,+ pinnedActivityRows,checkpointRows,latestTurnRow,sessionRow,@@ -2416,6 +2544,14 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {),),),+ listPinnedThreadActivityRowsByThread({ threadId }).pipe(+ Effect.mapError(+ toPersistenceSqlOrDecodeError(+ "ProjectionSnapshotQuery.getThreadDetailById:listPinnedActivities:query",+ "ProjectionSnapshotQuery.getThreadDetailById:listPinnedActivities:decodeRows",+ ),+ ),+ ),listCheckpointRowsByThread({ threadId }).pipe(Effect.mapError(toPersistenceSqlOrDecodeError(@@ -2446,6 +2582,17 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {return Option.none<OrchestrationThread>();}+ const selectedActivityRows = [+ ...new Map(+ [...activityRows, ...pinnedActivityRows].map((row) => [row.activityId, row] as const),+ ).values(),+ ].toSorted(+ (left, right) =>+ (left.sequence ?? -1) - (right.sequence ?? -1) ||+ left.createdAt.localeCompare(right.createdAt) ||+ left.activityId.localeCompare(right.activityId),+ );+const thread = {id: threadRow.value.threadId,projectId: threadRow.value.projectId,@@ -2483,7 +2630,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {return message;}),proposedPlans: proposedPlanRows.map(mapProposedPlanRow),- activities: activityRows.map((row) => {+ activities: selectedActivityRows.map((row) => {const activity = {id: row.activityId,tone: row.tone,