Compare commits

...
Author SHA1 Message Date
Theo Browne 1c3bf90886 fix(server): stop large thread history from exhausting memory 2026-07-30 02:41:43 -07:00
18 changed files with 602 additions and 82 deletions

No files matched your search

@@ -49,6 +49,7 @@ export interface ThreadDetailScreenProps {
readonly connectionError: string | null;
readonly environmentLabel: string | null;
readonly selectedThreadFeed: ReadonlyArray<ThreadFeedEntry>;
readonly hasMoreActivities: boolean;
readonly activeWorkStartedAt: string | null;
readonly activePendingApproval: PendingApproval | null;
readonly respondingApprovalId: ApprovalRequestId | null;
@@ -356,6 +357,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
threadId={props.selectedThread.id}
workspaceRoot={props.threadCwd}
feed={props.selectedThreadFeed}
hasMoreActivities={props.hasMoreActivities}
contentPresentation={props.contentPresentation}
agentLabel={agentLabel}
latestTurn={props.selectedThread.latestTurn}
@@ -149,6 +149,7 @@ export interface ThreadFeedProps {
readonly threadId: ThreadId;
readonly workspaceRoot?: string | null;
readonly feed: ReadonlyArray<ThreadFeedEntry>;
readonly hasMoreActivities?: boolean;
readonly contentPresentation: ThreadContentPresentation;
readonly agentLabel: string;
readonly latestTurn: ThreadFeedLatestTurn | null;
@@ -1893,7 +1894,16 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
onScroll={handleScroll}
scrollEventThrottle={16}
ListHeaderComponent={
usesNativeAutomaticInsets ? null : <View style={{ height: topContentInset }} />
usesNativeAutomaticInsets && props.hasMoreActivities !== true ? null : (
<View>
{!usesNativeAutomaticInsets ? <View style={{ height: topContentInset }} /> : null}
{props.hasMoreActivities === true ? (
<Text className="pb-2 text-center text-xs text-foreground-secondary opacity-60">
Earlier work activity not shown
</Text>
) : null}
</View>
)
}
contentContainerStyle={{
paddingTop: 12,
@@ -1902,6 +1912,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
/>
</View>
{props.feed.length === 0 &&
props.hasMoreActivities !== true &&
props.activeWorkStartedAt === null &&
props.contentPresentation.kind === "ready" ? (
<View pointerEvents="none" style={StyleSheet.absoluteFill}>
@@ -755,6 +755,7 @@ function ThreadRouteContent(
connectionError={routeConnectionError}
environmentLabel={selectedEnvironmentConnection?.environmentLabel ?? null}
selectedThreadFeed={composer.selectedThreadFeed}
hasMoreActivities={selectedThreadDetail?.hasMoreActivities === true}
activeWorkStartedAt={composer.activeWorkStartedAt}
activePendingApproval={requests.activePendingApproval}
respondingApprovalId={requests.respondingApprovalId}
+1 -1
View File
@@ -337,7 +337,7 @@ const dispatchLiveOrchestrationCommand = (
const getOfflineSnapshot = Effect.fn("getOfflineSnapshot")(function* () {
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
return yield* projectionSnapshotQuery.getSnapshot();
return yield* projectionSnapshotQuery.getCommandReadModel();
});
const tryResolveLiveProjectExecutionMode = Effect.fn("tryResolveLiveProjectExecutionMode")(
@@ -1270,6 +1270,175 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
}),
);
it.effect("windows thread activity while preserving unresolved request payloads", () =>
Effect.gen(function* () {
const snapshotQuery = yield* ProjectionSnapshotQuery;
const sql = yield* SqlClient.SqlClient;
yield* sql`DELETE FROM projection_pending_approvals`;
yield* sql`DELETE FROM projection_thread_activities`;
yield* sql`DELETE FROM projection_threads`;
yield* sql`DELETE FROM projection_projects`;
yield* sql`
INSERT INTO projection_projects (
project_id, title, workspace_root, default_model_selection_json,
scripts_json, created_at, updated_at, deleted_at
)
VALUES (
'project-window', 'Window Project', '/tmp/window-project',
'{"provider":"codex","model":"gpt-5-codex"}', '[]',
'2026-04-10T00:00:00.000Z', '2026-04-10T00:00:01.000Z', NULL
)
`;
yield* sql`
INSERT INTO projection_threads (
thread_id, project_id, title, model_selection_json, runtime_mode,
interaction_mode, branch, worktree_path, latest_turn_id,
latest_user_message_at, pending_approval_count, pending_user_input_count,
has_actionable_proposed_plan, created_at, updated_at, archived_at, deleted_at
)
VALUES (
'thread-window', 'project-window', 'Window Thread',
'{"provider":"codex","model":"gpt-5-codex"}', 'full-access', 'default',
NULL, NULL, NULL, NULL, 1, 1, 0,
'2026-04-10T00:00:02.000Z', '2026-04-10T00:00:03.000Z', NULL, NULL
)
`;
yield* sql`
INSERT INTO projection_thread_activities (
activity_id, thread_id, turn_id, tone, kind, summary, payload_json,
sequence, created_at
)
VALUES
(
'approval-old', 'thread-window', NULL, 'approval', 'approval.requested',
'Approve old command', '{"requestId":"approval-1","requestKind":"command"}',
NULL, '2026-04-10T00:00:04.000Z'
),
(
'user-input-old', 'thread-window', NULL, 'approval', 'user-input.requested',
'Answer old question',
'{"requestId":"input-1","questions":[{"id":"q1","header":"Choice","question":"Continue?","options":[{"label":"Yes","description":"Continue"}]}]}',
NULL, '2026-04-10T00:00:05.000Z'
),
(
'user-input-closed', 'thread-window', NULL, 'approval', 'user-input.requested',
'Closed old question', '{"requestId":"input-closed"}',
NULL, '2026-04-10T00:00:06.000Z'
),
(
'user-input-closed-resolution', 'thread-window', NULL, 'info',
'user-input.resolved', 'Closed old question', '{"requestId":"input-closed"}',
NULL, '2026-04-10T00:00:07.000Z'
)
`;
yield* sql`
INSERT INTO projection_pending_approvals (
request_id, thread_id, turn_id, status, decision, created_at, resolved_at
)
VALUES (
'approval-1', 'thread-window', NULL, 'pending', NULL,
'2026-04-10T00:00:04.000Z', NULL
)
`;
yield* sql`
WITH RECURSIVE activity_sequence(value) AS (
SELECT 1
UNION ALL
SELECT value + 1 FROM activity_sequence WHERE value < 510
)
INSERT INTO projection_thread_activities (
activity_id, thread_id, turn_id, tone, kind, summary, payload_json,
sequence, created_at
)
SELECT
printf('recent-%04d', value),
'thread-window',
NULL,
'tool',
'command',
printf('Recent activity %d', value),
'{}',
value,
'2026-04-10T00:01:00.000Z'
FROM activity_sequence
`;
yield* sql`
INSERT INTO projection_thread_activities (
activity_id, thread_id, turn_id, tone, kind, summary, payload_json,
sequence, created_at
)
VALUES (
'opaque-newest', 'thread-window', NULL, 'tool', 'command',
'Newest sequenced activity', '{}', 511, '2026-04-10T00:01:00.000Z'
)
`;
const detail = yield* snapshotQuery.getThreadDetailById(ThreadId.make("thread-window"));
assert.equal(detail._tag, "Some");
if (detail._tag === "Some") {
assert.equal(detail.value.hasMoreActivities, true);
assert.equal(detail.value.activities.length, 502);
assert.equal(
detail.value.activities.some((row) => row.id === "approval-old"),
true,
);
assert.equal(
detail.value.activities.some((row) => row.id === "user-input-old"),
true,
);
assert.equal(
detail.value.activities.some((row) => row.id === "user-input-closed"),
false,
);
assert.equal(
detail.value.activities.some((row) => row.id === "recent-0010"),
false,
);
assert.equal(
detail.value.activities.some((row) => row.id === "recent-0011"),
false,
);
assert.equal(
detail.value.activities.some((row) => row.id === "recent-0012"),
true,
);
assert.equal(detail.value.activities.at(-1)?.id, "opaque-newest");
}
yield* sql`
DELETE FROM projection_thread_activities
WHERE activity_id IN (
'user-input-old',
'user-input-closed',
'user-input-closed-resolution'
)
OR activity_id BETWEEN 'recent-0001' AND 'recent-0011'
`;
yield* sql`
UPDATE projection_threads
SET pending_user_input_count = 0
WHERE thread_id = 'thread-window'
`;
const fullyHydratedDetail = yield* snapshotQuery.getThreadDetailById(
ThreadId.make("thread-window"),
);
assert.equal(fullyHydratedDetail._tag, "Some");
if (fullyHydratedDetail._tag === "Some") {
assert.equal(fullyHydratedDetail.value.activities.length, 501);
assert.equal(fullyHydratedDetail.value.hasMoreActivities, undefined);
assert.equal(fullyHydratedDetail.value.activities[0]?.id, "approval-old");
}
}),
);
it.effect("uses projection_threads.latest_turn_id for bulk command and shell snapshots", () =>
Effect.gen(function* () {
const snapshotQuery = yield* ProjectionSnapshotQuery;
@@ -108,6 +108,9 @@ const ProjectionCountsRowSchema = Schema.Struct({
projectCount: Schema.Number,
threadCount: Schema.Number,
});
const ProjectionThreadActivityCountRowSchema = Schema.Struct({
activityCount: Schema.Number,
});
const WorkspaceRootLookupInput = Schema.Struct({
workspaceRoot: Schema.String,
});
@@ -139,6 +142,7 @@ const ProjectionFullThreadDiffContextRowSchema = Schema.Struct({
latestCheckpointTurnCount: Schema.NullOr(NonNegativeInt),
toCheckpointRef: Schema.NullOr(CheckpointRef),
});
const THREAD_DETAIL_ACTIVITY_WINDOW = 500;
const REQUIRED_SNAPSHOT_PROJECTORS = [
ORCHESTRATION_PROJECTOR_NAMES.projects,
@@ -254,6 +258,21 @@ function mapProposedPlanRow(
};
}
function mapThreadActivityRow(
row: Schema.Schema.Type<typeof ProjectionThreadActivityDbRowSchema>,
): OrchestrationThreadActivity {
return {
id: row.activityId,
tone: row.tone,
kind: row.kind,
summary: row.summary,
payload: row.payload,
turnId: row.turnId,
...(row.sequence !== null ? { sequence: row.sequence } : {}),
createdAt: row.createdAt,
};
}
function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) {
return (cause: unknown): ProjectionRepositoryError =>
Schema.isSchemaError(cause)
@@ -839,12 +858,128 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
payload_json AS "payload",
sequence,
created_at AS "createdAt"
FROM (
SELECT *
FROM projection_thread_activities
WHERE thread_id = ${threadId}
ORDER BY sequence DESC, created_at DESC, activity_id DESC
-- The extra row tells the caller whether older work activity exists.
LIMIT ${THREAD_DETAIL_ACTIVITY_WINDOW + 1}
)
ORDER BY sequence ASC, created_at ASC, activity_id ASC
`,
});
const getThreadActivityCount = SqlSchema.findOne({
Request: ThreadIdLookupInput,
Result: ProjectionThreadActivityCountRowSchema,
execute: ({ threadId }) =>
sql`
SELECT COUNT(*) AS "activityCount"
FROM projection_thread_activities
WHERE thread_id = ${threadId}
ORDER BY
sequence ASC,
created_at ASC,
activity_id ASC
`,
});
// Blocking requests must remain actionable even when their request activity
// predates the normal detail window. Return only the latest unresolved
// request row for each request id; callers merge these rows with the window.
const listPinnedThreadActivityRowsByThread = SqlSchema.findAll({
Request: ThreadIdLookupInput,
Result: ProjectionThreadActivityDbRowSchema,
execute: ({ threadId }) =>
sql`
WITH pending_approval_activities AS (
SELECT
activity.activity_id AS "activityId",
activity.thread_id AS "threadId",
activity.turn_id AS "turnId",
activity.tone,
activity.kind,
activity.summary,
activity.payload_json AS "payload",
activity.sequence,
activity.created_at AS "createdAt",
ROW_NUMBER() OVER (
PARTITION BY pending.request_id
ORDER BY activity.created_at DESC, activity.activity_id DESC
) AS request_order
FROM projection_pending_approvals AS pending
INNER JOIN projection_thread_activities AS activity
ON activity.thread_id = pending.thread_id
AND activity.kind = 'approval.requested'
AND json_extract(activity.payload_json, '$.requestId') = pending.request_id
WHERE pending.thread_id = ${threadId}
AND pending.status = 'pending'
),
user_input_lifecycle AS (
SELECT
activity_id AS "activityId",
thread_id AS "threadId",
turn_id AS "turnId",
tone,
kind,
summary,
payload_json AS "payload",
sequence,
created_at AS "createdAt",
ROW_NUMBER() OVER (
PARTITION BY json_extract(payload_json, '$.requestId')
ORDER BY created_at DESC, activity_id DESC
) AS request_order
FROM projection_thread_activities
WHERE thread_id = ${threadId}
AND EXISTS (
SELECT 1
FROM projection_threads
WHERE projection_threads.thread_id = ${threadId}
AND projection_threads.pending_user_input_count > 0
)
AND json_extract(payload_json, '$.requestId') IS NOT NULL
AND (
kind IN ('user-input.requested', 'user-input.resolved')
OR (
kind = 'provider.user-input.respond.failed'
AND (
lower(COALESCE(json_extract(payload_json, '$.detail'), ''))
LIKE '%stale pending user-input request%'
OR lower(COALESCE(json_extract(payload_json, '$.detail'), ''))
LIKE '%unknown pending user-input request%'
OR lower(COALESCE(json_extract(payload_json, '$.detail'), ''))
LIKE '%unknown pending user input request%'
OR lower(COALESCE(json_extract(payload_json, '$.detail'), ''))
LIKE '%unknown pending codex user input request%'
)
)
)
)
SELECT
"activityId",
"threadId",
"turnId",
tone,
kind,
summary,
"payload",
sequence,
"createdAt"
FROM pending_approval_activities
WHERE request_order = 1
UNION ALL
SELECT
"activityId",
"threadId",
"turnId",
tone,
kind,
summary,
"payload",
sequence,
"createdAt"
FROM user_input_lifecycle
WHERE request_order = 1
AND kind = 'user-input.requested'
ORDER BY "createdAt" ASC, "activityId" ASC
`,
});
@@ -1938,6 +2073,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
messageRows,
proposedPlanRows,
activityRows,
pinnedActivityRows,
checkpointRows,
latestTurnRow,
sessionRow,
@@ -1974,6 +2110,14 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
),
),
),
listPinnedThreadActivityRowsByThread({ threadId }).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getThreadDetailById:listPinnedActivities:query",
"ProjectionSnapshotQuery.getThreadDetailById:listPinnedActivities:decodeRows",
),
),
),
listCheckpointRowsByThread({ threadId }).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
@@ -2004,6 +2148,33 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
return Option.none<OrchestrationThread>();
}
const activityWindowOverflowed = activityRows.length > THREAD_DETAIL_ACTIVITY_WINDOW;
const recentActivityRows = activityWindowOverflowed
? activityRows.slice(activityRows.length - THREAD_DETAIL_ACTIVITY_WINDOW)
: activityRows;
const selectedActivityRows = [
...new Map(
[...recentActivityRows, ...pinnedActivityRows].map(
(row) => [row.activityId, row] as const,
),
).values(),
].toSorted(
(left, right) =>
(left.sequence ?? -1) - (right.sequence ?? -1) ||
left.createdAt.localeCompare(right.createdAt) ||
left.activityId.localeCompare(right.activityId),
);
const hasMoreActivities = activityWindowOverflowed
? (yield* getThreadActivityCount({ threadId }).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getThreadDetailById:getActivityCount:query",
"ProjectionSnapshotQuery.getThreadDetailById:getActivityCount:decodeRow",
),
),
)).activityCount > selectedActivityRows.length
: false;
const thread = {
id: threadRow.value.threadId,
projectId: threadRow.value.projectId,
@@ -2038,21 +2209,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
return message;
}),
proposedPlans: proposedPlanRows.map(mapProposedPlanRow),
activities: activityRows.map((row) => {
const activity = {
id: row.activityId,
tone: row.tone,
kind: row.kind,
summary: row.summary,
payload: row.payload,
turnId: row.turnId,
createdAt: row.createdAt,
};
if (row.sequence !== null) {
return Object.assign(activity, { sequence: row.sequence });
}
return activity;
}),
activities: selectedActivityRows.map(mapThreadActivityRow),
...(hasMoreActivities ? { hasMoreActivities: true } : {}),
checkpoints: checkpointRows.map((row) => ({
turnId: row.turnId,
checkpointTurnCount: row.checkpointTurnCount,
@@ -27,9 +27,8 @@ export interface OrchestrationEngineShape {
*
* @param fromSequenceExclusive - Sequence cursor (exclusive).
* @param limit - Maximum number of events to read. Defaults to the event
* store's page-bounded default; pass a higher value when the caller must
* read every event after the cursor (e.g. per-thread catch-up that filters
* a small subset out of a potentially larger global range).
* store's page-bounded default. Callers must keep this bounded and replace
* stale cursors with a projection snapshot.
* @returns Stream containing ordered events.
*/
readonly readEvents: (
+3 -1
View File
@@ -32,8 +32,10 @@ export const orchestrationHttpApiLayer = HttpApiBuilder.group(
Effect.fn("environment.orchestration.snapshot")(function* (args) {
yield* annotateEnvironmentRequest(args.endpoint.name);
yield* requireEnvironmentScope(AuthOrchestrationReadScope);
// This compatibility endpoint is only used to resolve projects. Keep
// its read model lightweight instead of hydrating every thread body.
return yield* projectionSnapshotQuery
.getSnapshot()
.getCommandReadModel()
.pipe(
Effect.catch((cause) =>
failEnvironmentInternal("orchestration_snapshot_failed", cause),
+128
View File
@@ -5975,6 +5975,134 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
}).pipe(Effect.provide(NodeHttpServer.layerTest), TestClock.withLive),
);
it.effect("replaces stale thread cursors before buffered live events synchronize", () =>
Effect.gen(function* () {
const snapshotSequence = 5_000;
const thread = makeDefaultOrchestrationReadModel().threads[0]!;
const liveEvents = yield* PubSub.unbounded<OrchestrationEvent>();
let replayCalls = 0;
const messageEvent = {
sequence: snapshotSequence + 1,
eventId: EventId.make("event-stale-cursor-message"),
aggregateKind: "thread",
aggregateId: defaultThreadId,
occurredAt: "2026-01-01T00:00:01.000Z",
commandId: null,
causationEventId: null,
correlationId: null,
metadata: {},
type: "thread.message-sent",
payload: {
threadId: defaultThreadId,
messageId: MessageId.make("message-stale-cursor"),
role: "user",
text: "Published while loading the replacement snapshot",
turnId: null,
streaming: false,
createdAt: "2026-01-01T00:00:01.000Z",
updatedAt: "2026-01-01T00:00:01.000Z",
},
} satisfies Extract<OrchestrationEvent, { type: "thread.message-sent" }>;
yield* buildAppUnderTest({
layers: {
projectionSnapshotQuery: {
getSnapshotSequence: () => Effect.succeed({ snapshotSequence }),
getThreadDetailSnapshot: () =>
Effect.gen(function* () {
yield* Effect.sleep("25 millis");
yield* PubSub.publish(liveEvents, messageEvent);
return Option.some({ snapshotSequence, thread });
}),
},
orchestrationEngine: {
streamDomainEvents: Stream.fromPubSub(liveEvents),
readEvents: () => {
replayCalls += 1;
return Stream.empty;
},
},
},
});
const wsUrl = yield* getWsServerUrl("/ws");
const items = yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) =>
client[ORCHESTRATION_WS_METHODS.subscribeThread]({
threadId: defaultThreadId,
afterSequence: 1,
requestCompletionMarker: true,
}).pipe(Stream.take(3), Stream.runCollect),
),
).pipe(Effect.timeout("2 seconds"));
assert.equal(replayCalls, 0);
assert.equal(items[0]?.kind, "snapshot");
assert.equal(items[1]?.kind, "event");
if (items[1]?.kind === "event") {
assert.equal(items[1].event.sequence, snapshotSequence + 1);
}
assert.deepEqual(items[2], { kind: "synchronized" });
}).pipe(Effect.provide(NodeHttpServer.layerTest), TestClock.withLive),
);
it.effect("bounds recent thread cursor replay to the captured projection head", () =>
Effect.gen(function* () {
let replayLimit: number | undefined;
const replayedEvent = {
sequence: 10,
eventId: EventId.make("event-recent-cursor-message"),
aggregateKind: "thread",
aggregateId: defaultThreadId,
occurredAt: "2026-01-01T00:00:01.000Z",
commandId: null,
causationEventId: null,
correlationId: null,
metadata: {},
type: "thread.message-sent",
payload: {
threadId: defaultThreadId,
messageId: MessageId.make("message-recent-cursor"),
role: "user",
text: "Replayed from the bounded range",
turnId: null,
streaming: false,
createdAt: "2026-01-01T00:00:01.000Z",
updatedAt: "2026-01-01T00:00:01.000Z",
},
} satisfies Extract<OrchestrationEvent, { type: "thread.message-sent" }>;
yield* buildAppUnderTest({
layers: {
projectionSnapshotQuery: {
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 10 }),
},
orchestrationEngine: {
readEvents: (_afterSequence, limit) => {
replayLimit = limit;
return Stream.make(replayedEvent);
},
},
},
});
const wsUrl = yield* getWsServerUrl("/ws");
const items = yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) =>
client[ORCHESTRATION_WS_METHODS.subscribeThread]({
threadId: defaultThreadId,
afterSequence: 9,
requestCompletionMarker: true,
}).pipe(Stream.take(2), Stream.runCollect),
),
);
assert.equal(replayLimit, 1);
assert.equal(items[0]?.kind, "event");
assert.deepEqual(items[1], { kind: "synchronized" });
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("subscribeShell sends a fresh snapshot instead of replaying a large gap", () =>
Effect.gen(function* () {
let readEventsCalls = 0;
+69 -7
View File
@@ -292,7 +292,19 @@ const PROVIDER_STATUS_DEBOUNCE_MS = 200;
// snapshot instead. Replaying each intervening event costs a shell refetch;
// past this gap a single O(active-threads) snapshot is cheaper and bounded.
// Matches the event store's default page size (DEFAULT_READ_FROM_SEQUENCE_LIMIT).
const SHELL_RESUME_MAX_GAP = 1_000;
const ORCHESTRATION_RESUME_MAX_GAP = 1_000;
function subscriptionReplayLimit(afterSequence: number, snapshotSequence: number): number | null {
const eventCount = snapshotSequence - afterSequence;
if (
!Number.isSafeInteger(eventCount) ||
eventCount < 0 ||
eventCount > ORCHESTRATION_RESUME_MAX_GAP
) {
return null;
}
return eventCount;
}
function toAuthAccessStreamEvent(
change: PairingGrantStore.BootstrapCredentialChange | SessionStore.SessionCredentialChange,
@@ -1172,7 +1184,7 @@ const makeWsRpcLayer = (
// is also invalid, so reset it with a snapshot. Send the snapshot
// followed by the buffered live tail, exactly as the
// no-afterSequence path does.
if (replayGap < 0 || replayGap > SHELL_RESUME_MAX_GAP) {
if (replayGap < 0 || replayGap > ORCHESTRATION_RESUME_MAX_GAP) {
const snapshot = yield* loadSnapshot;
return Stream.concat(
Stream.make({ kind: "snapshot" as const, snapshot }),
@@ -1263,14 +1275,64 @@ 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.
// A recent cursor replays the exact global range through the
// per-thread filter. A stale cursor receives a current thread
// snapshot so catch-up never materializes an unbounded event log.
if (input.afterSequence !== undefined) {
const afterSequence = input.afterSequence;
const { snapshotSequence } = yield* projectionSnapshotQuery
.getSnapshotSequence()
.pipe(
Effect.mapError(
(cause) =>
new OrchestrationGetSnapshotError({
message: "Failed to load orchestration snapshot sequence",
cause,
}),
),
);
const replayLimit = subscriptionReplayLimit(afterSequence, snapshotSequence);
if (replayLimit === null) {
const snapshot = yield* projectionSnapshotQuery
.getThreadDetailSnapshot(input.threadId)
.pipe(
Effect.mapError(
(cause) =>
new OrchestrationGetSnapshotError({
message: `Failed to load thread ${input.threadId}`,
cause,
}),
),
);
if (Option.isNone(snapshot)) {
return yield* new OrchestrationGetSnapshotError({
message: `Thread ${input.threadId} was not found`,
cause: input.threadId,
});
}
const afterReplacementSnapshot =
input.requestCompletionMarker === true
? Stream.concat(
Stream.fromEffect(
Queue.offer(liveBuffer, { kind: "synchronized" as const }),
).pipe(Stream.drain),
bufferedLiveStream,
)
: bufferedLiveStream;
return Stream.concat(
Stream.make({
kind: "snapshot" as const,
snapshot: projectThreadDetailSnapshot(snapshot.value),
}),
afterReplacementSnapshot,
);
}
const catchUpStream = orchestrationEngine
.readEvents(afterSequence, Number.MAX_SAFE_INTEGER)
.readEvents(afterSequence, replayLimit)
.pipe(
Stream.filter(isThisThreadDetailEvent),
Stream.map((event) => ({
+1
View File
@@ -5731,6 +5731,7 @@ function ChatViewContent(props: ChatViewProps) {
activeTurnStartedAt={activeWorkStartedAt}
listRef={legendListRef}
timelineEntries={timelineEntries}
hasMoreActivities={activeThread.hasMoreActivities === true}
latestTurn={activeLatestTurn}
runningTurnId={
activeThread.session?.status === "running"
@@ -3,7 +3,6 @@ import {
archiveSelectedThreadEntries,
buildMultiSelectThreadContextMenuItems,
createThreadJumpHintVisibilityController,
getSidebarThreadIdsToPrewarm,
getVisibleSidebarThreadIds,
resolveAdjacentThreadId,
getFallbackThreadIdAfterDelete,
@@ -309,20 +308,6 @@ describe("createThreadJumpHintVisibilityController", () => {
});
});
describe("getSidebarThreadIdsToPrewarm", () => {
it("returns only the first visible thread ids up to the prewarm limit", () => {
expect(getSidebarThreadIdsToPrewarm(["t1", "t2", "t3"], 2)).toEqual(["t1", "t2"]);
});
it("returns all visible thread ids when they fit within the limit", () => {
expect(getSidebarThreadIdsToPrewarm(["t1", "t2"], 10)).toEqual(["t1", "t2"]);
});
it("returns no thread ids when the limit is zero", () => {
expect(getSidebarThreadIdsToPrewarm(["t1", "t2"], 0)).toEqual([]);
});
});
describe("shouldClearThreadSelectionOnMouseDown", () => {
it("preserves selection for thread items", () => {
const child = {
-10
View File
@@ -15,9 +15,6 @@ import { resolveServerBackedAppStageLabel } from "../branding.logic";
export const THREAD_SELECTION_SAFE_SELECTOR = "[data-thread-item], [data-thread-selection-safe]";
export const THREAD_JUMP_HINT_SHOW_DELAY_MS = 100;
// Visible sidebar rows are prewarmed into the thread-detail cache so opening a
// nearby thread usually reuses an already-hot subscription.
export const SIDEBAR_THREAD_PREWARM_LIMIT = 10;
type SidebarProject = {
id: string;
title: string;
@@ -295,13 +292,6 @@ export function getVisibleSidebarThreadIds<TThreadId>(
);
}
export function getSidebarThreadIdsToPrewarm<TThreadId>(
visibleThreadIds: readonly TThreadId[],
limit = SIDEBAR_THREAD_PREWARM_LIMIT,
): TThreadId[] {
return visibleThreadIds.slice(0, Math.max(0, limit));
}
export function resolveAdjacentThreadId<T>(input: {
threadIds: readonly T[];
currentThreadId: T | null;
+1 -23
View File
@@ -112,7 +112,7 @@ import { useDesktopUpdateState } from "../state/desktopUpdate";
import { useThreadActions } from "../hooks/useThreadActions";
import { projectEnvironment } from "../state/projects";
import { useEnvironmentQuery } from "../state/query";
import { threadEnvironment, useEnvironmentThread } from "../state/threads";
import { threadEnvironment } from "../state/threads";
import { vcsEnvironment } from "../state/vcs";
import { useEnvironment, useEnvironments, usePrimaryEnvironmentId } from "../state/environments";
import {
@@ -172,7 +172,6 @@ import { openCommandPalette } from "../commandPaletteBus";
import {
archiveSelectedThreadEntries,
buildMultiSelectThreadContextMenuItems,
getSidebarThreadIdsToPrewarm,
resolveAdjacentThreadId,
isContextMenuPointerDown,
isTrailingDoubleClick,
@@ -227,11 +226,6 @@ const PROJECT_GROUPING_MODE_LABELS: Record<SidebarProjectGroupingMode, string> =
const SIDEBAR_ICON_ACTION_BUTTON_CLASS =
"inline-flex h-6 min-w-6 cursor-pointer items-center justify-center rounded-md px-[calc(--spacing(1)-1px)] text-muted-foreground/60 hover:text-foreground focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-ring";
function SidebarThreadDetailPrewarmer({ threadRef }: { readonly threadRef: ScopedThreadRef }) {
useEnvironmentThread(threadRef.environmentId, threadRef.threadId);
return null;
}
function clampSidebarThreadPreviewCount(value: number): SidebarThreadPreviewCount {
return Math.min(
MAX_SIDEBAR_THREAD_PREVIEW_COUNT,
@@ -3385,19 +3379,6 @@ export default function Sidebar() {
? threadJumpLabelByKey
: EMPTY_THREAD_JUMP_LABELS;
const orderedSidebarThreadKeys = visibleSidebarThreadKeys;
const prewarmedSidebarThreadKeys = useMemo(
() => getSidebarThreadIdsToPrewarm(visibleSidebarThreadKeys),
[visibleSidebarThreadKeys],
);
const prewarmedSidebarThreadRefs = useMemo(
() =>
prewarmedSidebarThreadKeys.flatMap((threadKey) => {
const ref = parseScopedThreadKey(threadKey);
return ref ? [ref] : [];
}),
[prewarmedSidebarThreadKeys],
);
useEffect(() => {
updateThreadJumpHintsVisibility(shouldShowThreadJumpHintsNow);
}, [shouldShowThreadJumpHintsNow, updateThreadJumpHintsVisibility]);
@@ -3589,9 +3570,6 @@ export default function Sidebar() {
return (
<>
{prewarmedSidebarThreadRefs.map((threadRef) => (
<SidebarThreadDetailPrewarmer key={scopedThreadKey(threadRef)} threadRef={threadRef} />
))}
<SidebarChromeHeader isElectron={isElectron} />
{isOnSettings ? (
@@ -239,6 +239,18 @@ describe("MessagesTimeline", () => {
expect(fadedMarkup).toContain("chat-timeline-scroll-fade");
});
it("labels a bounded work-activity timeline", () => {
const markup = renderToStaticMarkup(
<MessagesTimeline
{...buildProps()}
timelineEntries={[buildUserTimelineEntry("Hello")]}
hasMoreActivities
/>,
);
expect(markup).toContain("Earlier work activity not shown");
});
it("keeps assistant changed-files headers sticky below the thread header", () => {
const assistantMessageId = MessageId.make("message-assistant-with-files");
const turnId = TurnId.make("turn-with-files");
@@ -161,6 +161,7 @@ interface MessagesTimelineProps {
activeTurnStartedAt: string | null;
listRef: React.RefObject<LegendListRef | null>;
timelineEntries: ReturnType<typeof deriveTimelineEntries>;
hasMoreActivities?: boolean;
latestTurn: TimelineLatestTurn | null;
runningTurnId: TurnId | null;
turnDiffSummaryByAssistantMessageId: Map<MessageId, TurnDiffSummary>;
@@ -196,6 +197,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
activeTurnStartedAt,
listRef,
timelineEntries,
hasMoreActivities = false,
latestTurn,
runningTurnId,
turnDiffSummaryByAssistantMessageId,
@@ -467,7 +469,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
[],
);
if (rows.length === 0 && !isWorking) {
if (rows.length === 0 && !isWorking && !hasMoreActivities) {
if (hideEmptyPlaceholder) {
return null;
}
@@ -480,6 +482,21 @@ export const MessagesTimeline = memo(function MessagesTimeline({
);
}
const listHeader = hasMoreActivities ? (
<div
className={cn(
"mx-auto w-full max-w-3xl pb-2 text-center text-xs text-muted-foreground/55",
topFadeEnabled ? "pt-10 sm:pt-12" : "pt-3 sm:pt-4",
)}
>
Earlier work activity not shown
</div>
) : topFadeEnabled ? (
TIMELINE_LIST_FADE_HEADER
) : (
TIMELINE_LIST_HEADER
);
return (
<TimelineRowCtx value={sharedState}>
<TimelineRowActivityCtx value={activityState}>
@@ -515,7 +532,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
"scrollbar-gutter-both h-full min-h-0 overflow-x-hidden overscroll-y-contain px-3 [overflow-anchor:none] sm:px-5",
topFadeEnabled && "chat-timeline-scroll-fade",
)}
ListHeaderComponent={topFadeEnabled ? TIMELINE_LIST_FADE_HEADER : TIMELINE_LIST_HEADER}
ListHeaderComponent={listHeader}
ListFooterComponent={TIMELINE_LIST_FOOTER}
/>
<TimelineMinimap
@@ -459,6 +459,8 @@ const EnvironmentOrchestrationThreadSnapshotParams = Schema.Struct({
export class EnvironmentOrchestrationHttpApi extends HttpApiGroup.make("orchestration")
.add(
// Lightweight compatibility snapshot used for project resolution. Thread
// bodies are intentionally empty; clients load shell and detail separately.
HttpApiEndpoint.get("snapshot", "/api/orchestration/snapshot", {
headers: OptionalBearerHeaders,
success: OrchestrationReadModel,
+3
View File
@@ -372,6 +372,9 @@ export const OrchestrationThread = Schema.Struct({
Schema.withDecodingDefault(Effect.succeed([])),
),
activities: Schema.Array(OrchestrationThreadActivity),
// Optional so clients remain compatible with servers that predate bounded
// thread-detail activity snapshots.
hasMoreActivities: Schema.optional(Schema.Boolean),
checkpoints: Schema.Array(OrchestrationCheckpointSummary),
session: Schema.NullOr(OrchestrationSession),
});