Skip to content

Commit a21e53d

Browse files
Merge main into fix/issue-17418
2 parents 7bc11a5 + 22840ab commit a21e53d

21 files changed

Lines changed: 1296 additions & 49 deletions

‎apps/server/src/orchestration-v2/LiveStreamBudget.test.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,7 @@ describe("replayAndBufferLiveEvents", () => {
163163
const highWaterStarted = yield* Deferred.make<void>();
164164
const highWater = yield* Deferred.make<number>();
165165
const first = { sequence: 1, text: "first", threadId: "selected" };
166+
const unrelatedReplay = { sequence: 0, text: "unrelated replay", threadId: "other" };
166167
const overlap = { sequence: 2, text: "overlap", threadId: "selected" };
167168
const last = { sequence: 10, text: "last", threadId: "selected" };
168169
const reader = yield* replayAndBufferLiveEvents(
@@ -171,7 +172,7 @@ describe("replayAndBufferLiveEvents", () => {
171172
latestSequence: Deferred.succeed(highWaterStarted, undefined).pipe(
172173
Effect.andThen(Deferred.await(highWater)),
173174
),
174-
replay: () => Stream.make(first, overlap),
175+
replay: () => Stream.make(unrelatedReplay, first, overlap),
175176
filter: (event) => event.threadId === "selected",
176177
},
177178
{ maxItems: 4 },

‎apps/server/src/orchestration-v2/LiveStreamBudget.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -385,6 +385,7 @@ export const replayAndBufferProjectedLiveEvents = <
385385
// The finite database page is independent of the live tail.
386386
// Charge only the item being delivered so a fast reader can
387387
// consume a page larger than the budget without overflowing.
388+
Stream.filter((event) => input.filter?.(event) ?? true),
388389
Stream.rechunk(1),
389390
Stream.mapEffect((event) => budget.retain(input.project(event))),
390391
);

‎apps/server/src/orchestration-v2/ShellStream.test.ts‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { describe, expect, it } from "@effect/vitest";
22
import type {
3+
ApplicationStoredEvent,
34
OrchestrationV2ShellSnapshot,
45
OrchestrationV2ShellStreamItem,
56
OrchestrationV2ThreadShell,
@@ -21,6 +22,7 @@ import {
2122
dedupeShellEnrichment,
2223
shellStreamItemFromEnrichmentRefresh,
2324
shellStreamItemsFromInitialSnapshot,
25+
shouldPublishShellApplicationEvent,
2426
skipUnchangedThreadShells,
2527
} from "./ShellStream.ts";
2628

@@ -32,6 +34,49 @@ const emptyShellSnapshot = {
3234
archivedThreads: [],
3335
} as OrchestrationV2ShellSnapshot;
3436

37+
describe("subagent shell events", () => {
38+
const stored = (threadId: string, type: string) =>
39+
({ event: { threadId, type } }) as ApplicationStoredEvent;
40+
41+
it("keeps regular threads and subagent state changes while omitting subagent transcript updates", () => {
42+
const subagents = new Set(["child"]);
43+
expect(
44+
shouldPublishShellApplicationEvent(stored("parent", "turn-item.updated"), subagents),
45+
).toBe(true);
46+
expect(
47+
shouldPublishShellApplicationEvent(stored("child", "turn-item.updated"), subagents),
48+
).toBe(false);
49+
expect(shouldPublishShellApplicationEvent(stored("child", "node.updated"), subagents)).toBe(
50+
false,
51+
);
52+
expect(
53+
shouldPublishShellApplicationEvent(stored("child", "runtime-request.updated"), subagents),
54+
).toBe(true);
55+
expect(shouldPublishShellApplicationEvent(stored("child", "run.updated"), subagents)).toBe(
56+
true,
57+
);
58+
});
59+
60+
it("tracks subagents created after the subscription starts", () => {
61+
const subagents = new Set<string>();
62+
const created = {
63+
event: {
64+
threadId: "new-child",
65+
type: "thread.created",
66+
payload: { lineage: { relationshipToParent: "subagent" } },
67+
},
68+
} as ApplicationStoredEvent;
69+
expect(shouldPublishShellApplicationEvent(created, subagents)).toBe(true);
70+
expect(
71+
shouldPublishShellApplicationEvent(stored("new-child", "message.updated"), subagents),
72+
).toBe(false);
73+
expect(
74+
shouldPublishShellApplicationEvent(stored("new-child", "thread.deleted"), subagents),
75+
).toBe(true);
76+
expect(subagents.has("new-child")).toBe(true);
77+
});
78+
});
79+
3580
it.effect("coalesces a slow shell subscriber by identity and location in sequence order", () =>
3681
Effect.scoped(
3782
Effect.gen(function* () {

‎apps/server/src/orchestration-v2/ShellStream.ts‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,32 @@ export type ShellApplicationEvent =
106106
readonly event: Pick<OrchestrationV2StoredEvent["event"], "threadId">;
107107
};
108108

109+
/** Focused subagents receive these updates through their thread subscription. */
110+
export function shouldPublishShellApplicationEvent(
111+
stored: ApplicationStoredEvent,
112+
subagentThreadIds: Set<string>,
113+
): boolean {
114+
if ("aggregateKind" in stored) return true;
115+
const { event } = stored;
116+
if (event.type === "thread.created") {
117+
if (event.payload.lineage.relationshipToParent === "subagent") {
118+
subagentThreadIds.add(event.threadId);
119+
}
120+
return true;
121+
}
122+
if (event.type === "thread.deleted") {
123+
// Replay and the live tail overlap; keep known IDs so late events stay filtered.
124+
return true;
125+
}
126+
return !(
127+
subagentThreadIds.has(event.threadId) &&
128+
(event.type === "node.updated" ||
129+
event.type === "turn-item.updated" ||
130+
event.type === "provider-turn.updated" ||
131+
event.type === "message.updated")
132+
);
133+
}
134+
109135
/** Shell updates refetch an aggregate; drop transcript bodies before retaining an event. */
110136
export function toShellApplicationEvent(stored: ApplicationStoredEvent): ShellApplicationEvent {
111137
return "aggregateKind" in stored

‎apps/server/src/persistence/OrchestrationEventStore.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,7 @@ export class OrchestrationEventStore extends Context.Service<
118118
readonly streamProjectedApplicationEvents: <A extends { readonly sequence: number }>(input: {
119119
readonly afterSequence?: number;
120120
readonly project: (event: ApplicationStoredEvent) => A;
121+
readonly filter?: (event: ApplicationStoredEvent) => boolean;
121122
}) => Stream.Stream<A, OrchestrationEventStoreError>;
122123
}
123124
>()("t3/persistence/OrchestrationEventStore") {}
@@ -716,11 +717,17 @@ const makeEventStore = Effect.gen(function* () {
716717

717718
const streamProjectedApplicationEvents: OrchestrationEventStore["Service"]["streamProjectedApplicationEvents"] =
718719
(input) =>
719-
replayAndBufferProjectedLiveEvents({
720+
replayAndBufferProjectedLiveEvents<
721+
ApplicationStoredEvent,
722+
ReturnType<typeof input.project>,
723+
OrchestrationEventStoreError,
724+
never
725+
>({
720726
subscribe: PubSub.subscribe(committedEvents),
721727
latestSequence: latestApplicationSequence,
722728
afterSequence: input.afterSequence ?? 0,
723729
project: input.project,
730+
...(input.filter === undefined ? {} : { filter: input.filter }),
724731
replay: (throughSequence) =>
725732
catchUpApplicationEvents({
726733
afterSequence: input?.afterSequence ?? 0,

‎apps/server/src/ws.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -252,6 +252,7 @@ it.live.each(["thread", "shell"] as const)(
252252
const items = yield* subscription.pipe(
253253
Effect.provideService(ThreadManagement.ThreadManagementService, {
254254
ensureLegacyTranscript: () => Effect.void,
255+
getShellSnapshot: () => Effect.succeed({ threads: [] }),
255256
streamStoredEventsFrom: (
256257
input: Parameters<
257258
ThreadManagement.ThreadManagementService["Service"]["streamStoredEventsFrom"]

‎apps/server/src/ws.ts‎

Lines changed: 28 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@ import {
6262
OrchestrationV2ThreadLaunchError,
6363
type OrchestrationProjectShell,
6464
type OrchestrationV2ShellSnapshot,
65+
type ApplicationStoredEvent,
6566
type ProjectEntriesFailure,
6667
type ProjectFileFailure,
6768
type ProjectFileOperation,
@@ -131,6 +132,7 @@ import {
131132
shellStreamItemFromThreadShell,
132133
shellStreamItemsFromInitialSnapshot,
133134
shellStreamItemsFromResumeSnapshot,
135+
shouldPublishShellApplicationEvent,
134136
skipUnchangedThreadShells,
135137
toShellApplicationEvent,
136138
type ShellApplicationEvent,
@@ -965,6 +967,9 @@ export const subscribeOrchestrationV2Shell = Effect.fn("ws.orchestrationV2.subsc
965967
const projects = yield* ProjectStore.ProjectStoreV2;
966968
const projectService = yield* ProjectService.ProjectService;
967969
const projectEnrichment = yield* ProjectEnrichmentService.ProjectEnrichmentService;
970+
let subagentThreadIds = new Set<string>();
971+
const filterSubagentTranscript = (stored: ApplicationStoredEvent) =>
972+
shouldPublishShellApplicationEvent(stored, subagentThreadIds);
968973

969974
const enrichmentChanges = yield* projectEnrichment.subscribeChanges;
970975
const loadProjectMetadataSnapshot = Effect.fn("ws.orchestrationV2.loadProjectMetadataSnapshot")(
@@ -991,6 +996,11 @@ export const subscribeOrchestrationV2Shell = Effect.fn("ws.orchestrationV2.subsc
991996
latestSequence: applicationEvents.latestApplicationSequence,
992997
}),
993998
);
999+
subagentThreadIds = new Set(
1000+
base.threads
1001+
.filter((thread) => thread.lineage.relationshipToParent === "subagent")
1002+
.map((thread) => thread.id),
1003+
);
9941004
const enriched = yield* enrichProjectShells(base.projects);
9951005
return {
9961006
snapshot: { ...base, projects: enriched.projects } as OrchestrationV2ShellSnapshot,
@@ -1053,6 +1063,7 @@ export const subscribeOrchestrationV2Shell = Effect.fn("ws.orchestrationV2.subsc
10531063
applicationEvents.streamProjectedApplicationEvents({
10541064
afterSequence,
10551065
project: toShellApplicationEvent,
1066+
filter: filterSubagentTranscript,
10561067
}),
10571068
),
10581069
);
@@ -1143,16 +1154,25 @@ export const subscribeOrchestrationV2Shell = Effect.fn("ws.orchestrationV2.subsc
11431154
});
11441155
}
11451156

1157+
const currentShell = yield* threadManagement.getShellSnapshot({ location: "active" });
1158+
subagentThreadIds = new Set(
1159+
currentShell.threads
1160+
.filter((thread) => thread.lineage.relationshipToParent === "subagent")
1161+
.map((thread) => thread.id),
1162+
);
1163+
11461164
const loaded = yield* loadProjectMetadataSnapshot(highWater);
11471165
const replay = toShellStream(
1148-
applicationEvents.readApplicationEvents({
1149-
afterSequence: input.afterSequence,
1150-
throughSequence: highWater,
1151-
// A row a newer build wrote (e.g. after a downgrade) must not fail
1152-
// every shell resubscribe. The live tail below resumes from
1153-
// highWater, so a dropped row never hides later events.
1154-
skipUnknownEventTypes: true,
1155-
}),
1166+
applicationEvents
1167+
.readApplicationEvents({
1168+
afterSequence: input.afterSequence,
1169+
throughSequence: highWater,
1170+
// A row a newer build wrote (e.g. after a downgrade) must not fail
1171+
// every shell resubscribe. The live tail below resumes from
1172+
// highWater, so a dropped row never hides later events.
1173+
skipUnknownEventTypes: true,
1174+
})
1175+
.pipe(Stream.filter(filterSubagentTranscript)),
11561176
);
11571177
return composeShellStreamWithEnrichment({
11581178
initial: initialEnrichmentItems(loaded),

‎apps/web/src/components/AppSidebarLayout.tsx‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ import ThreadSidebar from "./Sidebar";
4343
import { SettingsSidebarNav } from "./settings/SettingsSidebarNav";
4444
import { SidebarBrandWidthProbe, SidebarChromeHeader } from "./sidebar/SidebarChrome";
4545
import { MainAppLocationTracker } from "./sidebar/mainAppLocation";
46+
import type { SidebarRouteReveal } from "./sidebar/routeReveal";
4647
import { useSidebarStageBackdropVariant } from "./SidebarStageBackdrop";
4748
import { useProjects } from "../state/entities";
4849
import {
@@ -330,6 +331,10 @@ function ProjectProjectionRetention() {
330331
export function AppSidebarLayout({ children }: { children: ReactNode }) {
331332
const navigate = useNavigate();
332333
const legacySidebarEnabled = useLegacySidebarEnabled();
334+
const [sidebarRouteReveal] = useState<SidebarRouteReveal>(() => ({
335+
observedKey: null,
336+
pendingKey: null,
337+
}));
333338
const { active: panelAnimationsActive, durationMs: panelAnimationDurationMs } =
334339
usePanelAnimationSettings();
335340
useThreadVisitedMigration();
@@ -422,9 +427,9 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {
422427
<SettingsSidebarNav pathname={pathname} />
423428
</>
424429
) : legacySidebarEnabled ? (
425-
<LegacyThreadSidebar />
430+
<LegacyThreadSidebar routeReveal={sidebarRouteReveal} />
426431
) : (
427-
<ThreadSidebar />
432+
<ThreadSidebar routeReveal={sidebarRouteReveal} />
428433
)}
429434
<SidebarRail onDoubleClick={resetSidebarWidth} />
430435
</Sidebar>

‎apps/web/src/components/LegacySidebar.tsx‎

Lines changed: 51 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -223,6 +223,11 @@ import {
223223
} from "../sidebarProjectGrouping";
224224
import { PullRequestGlyph } from "~/components/pullRequest/pullRequestIcons";
225225
import { useThreadRouteTarget } from "../hooks/useThreadRouteTarget";
226+
import {
227+
completeSidebarRouteReveal,
228+
pendingSidebarRouteReveal,
229+
type SidebarRouteReveal,
230+
} from "./sidebar/routeReveal";
226231
const SIDEBAR_SORT_LABELS: Record<SidebarProjectSortOrder, string> = {
227232
updated_at: "Last user message",
228233
created_at: "Created at",
@@ -1199,20 +1204,26 @@ function useProjectThreadPanel(input: {
11991204
(settings) => settings.sidebarThreadPreviewCount,
12001205
);
12011206
const activeThreadKey = activeRouteThreadKey ?? undefined;
1202-
const pinnedCollapsedThread =
1203-
!activeThreadKey || projectExpanded
1204-
? null
1205-
: (visibleProjectThreads.find(
1206-
(thread) =>
1207-
scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)) === activeThreadKey,
1208-
) ?? null);
1209-
const hasOverflowingThreads = visibleProjectThreads.length > sidebarThreadPreviewCount;
1207+
const activeThread = activeThreadKey
1208+
? (visibleProjectThreads.find(
1209+
(thread) =>
1210+
scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)) === activeThreadKey,
1211+
) ?? null)
1212+
: null;
1213+
const pinnedCollapsedThread = projectExpanded ? null : activeThread;
1214+
// The open thread stays listed past the preview cut, as it does in a
1215+
// collapsed project, so it alone does not overflow the preview.
1216+
const hasOverflowingThreads = visibleProjectThreads.some(
1217+
(thread, index) =>
1218+
index >= sidebarThreadPreviewCount &&
1219+
scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)) !== activeThreadKey,
1220+
);
12101221
const previewThreads =
12111222
isThreadListExpanded || !hasOverflowingThreads
12121223
? visibleProjectThreads
12131224
: visibleProjectThreads.slice(0, sidebarThreadPreviewCount);
12141225
const visibleThreadKeys = new Set(
1215-
[...previewThreads, ...(pinnedCollapsedThread ? [pinnedCollapsedThread] : [])].map((thread) =>
1226+
[...previewThreads, ...(activeThread ? [activeThread] : [])].map((thread) =>
12161227
scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
12171228
),
12181229
);
@@ -3202,10 +3213,17 @@ function useLegacySidebarThreads(input: {
32023213
isThreadListExpanded || !hasOverflowingThreads
32033214
? projectThreads
32043215
: projectThreads.slice(0, sidebarThreadPreviewCount);
3205-
const renderedThreads = pinnedCollapsedThread ? [pinnedCollapsedThread] : previewThreads;
3206-
return renderedThreads.map((thread) =>
3207-
scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
3208-
);
3216+
if (pinnedCollapsedThread) {
3217+
return [
3218+
scopedThreadKey(
3219+
scopeThreadRef(pinnedCollapsedThread.environmentId, pinnedCollapsedThread.id),
3220+
),
3221+
];
3222+
}
3223+
return projectThreads.flatMap((thread, index) => {
3224+
const threadKey = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id));
3225+
return index < previewThreads.length || threadKey === activeThreadKey ? [threadKey] : [];
3226+
});
32093227
});
32103228
const threadJumpCommandByKey = new Map<
32113229
string,
@@ -3234,7 +3252,7 @@ function useLegacySidebarThreads(input: {
32343252
};
32353253
}
32363254

3237-
export default function LegacySidebar() {
3255+
export default function LegacySidebar({ routeReveal }: { routeReveal: SidebarRouteReveal }) {
32383256
const reorderProjects = useUiStateStore((store) => store.reorderProjects);
32393257
const navigate = useNavigate();
32403258
const sidebarThreadSortOrder = useClientSettings((s) => s.sidebarThreadSortOrder);
@@ -3298,6 +3316,25 @@ export default function LegacySidebar() {
32983316
sidebarThreadPreviewCount,
32993317
expandedThreadListsByProject,
33003318
});
3319+
// History and the command palette can open a thread scrolled out of view,
3320+
// and a remount starts the list at the top, so each route change and each
3321+
// mount scroll to the open thread once. Its row can mount after the route
3322+
// does, once its environment's shells arrive, so the reveal waits for it.
3323+
const mountRevealOwed = useRef(true);
3324+
const routeRowRendered =
3325+
routeThreadKey !== null && visibleSidebarThreadKeys.includes(routeThreadKey);
3326+
const revealRouteRow = useStableCallback(() => {
3327+
const pendingKey = pendingSidebarRouteReveal(routeReveal, routeThreadKey);
3328+
if (pendingKey === null && (!mountRevealOwed.current || routeThreadKey === null)) return;
3329+
const activeRow = document.querySelector(
3330+
'[data-sidebar="content"] [data-thread-item] [data-active="true"]',
3331+
);
3332+
if (!activeRow) return;
3333+
completeSidebarRouteReveal(routeReveal);
3334+
mountRevealOwed.current = false;
3335+
activeRow.scrollIntoView({ block: "nearest" });
3336+
});
3337+
useEffect(revealRouteRow, [revealRouteRow, routeThreadKey, routeRowRendered]);
33013338
const newThreadShortcutLabelOptions = {
33023339
platform,
33033340
context: {

0 commit comments

Comments
 (0)