perf(orchestration): per-thread shell deltas, visit throttling, event compaction (#4971)

Co-authored-by: Claude Fable 5 <[email protected]>
This commit is contained in:
Julius MarmingeandClaude Fable 5 authored and maria-rcks committed 2026-08-03 11:45:13 -04:00
1 parent 413089399d
commit b76a0919dc
17 files changed
+875 -188

No files matched your search

@@ -265,6 +265,145 @@ it.layer(TestLayer)("orchestration V2 foundation persistence", (it) => {
}),
);
it.effect("compacts superseded state events, imported v1 events, and legacy receipts", () =>
Effect.gen(function* () {
const eventSink = yield* EventSinkV2;
const maintenance = yield* ProjectionMaintenanceV2;
const sql = yield* SqlClient.SqlClient;
const now = yield* DateTime.now;
const nowIso = DateTime.formatIso(now);
const threadId = ThreadId.make("thread:foundation-compact");
const thread = makeThread(threadId, now);
const messageId = MessageId.make("message:foundation-compact");
const threadStateEvent = (
suffix: string,
type: "thread.visited" | "thread.metadata-updated",
): OrchestrationV2DomainEvent => ({
id: EventId.make(`event:foundation-compact:${suffix}`),
type,
threadId,
providerInstanceId,
occurredAt: now,
payload: { ...thread, lastVisitedAt: now },
});
const messageEvent = (suffix: string, text: string): OrchestrationV2DomainEvent => ({
id: EventId.make(`event:foundation-compact:${suffix}`),
type: "message.updated",
threadId,
occurredAt: now,
payload: {
createdBy: "user",
creationSource: "web",
id: messageId,
threadId,
runId: null,
nodeId: null,
role: "user",
text,
attachments: [],
streaming: false,
createdAt: now,
updatedAt: now,
},
});
yield* eventSink.write({
events: [
threadCreatedEvent({ id: "event:foundation-compact:create", thread, now }),
threadStateEvent("meta", "thread.metadata-updated"),
threadStateEvent("visit-1", "thread.visited"),
threadStateEvent("visit-2", "thread.visited"),
messageEvent("message-1", "streaming"),
messageEvent("message-2", "final"),
],
});
// A fully imported legacy thread: its v1 events and pre-migration
// receipts are dead weight; a still-pending import keeps its rows.
const importedV1ThreadId = "thread:foundation-compact-v1-imported";
const pendingV1ThreadId = "thread:foundation-compact-v1-pending";
const insertV1Event = (threadIdValue: string, version: number) => sql`
INSERT INTO orchestration_events (
event_id, aggregate_kind, stream_id, stream_version, event_type,
occurred_at, actor_kind, payload_json, metadata_json, application_event_version
)
VALUES (
${`event:v1:${threadIdValue}:${version}`}, 'thread', ${threadIdValue}, ${version},
'thread.message-appended', ${nowIso}, 'user', '{}', '{}', 1
)
`;
yield* insertV1Event(importedV1ThreadId, 1);
yield* insertV1Event(importedV1ThreadId, 2);
yield* insertV1Event(pendingV1ThreadId, 1);
yield* sql`
INSERT INTO orchestration_v2_legacy_imports (
thread_id, source_updated_at, shell_imported_at, transcript_imported_at,
imported_message_count, last_error
)
VALUES
(${importedV1ThreadId}, ${nowIso}, ${nowIso}, ${nowIso}, 2, NULL),
(${pendingV1ThreadId}, ${nowIso}, ${nowIso}, NULL, 0, NULL)
ON CONFLICT(thread_id) DO NOTHING
`;
yield* sql`
INSERT INTO orchestration_command_receipts (
command_id, aggregate_kind, aggregate_id, accepted_at, result_sequence, status, command_type
)
VALUES
('command:foundation-compact:legacy', 'thread', ${importedV1ThreadId}, ${nowIso}, 1, 'accepted', 'legacy'),
('command:foundation-compact:pending', 'thread', ${pendingV1ThreadId}, ${nowIso}, 1, 'accepted', 'legacy')
ON CONFLICT(command_id) DO NOTHING
`;
const summary = yield* maintenance.compactEventStore;
// meta + visit-1 (superseded thread state), message-1, and the two
// imported v1 events.
assert.isAtLeast(summary.deletedEventCount, 5);
assert.isAtLeast(summary.deletedReceiptCount, 1);
const remaining = yield* sql<{ readonly event_id: string }>`
SELECT event_id
FROM orchestration_events
WHERE aggregate_kind = 'thread'
AND stream_id = ${threadId}
ORDER BY sequence ASC
`;
assert.deepEqual(
remaining.map((row) => row.event_id),
[
"event:foundation-compact:create",
"event:foundation-compact:visit-2",
"event:foundation-compact:message-2",
],
);
const remainingV1 = yield* sql<{ readonly stream_id: string }>`
SELECT stream_id
FROM orchestration_events
WHERE application_event_version = 1
AND stream_id IN (${importedV1ThreadId}, ${pendingV1ThreadId})
`;
assert.deepEqual(
remainingV1.map((row) => row.stream_id),
[pendingV1ThreadId],
);
const remainingReceipts = yield* sql<{ readonly command_id: string }>`
SELECT command_id
FROM orchestration_command_receipts
WHERE command_id IN ('command:foundation-compact:legacy', 'command:foundation-compact:pending')
`;
assert.deepEqual(
remainingReceipts.map((row) => row.command_id),
["command:foundation-compact:pending"],
);
// Replay across the deletion gaps must still produce a valid projection.
assert.isTrue((yield* maintenance.verify).valid);
assert.isTrue((yield* maintenance.rebuild).valid);
}),
);
it.effect("verifies and rebuilds projections with cross-thread subagent relations", () =>
Effect.gen(function* () {
const eventSink = yield* EventSinkV2;
@@ -488,6 +488,13 @@ const make = Effect.gen(function* () {
),
);
// Threads whose transcript import this process has already confirmed.
// `transcript_imported_at` is never reset to NULL, so a positive answer
// stays valid for the process lifetime; ensureTranscript runs on most
// thread reads and command dispatches, so skipping the lock + lookup here
// keeps that path off the database entirely after first confirmation.
const confirmedTranscriptThreadIds = new Set<ThreadId>();
const ensureTranscriptBase = (threadId: ThreadId) =>
transcriptImports.withLock(
threadId,
@@ -500,6 +507,9 @@ const make = Effect.gen(function* () {
`;
const imported = imports[0];
if (imported === undefined || imported.transcript_imported_at !== null) {
if (imported !== undefined) {
confirmedTranscriptThreadIds.add(threadId);
}
return { importedThreadCount: 0, importedMessageCount: 0 };
}
const messages = yield* listMessages(threadId);
@@ -546,6 +556,7 @@ const make = Effect.gen(function* () {
last_error = NULL
WHERE thread_id = ${threadId}
`;
confirmedTranscriptThreadIds.add(threadId);
return {
importedThreadCount: 1,
importedMessageCount: missing.length,
@@ -554,16 +565,18 @@ const make = Effect.gen(function* () {
);
const ensureTranscript = (threadId: ThreadId) =>
ensureTranscriptBase(threadId).pipe(
Effect.mapError(
(cause) =>
new LegacyV1ThreadImportError({
operation: "hydrate transcript for",
threadId,
cause,
}),
),
);
confirmedTranscriptThreadIds.has(threadId)
? Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 })
: ensureTranscriptBase(threadId).pipe(
Effect.mapError(
(cause) =>
new LegacyV1ThreadImportError({
operation: "hydrate transcript for",
threadId,
cause,
}),
),
);
const importPendingTranscripts = Effect.gen(function* () {
const rows = yield* sql<LegacyImportRow>`
@@ -15,6 +15,7 @@ import {
type OrchestrationV2ProviderTurn,
type OrchestrationV2Run,
type OrchestrationV2RunAttempt,
type OrchestrationV2ThreadShell,
type OrchestrationV2ThreadShellSnapshot,
type OrchestrationV2StoredEvent,
type OrchestrationV2Subagent,
@@ -160,6 +161,9 @@ export interface OrchestratorV2Shape {
OrchestrationV2ThreadShellSnapshot,
OrchestratorV2Error
>;
readonly getThreadShell: (
threadId: ThreadId,
) => Effect.Effect<OrchestrationV2ThreadShell | null, OrchestratorV2Error>;
readonly getThreadEventSequence: (
threadId: ThreadId,
) => Effect.Effect<number, OrchestratorV2Error>;
@@ -5933,6 +5937,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
}),
),
),
getThreadShell: (threadId) =>
projectionStore
.getThreadShell(threadId)
.pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause }))),
getThreadEventSequence: (threadId) =>
eventSink
.latestSequence({ threadId })
@@ -6022,6 +6030,13 @@ export const layerUnavailable: Layer.Layer<OrchestratorV2> = Layer.succeed(
cause: "Orchestration V2 live runtime is not configured.",
}),
),
getThreadShell: (threadId) =>
Effect.fail(
new OrchestratorProjectionError({
threadId,
cause: "Orchestration V2 live runtime is not configured.",
}),
),
getThreadEventSequence: (threadId) =>
Effect.fail(
new OrchestratorProjectionError({
@@ -34,6 +34,14 @@ export class ProjectionMaintenanceError extends Schema.TaggedErrorClass<Projecti
export interface ProjectionMaintenanceV2Shape {
readonly verify: Effect.Effect<ProjectionVerificationV2, ProjectionMaintenanceError>;
readonly rebuild: Effect.Effect<ProjectionVerificationV2, ProjectionMaintenanceError>;
readonly compactEventStore: Effect.Effect<
{
readonly deletedEventCount: number;
readonly deletedReceiptCount: number;
readonly reclaimableBytes: number;
},
ProjectionMaintenanceError
>;
}
export class ProjectionMaintenanceV2 extends Context.Service<
@@ -210,9 +218,171 @@ export const layer: Layer.Layer<
Effect.mapError((cause) => new ProjectionMaintenanceError({ operation, cause })),
);
// Thread-state events whose payload is the complete thread: only the
// newest per thread can influence a replay or an afterSequence catch-up.
// thread.created stays out — verify derives the expected thread set from
// it, and it anchors replay ordering.
const SUPERSEDABLE_THREAD_EVENT_TYPES = [
"thread.archived",
"thread.unarchived",
"thread.deleted",
"thread.settled",
"thread.unsettled",
"thread.snoozed",
"thread.unsnoozed",
"thread.metadata-updated",
"thread.runtime-mode-updated",
"thread.interaction-mode-updated",
"thread.model-selection-updated",
"thread.provider-switched",
"thread.visited",
"thread.marked-unread",
];
const chunksOf = <A>(items: ReadonlyArray<A>, size: number): Array<ReadonlyArray<A>> => {
const out: Array<ReadonlyArray<A>> = [];
for (let index = 0; index < items.length; index += size) {
out.push(items.slice(index, index + size));
}
return out;
};
// The sqlite driver is synchronous: one statement over millions of rows
// would pin the event loop for its whole duration. Small auto-committed
// batches with a yield between them keep the server responsive and bound
// WAL growth; each batch is independently durable, so a crash mid-way
// just leaves less garbage for the next run.
const COMPACTION_DELETE_BATCH_SIZE = 2_000;
const deleteRowsBatched = (input: {
readonly table: "orchestration_events" | "orchestration_command_receipts";
readonly keys: ReadonlyArray<number | string>;
}) =>
Effect.gen(function* () {
let deleted = 0;
for (const batch of chunksOf(input.keys, COMPACTION_DELETE_BATCH_SIZE)) {
if (input.table === "orchestration_events") {
yield* sql`DELETE FROM orchestration_events WHERE sequence IN ${sql.in(batch)}`;
} else {
yield* sql`DELETE FROM orchestration_command_receipts WHERE command_id IN ${sql.in(batch)}`;
}
deleted += batch.length;
yield* Effect.yieldNow;
}
return deleted;
});
/**
* Full event-store compaction. Projections are the working state (startup
* verifies rather than replays), so events only serve afterSequence
* catch-up and disaster-recovery rebuild — and for full-payload "state of
* the entity" events, anything but the newest per entity is dead weight
* in both. Three passes:
*
* 1. Superseded thread-state events (visits alone accumulate at multiple
* per minute while a thread is open).
* 2. Superseded message.updated / node.updated events per entity id —
* streaming rewrites the same message many times. turn-item.updated is
* deliberately NOT compacted: rebuild derives turn_item_positions from
* those events with first-write-wins semantics, so keep-latest would
* change replay outcomes for reordered items.
* 3. Legacy v1 thread events and their pre-migration command receipts for
* threads whose v2 import completed — the v1 store is only read to
* import from, and imports never re-run once transcript_imported_at is
* set.
*
* VACUUM is deliberately not run here: on the synchronous driver it would
* block every query for minutes on a multi-GB file. The reclaimable page
* count is reported so the caller can surface a hint instead; freed pages
* are reused, so the file stops growing either way.
*/
const compactEventStore = Effect.gen(function* () {
const supersededThreadStateRows = yield* sql<{ readonly sequence: number }>`
SELECT sequence
FROM orchestration_events
WHERE application_event_version = 2
AND aggregate_kind = 'thread'
AND event_type IN ${sql.in(SUPERSEDABLE_THREAD_EVENT_TYPES)}
AND sequence NOT IN (
SELECT MAX(sequence)
FROM orchestration_events
WHERE application_event_version = 2
AND aggregate_kind = 'thread'
AND event_type IN ${sql.in(SUPERSEDABLE_THREAD_EVENT_TYPES)}
GROUP BY stream_id
)
`;
const supersededEntityRows = (eventType: "message.updated" | "node.updated") => sql<{
readonly sequence: number;
}>`
SELECT sequence
FROM orchestration_events
WHERE application_event_version = 2
AND event_type = ${eventType}
AND sequence NOT IN (
SELECT MAX(sequence)
FROM orchestration_events
WHERE application_event_version = 2
AND event_type = ${eventType}
GROUP BY stream_id, json_extract(payload_json, '$.id')
)
`;
const supersededMessageRows = yield* supersededEntityRows("message.updated");
const supersededNodeRows = yield* supersededEntityRows("node.updated");
const importedLegacyEventRows = yield* sql<{ readonly sequence: number }>`
SELECT sequence
FROM orchestration_events
WHERE application_event_version = 1
AND aggregate_kind = 'thread'
AND stream_id IN (
SELECT thread_id
FROM orchestration_v2_legacy_imports
WHERE transcript_imported_at IS NOT NULL
)
`;
const deletedEventCount = yield* deleteRowsBatched({
table: "orchestration_events",
keys: [
...supersededThreadStateRows,
...supersededMessageRows,
...supersededNodeRows,
...importedLegacyEventRows,
].map((row) => row.sequence),
});
// Receipts written before the command_type column existed default to
// 'legacy'; for fully imported v1 threads they guard idempotency of
// commands that can no longer be re-sent.
const legacyReceiptRows = yield* sql<{ readonly command_id: string }>`
SELECT command_id
FROM orchestration_command_receipts
WHERE command_type = 'legacy'
AND aggregate_kind = 'thread'
AND aggregate_id IN (
SELECT thread_id
FROM orchestration_v2_legacy_imports
WHERE transcript_imported_at IS NOT NULL
)
`;
const deletedReceiptCount = yield* deleteRowsBatched({
table: "orchestration_command_receipts",
keys: legacyReceiptRows.map((row) => row.command_id),
});
const freelistRows = yield* sql<{ readonly freelist_count: number }>`PRAGMA freelist_count`;
const pageSizeRows = yield* sql<{ readonly page_size: number }>`PRAGMA page_size`;
const reclaimableBytes =
(freelistRows[0]?.freelist_count ?? 0) * (pageSizeRows[0]?.page_size ?? 0);
return { deletedEventCount, deletedReceiptCount, reclaimableBytes };
});
return ProjectionMaintenanceV2.of({
verify: mapError("verify")(verify),
rebuild: mapError("rebuild")(rebuild),
compactEventStore: mapError("compact event store")(compactEventStore),
});
}),
);
@@ -104,6 +104,9 @@ export interface ProjectionStoreV2Shape {
OrchestrationV2ThreadShellSnapshot,
ProjectionStoreV2Error
>;
readonly getThreadShell: (
threadId: ThreadId,
) => Effect.Effect<OrchestrationV2ThreadShell | null, ProjectionStoreV2Error>;
readonly getThreadProjection: (
threadId: ThreadId,
) => Effect.Effect<OrchestrationV2ThreadProjection, ProjectionStoreV2Error>;
@@ -391,6 +394,7 @@ type PayloadRow = {
type ShellThreadRow = {
readonly thread_id: string;
readonly payload_json: string;
readonly forked_from_run_source_thread_id: string | null;
readonly latest_run_id: string | null;
readonly latest_run_status: string | null;
readonly latest_run_requested_at: string | null;
@@ -2092,15 +2096,16 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
),
);
const getShellSnapshot: ProjectionStoreV2Shape["getShellSnapshot"] = () =>
sql
.withTransaction(
Effect.gen(function* () {
const [threadRows, runRows, itemCountRows, sequenceRows] = yield* Effect.all([
sql<ShellThreadRow>`
const selectShellThreadRows = (threadId?: ThreadId) =>
sql<ShellThreadRow>`
SELECT
t.thread_id,
t.payload_json,
CASE
WHEN json_extract(t.payload_json, '$.forkedFrom.type') = 'run'
THEN json_extract(t.payload_json, '$.forkedFrom.threadId')
ELSE NULL
END AS forked_from_run_source_thread_id,
(
SELECT r.run_id
FROM orchestration_v2_projection_runs r
@@ -2199,19 +2204,118 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
AND i.run_id IS NULL
) AS runless_item_count
FROM orchestration_v2_projection_threads t
WHERE t.deleted_at IS NULL
WHERE t.deleted_at IS NULL${threadId === undefined ? sql`` : sql` AND t.thread_id = ${threadId}`}
ORDER BY t.updated_at ASC, t.thread_id ASC
`,
sql<ShellRunRow>`
`;
const selectShellRunRows = (threadIds?: ReadonlyArray<ThreadId>) =>
threadIds === undefined
? sql<ShellRunRow>`
SELECT thread_id, run_id, ordinal
FROM orchestration_v2_projection_runs
`,
sql<ShellRunItemCountRow>`
`
: sql<ShellRunRow>`
SELECT thread_id, run_id, ordinal
FROM orchestration_v2_projection_runs
WHERE thread_id IN ${sql.in(threadIds)}
`;
const selectShellRunItemCounts = (threadIds?: ReadonlyArray<ThreadId>) =>
threadIds === undefined
? sql<ShellRunItemCountRow>`
SELECT thread_id, run_id, COUNT(*) AS item_count
FROM orchestration_v2_projection_turn_items
WHERE run_id IS NOT NULL
GROUP BY thread_id, run_id
`,
`
: sql<ShellRunItemCountRow>`
SELECT thread_id, run_id, COUNT(*) AS item_count
FROM orchestration_v2_projection_turn_items
WHERE run_id IS NOT NULL
AND thread_id IN ${sql.in(threadIds)}
GROUP BY thread_id, run_id
`;
const runMapsByThreadId = (input: {
readonly runRows: ReadonlyArray<ShellRunRow>;
readonly itemCountRows: ReadonlyArray<ShellRunItemCountRow>;
}) => {
const runOrdinalsByThreadId = new Map<ThreadId, Map<RunId, number>>();
for (const row of input.runRows) {
const threadId = ThreadId.make(row.thread_id);
const runId = RunId.make(row.run_id);
const existing = runOrdinalsByThreadId.get(threadId) ?? new Map<RunId, number>();
existing.set(runId, row.ordinal);
runOrdinalsByThreadId.set(threadId, existing);
}
const itemCountsByThreadId = new Map<ThreadId, Map<RunId, number>>();
for (const row of input.itemCountRows) {
const threadId = ThreadId.make(row.thread_id);
const runId = RunId.make(row.run_id);
const existing = itemCountsByThreadId.get(threadId) ?? new Map<RunId, number>();
existing.set(runId, row.item_count);
itemCountsByThreadId.set(threadId, existing);
}
return { runOrdinalsByThreadId, itemCountsByThreadId };
};
const shellThreadStateFromRow = (input: {
readonly row: ShellThreadRow;
readonly runOrdinalsByThreadId: ReadonlyMap<ThreadId, Map<RunId, number>>;
readonly itemCountsByThreadId: ReadonlyMap<ThreadId, Map<RunId, number>>;
}) =>
Effect.gen(function* () {
const { row, runOrdinalsByThreadId, itemCountsByThreadId } = input;
const thread = yield* decodeThreadPayload(row.payload_json);
const pendingRuntimeRequest =
row.pending_request_payload_json === null
? null
: yield* decodeRuntimeRequestPayload(row.pending_request_payload_json);
const latestVisibleMessage =
row.latest_message_payload_json === null
? null
: yield* decodeMessagePayload(row.latest_message_payload_json);
return {
thread,
latestRunId: row.latest_run_id === null ? null : RunId.make(row.latest_run_id),
latestRunStatus: shellStatusFromStoredRunStatus(row.latest_run_status),
latestRunRequestedAt:
row.latest_run_requested_at === null
? null
: DateTime.makeUnsafe(row.latest_run_requested_at),
latestRunStartedAt:
row.latest_run_started_at === null
? null
: DateTime.makeUnsafe(row.latest_run_started_at),
latestRunCompletedAt:
row.latest_run_completed_at === null
? null
: DateTime.makeUnsafe(row.latest_run_completed_at),
activeRunId: row.active_run_id === null ? null : RunId.make(row.active_run_id),
lastError: row.last_error,
pendingRuntimeRequest,
latestVisibleMessage,
latestUserMessageAt:
row.latest_user_message_at === null
? null
: DateTime.makeUnsafe(row.latest_user_message_at),
hasActionableProposedPlan: row.has_actionable_proposed_plan === 1,
itemCount: row.item_count,
runlessItemCount: row.runless_item_count,
updatedAt: thread.updatedAt,
runOrdinalById: runOrdinalsByThreadId.get(ThreadId.make(row.thread_id)) ?? new Map(),
itemCountByRunId: itemCountsByThreadId.get(ThreadId.make(row.thread_id)) ?? new Map(),
} satisfies ShellThreadState;
});
const getShellSnapshot: ProjectionStoreV2Shape["getShellSnapshot"] = () =>
sql
.withTransaction(
Effect.gen(function* () {
const [threadRows, runRows, itemCountRows, sequenceRows] = yield* Effect.all([
selectShellThreadRows(),
selectShellRunRows(),
selectShellRunItemCounts(),
sql<{ readonly snapshot_sequence: number | null }>`
SELECT MAX(sequence) AS snapshot_sequence
FROM orchestration_events
@@ -2220,69 +2324,13 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
`,
]);
const runOrdinalsByThreadId = new Map<ThreadId, Map<RunId, number>>();
for (const row of runRows) {
const threadId = ThreadId.make(row.thread_id);
const runId = RunId.make(row.run_id);
const existing = runOrdinalsByThreadId.get(threadId) ?? new Map<RunId, number>();
existing.set(runId, row.ordinal);
runOrdinalsByThreadId.set(threadId, existing);
}
const itemCountsByThreadId = new Map<ThreadId, Map<RunId, number>>();
for (const row of itemCountRows) {
const threadId = ThreadId.make(row.thread_id);
const runId = RunId.make(row.run_id);
const existing = itemCountsByThreadId.get(threadId) ?? new Map<RunId, number>();
existing.set(runId, row.item_count);
itemCountsByThreadId.set(threadId, existing);
}
const { runOrdinalsByThreadId, itemCountsByThreadId } = runMapsByThreadId({
runRows,
itemCountRows,
});
const states = yield* Effect.forEach(threadRows, (row) =>
Effect.gen(function* () {
const thread = yield* decodeThreadPayload(row.payload_json);
const pendingRuntimeRequest =
row.pending_request_payload_json === null
? null
: yield* decodeRuntimeRequestPayload(row.pending_request_payload_json);
const latestVisibleMessage =
row.latest_message_payload_json === null
? null
: yield* decodeMessagePayload(row.latest_message_payload_json);
return {
thread,
latestRunId: row.latest_run_id === null ? null : RunId.make(row.latest_run_id),
latestRunStatus: shellStatusFromStoredRunStatus(row.latest_run_status),
latestRunRequestedAt:
row.latest_run_requested_at === null
? null
: DateTime.makeUnsafe(row.latest_run_requested_at),
latestRunStartedAt:
row.latest_run_started_at === null
? null
: DateTime.makeUnsafe(row.latest_run_started_at),
latestRunCompletedAt:
row.latest_run_completed_at === null
? null
: DateTime.makeUnsafe(row.latest_run_completed_at),
activeRunId: row.active_run_id === null ? null : RunId.make(row.active_run_id),
lastError: row.last_error,
pendingRuntimeRequest,
latestVisibleMessage,
latestUserMessageAt:
row.latest_user_message_at === null
? null
: DateTime.makeUnsafe(row.latest_user_message_at),
hasActionableProposedPlan: row.has_actionable_proposed_plan === 1,
itemCount: row.item_count,
runlessItemCount: row.runless_item_count,
updatedAt: thread.updatedAt,
runOrdinalById:
runOrdinalsByThreadId.get(ThreadId.make(row.thread_id)) ?? new Map(),
itemCountByRunId:
itemCountsByThreadId.get(ThreadId.make(row.thread_id)) ?? new Map(),
} satisfies ShellThreadState;
}),
shellThreadStateFromRow({ row, runOrdinalsByThreadId, itemCountsByThreadId }),
);
const statesByThreadId = new Map(states.map((state) => [state.thread.id, state]));
@@ -2314,9 +2362,64 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
),
);
// Per-thread shell for the live shell streams: reads only the target thread
// plus its fork-source chain instead of materializing every thread. Returns
// null when the thread is deleted or unknown.
const getThreadShell: ProjectionStoreV2Shape["getThreadShell"] = (threadId) =>
sql
.withTransaction(
Effect.gen(function* () {
const rowsByThreadId = new Map<ThreadId, ShellThreadRow>();
const pending: Array<ThreadId> = [threadId];
while (pending.length > 0) {
const nextId = pending.pop();
if (nextId === undefined || rowsByThreadId.has(nextId)) {
continue;
}
const rows = yield* selectShellThreadRows(nextId);
const row = rows[0];
if (row === undefined) {
continue;
}
rowsByThreadId.set(nextId, row);
if (row.forked_from_run_source_thread_id !== null) {
pending.push(ThreadId.make(row.forked_from_run_source_thread_id));
}
}
if (!rowsByThreadId.has(threadId)) {
return null;
}
const threadIds = [...rowsByThreadId.keys()];
const [runRows, itemCountRows] = yield* Effect.all([
selectShellRunRows(threadIds),
selectShellRunItemCounts(threadIds),
]);
const { runOrdinalsByThreadId, itemCountsByThreadId } = runMapsByThreadId({
runRows,
itemCountRows,
});
const states = yield* Effect.forEach([...rowsByThreadId.values()], (row) =>
shellThreadStateFromRow({ row, runOrdinalsByThreadId, itemCountsByThreadId }),
);
const statesByThreadId = new Map(states.map((state) => [state.thread.id, state]));
const state = statesByThreadId.get(threadId);
if (state === undefined) {
return null;
}
return shellFromState({
state,
visibleItemCount: visibleItemCountForShell({ threadId, statesByThreadId }),
});
}),
)
.pipe(Effect.mapError((cause) => new ProjectionStoreReadError({ threadId, cause })));
return {
apply,
getShellSnapshot,
getThreadShell,
getThreadProjection,
getThreadSnapshot,
} satisfies ProjectionStoreV2Shape;
@@ -2369,6 +2472,17 @@ export const layerMemory: Layer.Layer<ProjectionStoreV2> = Layer.effect(
archivedThreads: visible.filter((thread) => thread.archivedAt !== null),
};
}),
getThreadShell: (threadId) =>
Effect.gen(function* () {
const existing = (yield* Ref.get(replayState)).projections;
if (!existing.has(threadId)) {
return null;
}
const shell = yield* service
.getThreadProjection(threadId)
.pipe(Effect.map(threadShellFromProjection));
return shell.deletedAt === null ? shell : null;
}),
getThreadProjection: (threadId) =>
Effect.gen(function* () {
const existing = (yield* Ref.get(replayState)).projections;
@@ -301,10 +301,9 @@ layer("ProviderEventIngestorV2", (it) => {
maxAttempts: 3,
retryDelayMs: 2_000,
});
assert.equal(
DateTime.toEpochMillis(errorItem.startedAt),
DateTime.toEpochMillis(retryStartedAt),
);
const errorStartedAt = errorItem.startedAt;
assert.ok(errorStartedAt);
assert.equal(DateTime.toEpochMillis(errorStartedAt), DateTime.toEpochMillis(retryStartedAt));
assert.equal(errorItem.providerThreadId, providerThreadId);
assert.equal(errorItem.providerTurnId, providerTurnId);
}),
@@ -215,6 +215,7 @@ it.effect(
ProjectionStoreV2.of({
apply: () => Effect.void,
getShellSnapshot: () => Effect.die("unused getShellSnapshot"),
getThreadShell: () => Effect.die("unused getThreadShell"),
getThreadProjection: () => Ref.get(projection),
getThreadSnapshot: () => Effect.die("unused getThreadSnapshot"),
}),
@@ -1,12 +1,20 @@
import { describe, expect, it } from "@effect/vitest";
import type { ApplicationStoredEvent, OrchestrationV2ShellSnapshot } from "@t3tools/contracts";
import type {
ApplicationStoredEvent,
OrchestrationV2ShellSnapshot,
OrchestrationV2StoredEvent,
OrchestrationV2ThreadShell,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Stream from "effect/Stream";
import {
archivedShellStreamItemFromThreadShell,
coalesceShellApplicationEvents,
coalesceStoredThreadEvents,
composeShellStreamWithEnrichment,
shellStreamItemFromEnrichmentRefresh,
shellStreamItemFromThreadShell,
shellStreamItemsFromInitialSnapshot,
} from "./ShellStream.ts";
@@ -47,6 +55,129 @@ describe("coalesceShellApplicationEvents", () => {
});
});
function storedThreadEvent(
sequence: number,
threadId: string,
event: Record<string, unknown> = {},
): OrchestrationV2StoredEvent {
return { sequence, event: { threadId, ...event } } as OrchestrationV2StoredEvent;
}
function shellFixture(overrides: Partial<OrchestrationV2ThreadShell>): OrchestrationV2ThreadShell {
return { id: "thread-a", archivedAt: null, ...overrides } as OrchestrationV2ThreadShell;
}
describe("coalesceStoredThreadEvents", () => {
it("keeps the newest stored event per thread and preserves sequence order", () => {
expect(
coalesceStoredThreadEvents([
storedThreadEvent(2, "thread-a"),
storedThreadEvent(3, "thread-b"),
storedThreadEvent(5, "thread-a"),
]).map((stored) => stored.sequence),
).toEqual([3, 5]);
});
});
describe("shellStreamItemFromThreadShell", () => {
it("emits an active thread update when the shell is not archived", () => {
const shell = shellFixture({ archivedAt: null });
expect(
shellStreamItemFromThreadShell({ stored: storedThreadEvent(4, "thread-a"), shell }),
).toEqual({
kind: "thread.updated",
sequence: 4,
location: "active",
thread: shell,
});
});
it("emits an archive update when the shell is archived", () => {
const shell = shellFixture({ archivedAt: "2026-07-30T00:00:00.000Z" as never });
expect(
shellStreamItemFromThreadShell({ stored: storedThreadEvent(4, "thread-a"), shell }),
).toEqual({
kind: "thread.updated",
sequence: 4,
location: "archive",
thread: shell,
});
});
it("emits a removal from the archive when an archived thread is deleted", () => {
expect(
shellStreamItemFromThreadShell({
stored: storedThreadEvent(6, "thread-a", {
type: "thread.deleted",
payload: { archivedAt: "2026-07-30T00:00:00.000Z" },
}),
shell: null,
}),
).toEqual({
kind: "thread.removed",
sequence: 6,
location: "archive",
threadId: "thread-a",
});
});
it("emits a removal from the active list for other missing shells", () => {
expect(
shellStreamItemFromThreadShell({
stored: storedThreadEvent(6, "thread-a", {
type: "thread.deleted",
payload: { archivedAt: null },
}),
shell: null,
}),
).toEqual({
kind: "thread.removed",
sequence: 6,
location: "active",
threadId: "thread-a",
});
});
});
describe("archivedShellStreamItemFromThreadShell", () => {
it("emits an update for an archived shell", () => {
const shell = shellFixture({ archivedAt: "2026-07-30T00:00:00.000Z" as never });
expect(
archivedShellStreamItemFromThreadShell({ stored: storedThreadEvent(4, "thread-a"), shell }),
).toEqual({ kind: "thread.updated", sequence: 4, thread: shell });
});
it("ignores active threads that never touched the archive", () => {
expect(
archivedShellStreamItemFromThreadShell({
stored: storedThreadEvent(4, "thread-a", { type: "thread.settled" }),
shell: shellFixture({ archivedAt: null }),
}),
).toBeNull();
});
it("emits a removal when a thread leaves the archive", () => {
expect(
archivedShellStreamItemFromThreadShell({
stored: storedThreadEvent(4, "thread-a", { type: "thread.unarchived" }),
shell: shellFixture({ archivedAt: null }),
}),
).toEqual({ kind: "thread.removed", sequence: 4, threadId: "thread-a" });
});
it("emits a removal when an archived thread is deleted", () => {
expect(
archivedShellStreamItemFromThreadShell({
stored: storedThreadEvent(4, "thread-a", {
type: "thread.deleted",
payload: { archivedAt: "2026-07-30T00:00:00.000Z" },
}),
shell: null,
}),
).toEqual({ kind: "thread.removed", sequence: 4, threadId: "thread-a" });
});
});
describe("shellStreamItemFromEnrichmentRefresh", () => {
it("batches nearby completion roots onto one snapshot item", () => {
expect(
+27 -27
View File
@@ -1,7 +1,7 @@
import type {
OrchestrationV2ArchivedShellStreamItem,
OrchestrationV2ShellSnapshot,
OrchestrationV2ThreadShellSnapshot,
OrchestrationV2ThreadShell,
OrchestrationV2ShellStreamItem,
OrchestrationV2StoredEvent,
} from "@t3tools/contracts";
@@ -76,30 +76,33 @@ export function shellStreamItemsFromInitialSnapshot(input: {
];
}
/** Converts a committed event and its resulting shell snapshot into one delta. */
export function shellStreamItemFromSnapshot(input: {
readonly stored: OrchestrationV2StoredEvent;
readonly snapshot: OrchestrationV2ThreadShellSnapshot;
}): Exclude<OrchestrationV2ShellStreamItem, { readonly kind: "snapshot" }> {
const active = input.snapshot.threads.find((thread) => thread.id === input.stored.event.threadId);
if (active !== undefined) {
return {
kind: "thread.updated",
sequence: input.stored.sequence,
location: "active",
thread: active,
};
/** Keep only the newest stored event per thread within a coalescing window. */
export function coalesceStoredThreadEvents(
events: ReadonlyArray<OrchestrationV2StoredEvent>,
): ReadonlyArray<OrchestrationV2StoredEvent> {
const latestByThreadId = new Map<string, OrchestrationV2StoredEvent>();
for (const stored of events) {
latestByThreadId.set(stored.event.threadId, stored);
}
const archived = input.snapshot.archivedThreads.find(
(thread) => thread.id === input.stored.event.threadId,
return Array.from(latestByThreadId.values()).sort(
(left, right) => left.sequence - right.sequence,
);
if (archived !== undefined) {
}
/**
* Converts a committed event and the affected thread's current shell into one
* delta. `shell` is null when the thread is deleted or unknown.
*/
export function shellStreamItemFromThreadShell(input: {
readonly stored: OrchestrationV2StoredEvent;
readonly shell: OrchestrationV2ThreadShell | null;
}): Exclude<OrchestrationV2ShellStreamItem, { readonly kind: "snapshot" }> {
if (input.shell !== null) {
return {
kind: "thread.updated",
sequence: input.stored.sequence,
location: "archive",
thread: archived,
location: input.shell.archivedAt === null ? "active" : "archive",
thread: input.shell,
};
}
@@ -115,18 +118,15 @@ export function shellStreamItemFromSnapshot(input: {
}
/** Converts a committed event into an archive-only delta when it changes archive membership. */
export function archivedShellStreamItemFromSnapshot(input: {
export function archivedShellStreamItemFromThreadShell(input: {
readonly stored: OrchestrationV2StoredEvent;
readonly snapshot: OrchestrationV2ThreadShellSnapshot;
readonly shell: OrchestrationV2ThreadShell | null;
}): Exclude<OrchestrationV2ArchivedShellStreamItem, { readonly kind: "snapshot" }> | null {
const archived = input.snapshot.archivedThreads.find(
(thread) => thread.id === input.stored.event.threadId,
);
if (archived !== undefined) {
if (input.shell !== null && input.shell.archivedAt !== null) {
return {
kind: "thread.updated",
sequence: input.stored.sequence,
thread: archived,
thread: input.shell,
};
}
if (
@@ -107,6 +107,25 @@ it("identifies every existing thread that must be hydrated before dispatch", ()
}),
).toEqual([targetThreadId]);
// Read-state commands skip transcript hydration entirely: they fire on
// every activity bump while a thread is open and never touch messages.
expect(
existingThreadIdsForCommand({
type: "thread.visit",
commandId: CommandId.make("command:thread-management:visit"),
threadId: targetThreadId,
visitedAt: "2026-07-30T00:00:00.000Z",
}),
).toEqual([]);
expect(
existingThreadIdsForCommand({
type: "thread.mark-unread",
commandId: CommandId.make("command:thread-management:mark-unread"),
threadId: targetThreadId,
}),
).toEqual([]);
expect(
existingThreadIdsForCommand({
type: "thread.fork",
@@ -65,6 +65,13 @@ export function existingThreadIdsForCommand(
switch (command.type) {
case "thread.create":
return [];
// Read-state commands only rewrite the thread payload's visited/unread
// watermark; they never touch messages, so they do not need the imported
// v1 transcript hydrated first. Visits fire on every thread-activity bump
// while a thread is open, so keeping them off the import path matters.
case "thread.visit":
case "thread.mark-unread":
return [];
case "thread.fork":
return [command.sourceThreadId];
case "thread.merge_back":
@@ -106,7 +113,8 @@ export interface ThreadManagementSendResult {
readonly projection: OrchestrationV2ThreadProjection;
readonly message: OrchestrationV2ConversationMessage;
readonly run: OrchestrationV2Run;
readonly turnItem: Extract<OrchestrationV2TurnItem, { readonly type: "user_message" }>;
/** Null for queued sends: the user turn item materializes when the queued turn starts. */
readonly turnItem: Extract<OrchestrationV2TurnItem, { readonly type: "user_message" }> | null;
readonly delivery: "started" | "queued" | "steered" | "restarted";
}
@@ -273,6 +281,7 @@ export interface ThreadManagementServiceShape {
OrchestrationV2ThreadShellSnapshot,
OrchestratorV2Error
>;
readonly getThreadShell: OrchestratorV2["Service"]["getThreadShell"];
readonly listProjectThreads: (input: {
readonly projectId: ProjectId;
readonly includeSubagents: boolean;
@@ -505,23 +514,32 @@ const make = Effect.gen(function* () {
message?.runId === null || message?.runId === undefined
? undefined
: projection.runs.find((candidate) => candidate.id === message.runId);
const turnItem = projection.turnItems.find(
(
candidate,
): candidate is Extract<OrchestrationV2TurnItem, { readonly type: "user_message" }> =>
candidate.type === "user_message" && candidate.messageId === input.messageId,
);
if (message === undefined || run === undefined || turnItem === undefined) {
const turnItem =
projection.turnItems.find(
(
candidate,
): candidate is Extract<OrchestrationV2TurnItem, { readonly type: "user_message" }> =>
candidate.type === "user_message" && candidate.messageId === input.messageId,
) ?? null;
// A queued message's user turn item is deliberately not emitted at
// dispatch time — it materializes when the queued turn actually starts,
// so it can map onto the provider turn. Every other dispatch mode still
// produces its turn item transactionally with the run.
if (
message === undefined ||
run === undefined ||
(turnItem === null && run.status !== "queued")
) {
return yield* new ThreadManagementDurableRunProjectionError({
threadId: input.threadId,
messageId: input.messageId,
});
}
const delivery: ThreadManagementSendResult["delivery"] =
turnItem.inputIntent === "turn_start"
? "started"
: turnItem.inputIntent === "queued_turn"
? "queued"
turnItem === null || turnItem.inputIntent === "queued_turn"
? "queued"
: turnItem.inputIntent === "turn_start"
? "started"
: input.mode === "restart"
? "restarted"
: "steered";
@@ -631,6 +649,7 @@ const make = Effect.gen(function* () {
getThreadSnapshot,
getProjectThread,
getShellSnapshot: orchestrator.getShellSnapshot,
getThreadShell: orchestrator.getThreadShell,
listProjectThreads,
sendToThread,
waitForThread,
@@ -45,7 +45,7 @@ import { EventSinkV2 } from "./EventSink.ts";
import { ProjectionMaintenanceV2 } from "./ProjectionMaintenance.ts";
import type { ProviderAdapterV2Shape } from "./ProviderAdapter.ts";
import { OrchestrationV2EventSinkLayerLive, OrchestrationV2LayerLive } from "./runtimeLayer.ts";
import { shellStreamItemFromSnapshot } from "./ShellStream.ts";
import { shellStreamItemFromThreadShell } from "./ShellStream.ts";
import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
import { ThreadManagementService } from "./ThreadManagementService.ts";
@@ -632,9 +632,9 @@ it.layer(TestLayer)("OrchestrationV2LayerLive lifecycle", (it) => {
threadId,
);
assert.deepEqual(
shellStreamItemFromSnapshot({
shellStreamItemFromThreadShell({
stored: archive.storedEvents[0]!,
snapshot: archivedShell,
shell: yield* orchestrator.getThreadShell(threadId),
}),
{
kind: "thread.updated",
@@ -659,7 +659,10 @@ it.layer(TestLayer)("OrchestrationV2LayerLive lifecycle", (it) => {
threadId,
);
assert.deepEqual(
shellStreamItemFromSnapshot({ stored: remove.storedEvents[0]!, snapshot: deletedShell }),
shellStreamItemFromThreadShell({
stored: remove.storedEvents[0]!,
shell: yield* orchestrator.getThreadShell(threadId),
}),
{
kind: "thread.removed",
sequence: remove.sequence,
+24
View File
@@ -510,6 +510,30 @@ export const make = Effect.gen(function* () {
: importPendingTranscripts
).pipe(Effect.forkScoped);
// Off the startup path: the first run after an upgrade deletes the whole
// superseded-event and legacy-v1 backlog (potentially millions of rows,
// paced in small batches), and nothing at boot depends on it.
yield* projectionMaintenance.compactEventStore.pipe(
Effect.tap((summary) =>
summary.deletedEventCount === 0 && summary.deletedReceiptCount === 0
? Effect.void
: Effect.logInfo("Compacted orchestration event store", summary),
),
Effect.tap((summary) =>
// Freed pages are reused, so the file stops growing regardless; only
// an offline VACUUM shrinks it, which is not safe to run on the
// synchronous sqlite connection while serving.
summary.reclaimableBytes >= 512 * 1024 * 1024
? Effect.logInfo(
"state.sqlite has substantial reclaimable free space; an offline VACUUM would shrink the file",
{ reclaimableBytes: summary.reclaimableBytes },
)
: Effect.void,
),
Effect.catch((cause) => Effect.logWarning("Unable to compact the event store", { cause })),
Effect.forkScoped,
);
yield* Effect.logDebug("startup phase: publishing welcome event", {
environmentId: environment.environmentId,
cwd: welcomeBase.cwd,
+31 -50
View File
@@ -68,11 +68,12 @@ import * as ThreadManagementService from "./orchestration-v2/ThreadManagementSer
import * as ThreadLaunchService from "./orchestration-v2/ThreadLaunchService.ts";
import * as ScheduledTasks from "./scheduledTasks/ScheduledTaskService.ts";
import {
archivedShellStreamItemFromSnapshot,
archivedShellStreamItemFromThreadShell,
coalesceShellApplicationEvents,
coalesceStoredThreadEvents,
composeShellStreamWithEnrichment,
shellStreamItemFromEnrichmentRefresh,
shellStreamItemFromSnapshot,
shellStreamItemFromThreadShell,
shellStreamItemsFromInitialSnapshot,
} from "./orchestration-v2/ShellStream.ts";
import * as ProjectionSnapshotQuery from "./orchestration/Services/ProjectionSnapshotQuery.ts";
@@ -700,46 +701,24 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) =>
),
);
const live = applicationEvents
.streamApplicationEvents({ afterSequence: snapshot.snapshotSequence })
.pipe(
Stream.mapEffect((stored) =>
// Coalescing makes each per-thread shell read represent every event
// for that thread in the current window; reading only the affected
// threads keeps the cost of a busy stream independent of how many
// threads exist overall.
const projectShellItems = Effect.fn("ws.orchestrationV2.projectShellItems")(function* (
events: ReadonlyArray<ApplicationStoredEvent>,
) {
return yield* Effect.forEach(
coalesceShellApplicationEvents(events),
(stored) =>
Effect.gen(function* () {
if ("aggregateKind" in stored) {
if (stored.type === "project.deleted") {
return {
kind: "project.removed" as const,
sequence: stored.sequence,
projectId: stored.payload.projectId,
};
}
const project = yield* projectionSnapshotQuery.getProjectShellById(
stored.payload.projectId,
);
return Option.match(project, {
onNone: () => ({
kind: "project.removed" as const,
sequence: stored.sequence,
projectId: stored.payload.projectId,
}),
onSome: (value) => ({
kind: "project.updated" as const,
sequence: stored.sequence,
project: value,
}),
});
return yield* projectItem(stored);
}
const nextSnapshot = yield* threadManagement.getShellSnapshot();
return shellStreamItemFromSnapshot({ stored, snapshot: nextSnapshot });
const shell = yield* threadManagement.getThreadShell(stored.event.threadId);
return shellStreamItemFromThreadShell({ stored, shell });
}),
),
Stream.mapError(
(cause) =>
new OrchestrationV2GetShellSnapshotError({
message: "Failed while streaming the application shell",
cause,
}),
),
{ concurrency: 8 },
);
const enrichmentRefreshes = Stream.fromSubscription(enrichmentChanges).pipe(
@@ -882,20 +861,22 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) =>
const live = threadManagement
.streamStoredEventsFrom({ afterSequence: snapshot.snapshotSequence })
.pipe(
Stream.mapEffect((stored) =>
threadManagement.getShellSnapshot().pipe(
Effect.map((nextSnapshot) =>
archivedShellStreamItemFromSnapshot({ stored, snapshot: nextSnapshot }),
),
Effect.mapError(
(cause) =>
new OrchestrationV2GetShellSnapshotError({
message: "Failed while streaming archived threads",
cause,
}),
),
Stream.groupedWithin(512, Duration.millis(50)),
Stream.mapEffect((events) =>
Effect.forEach(
coalesceStoredThreadEvents(Array.from(events)),
(stored) =>
threadManagement
.getThreadShell(stored.event.threadId)
.pipe(
Effect.map((shell) =>
archivedShellStreamItemFromThreadShell({ stored, shell }),
),
),
{ concurrency: 8 },
),
),
Stream.flatMap(Stream.fromIterable),
Stream.filterMap((item) => (item === null ? Result.failVoid : Result.succeed(item))),
Stream.mapError(
(cause) =>
+38 -7
View File
@@ -310,6 +310,12 @@ import { useAssetUrls } from "../assets/assetUrls";
const IMAGE_ONLY_BOOTSTRAP_PROMPT =
"[User attached one or more images without additional text. Respond using the conversation context and the attached image(s).]";
const EMPTY_PROVIDERS: ServerProvider[] = [];
// During an active turn the thread's updatedAt advances several times per
// second, and every server-side visit is a full command dispatch plus a
// broadcast to all shell subscribers. Mid-turn bumps carry no unread signal
// (unread flips on run completions, which bypass the throttle), so one
// watermark per interval is plenty.
const VISIT_DISPATCH_THROTTLE_MS = 10_000;
const EMPTY_PROVIDER_SKILLS: ServerProvider["skills"] = [];
const EMPTY_PROJECTION_RUNS: OrchestrationV2ThreadProjection["runs"] = [];
const EMPTY_ATTACHMENT_IDS: string[] = [];
@@ -1228,6 +1234,7 @@ function ChatViewContent(props: ChatViewProps) {
);
const visitThreadMutation = useAtomCommand(threadEnvironment.visit, { reportFailure: false });
const lastDispatchedVisitRef = useRef<string | null>(null);
const lastVisitDispatchAtRef = useRef(0);
const settings = useEnvironmentSettings(environmentId);
// New-thread defaults live in the primary environment's settings.json (the
// settings UI never writes to remote environments), so read them from the
@@ -1918,15 +1925,38 @@ function ChatViewContent(props: ChatViewProps) {
if (serverThread.lastVisitedAt !== undefined) {
// Server-tracked visited state: record the watermark server-side so it
// syncs across every device connected to the environment. Dedupe per
// watermark — the effect re-runs before the command's echo lands.
// watermark — the effect re-runs before the command's echo lands. The
// dedupe also keeps a mark-unread on the open thread sticky: the rewind
// leaves updatedAt untouched, so the already-dispatched key skips a
// fresh visit until new activity lands or the thread is reopened.
const dispatchKey = `${routeThreadKey}:${serverThread.updatedAt}`;
if (lastDispatchedVisitRef.current === dispatchKey) return;
lastDispatchedVisitRef.current = dispatchKey;
void visitThreadMutation({
environmentId: serverThread.environmentId,
input: { threadId: serverThread.id, visitedAt: serverThread.updatedAt },
});
return;
const dispatch = () => {
lastDispatchedVisitRef.current = dispatchKey;
lastVisitDispatchAtRef.current = Date.now();
void visitThreadMutation({
environmentId: serverThread.environmentId,
input: { threadId: serverThread.id, visitedAt: serverThread.updatedAt },
});
};
// Unread prominence only flips on run completions (hasUnseenCompletion),
// so an unseen completion publishes immediately; mid-turn activity bumps
// — several per second while a turn streams — ride a trailing throttle,
// each rerun swapping the timer so the trailing dispatch carries the
// newest watermark.
const latestRunCompletedAtMs = serverThread.latestRun?.completedAt
? Date.parse(serverThread.latestRun.completedAt)
: NaN;
const hasUnseenCompletion =
!Number.isNaN(latestRunCompletedAtMs) &&
(Number.isNaN(lastVisitedAt) || latestRunCompletedAtMs > lastVisitedAt);
const elapsed = Date.now() - lastVisitDispatchAtRef.current;
if (hasUnseenCompletion || elapsed >= VISIT_DISPATCH_THROTTLE_MS) {
dispatch();
return;
}
const timer = setTimeout(dispatch, VISIT_DISPATCH_THROTTLE_MS - elapsed);
return () => clearTimeout(timer);
}
markThreadVisited(
@@ -1940,6 +1970,7 @@ function ChatViewContent(props: ChatViewProps) {
serverThread?.environmentId,
serverThread?.id,
serverThread?.lastVisitedAt,
serverThread?.latestRun?.completedAt,
serverThread?.updatedAt,
visitThreadMutation,
]);
@@ -29,6 +29,7 @@ import {
shouldClearThreadSelectionOnMouseDown,
sortLogicalProjectsForSidebar,
sortSidebarV2ProjectGroups,
resolveThreadLastVisitedAt,
sortSettledThreadsForSidebarV2,
sortThreadsForSidebarV2,
sortProjectsForSidebar,
@@ -1613,3 +1614,27 @@ describe("sortSidebarV2ProjectGroups", () => {
).toEqual(["logical-newer", "logical-older"]);
});
});
describe("resolveThreadLastVisitedAt", () => {
it("uses the local watermark when the server does not track visits", () => {
expect(resolveThreadLastVisitedAt(undefined, "2026-07-30T10:00:00.000Z")).toBe(
"2026-07-30T10:00:00.000Z",
);
expect(resolveThreadLastVisitedAt(undefined, undefined)).toBeUndefined();
});
it("keeps the server watermark authoritative when visited tracking exists", () => {
// A rewound server value (mark-unread) must win even over a newer local
// watermark left behind by earlier viewing on this device.
expect(resolveThreadLastVisitedAt("2026-07-30T10:00:00.000Z", "2026-07-30T10:00:05.000Z")).toBe(
"2026-07-30T10:00:00.000Z",
);
expect(resolveThreadLastVisitedAt("2026-07-30T10:00:00.000Z", undefined)).toBe(
"2026-07-30T10:00:00.000Z",
);
});
it("treats an explicit server-side null as never visited", () => {
expect(resolveThreadLastVisitedAt(null, "2026-07-30T10:00:00.000Z")).toBeUndefined();
});
});
+3
View File
@@ -213,6 +213,9 @@ export function resolveThreadLastVisitedAt(
serverLastVisitedAt: string | null | undefined,
localLastVisitedAt: string | undefined,
): string | undefined {
// When the server tracks visits it is authoritative — including explicit
// rewinds from mark-unread, which a newer browser-local watermark must not
// mask. The local value only carries servers without visited tracking.
if (serverLastVisitedAt === undefined) return localLastVisitedAt;
return serverLastVisitedAt ?? undefined;
}