Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 22 additions & 6 deletions apps/server/src/orchestration/projector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,12 +117,26 @@ function settledTurnStateForSessionStatus(
}
}

// Runs for every thread event (including streaming deltas) against every
// thread the server has ever seen, so copy the array rather than map it.
function updateThread(
threads: ReadonlyArray<OrchestrationThread>,
threadId: ThreadId,
patch: ThreadPatch,
): OrchestrationThread[] {
return threads.map((thread) => (thread.id === threadId ? { ...thread, ...patch } : thread));
): ReadonlyArray<OrchestrationThread> {
const index = threads.findIndex((thread) => thread.id === threadId);
return index === -1 ? threads : patchThreadAt(threads, index, patch);
}

/** For callers that already located the thread and must not scan again. */
function patchThreadAt(
threads: ReadonlyArray<OrchestrationThread>,
index: number,
patch: ThreadPatch,
): ReadonlyArray<OrchestrationThread> {
const next = threads.slice();
next[index] = { ...threads[index]!, ...patch };
return next;
}

/** Patch that swaps a thread's links and re-derives the legacy single-PR field from them. */
Expand Down Expand Up @@ -767,7 +781,8 @@ export function projectEvent(
event.type,
"payload",
);
const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);
const threadIndex = nextBase.threads.findIndex((entry) => entry.id === payload.threadId);
const thread = nextBase.threads[threadIndex];
if (!thread) {
return nextBase;
}
Expand Down Expand Up @@ -815,7 +830,7 @@ export function projectEvent(

return {
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
threads: patchThreadAt(nextBase.threads, threadIndex, {
messages: cappedMessages,
updatedAt: event.occurredAt,
}),
Expand Down Expand Up @@ -1055,7 +1070,8 @@ export function projectEvent(
"payload",
).pipe(
Effect.map((payload) => {
const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);
const threadIndex = nextBase.threads.findIndex((entry) => entry.id === payload.threadId);
const thread = nextBase.threads[threadIndex];
if (!thread) {
return nextBase;
}
Expand All @@ -1069,7 +1085,7 @@ export function projectEvent(

return {
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
threads: patchThreadAt(nextBase.threads, threadIndex, {
activities,
updatedAt: event.occurredAt,
}),
Expand Down
Loading