perf: fix sustained-CPU hot paths from the July 2026 web performance audit
Addresses the audit's findings with minimal, desktop-first changes (no payload deferral, no streaming-path work since streaming is off by default): - Sidebar: replace the 10-thread bulk detail prewarm with a single hover-based prewarm; at idle one shell stream + at most one detail stream - Server replay: thread catch-up reads only the thread's aggregate stream via the (aggregate_kind, stream_id, sequence) index instead of scanning the global log; shell catch-up is bounded (500 events) with a shell snapshot fallback for stale cursors - Shell summaries: thread.message-sent updates latestUserMessageAt incrementally; activity-appended triggers the history-wide summary rebuild only for approval/user-input activity kinds; streaming assistant chunks no longer fan out per-chunk shell upserts - Client runtime: O(1) activity appends when order is preserved; skip IndexedDB full-snapshot encodes while a turn is running (settle event and scope finalizer persist the final state) - Timeline derivation: share one ordered activities view across the four derivations (identity-cached, O(n) sorted check); k-way merge for the combined timeline instead of concat+sort - Composer drafts: debounce JSON serialization itself, and cache per-draft partialization by object identity so typing doesn't re-clone every retained draft - Shiki: negative-cache languages without grammars (sh, yaml) so those fences stop retrying and throwing on every render - Bootstrap polling: one shared change-detecting poller instead of one 2s interval per consumer; minimap only writes data-in-view on change Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
1 parent
3201e00ad4
commit
bc23ec5073
24 files changed
+963
-173
No files matched your search
@@ -102,6 +102,7 @@ describe("OrchestrationEngine", () => {
|
||||
return savedEvent;
|
||||
}),
|
||||
readFromSequence: () => Stream.empty,
|
||||
readAggregateFromSequence: () => Stream.empty,
|
||||
readAll: () =>
|
||||
Stream.fail(
|
||||
new PersistenceSqlError({
|
||||
@@ -772,6 +773,16 @@ describe("OrchestrationEngine", () => {
|
||||
readFromSequence(sequenceExclusive) {
|
||||
return Stream.fromIterable(events.filter((event) => event.sequence > sequenceExclusive));
|
||||
},
|
||||
readAggregateFromSequence(aggregateKind, aggregateId, sequenceExclusive) {
|
||||
return Stream.fromIterable(
|
||||
events.filter(
|
||||
(event) =>
|
||||
event.aggregateKind === aggregateKind &&
|
||||
event.aggregateId === aggregateId &&
|
||||
event.sequence > sequenceExclusive,
|
||||
),
|
||||
);
|
||||
},
|
||||
readAll() {
|
||||
return Stream.fromIterable(events);
|
||||
},
|
||||
@@ -1004,6 +1015,16 @@ describe("OrchestrationEngine", () => {
|
||||
readFromSequence(sequenceExclusive) {
|
||||
return Stream.fromIterable(events.filter((event) => event.sequence > sequenceExclusive));
|
||||
},
|
||||
readAggregateFromSequence(aggregateKind, aggregateId, sequenceExclusive) {
|
||||
return Stream.fromIterable(
|
||||
events.filter(
|
||||
(event) =>
|
||||
event.aggregateKind === aggregateKind &&
|
||||
event.aggregateId === aggregateId &&
|
||||
event.sequence > sequenceExclusive,
|
||||
),
|
||||
);
|
||||
},
|
||||
readAll() {
|
||||
return Stream.fromIterable(events);
|
||||
},
|
||||
|
||||
@@ -309,6 +309,14 @@ const makeOrchestrationEngine = Effect.gen(function* () {
|
||||
const readEvents: OrchestrationEngineShape["readEvents"] = (fromSequenceExclusive, limit) =>
|
||||
eventStore.readFromSequence(fromSequenceExclusive, limit);
|
||||
|
||||
const readAggregateEvents: OrchestrationEngineShape["readAggregateEvents"] = (
|
||||
aggregateKind,
|
||||
aggregateId,
|
||||
fromSequenceExclusive,
|
||||
limit,
|
||||
) =>
|
||||
eventStore.readAggregateFromSequence(aggregateKind, aggregateId, fromSequenceExclusive, limit);
|
||||
|
||||
const dispatch: OrchestrationEngineShape["dispatch"] = (command) =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* Deferred.make<{ sequence: number }, OrchestrationDispatchError>();
|
||||
@@ -322,6 +330,7 @@ const makeOrchestrationEngine = Effect.gen(function* () {
|
||||
|
||||
return {
|
||||
readEvents,
|
||||
readAggregateEvents,
|
||||
dispatch,
|
||||
// Each access creates a fresh PubSub subscription so that multiple
|
||||
// consumers (wsServer, ProviderRuntimeIngestion, CheckpointReactor, etc.)
|
||||
|
||||
@@ -2013,6 +2013,107 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("updates shell summary fields incrementally for message events", () =>
|
||||
Effect.gen(function* () {
|
||||
const projectionPipeline = yield* OrchestrationProjectionPipeline;
|
||||
const eventStore = yield* OrchestrationEventStore;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const appendAndProject = (event: Parameters<typeof eventStore.append>[0]) =>
|
||||
eventStore
|
||||
.append(event)
|
||||
.pipe(Effect.flatMap((savedEvent) => projectionPipeline.projectEvent(savedEvent)));
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "thread.created",
|
||||
eventId: EventId.make("evt-incremental-1"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.make("thread-incremental"),
|
||||
occurredAt: "2026-02-26T14:00:00.000Z",
|
||||
commandId: CommandId.make("cmd-incremental-1"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-incremental-1"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: ThreadId.make("thread-incremental"),
|
||||
projectId: ProjectId.make("project-incremental"),
|
||||
title: "Thread Incremental",
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: "2026-02-26T14:00:00.000Z",
|
||||
updatedAt: "2026-02-26T14:00:00.000Z",
|
||||
},
|
||||
});
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "thread.message-sent",
|
||||
eventId: EventId.make("evt-incremental-2"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.make("thread-incremental"),
|
||||
occurredAt: "2026-02-26T14:00:01.000Z",
|
||||
commandId: CommandId.make("cmd-incremental-2"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-incremental-2"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: ThreadId.make("thread-incremental"),
|
||||
messageId: MessageId.make("message-incremental-user"),
|
||||
role: "user",
|
||||
text: "Do the thing",
|
||||
turnId: null,
|
||||
streaming: false,
|
||||
createdAt: "2026-02-26T14:00:01.000Z",
|
||||
updatedAt: "2026-02-26T14:00:01.000Z",
|
||||
},
|
||||
});
|
||||
|
||||
// A streaming assistant chunk must not move updatedAt (no shell fan-out).
|
||||
yield* appendAndProject({
|
||||
type: "thread.message-sent",
|
||||
eventId: EventId.make("evt-incremental-3"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.make("thread-incremental"),
|
||||
occurredAt: "2026-02-26T14:00:02.000Z",
|
||||
commandId: CommandId.make("cmd-incremental-3"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-incremental-3"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: ThreadId.make("thread-incremental"),
|
||||
messageId: MessageId.make("message-incremental-assistant"),
|
||||
role: "assistant",
|
||||
text: "Work",
|
||||
turnId: null,
|
||||
streaming: true,
|
||||
createdAt: "2026-02-26T14:00:02.000Z",
|
||||
updatedAt: "2026-02-26T14:00:02.000Z",
|
||||
},
|
||||
});
|
||||
|
||||
const threadRows = yield* sql<{
|
||||
readonly latestUserMessageAt: string | null;
|
||||
readonly updatedAt: string;
|
||||
}>`
|
||||
SELECT
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
updated_at AS "updatedAt"
|
||||
FROM projection_threads
|
||||
WHERE thread_id = 'thread-incremental'
|
||||
`;
|
||||
assert.deepEqual(threadRows, [
|
||||
{
|
||||
latestUserMessageAt: "2026-02-26T14:00:01.000Z",
|
||||
updatedAt: "2026-02-26T14:00:01.000Z",
|
||||
},
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("ignores non-stale provider approval response failures", () =>
|
||||
Effect.gen(function* () {
|
||||
const projectionPipeline = yield* OrchestrationProjectionPipeline;
|
||||
|
||||
@@ -176,6 +176,19 @@ function derivePendingUserInputCountFromActivities(
|
||||
return openRequestIds.size;
|
||||
}
|
||||
|
||||
// Activity kinds that can change the shell summary's pending-approval or
|
||||
// pending-user-input counters. All other activity kinds (command output,
|
||||
// file edits, streaming progress, ...) leave the summary untouched, so they
|
||||
// must not trigger the history-wide summary rebuild.
|
||||
const SHELL_SUMMARY_ACTIVITY_KINDS: ReadonlySet<string> = new Set([
|
||||
"approval.requested",
|
||||
"approval.resolved",
|
||||
"provider.approval.respond.failed",
|
||||
"user-input.requested",
|
||||
"user-input.resolved",
|
||||
"provider.user-input.respond.failed",
|
||||
]);
|
||||
|
||||
function deriveHasActionableProposedPlan(input: {
|
||||
readonly latestTurnId: string | null;
|
||||
readonly proposedPlans: ReadonlyArray<ProjectionThreadProposedPlan>;
|
||||
@@ -713,9 +726,55 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
return;
|
||||
}
|
||||
|
||||
case "thread.message-sent":
|
||||
case "thread.message-sent": {
|
||||
const existingRow = yield* projectionThreadRepository.getById({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
if (Option.isNone(existingRow)) {
|
||||
return;
|
||||
}
|
||||
// A message can only move latestUserMessageAt forward; the other
|
||||
// summary fields depend on activities/plans/approvals, which this
|
||||
// event cannot touch. Update incrementally instead of re-reading the
|
||||
// whole message/plan/activity/approval history per (streamed) chunk.
|
||||
const latestUserMessageAt =
|
||||
event.payload.role === "user" &&
|
||||
(existingRow.value.latestUserMessageAt === null ||
|
||||
event.payload.createdAt > existingRow.value.latestUserMessageAt)
|
||||
? event.payload.createdAt
|
||||
: existingRow.value.latestUserMessageAt;
|
||||
yield* projectionThreadRepository.upsert({
|
||||
...existingRow.value,
|
||||
latestUserMessageAt,
|
||||
// Streaming assistant chunks arrive many times per second and
|
||||
// change no shell-visible field; leaving updatedAt untouched lets
|
||||
// the shell stream skip per-chunk upsert fan-out (toShellStreamEvent).
|
||||
updatedAt:
|
||||
event.payload.streaming && event.payload.role === "assistant"
|
||||
? existingRow.value.updatedAt
|
||||
: event.occurredAt,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
case "thread.activity-appended": {
|
||||
const existingRow = yield* projectionThreadRepository.getById({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
if (Option.isNone(existingRow)) {
|
||||
return;
|
||||
}
|
||||
yield* projectionThreadRepository.upsert({
|
||||
...existingRow.value,
|
||||
updatedAt: event.occurredAt,
|
||||
});
|
||||
if (SHELL_SUMMARY_ACTIVITY_KINDS.has(event.payload.activity.kind)) {
|
||||
yield* refreshThreadShellSummary(event.payload.threadId);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
case "thread.proposed-plan-upserted":
|
||||
case "thread.activity-appended":
|
||||
case "thread.approval-response-requested":
|
||||
case "thread.user-input-response-requested": {
|
||||
const existingRow = yield* projectionThreadRepository.getById({
|
||||
|
||||
@@ -37,6 +37,18 @@ export interface OrchestrationEngineShape {
|
||||
limit?: number,
|
||||
) => Stream.Stream<OrchestrationEvent, OrchestrationEventStoreError, never>;
|
||||
|
||||
/**
|
||||
* Replay a single aggregate's persisted events from an exclusive sequence
|
||||
* cursor. Reads via the aggregate stream index, so per-thread catch-up does
|
||||
* not scan the global event range after the cursor.
|
||||
*/
|
||||
readonly readAggregateEvents: (
|
||||
aggregateKind: OrchestrationEvent["aggregateKind"],
|
||||
aggregateId: string,
|
||||
fromSequenceExclusive: number,
|
||||
limit?: number,
|
||||
) => Stream.Stream<OrchestrationEvent, OrchestrationEventStoreError, never>;
|
||||
|
||||
/**
|
||||
* Dispatch a validated orchestration command.
|
||||
*
|
||||
|
||||
@@ -69,6 +69,51 @@ layer("OrchestrationEventStore", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("replays only the requested aggregate's events after the cursor", () =>
|
||||
Effect.gen(function* () {
|
||||
const eventStore = yield* OrchestrationEventStore;
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
|
||||
const appendProjectCreated = (suffix: string) =>
|
||||
eventStore.append({
|
||||
type: "project.created",
|
||||
eventId: EventId.make(`evt-aggregate-${suffix}`),
|
||||
aggregateKind: "project",
|
||||
aggregateId: ProjectId.make(`project-${suffix}`),
|
||||
occurredAt: now,
|
||||
commandId: CommandId.make(`cmd-aggregate-${suffix}`),
|
||||
causationEventId: null,
|
||||
correlationId: null,
|
||||
metadata: {},
|
||||
payload: {
|
||||
projectId: ProjectId.make(`project-${suffix}`),
|
||||
title: `Project ${suffix}`,
|
||||
workspaceRoot: `/tmp/project-${suffix}`,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
});
|
||||
|
||||
const first = yield* appendProjectCreated("a");
|
||||
yield* appendProjectCreated("b");
|
||||
|
||||
const replayed = yield* Stream.runCollect(
|
||||
eventStore.readAggregateFromSequence("project", first.aggregateId, 0),
|
||||
).pipe(Effect.map((chunk) => Array.from(chunk)));
|
||||
assert.deepStrictEqual(
|
||||
replayed.map((event) => event.aggregateId),
|
||||
[first.aggregateId],
|
||||
);
|
||||
|
||||
const afterCursor = yield* Stream.runCollect(
|
||||
eventStore.readAggregateFromSequence("project", first.aggregateId, first.sequence),
|
||||
).pipe(Effect.map((chunk) => Array.from(chunk)));
|
||||
assert.deepStrictEqual(afterCursor, []);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("fails with PersistenceDecodeError when stored json is invalid", () =>
|
||||
Effect.gen(function* () {
|
||||
const eventStore = yield* OrchestrationEventStore;
|
||||
|
||||
@@ -64,6 +64,12 @@ const ReadFromSequenceRequestSchema = Schema.Struct({
|
||||
sequenceExclusive: NonNegativeInt,
|
||||
limit: Schema.Number,
|
||||
});
|
||||
const ReadAggregateFromSequenceRequestSchema = Schema.Struct({
|
||||
aggregateKind: OrchestrationAggregateKind,
|
||||
aggregateId: Schema.String,
|
||||
sequenceExclusive: NonNegativeInt,
|
||||
limit: Schema.Number,
|
||||
});
|
||||
const DEFAULT_READ_FROM_SEQUENCE_LIMIT = 1_000;
|
||||
const READ_PAGE_SIZE = 500;
|
||||
|
||||
@@ -181,6 +187,32 @@ const makeEventStore = Effect.gen(function* () {
|
||||
`,
|
||||
});
|
||||
|
||||
const readAggregateEventRowsFromSequence = SqlSchema.findAll({
|
||||
Request: ReadAggregateFromSequenceRequestSchema,
|
||||
Result: OrchestrationEventPersistedRowSchema,
|
||||
execute: (request) =>
|
||||
sql`
|
||||
SELECT
|
||||
sequence,
|
||||
event_id AS "eventId",
|
||||
event_type AS "type",
|
||||
aggregate_kind AS "aggregateKind",
|
||||
stream_id AS "aggregateId",
|
||||
occurred_at AS "occurredAt",
|
||||
command_id AS "commandId",
|
||||
causation_event_id AS "causationEventId",
|
||||
correlation_id AS "correlationId",
|
||||
payload_json AS "payload",
|
||||
metadata_json AS "metadata"
|
||||
FROM orchestration_events
|
||||
WHERE aggregate_kind = ${request.aggregateKind}
|
||||
AND stream_id = ${request.aggregateId}
|
||||
AND sequence > ${request.sequenceExclusive}
|
||||
ORDER BY sequence ASC
|
||||
LIMIT ${request.limit}
|
||||
`,
|
||||
});
|
||||
|
||||
const append: OrchestrationEventStoreShape["append"] = (event) =>
|
||||
appendEventRow({
|
||||
eventId: event.eventId,
|
||||
@@ -208,10 +240,18 @@ const makeEventStore = Effect.gen(function* () {
|
||||
),
|
||||
);
|
||||
|
||||
const readFromSequence: OrchestrationEventStoreShape["readFromSequence"] = (
|
||||
sequenceExclusive,
|
||||
limit = DEFAULT_READ_FROM_SEQUENCE_LIMIT,
|
||||
) => {
|
||||
const readPagedEvents = <E>(
|
||||
operation: string,
|
||||
readRows: (
|
||||
cursor: number,
|
||||
pageLimit: number,
|
||||
) => Effect.Effect<
|
||||
ReadonlyArray<Schema.Schema.Type<typeof OrchestrationEventPersistedRowSchema>>,
|
||||
E
|
||||
>,
|
||||
sequenceExclusive: number,
|
||||
limit: number,
|
||||
): Stream.Stream<OrchestrationEvent, OrchestrationEventStoreError> => {
|
||||
const normalizedLimit = Math.max(0, Math.floor(limit));
|
||||
if (normalizedLimit === 0) {
|
||||
return Stream.empty;
|
||||
@@ -221,22 +261,14 @@ const makeEventStore = Effect.gen(function* () {
|
||||
remaining: number,
|
||||
): Stream.Stream<OrchestrationEvent, OrchestrationEventStoreError> =>
|
||||
Stream.fromEffect(
|
||||
readEventRowsFromSequence({
|
||||
sequenceExclusive: cursor,
|
||||
limit: Math.min(remaining, READ_PAGE_SIZE),
|
||||
}).pipe(
|
||||
readRows(cursor, Math.min(remaining, READ_PAGE_SIZE)).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"OrchestrationEventStore.readFromSequence:query",
|
||||
"OrchestrationEventStore.readFromSequence:decodeRows",
|
||||
),
|
||||
toPersistenceSqlOrDecodeError(`${operation}:query`, `${operation}:decodeRows`),
|
||||
),
|
||||
Effect.flatMap((rows) =>
|
||||
Effect.forEach(rows, (row) =>
|
||||
decodeEvent(row).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceDecodeError("OrchestrationEventStore.readFromSequence:rowToEvent"),
|
||||
),
|
||||
Effect.mapError(toPersistenceDecodeError(`${operation}:rowToEvent`)),
|
||||
),
|
||||
),
|
||||
),
|
||||
@@ -260,9 +292,41 @@ const makeEventStore = Effect.gen(function* () {
|
||||
return readPage(sequenceExclusive, normalizedLimit);
|
||||
};
|
||||
|
||||
const readFromSequence: OrchestrationEventStoreShape["readFromSequence"] = (
|
||||
sequenceExclusive,
|
||||
limit = DEFAULT_READ_FROM_SEQUENCE_LIMIT,
|
||||
) =>
|
||||
readPagedEvents(
|
||||
"OrchestrationEventStore.readFromSequence",
|
||||
(cursor, pageLimit) =>
|
||||
readEventRowsFromSequence({ sequenceExclusive: cursor, limit: pageLimit }),
|
||||
sequenceExclusive,
|
||||
limit,
|
||||
);
|
||||
|
||||
const readAggregateFromSequence: OrchestrationEventStoreShape["readAggregateFromSequence"] = (
|
||||
aggregateKind,
|
||||
aggregateId,
|
||||
sequenceExclusive,
|
||||
limit = Number.MAX_SAFE_INTEGER,
|
||||
) =>
|
||||
readPagedEvents(
|
||||
"OrchestrationEventStore.readAggregateFromSequence",
|
||||
(cursor, pageLimit) =>
|
||||
readAggregateEventRowsFromSequence({
|
||||
aggregateKind,
|
||||
aggregateId,
|
||||
sequenceExclusive: cursor,
|
||||
limit: pageLimit,
|
||||
}),
|
||||
sequenceExclusive,
|
||||
limit,
|
||||
);
|
||||
|
||||
return {
|
||||
append,
|
||||
readFromSequence,
|
||||
readAggregateFromSequence,
|
||||
readAll: () => readFromSequence(0, Number.MAX_SAFE_INTEGER),
|
||||
} satisfies OrchestrationEventStoreShape;
|
||||
});
|
||||
|
||||
@@ -46,6 +46,26 @@ export interface OrchestrationEventStoreShape {
|
||||
limit?: number,
|
||||
) => Stream.Stream<OrchestrationEvent, OrchestrationEventStoreError>;
|
||||
|
||||
/**
|
||||
* Replay a single aggregate's events after the provided sequence.
|
||||
*
|
||||
* @param aggregateKind - Aggregate kind of the stream.
|
||||
* @param aggregateId - Aggregate id of the stream.
|
||||
* @param sequenceExclusive - Sequence cursor (exclusive).
|
||||
* @param limit - Maximum number of events to emit.
|
||||
* @returns Stream containing ordered events for that aggregate only.
|
||||
*
|
||||
* The filter runs in SQL against the (aggregate_kind, stream_id, sequence)
|
||||
* index, so the cost scales with the aggregate's own events rather than the
|
||||
* global event range after the cursor.
|
||||
*/
|
||||
readonly readAggregateFromSequence: (
|
||||
aggregateKind: OrchestrationEvent["aggregateKind"],
|
||||
aggregateId: string,
|
||||
sequenceExclusive: number,
|
||||
limit?: number,
|
||||
) => Stream.Stream<OrchestrationEvent, OrchestrationEventStoreError>;
|
||||
|
||||
/**
|
||||
* Read all events from the beginning of the stream.
|
||||
*
|
||||
|
||||
@@ -459,6 +459,7 @@ describe.sequential("signRelayAgentActivityPublishProof", () => {
|
||||
|
||||
const orchestrationEngine = {
|
||||
readEvents: () => Stream.empty,
|
||||
readAggregateEvents: () => Stream.empty,
|
||||
dispatch: () => Effect.succeed({ sequence: 1 }),
|
||||
streamDomainEvents: Stream.fromQueue(events),
|
||||
} satisfies OrchestrationEngineShape;
|
||||
@@ -648,6 +649,7 @@ describe.sequential("signRelayAgentActivityPublishProof", () => {
|
||||
}),
|
||||
Layer.succeed(OrchestrationEngineService, {
|
||||
readEvents: () => Stream.empty,
|
||||
readAggregateEvents: () => Stream.empty,
|
||||
dispatch: () => Effect.succeed({ sequence: 1 }),
|
||||
streamDomainEvents: Stream.fromQueue(events),
|
||||
} satisfies OrchestrationEngineShape),
|
||||
|
||||
@@ -675,6 +675,7 @@ const buildAppUnderTest = (options?: {
|
||||
Layer.provide(
|
||||
Layer.mock(OrchestrationEngine.OrchestrationEngineService)({
|
||||
readEvents: () => Stream.empty,
|
||||
readAggregateEvents: () => Stream.empty,
|
||||
dispatch: () => Effect.succeed({ sequence: 0 }),
|
||||
streamDomainEvents: Stream.empty,
|
||||
...options?.layers?.orchestrationEngine,
|
||||
|
||||
@@ -163,6 +163,7 @@ it.effect("resolveAutoBootstrapWelcomeTargets returns existing project and threa
|
||||
}),
|
||||
Effect.provideService(OrchestrationEngine.OrchestrationEngineService, {
|
||||
readEvents: () => Stream.empty,
|
||||
readAggregateEvents: () => Stream.empty,
|
||||
dispatch: (command) =>
|
||||
Ref.update(dispatchCalls, (calls) => [...calls, command.type]).pipe(
|
||||
Effect.as({ sequence: 1 }),
|
||||
@@ -206,6 +207,7 @@ it.effect("resolveAutoBootstrapWelcomeTargets creates a project and thread when
|
||||
}),
|
||||
Effect.provideService(OrchestrationEngine.OrchestrationEngineService, {
|
||||
readEvents: () => Stream.empty,
|
||||
readAggregateEvents: () => Stream.empty,
|
||||
dispatch: (command) =>
|
||||
Ref.update(dispatchCalls, (calls) => [...calls, command.type]).pipe(
|
||||
Effect.as({ sequence: 1 }),
|
||||
@@ -255,6 +257,7 @@ it.effect("resolveAutoBootstrapWelcomeTargets preserves typed UUID generation fa
|
||||
}),
|
||||
Effect.provideService(OrchestrationEngine.OrchestrationEngineService, {
|
||||
readEvents: () => Stream.empty,
|
||||
readAggregateEvents: () => Stream.empty,
|
||||
dispatch: (command) =>
|
||||
Ref.update(dispatchCalls, (calls) => [...calls, command.type]).pipe(
|
||||
Effect.as({ sequence: 1 }),
|
||||
|
||||
+56
-18
@@ -276,6 +276,11 @@ function isThreadDetailEvent(event: OrchestrationEvent): event is Extract<
|
||||
|
||||
const PROVIDER_STATUS_DEBOUNCE_MS = 200;
|
||||
|
||||
// Shell catch-up replays the global event stream (shell relevance is only known
|
||||
// after reading), so a stale cursor must not scan an unbounded gap. Past this
|
||||
// many events it is cheaper to re-send the projection-backed shell snapshot.
|
||||
const MAX_SHELL_CATCH_UP_EVENTS = 500;
|
||||
|
||||
const RPC_REQUIRED_SCOPE = new Map<string, AuthEnvironmentScope>([
|
||||
[ORCHESTRATION_WS_METHODS.dispatchCommand, AuthOrchestrationOperateScope],
|
||||
[ORCHESTRATION_WS_METHODS.getTurnDiff, AuthOrchestrationReadScope],
|
||||
@@ -662,6 +667,16 @@ const makeWsRpcLayer = (
|
||||
if (event.aggregateKind !== "thread") {
|
||||
return Effect.succeed(Option.none());
|
||||
}
|
||||
// Streaming assistant chunks change no shell-visible field (the
|
||||
// projection leaves updatedAt untouched for them), so don't read
|
||||
// and re-broadcast the thread shell row once per token.
|
||||
if (
|
||||
event.type === "thread.message-sent" &&
|
||||
event.payload.streaming &&
|
||||
event.payload.role === "assistant"
|
||||
) {
|
||||
return Effect.succeed(Option.none());
|
||||
}
|
||||
return projectionSnapshotQuery
|
||||
.getThreadShellById(ThreadId.make(event.aggregateId))
|
||||
.pipe(
|
||||
@@ -1079,8 +1094,13 @@ const makeWsRpcLayer = (
|
||||
// live subscription is attached (into a scope-bound buffer) before
|
||||
// draining the catch-up replay so no event published during the
|
||||
// replay window is lost; overlapping events are deduped by sequence
|
||||
// on the client. The full range is read (not the store's default
|
||||
// page limit) since the shell filter runs after reading.
|
||||
// on the client.
|
||||
//
|
||||
// Shell events are filtered out of the global event stream after
|
||||
// reading, so a stale cursor would otherwise scan every event
|
||||
// appended since it. The catch-up read is therefore bounded: past
|
||||
// the bound it is cheaper to re-send the projection-backed shell
|
||||
// snapshot than to replay (and per-event enrich) the whole gap.
|
||||
if (input.afterSequence !== undefined) {
|
||||
const afterSequence = input.afterSequence;
|
||||
return Stream.unwrap(
|
||||
@@ -1089,22 +1109,41 @@ const makeWsRpcLayer = (
|
||||
yield* Effect.forkScoped(
|
||||
liveStream.pipe(Stream.runForEach((item) => Queue.offer(liveBuffer, item))),
|
||||
);
|
||||
const catchUpStream = orchestrationEngine
|
||||
.readEvents(afterSequence, Number.MAX_SAFE_INTEGER)
|
||||
.pipe(
|
||||
const catchUpEvents = yield* Stream.runCollect(
|
||||
orchestrationEngine.readEvents(afterSequence, MAX_SHELL_CATCH_UP_EVENTS + 1),
|
||||
).pipe(
|
||||
Effect.map((events) => Array.from(events)),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new OrchestrationGetSnapshotError({
|
||||
message: "Failed to replay orchestration shell events",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (catchUpEvents.length <= MAX_SHELL_CATCH_UP_EVENTS) {
|
||||
const catchUpStream = Stream.fromIterable(catchUpEvents).pipe(
|
||||
Stream.mapEffect(toShellStreamEvent),
|
||||
Stream.flatMap((event) =>
|
||||
Option.isSome(event) ? Stream.succeed(event.value) : Stream.empty,
|
||||
),
|
||||
Stream.mapError(
|
||||
(cause) =>
|
||||
new OrchestrationGetSnapshotError({
|
||||
message: "Failed to replay orchestration shell events",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return Stream.concat(catchUpStream, Stream.fromQueue(liveBuffer));
|
||||
return Stream.concat(catchUpStream, Stream.fromQueue(liveBuffer));
|
||||
}
|
||||
|
||||
const snapshot = yield* projectionSnapshotQuery.getShellSnapshot().pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new OrchestrationGetSnapshotError({
|
||||
message: "Failed to load orchestration shell snapshot",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return Stream.concat(
|
||||
Stream.make({ kind: "snapshot" as const, snapshot }),
|
||||
Stream.fromQueue(liveBuffer),
|
||||
);
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -1179,10 +1218,9 @@ const makeWsRpcLayer = (
|
||||
// catch-up followed by the buffered/ongoing live events. Overlapping
|
||||
// events are deduped by sequence on the client.
|
||||
//
|
||||
// Read the full range after the cursor (not the store's default
|
||||
// page-bounded limit): the range is normally tiny (a fresh HTTP
|
||||
// snapshot sequence) and the per-thread filter runs after reading,
|
||||
// so a global cap could otherwise omit this thread's events.
|
||||
// The catch-up read targets this thread's aggregate stream (via
|
||||
// the aggregate stream index), so a stale cursor replays only this
|
||||
// thread's events instead of scanning the global range after it.
|
||||
if (input.afterSequence !== undefined) {
|
||||
const afterSequence = input.afterSequence;
|
||||
return Stream.unwrap(
|
||||
@@ -1192,7 +1230,7 @@ const makeWsRpcLayer = (
|
||||
liveStream.pipe(Stream.runForEach((item) => Queue.offer(liveBuffer, item))),
|
||||
);
|
||||
const catchUpStream = orchestrationEngine
|
||||
.readEvents(afterSequence, Number.MAX_SAFE_INTEGER)
|
||||
.readAggregateEvents("thread", input.threadId, afterSequence)
|
||||
.pipe(
|
||||
Stream.filter(isThisThreadDetailEvent),
|
||||
Stream.map((event) => ({ kind: "event" as const, event })),
|
||||
|
||||
Reference in new issue
Block a user