Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e5d5249680 | ||
|
|
6b2f3f8ae8 | ||
|
|
05e623fee9 | ||
|
|
bc23ec5073 |
No files matched your search
@@ -102,6 +102,7 @@ describe("OrchestrationEngine", () => {
|
|||||||
return savedEvent;
|
return savedEvent;
|
||||||
}),
|
}),
|
||||||
readFromSequence: () => Stream.empty,
|
readFromSequence: () => Stream.empty,
|
||||||
|
readAggregateFromSequence: () => Stream.empty,
|
||||||
readAll: () =>
|
readAll: () =>
|
||||||
Stream.fail(
|
Stream.fail(
|
||||||
new PersistenceSqlError({
|
new PersistenceSqlError({
|
||||||
@@ -772,6 +773,16 @@ describe("OrchestrationEngine", () => {
|
|||||||
readFromSequence(sequenceExclusive) {
|
readFromSequence(sequenceExclusive) {
|
||||||
return Stream.fromIterable(events.filter((event) => event.sequence > 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() {
|
readAll() {
|
||||||
return Stream.fromIterable(events);
|
return Stream.fromIterable(events);
|
||||||
},
|
},
|
||||||
@@ -1004,6 +1015,16 @@ describe("OrchestrationEngine", () => {
|
|||||||
readFromSequence(sequenceExclusive) {
|
readFromSequence(sequenceExclusive) {
|
||||||
return Stream.fromIterable(events.filter((event) => event.sequence > 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() {
|
readAll() {
|
||||||
return Stream.fromIterable(events);
|
return Stream.fromIterable(events);
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -309,6 +309,14 @@ const makeOrchestrationEngine = Effect.gen(function* () {
|
|||||||
const readEvents: OrchestrationEngineShape["readEvents"] = (fromSequenceExclusive, limit) =>
|
const readEvents: OrchestrationEngineShape["readEvents"] = (fromSequenceExclusive, limit) =>
|
||||||
eventStore.readFromSequence(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) =>
|
const dispatch: OrchestrationEngineShape["dispatch"] = (command) =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const result = yield* Deferred.make<{ sequence: number }, OrchestrationDispatchError>();
|
const result = yield* Deferred.make<{ sequence: number }, OrchestrationDispatchError>();
|
||||||
@@ -322,6 +330,7 @@ const makeOrchestrationEngine = Effect.gen(function* () {
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
readEvents,
|
readEvents,
|
||||||
|
readAggregateEvents,
|
||||||
dispatch,
|
dispatch,
|
||||||
// Each access creates a fresh PubSub subscription so that multiple
|
// Each access creates a fresh PubSub subscription so that multiple
|
||||||
// consumers (wsServer, ProviderRuntimeIngestion, CheckpointReactor, etc.)
|
// 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", () =>
|
it.effect("ignores non-stale provider approval response failures", () =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const projectionPipeline = yield* OrchestrationProjectionPipeline;
|
const projectionPipeline = yield* OrchestrationProjectionPipeline;
|
||||||
|
|||||||
@@ -176,6 +176,20 @@ function derivePendingUserInputCountFromActivities(
|
|||||||
return openRequestIds.size;
|
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 — and the shell stream
|
||||||
|
// (ws.ts toShellStreamEvent) skips re-broadcasting the thread row for them.
|
||||||
|
export 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: {
|
function deriveHasActionableProposedPlan(input: {
|
||||||
readonly latestTurnId: string | null;
|
readonly latestTurnId: string | null;
|
||||||
readonly proposedPlans: ReadonlyArray<ProjectionThreadProposedPlan>;
|
readonly proposedPlans: ReadonlyArray<ProjectionThreadProposedPlan>;
|
||||||
@@ -713,9 +727,61 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
|||||||
return;
|
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": {
|
||||||
|
// Non-summary activities (command output, file edits, progress, ...)
|
||||||
|
// change no shell-visible field: the sidebar timestamp prefers
|
||||||
|
// latestUserMessageAt and status pills derive from session/approval
|
||||||
|
// state. Skip the row churn entirely so high-volume activity streams
|
||||||
|
// don't bump updatedAt (and fan out shell upserts) per event.
|
||||||
|
if (!SHELL_SUMMARY_ACTIVITY_KINDS.has(event.payload.activity.kind)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const existingRow = yield* projectionThreadRepository.getById({
|
||||||
|
threadId: event.payload.threadId,
|
||||||
|
});
|
||||||
|
if (Option.isNone(existingRow)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
yield* projectionThreadRepository.upsert({
|
||||||
|
...existingRow.value,
|
||||||
|
updatedAt: event.occurredAt,
|
||||||
|
});
|
||||||
|
yield* refreshThreadShellSummary(event.payload.threadId);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
case "thread.proposed-plan-upserted":
|
case "thread.proposed-plan-upserted":
|
||||||
case "thread.activity-appended":
|
|
||||||
case "thread.approval-response-requested":
|
case "thread.approval-response-requested":
|
||||||
case "thread.user-input-response-requested": {
|
case "thread.user-input-response-requested": {
|
||||||
const existingRow = yield* projectionThreadRepository.getById({
|
const existingRow = yield* projectionThreadRepository.getById({
|
||||||
|
|||||||
@@ -37,6 +37,18 @@ export interface OrchestrationEngineShape {
|
|||||||
limit?: number,
|
limit?: number,
|
||||||
) => Stream.Stream<OrchestrationEvent, OrchestrationEventStoreError, never>;
|
) => 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.
|
* 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", () =>
|
it.effect("fails with PersistenceDecodeError when stored json is invalid", () =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const eventStore = yield* OrchestrationEventStore;
|
const eventStore = yield* OrchestrationEventStore;
|
||||||
|
|||||||
@@ -64,6 +64,12 @@ const ReadFromSequenceRequestSchema = Schema.Struct({
|
|||||||
sequenceExclusive: NonNegativeInt,
|
sequenceExclusive: NonNegativeInt,
|
||||||
limit: Schema.Number,
|
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 DEFAULT_READ_FROM_SEQUENCE_LIMIT = 1_000;
|
||||||
const READ_PAGE_SIZE = 500;
|
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) =>
|
const append: OrchestrationEventStoreShape["append"] = (event) =>
|
||||||
appendEventRow({
|
appendEventRow({
|
||||||
eventId: event.eventId,
|
eventId: event.eventId,
|
||||||
@@ -208,10 +240,18 @@ const makeEventStore = Effect.gen(function* () {
|
|||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
const readFromSequence: OrchestrationEventStoreShape["readFromSequence"] = (
|
const readPagedEvents = <E>(
|
||||||
sequenceExclusive,
|
operation: string,
|
||||||
limit = DEFAULT_READ_FROM_SEQUENCE_LIMIT,
|
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));
|
const normalizedLimit = Math.max(0, Math.floor(limit));
|
||||||
if (normalizedLimit === 0) {
|
if (normalizedLimit === 0) {
|
||||||
return Stream.empty;
|
return Stream.empty;
|
||||||
@@ -221,22 +261,14 @@ const makeEventStore = Effect.gen(function* () {
|
|||||||
remaining: number,
|
remaining: number,
|
||||||
): Stream.Stream<OrchestrationEvent, OrchestrationEventStoreError> =>
|
): Stream.Stream<OrchestrationEvent, OrchestrationEventStoreError> =>
|
||||||
Stream.fromEffect(
|
Stream.fromEffect(
|
||||||
readEventRowsFromSequence({
|
readRows(cursor, Math.min(remaining, READ_PAGE_SIZE)).pipe(
|
||||||
sequenceExclusive: cursor,
|
|
||||||
limit: Math.min(remaining, READ_PAGE_SIZE),
|
|
||||||
}).pipe(
|
|
||||||
Effect.mapError(
|
Effect.mapError(
|
||||||
toPersistenceSqlOrDecodeError(
|
toPersistenceSqlOrDecodeError(`${operation}:query`, `${operation}:decodeRows`),
|
||||||
"OrchestrationEventStore.readFromSequence:query",
|
|
||||||
"OrchestrationEventStore.readFromSequence:decodeRows",
|
|
||||||
),
|
|
||||||
),
|
),
|
||||||
Effect.flatMap((rows) =>
|
Effect.flatMap((rows) =>
|
||||||
Effect.forEach(rows, (row) =>
|
Effect.forEach(rows, (row) =>
|
||||||
decodeEvent(row).pipe(
|
decodeEvent(row).pipe(
|
||||||
Effect.mapError(
|
Effect.mapError(toPersistenceDecodeError(`${operation}:rowToEvent`)),
|
||||||
toPersistenceDecodeError("OrchestrationEventStore.readFromSequence:rowToEvent"),
|
|
||||||
),
|
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
@@ -260,9 +292,41 @@ const makeEventStore = Effect.gen(function* () {
|
|||||||
return readPage(sequenceExclusive, normalizedLimit);
|
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 {
|
return {
|
||||||
append,
|
append,
|
||||||
readFromSequence,
|
readFromSequence,
|
||||||
|
readAggregateFromSequence,
|
||||||
readAll: () => readFromSequence(0, Number.MAX_SAFE_INTEGER),
|
readAll: () => readFromSequence(0, Number.MAX_SAFE_INTEGER),
|
||||||
} satisfies OrchestrationEventStoreShape;
|
} satisfies OrchestrationEventStoreShape;
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -46,6 +46,26 @@ export interface OrchestrationEventStoreShape {
|
|||||||
limit?: number,
|
limit?: number,
|
||||||
) => Stream.Stream<OrchestrationEvent, OrchestrationEventStoreError>;
|
) => 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.
|
* Read all events from the beginning of the stream.
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -459,6 +459,7 @@ describe.sequential("signRelayAgentActivityPublishProof", () => {
|
|||||||
|
|
||||||
const orchestrationEngine = {
|
const orchestrationEngine = {
|
||||||
readEvents: () => Stream.empty,
|
readEvents: () => Stream.empty,
|
||||||
|
readAggregateEvents: () => Stream.empty,
|
||||||
dispatch: () => Effect.succeed({ sequence: 1 }),
|
dispatch: () => Effect.succeed({ sequence: 1 }),
|
||||||
streamDomainEvents: Stream.fromQueue(events),
|
streamDomainEvents: Stream.fromQueue(events),
|
||||||
} satisfies OrchestrationEngineShape;
|
} satisfies OrchestrationEngineShape;
|
||||||
@@ -648,6 +649,7 @@ describe.sequential("signRelayAgentActivityPublishProof", () => {
|
|||||||
}),
|
}),
|
||||||
Layer.succeed(OrchestrationEngineService, {
|
Layer.succeed(OrchestrationEngineService, {
|
||||||
readEvents: () => Stream.empty,
|
readEvents: () => Stream.empty,
|
||||||
|
readAggregateEvents: () => Stream.empty,
|
||||||
dispatch: () => Effect.succeed({ sequence: 1 }),
|
dispatch: () => Effect.succeed({ sequence: 1 }),
|
||||||
streamDomainEvents: Stream.fromQueue(events),
|
streamDomainEvents: Stream.fromQueue(events),
|
||||||
} satisfies OrchestrationEngineShape),
|
} satisfies OrchestrationEngineShape),
|
||||||
|
|||||||
@@ -675,6 +675,7 @@ const buildAppUnderTest = (options?: {
|
|||||||
Layer.provide(
|
Layer.provide(
|
||||||
Layer.mock(OrchestrationEngine.OrchestrationEngineService)({
|
Layer.mock(OrchestrationEngine.OrchestrationEngineService)({
|
||||||
readEvents: () => Stream.empty,
|
readEvents: () => Stream.empty,
|
||||||
|
readAggregateEvents: () => Stream.empty,
|
||||||
dispatch: () => Effect.succeed({ sequence: 0 }),
|
dispatch: () => Effect.succeed({ sequence: 0 }),
|
||||||
streamDomainEvents: Stream.empty,
|
streamDomainEvents: Stream.empty,
|
||||||
...options?.layers?.orchestrationEngine,
|
...options?.layers?.orchestrationEngine,
|
||||||
|
|||||||
@@ -163,6 +163,7 @@ it.effect("resolveAutoBootstrapWelcomeTargets returns existing project and threa
|
|||||||
}),
|
}),
|
||||||
Effect.provideService(OrchestrationEngine.OrchestrationEngineService, {
|
Effect.provideService(OrchestrationEngine.OrchestrationEngineService, {
|
||||||
readEvents: () => Stream.empty,
|
readEvents: () => Stream.empty,
|
||||||
|
readAggregateEvents: () => Stream.empty,
|
||||||
dispatch: (command) =>
|
dispatch: (command) =>
|
||||||
Ref.update(dispatchCalls, (calls) => [...calls, command.type]).pipe(
|
Ref.update(dispatchCalls, (calls) => [...calls, command.type]).pipe(
|
||||||
Effect.as({ sequence: 1 }),
|
Effect.as({ sequence: 1 }),
|
||||||
@@ -206,6 +207,7 @@ it.effect("resolveAutoBootstrapWelcomeTargets creates a project and thread when
|
|||||||
}),
|
}),
|
||||||
Effect.provideService(OrchestrationEngine.OrchestrationEngineService, {
|
Effect.provideService(OrchestrationEngine.OrchestrationEngineService, {
|
||||||
readEvents: () => Stream.empty,
|
readEvents: () => Stream.empty,
|
||||||
|
readAggregateEvents: () => Stream.empty,
|
||||||
dispatch: (command) =>
|
dispatch: (command) =>
|
||||||
Ref.update(dispatchCalls, (calls) => [...calls, command.type]).pipe(
|
Ref.update(dispatchCalls, (calls) => [...calls, command.type]).pipe(
|
||||||
Effect.as({ sequence: 1 }),
|
Effect.as({ sequence: 1 }),
|
||||||
@@ -255,6 +257,7 @@ it.effect("resolveAutoBootstrapWelcomeTargets preserves typed UUID generation fa
|
|||||||
}),
|
}),
|
||||||
Effect.provideService(OrchestrationEngine.OrchestrationEngineService, {
|
Effect.provideService(OrchestrationEngine.OrchestrationEngineService, {
|
||||||
readEvents: () => Stream.empty,
|
readEvents: () => Stream.empty,
|
||||||
|
readAggregateEvents: () => Stream.empty,
|
||||||
dispatch: (command) =>
|
dispatch: (command) =>
|
||||||
Ref.update(dispatchCalls, (calls) => [...calls, command.type]).pipe(
|
Ref.update(dispatchCalls, (calls) => [...calls, command.type]).pipe(
|
||||||
Effect.as({ sequence: 1 }),
|
Effect.as({ sequence: 1 }),
|
||||||
|
|||||||
+66
-18
@@ -68,6 +68,7 @@ import * as ServerConfig from "./config.ts";
|
|||||||
import * as Keybindings from "./keybindings.ts";
|
import * as Keybindings from "./keybindings.ts";
|
||||||
import * as ExternalLauncher from "./process/externalLauncher.ts";
|
import * as ExternalLauncher from "./process/externalLauncher.ts";
|
||||||
import { normalizeDispatchCommand } from "./orchestration/Normalizer.ts";
|
import { normalizeDispatchCommand } from "./orchestration/Normalizer.ts";
|
||||||
|
import { SHELL_SUMMARY_ACTIVITY_KINDS } from "./orchestration/Layers/ProjectionPipeline.ts";
|
||||||
import * as OrchestrationEngine from "./orchestration/Services/OrchestrationEngine.ts";
|
import * as OrchestrationEngine from "./orchestration/Services/OrchestrationEngine.ts";
|
||||||
import * as ProjectionSnapshotQuery from "./orchestration/Services/ProjectionSnapshotQuery.ts";
|
import * as ProjectionSnapshotQuery from "./orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||||
import {
|
import {
|
||||||
@@ -276,6 +277,11 @@ function isThreadDetailEvent(event: OrchestrationEvent): event is Extract<
|
|||||||
|
|
||||||
const PROVIDER_STATUS_DEBOUNCE_MS = 200;
|
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>([
|
const RPC_REQUIRED_SCOPE = new Map<string, AuthEnvironmentScope>([
|
||||||
[ORCHESTRATION_WS_METHODS.dispatchCommand, AuthOrchestrationOperateScope],
|
[ORCHESTRATION_WS_METHODS.dispatchCommand, AuthOrchestrationOperateScope],
|
||||||
[ORCHESTRATION_WS_METHODS.getTurnDiff, AuthOrchestrationReadScope],
|
[ORCHESTRATION_WS_METHODS.getTurnDiff, AuthOrchestrationReadScope],
|
||||||
@@ -662,6 +668,25 @@ const makeWsRpcLayer = (
|
|||||||
if (event.aggregateKind !== "thread") {
|
if (event.aggregateKind !== "thread") {
|
||||||
return Effect.succeed(Option.none());
|
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());
|
||||||
|
}
|
||||||
|
// Same for high-volume activity kinds (command output, file edits,
|
||||||
|
// progress): the projection skips the thread row for them, so a
|
||||||
|
// shell broadcast would be a no-op re-send of unchanged data.
|
||||||
|
if (
|
||||||
|
event.type === "thread.activity-appended" &&
|
||||||
|
!SHELL_SUMMARY_ACTIVITY_KINDS.has(event.payload.activity.kind)
|
||||||
|
) {
|
||||||
|
return Effect.succeed(Option.none());
|
||||||
|
}
|
||||||
return projectionSnapshotQuery
|
return projectionSnapshotQuery
|
||||||
.getThreadShellById(ThreadId.make(event.aggregateId))
|
.getThreadShellById(ThreadId.make(event.aggregateId))
|
||||||
.pipe(
|
.pipe(
|
||||||
@@ -1079,8 +1104,13 @@ const makeWsRpcLayer = (
|
|||||||
// live subscription is attached (into a scope-bound buffer) before
|
// live subscription is attached (into a scope-bound buffer) before
|
||||||
// draining the catch-up replay so no event published during the
|
// draining the catch-up replay so no event published during the
|
||||||
// replay window is lost; overlapping events are deduped by sequence
|
// replay window is lost; overlapping events are deduped by sequence
|
||||||
// on the client. The full range is read (not the store's default
|
// on the client.
|
||||||
// page limit) since the shell filter runs after reading.
|
//
|
||||||
|
// 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) {
|
if (input.afterSequence !== undefined) {
|
||||||
const afterSequence = input.afterSequence;
|
const afterSequence = input.afterSequence;
|
||||||
return Stream.unwrap(
|
return Stream.unwrap(
|
||||||
@@ -1089,22 +1119,41 @@ const makeWsRpcLayer = (
|
|||||||
yield* Effect.forkScoped(
|
yield* Effect.forkScoped(
|
||||||
liveStream.pipe(Stream.runForEach((item) => Queue.offer(liveBuffer, item))),
|
liveStream.pipe(Stream.runForEach((item) => Queue.offer(liveBuffer, item))),
|
||||||
);
|
);
|
||||||
const catchUpStream = orchestrationEngine
|
const catchUpEvents = yield* Stream.runCollect(
|
||||||
.readEvents(afterSequence, Number.MAX_SAFE_INTEGER)
|
orchestrationEngine.readEvents(afterSequence, MAX_SHELL_CATCH_UP_EVENTS + 1),
|
||||||
.pipe(
|
).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.mapEffect(toShellStreamEvent),
|
||||||
Stream.flatMap((event) =>
|
Stream.flatMap((event) =>
|
||||||
Option.isSome(event) ? Stream.succeed(event.value) : Stream.empty,
|
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 +1228,9 @@ const makeWsRpcLayer = (
|
|||||||
// catch-up followed by the buffered/ongoing live events. Overlapping
|
// catch-up followed by the buffered/ongoing live events. Overlapping
|
||||||
// events are deduped by sequence on the client.
|
// events are deduped by sequence on the client.
|
||||||
//
|
//
|
||||||
// Read the full range after the cursor (not the store's default
|
// The catch-up read targets this thread's aggregate stream (via
|
||||||
// page-bounded limit): the range is normally tiny (a fresh HTTP
|
// the aggregate stream index), so a stale cursor replays only this
|
||||||
// snapshot sequence) and the per-thread filter runs after reading,
|
// thread's events instead of scanning the global range after it.
|
||||||
// so a global cap could otherwise omit this thread's events.
|
|
||||||
if (input.afterSequence !== undefined) {
|
if (input.afterSequence !== undefined) {
|
||||||
const afterSequence = input.afterSequence;
|
const afterSequence = input.afterSequence;
|
||||||
return Stream.unwrap(
|
return Stream.unwrap(
|
||||||
@@ -1192,7 +1240,7 @@ const makeWsRpcLayer = (
|
|||||||
liveStream.pipe(Stream.runForEach((item) => Queue.offer(liveBuffer, item))),
|
liveStream.pipe(Stream.runForEach((item) => Queue.offer(liveBuffer, item))),
|
||||||
);
|
);
|
||||||
const catchUpStream = orchestrationEngine
|
const catchUpStream = orchestrationEngine
|
||||||
.readEvents(afterSequence, Number.MAX_SAFE_INTEGER)
|
.readAggregateEvents("thread", input.threadId, afterSequence)
|
||||||
.pipe(
|
.pipe(
|
||||||
Stream.filter(isThisThreadDetailEvent),
|
Stream.filter(isThisThreadDetailEvent),
|
||||||
Stream.map((event) => ({ kind: "event" as const, event })),
|
Stream.map((event) => ({ kind: "event" as const, event })),
|
||||||
|
|||||||
@@ -140,6 +140,12 @@ const highlightedCodeCache = new LRUCache<string>(
|
|||||||
MAX_HIGHLIGHT_CACHE_MEMORY_BYTES,
|
MAX_HIGHLIGHT_CACHE_MEMORY_BYTES,
|
||||||
);
|
);
|
||||||
const highlighterPromiseCache = new Map<string, Promise<DiffsHighlighter>>();
|
const highlighterPromiseCache = new Map<string, Promise<DiffsHighlighter>>();
|
||||||
|
// Languages Shiki has no grammar for (e.g. `sh` fences). Without this negative
|
||||||
|
// cache every render of such a block retries the grammar load and throws again.
|
||||||
|
// Fence labels are arbitrary text, so cap both caches: past the cap, unknown
|
||||||
|
// languages just retry (the pre-cache behavior) instead of growing memory.
|
||||||
|
const fallbackHighlightLanguages = new Set<string>();
|
||||||
|
const MAX_FALLBACK_HIGHLIGHT_LANGUAGES = 100;
|
||||||
|
|
||||||
function findTaskListMarkerOffset(markdown: string, listItemStart: number): number | null {
|
function findTaskListMarkerOffset(markdown: string, listItemStart: number): number | null {
|
||||||
const firstLineEnd = markdown.indexOf("\n", listItemStart);
|
const firstLineEnd = markdown.indexOf("\n", listItemStart);
|
||||||
@@ -273,6 +279,9 @@ function estimateHighlightedSize(html: string, code: string): number {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function getHighlighterPromise(language: string): Promise<DiffsHighlighter> {
|
function getHighlighterPromise(language: string): Promise<DiffsHighlighter> {
|
||||||
|
if (fallbackHighlightLanguages.has(language)) {
|
||||||
|
return getHighlighterPromise("text");
|
||||||
|
}
|
||||||
const cached = highlighterPromiseCache.get(language);
|
const cached = highlighterPromiseCache.get(language);
|
||||||
if (cached) return cached;
|
if (cached) return cached;
|
||||||
|
|
||||||
@@ -281,12 +290,19 @@ function getHighlighterPromise(language: string): Promise<DiffsHighlighter> {
|
|||||||
langs: [language as SupportedLanguages],
|
langs: [language as SupportedLanguages],
|
||||||
preferredHighlighter: "shiki-js",
|
preferredHighlighter: "shiki-js",
|
||||||
}).catch((err) => {
|
}).catch((err) => {
|
||||||
|
// Failed loads never stay in the promise cache: unsupported languages are
|
||||||
|
// remembered in the (bounded) negative cache instead, and transient
|
||||||
|
// failures for real languages stay retryable.
|
||||||
highlighterPromiseCache.delete(language);
|
highlighterPromiseCache.delete(language);
|
||||||
if (language === "text") {
|
if (language === "text") {
|
||||||
// "text" itself failed — Shiki cannot initialize at all, surface the error
|
// "text" itself failed — Shiki cannot initialize at all, surface the error
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
// Language not supported by Shiki — fall back to "text"
|
// Language not supported by Shiki — remember that and fall back to "text"
|
||||||
|
// so blocks with that language stop retrying the grammar load per render.
|
||||||
|
if (fallbackHighlightLanguages.size < MAX_FALLBACK_HIGHLIGHT_LANGUAGES) {
|
||||||
|
fallbackHighlightLanguages.add(language);
|
||||||
|
}
|
||||||
return getHighlighterPromise("text");
|
return getHighlighterPromise("text");
|
||||||
});
|
});
|
||||||
highlighterPromiseCache.set(language, promise);
|
highlighterPromiseCache.set(language, promise);
|
||||||
@@ -684,15 +700,18 @@ function UncachedShikiCodeBlock({
|
|||||||
}: UncachedShikiCodeBlockProps) {
|
}: UncachedShikiCodeBlockProps) {
|
||||||
const highlighter = use(getHighlighterPromise(language));
|
const highlighter = use(getHighlighterPromise(language));
|
||||||
const highlightedHtml = useMemo(() => {
|
const highlightedHtml = useMemo(() => {
|
||||||
|
const effectiveLanguage = fallbackHighlightLanguages.has(language) ? "text" : language;
|
||||||
try {
|
try {
|
||||||
return highlighter.codeToHtml(code, { lang: language, theme: themeName });
|
return highlighter.codeToHtml(code, { lang: effectiveLanguage, theme: themeName });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// Log highlighting failures for debugging while falling back to plain text
|
// Log highlighting failures for debugging while falling back to plain
|
||||||
|
// text. Render-time throws can be content-specific, so they don't join
|
||||||
|
// the negative cache — one pathological block must not disable
|
||||||
|
// highlighting for the whole language. Retries are bounded by the memo.
|
||||||
console.warn(
|
console.warn(
|
||||||
`Code highlighting failed for language "${language}", falling back to plain text.`,
|
`Code highlighting failed for language "${language}", falling back to plain text.`,
|
||||||
error instanceof Error ? error.message : error,
|
error instanceof Error ? error.message : error,
|
||||||
);
|
);
|
||||||
// If highlighting fails for this language, render as plain text
|
|
||||||
return highlighter.codeToHtml(code, { lang: "text", theme: themeName });
|
return highlighter.codeToHtml(code, { lang: "text", theme: themeName });
|
||||||
}
|
}
|
||||||
}, [code, highlighter, language, themeName]);
|
}, [code, highlighter, language, themeName]);
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
|
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
|
||||||
import {
|
import {
|
||||||
|
createSidebarHoverPrewarmController,
|
||||||
createThreadJumpHintVisibilityController,
|
createThreadJumpHintVisibilityController,
|
||||||
getSidebarThreadIdsToPrewarm,
|
|
||||||
getVisibleSidebarThreadIds,
|
getVisibleSidebarThreadIds,
|
||||||
resolveAdjacentThreadId,
|
resolveAdjacentThreadId,
|
||||||
getFallbackThreadIdAfterDelete,
|
getFallbackThreadIdAfterDelete,
|
||||||
@@ -19,6 +19,7 @@ import {
|
|||||||
resolveThreadStatusPill,
|
resolveThreadStatusPill,
|
||||||
shouldClearThreadSelectionOnMouseDown,
|
shouldClearThreadSelectionOnMouseDown,
|
||||||
sortProjectsForSidebar,
|
sortProjectsForSidebar,
|
||||||
|
SIDEBAR_THREAD_HOVER_PREWARM_DELAY_MS,
|
||||||
THREAD_JUMP_HINT_SHOW_DELAY_MS,
|
THREAD_JUMP_HINT_SHOW_DELAY_MS,
|
||||||
} from "./Sidebar.logic";
|
} from "./Sidebar.logic";
|
||||||
import {
|
import {
|
||||||
@@ -181,17 +182,80 @@ describe("createThreadJumpHintVisibilityController", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("getSidebarThreadIdsToPrewarm", () => {
|
describe("createSidebarHoverPrewarmController", () => {
|
||||||
it("returns only the first visible thread ids up to the prewarm limit", () => {
|
beforeEach(() => {
|
||||||
expect(getSidebarThreadIdsToPrewarm(["t1", "t2", "t3"], 2)).toEqual(["t1", "t2"]);
|
vi.useFakeTimers();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("returns all visible thread ids when they fit within the limit", () => {
|
afterEach(() => {
|
||||||
expect(getSidebarThreadIdsToPrewarm(["t1", "t2"], 10)).toEqual(["t1", "t2"]);
|
vi.useRealTimers();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("returns no thread ids when the limit is zero", () => {
|
const makeController = () => {
|
||||||
expect(getSidebarThreadIdsToPrewarm(["t1", "t2"], 0)).toEqual([]);
|
const targets: Array<string | null> = [];
|
||||||
|
const controller = createSidebarHoverPrewarmController({
|
||||||
|
delayMs: SIDEBAR_THREAD_HOVER_PREWARM_DELAY_MS,
|
||||||
|
onPrewarmTargetChange: (threadKey) => {
|
||||||
|
targets.push(threadKey);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return { controller, targets };
|
||||||
|
};
|
||||||
|
|
||||||
|
it("prewarms a row only after the pointer rests on it", () => {
|
||||||
|
const { controller, targets } = makeController();
|
||||||
|
|
||||||
|
controller.hover("t1");
|
||||||
|
vi.advanceTimersByTime(SIDEBAR_THREAD_HOVER_PREWARM_DELAY_MS - 1);
|
||||||
|
expect(targets).toEqual([]);
|
||||||
|
|
||||||
|
vi.advanceTimersByTime(1);
|
||||||
|
expect(targets).toEqual(["t1"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("prewarms at most one thread while sweeping across rows", () => {
|
||||||
|
const { controller, targets } = makeController();
|
||||||
|
|
||||||
|
controller.hover("t1");
|
||||||
|
vi.advanceTimersByTime(SIDEBAR_THREAD_HOVER_PREWARM_DELAY_MS / 2);
|
||||||
|
controller.hover("t2");
|
||||||
|
vi.advanceTimersByTime(SIDEBAR_THREAD_HOVER_PREWARM_DELAY_MS / 2);
|
||||||
|
controller.hover("t3");
|
||||||
|
vi.advanceTimersByTime(SIDEBAR_THREAD_HOVER_PREWARM_DELAY_MS);
|
||||||
|
|
||||||
|
expect(targets).toEqual(["t3"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps an established prewarm when re-entering the same row", () => {
|
||||||
|
const { controller, targets } = makeController();
|
||||||
|
|
||||||
|
controller.hover("t1");
|
||||||
|
vi.advanceTimersByTime(SIDEBAR_THREAD_HOVER_PREWARM_DELAY_MS);
|
||||||
|
controller.hover("t1");
|
||||||
|
vi.advanceTimersByTime(SIDEBAR_THREAD_HOVER_PREWARM_DELAY_MS);
|
||||||
|
|
||||||
|
expect(targets).toEqual(["t1"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("releases the prewarm target when the pointer leaves thread rows", () => {
|
||||||
|
const { controller, targets } = makeController();
|
||||||
|
|
||||||
|
controller.hover("t1");
|
||||||
|
vi.advanceTimersByTime(SIDEBAR_THREAD_HOVER_PREWARM_DELAY_MS);
|
||||||
|
controller.hover(null);
|
||||||
|
|
||||||
|
expect(targets).toEqual(["t1", null]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("cancels a pending prewarm when the pointer leaves early", () => {
|
||||||
|
const { controller, targets } = makeController();
|
||||||
|
|
||||||
|
controller.hover("t1");
|
||||||
|
vi.advanceTimersByTime(SIDEBAR_THREAD_HOVER_PREWARM_DELAY_MS / 2);
|
||||||
|
controller.hover(null);
|
||||||
|
vi.advanceTimersByTime(SIDEBAR_THREAD_HOVER_PREWARM_DELAY_MS);
|
||||||
|
|
||||||
|
expect(targets).toEqual([]);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -13,9 +13,9 @@ import { resolveServerBackedAppStageLabel } from "../branding.logic";
|
|||||||
|
|
||||||
export const THREAD_SELECTION_SAFE_SELECTOR = "[data-thread-item], [data-thread-selection-safe]";
|
export const THREAD_SELECTION_SAFE_SELECTOR = "[data-thread-item], [data-thread-selection-safe]";
|
||||||
export const THREAD_JUMP_HINT_SHOW_DELAY_MS = 100;
|
export const THREAD_JUMP_HINT_SHOW_DELAY_MS = 100;
|
||||||
// Visible sidebar rows are prewarmed into the thread-detail cache so opening a
|
// A pointer resting on a row signals intent to open it; sweeping past rows must
|
||||||
// nearby thread usually reuses an already-hot subscription.
|
// not open a detail subscription per row.
|
||||||
export const SIDEBAR_THREAD_PREWARM_LIMIT = 10;
|
export const SIDEBAR_THREAD_HOVER_PREWARM_DELAY_MS = 120;
|
||||||
export type SidebarNewThreadEnvMode = "local" | "worktree";
|
export type SidebarNewThreadEnvMode = "local" | "worktree";
|
||||||
type SidebarProject = {
|
type SidebarProject = {
|
||||||
id: string;
|
id: string;
|
||||||
@@ -283,11 +283,64 @@ export function getVisibleSidebarThreadIds<TThreadId>(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getSidebarThreadIdsToPrewarm<TThreadId>(
|
export interface SidebarHoverPrewarmController {
|
||||||
visibleThreadIds: readonly TThreadId[],
|
hover: (threadKey: string | null) => void;
|
||||||
limit = SIDEBAR_THREAD_PREWARM_LIMIT,
|
dispose: () => void;
|
||||||
): TThreadId[] {
|
}
|
||||||
return visibleThreadIds.slice(0, Math.max(0, limit));
|
|
||||||
|
// Prewarms at most one thread at a time: the row the pointer has rested on.
|
||||||
|
// The route mounts the active thread's detail subscription itself, so this is
|
||||||
|
// the only sidebar-driven detail stream.
|
||||||
|
export function createSidebarHoverPrewarmController(input: {
|
||||||
|
delayMs: number;
|
||||||
|
onPrewarmTargetChange: (threadKey: string | null) => void;
|
||||||
|
}): SidebarHoverPrewarmController {
|
||||||
|
let target: string | null = null;
|
||||||
|
let pendingKey: string | null = null;
|
||||||
|
let timeoutId: ReturnType<typeof setTimeout> | null = null;
|
||||||
|
|
||||||
|
const clearPending = () => {
|
||||||
|
if (timeoutId === null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
clearTimeout(timeoutId);
|
||||||
|
timeoutId = null;
|
||||||
|
pendingKey = null;
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
hover: (threadKey) => {
|
||||||
|
if (threadKey === null) {
|
||||||
|
clearPending();
|
||||||
|
if (target !== null) {
|
||||||
|
target = null;
|
||||||
|
input.onPrewarmTargetChange(null);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (threadKey === target) {
|
||||||
|
clearPending();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (threadKey === pendingKey) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
clearPending();
|
||||||
|
pendingKey = threadKey;
|
||||||
|
timeoutId = setTimeout(() => {
|
||||||
|
timeoutId = null;
|
||||||
|
pendingKey = null;
|
||||||
|
target = threadKey;
|
||||||
|
input.onPrewarmTargetChange(threadKey);
|
||||||
|
}, input.delayMs);
|
||||||
|
},
|
||||||
|
dispose: () => {
|
||||||
|
clearPending();
|
||||||
|
},
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export function resolveAdjacentThreadId<T>(input: {
|
export function resolveAdjacentThreadId<T>(input: {
|
||||||
|
|||||||
@@ -184,7 +184,8 @@ import {
|
|||||||
import { useThreadSelectionStore } from "../threadSelectionStore";
|
import { useThreadSelectionStore } from "../threadSelectionStore";
|
||||||
import { useOpenAddProjectCommandPalette } from "../commandPaletteContext";
|
import { useOpenAddProjectCommandPalette } from "../commandPaletteContext";
|
||||||
import {
|
import {
|
||||||
getSidebarThreadIdsToPrewarm,
|
createSidebarHoverPrewarmController,
|
||||||
|
SIDEBAR_THREAD_HOVER_PREWARM_DELAY_MS,
|
||||||
resolveAdjacentThreadId,
|
resolveAdjacentThreadId,
|
||||||
isContextMenuPointerDown,
|
isContextMenuPointerDown,
|
||||||
isTrailingDoubleClick,
|
isTrailingDoubleClick,
|
||||||
@@ -248,6 +249,40 @@ function SidebarThreadDetailPrewarmer({ threadRef }: { readonly threadRef: Scope
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Self-contained so hover changes re-render only this component, never the
|
||||||
|
// sidebar tree. Delegated `pointerover` avoids threading a hover callback
|
||||||
|
// through the memoized row tree.
|
||||||
|
function SidebarHoverThreadPrewarmer() {
|
||||||
|
const [prewarmThreadKey, setPrewarmThreadKey] = useState<string | null>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const controller = createSidebarHoverPrewarmController({
|
||||||
|
delayMs: SIDEBAR_THREAD_HOVER_PREWARM_DELAY_MS,
|
||||||
|
onPrewarmTargetChange: setPrewarmThreadKey,
|
||||||
|
});
|
||||||
|
const onPointerOver = (event: globalThis.PointerEvent) => {
|
||||||
|
// Element, not HTMLElement: row icons are SVG and must still resolve to
|
||||||
|
// their row's key instead of cancelling the hover.
|
||||||
|
const target = event.target instanceof Element ? event.target : null;
|
||||||
|
controller.hover(
|
||||||
|
target?.closest("[data-thread-prewarm-key]")?.getAttribute("data-thread-prewarm-key") ??
|
||||||
|
null,
|
||||||
|
);
|
||||||
|
};
|
||||||
|
window.addEventListener("pointerover", onPointerOver, { passive: true });
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener("pointerover", onPointerOver);
|
||||||
|
controller.dispose();
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const prewarmThreadRef = useMemo(
|
||||||
|
() => (prewarmThreadKey === null ? null : parseScopedThreadKey(prewarmThreadKey)),
|
||||||
|
[prewarmThreadKey],
|
||||||
|
);
|
||||||
|
return prewarmThreadRef ? <SidebarThreadDetailPrewarmer threadRef={prewarmThreadRef} /> : null;
|
||||||
|
}
|
||||||
|
|
||||||
function clampSidebarThreadPreviewCount(value: number): SidebarThreadPreviewCount {
|
function clampSidebarThreadPreviewCount(value: number): SidebarThreadPreviewCount {
|
||||||
return Math.min(
|
return Math.min(
|
||||||
MAX_SIDEBAR_THREAD_PREVIEW_COUNT,
|
MAX_SIDEBAR_THREAD_PREVIEW_COUNT,
|
||||||
@@ -673,6 +708,7 @@ export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThr
|
|||||||
<SidebarMenuSubItem
|
<SidebarMenuSubItem
|
||||||
className="w-full"
|
className="w-full"
|
||||||
data-thread-item
|
data-thread-item
|
||||||
|
data-thread-prewarm-key={threadKey}
|
||||||
onMouseLeave={handleMouseLeave}
|
onMouseLeave={handleMouseLeave}
|
||||||
onBlurCapture={handleBlurCapture}
|
onBlurCapture={handleBlurCapture}
|
||||||
>
|
>
|
||||||
@@ -3491,18 +3527,6 @@ export default function Sidebar() {
|
|||||||
? threadJumpLabelByKey
|
? threadJumpLabelByKey
|
||||||
: EMPTY_THREAD_JUMP_LABELS;
|
: EMPTY_THREAD_JUMP_LABELS;
|
||||||
const orderedSidebarThreadKeys = visibleSidebarThreadKeys;
|
const orderedSidebarThreadKeys = visibleSidebarThreadKeys;
|
||||||
const prewarmedSidebarThreadKeys = useMemo(
|
|
||||||
() => getSidebarThreadIdsToPrewarm(visibleSidebarThreadKeys),
|
|
||||||
[visibleSidebarThreadKeys],
|
|
||||||
);
|
|
||||||
const prewarmedSidebarThreadRefs = useMemo(
|
|
||||||
() =>
|
|
||||||
prewarmedSidebarThreadKeys.flatMap((threadKey) => {
|
|
||||||
const ref = parseScopedThreadKey(threadKey);
|
|
||||||
return ref ? [ref] : [];
|
|
||||||
}),
|
|
||||||
[prewarmedSidebarThreadKeys],
|
|
||||||
);
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
updateThreadJumpHintsVisibility(shouldShowThreadJumpHintsNow);
|
updateThreadJumpHintsVisibility(shouldShowThreadJumpHintsNow);
|
||||||
@@ -3695,9 +3719,7 @@ export default function Sidebar() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
{prewarmedSidebarThreadRefs.map((threadRef) => (
|
<SidebarHoverThreadPrewarmer />
|
||||||
<SidebarThreadDetailPrewarmer key={scopedThreadKey(threadRef)} threadRef={threadRef} />
|
|
||||||
))}
|
|
||||||
<SidebarChromeHeader isElectron={isElectron} />
|
<SidebarChromeHeader isElectron={isElectron} />
|
||||||
|
|
||||||
{isOnSettings ? (
|
{isOnSettings ? (
|
||||||
|
|||||||
@@ -373,7 +373,13 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
|||||||
rowTop < scrollBottom &&
|
rowTop < scrollBottom &&
|
||||||
rowTop + Math.max(1, rowHeight ?? 1) > scrollTop;
|
rowTop + Math.max(1, rowHeight ?? 1) > scrollTop;
|
||||||
|
|
||||||
strip.dataset.inView = inView ? "true" : "false";
|
// Scroll fires per frame; unconditional writes would dirty every strip's
|
||||||
|
// attributes each frame even though only rows crossing the viewport edge
|
||||||
|
// change.
|
||||||
|
const nextInView = inView ? "true" : "false";
|
||||||
|
if (strip.dataset.inView !== nextInView) {
|
||||||
|
strip.dataset.inView = nextInView;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}, [listRef, minimapItems, minimapStripMap, onIsAtEndChange]);
|
}, [listRef, minimapItems, minimapStripMap, onIsAtEndChange]);
|
||||||
|
|
||||||
|
|||||||
@@ -75,7 +75,7 @@ import {
|
|||||||
insertInlineTerminalContextPlaceholder,
|
insertInlineTerminalContextPlaceholder,
|
||||||
type TerminalContextDraft,
|
type TerminalContextDraft,
|
||||||
} from "./lib/terminalContext";
|
} from "./lib/terminalContext";
|
||||||
import { createDebouncedStorage } from "./lib/storage";
|
import { createDebouncedJsonStorage } from "./lib/storage";
|
||||||
|
|
||||||
function makeImage(input: {
|
function makeImage(input: {
|
||||||
id: string;
|
id: string;
|
||||||
@@ -1648,7 +1648,7 @@ describe("composerDraftStore runtime and interaction settings", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
// createDebouncedStorage
|
// createDebouncedJsonStorage
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
function createMockStorage() {
|
function createMockStorage() {
|
||||||
@@ -1664,7 +1664,11 @@ function createMockStorage() {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
describe("createDebouncedStorage", () => {
|
describe("createDebouncedJsonStorage", () => {
|
||||||
|
const v1 = { state: { value: "v1" }, version: 1 };
|
||||||
|
const v2 = { state: { value: "v2" }, version: 1 };
|
||||||
|
const v3 = { state: { value: "v3" }, version: 1 };
|
||||||
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
vi.useFakeTimers();
|
vi.useFakeTimers();
|
||||||
});
|
});
|
||||||
@@ -1673,47 +1677,54 @@ describe("createDebouncedStorage", () => {
|
|||||||
vi.useRealTimers();
|
vi.useRealTimers();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("delegates getItem immediately", () => {
|
it("parses getItem results immediately", () => {
|
||||||
const base = createMockStorage();
|
const base = createMockStorage();
|
||||||
base.getItem.mockReturnValueOnce("value");
|
base.getItem.mockReturnValueOnce(JSON.stringify(v1));
|
||||||
const storage = createDebouncedStorage(base);
|
const storage = createDebouncedJsonStorage(base);
|
||||||
|
|
||||||
expect(storage.getItem("key")).toBe("value");
|
expect(storage.getItem("key")).toEqual(v1);
|
||||||
expect(base.getItem).toHaveBeenCalledWith("key");
|
expect(base.getItem).toHaveBeenCalledWith("key");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("does not write to base storage until the debounce fires", () => {
|
it("returns null from getItem when nothing is stored", () => {
|
||||||
const base = createMockStorage();
|
const base = createMockStorage();
|
||||||
const storage = createDebouncedStorage(base);
|
const storage = createDebouncedJsonStorage(base);
|
||||||
|
|
||||||
storage.setItem("key", "v1");
|
expect(storage.getItem("key")).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not serialize or write until the debounce fires", () => {
|
||||||
|
const base = createMockStorage();
|
||||||
|
const storage = createDebouncedJsonStorage(base);
|
||||||
|
|
||||||
|
storage.setItem("key", v1);
|
||||||
expect(base.setItem).not.toHaveBeenCalled();
|
expect(base.setItem).not.toHaveBeenCalled();
|
||||||
|
|
||||||
vi.advanceTimersByTime(299);
|
vi.advanceTimersByTime(299);
|
||||||
expect(base.setItem).not.toHaveBeenCalled();
|
expect(base.setItem).not.toHaveBeenCalled();
|
||||||
|
|
||||||
vi.advanceTimersByTime(1);
|
vi.advanceTimersByTime(1);
|
||||||
expect(base.setItem).toHaveBeenCalledWith("key", "v1");
|
expect(base.setItem).toHaveBeenCalledWith("key", JSON.stringify(v1));
|
||||||
});
|
});
|
||||||
|
|
||||||
it("only writes the last value when setItem is called rapidly", () => {
|
it("only writes the last value when setItem is called rapidly", () => {
|
||||||
const base = createMockStorage();
|
const base = createMockStorage();
|
||||||
const storage = createDebouncedStorage(base);
|
const storage = createDebouncedJsonStorage(base);
|
||||||
|
|
||||||
storage.setItem("key", "v1");
|
storage.setItem("key", v1);
|
||||||
storage.setItem("key", "v2");
|
storage.setItem("key", v2);
|
||||||
storage.setItem("key", "v3");
|
storage.setItem("key", v3);
|
||||||
|
|
||||||
vi.advanceTimersByTime(300);
|
vi.advanceTimersByTime(300);
|
||||||
expect(base.setItem).toHaveBeenCalledTimes(1);
|
expect(base.setItem).toHaveBeenCalledTimes(1);
|
||||||
expect(base.setItem).toHaveBeenCalledWith("key", "v3");
|
expect(base.setItem).toHaveBeenCalledWith("key", JSON.stringify(v3));
|
||||||
});
|
});
|
||||||
|
|
||||||
it("removeItem cancels a pending setItem write", () => {
|
it("removeItem cancels a pending setItem write", () => {
|
||||||
const base = createMockStorage();
|
const base = createMockStorage();
|
||||||
const storage = createDebouncedStorage(base);
|
const storage = createDebouncedJsonStorage(base);
|
||||||
|
|
||||||
storage.setItem("key", "v1");
|
storage.setItem("key", v1);
|
||||||
storage.removeItem("key");
|
storage.removeItem("key");
|
||||||
|
|
||||||
vi.advanceTimersByTime(300);
|
vi.advanceTimersByTime(300);
|
||||||
@@ -1723,13 +1734,13 @@ describe("createDebouncedStorage", () => {
|
|||||||
|
|
||||||
it("flush writes the pending value immediately", () => {
|
it("flush writes the pending value immediately", () => {
|
||||||
const base = createMockStorage();
|
const base = createMockStorage();
|
||||||
const storage = createDebouncedStorage(base);
|
const storage = createDebouncedJsonStorage(base);
|
||||||
|
|
||||||
storage.setItem("key", "v1");
|
storage.setItem("key", v1);
|
||||||
expect(base.setItem).not.toHaveBeenCalled();
|
expect(base.setItem).not.toHaveBeenCalled();
|
||||||
|
|
||||||
storage.flush();
|
storage.flush();
|
||||||
expect(base.setItem).toHaveBeenCalledWith("key", "v1");
|
expect(base.setItem).toHaveBeenCalledWith("key", JSON.stringify(v1));
|
||||||
|
|
||||||
// Timer should be cancelled; no duplicate write.
|
// Timer should be cancelled; no duplicate write.
|
||||||
vi.advanceTimersByTime(300);
|
vi.advanceTimersByTime(300);
|
||||||
@@ -1738,7 +1749,7 @@ describe("createDebouncedStorage", () => {
|
|||||||
|
|
||||||
it("flush is a no-op when nothing is pending", () => {
|
it("flush is a no-op when nothing is pending", () => {
|
||||||
const base = createMockStorage();
|
const base = createMockStorage();
|
||||||
const storage = createDebouncedStorage(base);
|
const storage = createDebouncedJsonStorage(base);
|
||||||
|
|
||||||
storage.flush();
|
storage.flush();
|
||||||
expect(base.setItem).not.toHaveBeenCalled();
|
expect(base.setItem).not.toHaveBeenCalled();
|
||||||
@@ -1746,9 +1757,9 @@ describe("createDebouncedStorage", () => {
|
|||||||
|
|
||||||
it("flush after removeItem is a no-op", () => {
|
it("flush after removeItem is a no-op", () => {
|
||||||
const base = createMockStorage();
|
const base = createMockStorage();
|
||||||
const storage = createDebouncedStorage(base);
|
const storage = createDebouncedJsonStorage(base);
|
||||||
|
|
||||||
storage.setItem("key", "v1");
|
storage.setItem("key", v1);
|
||||||
storage.removeItem("key");
|
storage.removeItem("key");
|
||||||
storage.flush();
|
storage.flush();
|
||||||
|
|
||||||
@@ -1757,14 +1768,14 @@ describe("createDebouncedStorage", () => {
|
|||||||
|
|
||||||
it("setItem works normally after removeItem cancels a pending write", () => {
|
it("setItem works normally after removeItem cancels a pending write", () => {
|
||||||
const base = createMockStorage();
|
const base = createMockStorage();
|
||||||
const storage = createDebouncedStorage(base);
|
const storage = createDebouncedJsonStorage(base);
|
||||||
|
|
||||||
storage.setItem("key", "v1");
|
storage.setItem("key", v1);
|
||||||
storage.removeItem("key");
|
storage.removeItem("key");
|
||||||
storage.setItem("key", "v2");
|
storage.setItem("key", v2);
|
||||||
|
|
||||||
vi.advanceTimersByTime(300);
|
vi.advanceTimersByTime(300);
|
||||||
expect(base.setItem).toHaveBeenCalledTimes(1);
|
expect(base.setItem).toHaveBeenCalledTimes(1);
|
||||||
expect(base.setItem).toHaveBeenCalledWith("key", "v2");
|
expect(base.setItem).toHaveBeenCalledWith("key", JSON.stringify(v2));
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -46,9 +46,9 @@ import {
|
|||||||
newElementContextId,
|
newElementContextId,
|
||||||
} from "./lib/elementContext";
|
} from "./lib/elementContext";
|
||||||
import { create } from "zustand";
|
import { create } from "zustand";
|
||||||
import { createJSONStorage, persist } from "zustand/middleware";
|
import { persist } from "zustand/middleware";
|
||||||
import { useShallow } from "zustand/react/shallow";
|
import { useShallow } from "zustand/react/shallow";
|
||||||
import { createDebouncedStorage, createMemoryStorage } from "./lib/storage";
|
import { createDebouncedJsonStorage, createMemoryStorage } from "./lib/storage";
|
||||||
import { getDefaultServerModel } from "./providerModels";
|
import { getDefaultServerModel } from "./providerModels";
|
||||||
import { UnifiedSettings } from "@t3tools/contracts/settings";
|
import { UnifiedSettings } from "@t3tools/contracts/settings";
|
||||||
import { ReviewCommentContextSchema, type ReviewCommentContext } from "./reviewCommentContext";
|
import { ReviewCommentContextSchema, type ReviewCommentContext } from "./reviewCommentContext";
|
||||||
@@ -66,7 +66,7 @@ export type DraftId = typeof DraftId.Type;
|
|||||||
|
|
||||||
const COMPOSER_PERSIST_DEBOUNCE_MS = 300;
|
const COMPOSER_PERSIST_DEBOUNCE_MS = 300;
|
||||||
|
|
||||||
const composerDebouncedStorage = createDebouncedStorage(
|
const composerDebouncedStorage = createDebouncedJsonStorage<PersistedComposerDraftStoreState>(
|
||||||
typeof localStorage !== "undefined" ? localStorage : createMemoryStorage(),
|
typeof localStorage !== "undefined" ? localStorage : createMemoryStorage(),
|
||||||
COMPOSER_PERSIST_DEBOUNCE_MS,
|
COMPOSER_PERSIST_DEBOUNCE_MS,
|
||||||
);
|
);
|
||||||
@@ -1825,78 +1825,11 @@ function partializeComposerDraftStoreState(
|
|||||||
if (typeof threadKey !== "string" || threadKey.length === 0) {
|
if (typeof threadKey !== "string" || threadKey.length === 0) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
const hasModelData =
|
const persisted = partializeComposerThreadDraft(draft);
|
||||||
Object.keys(draft.modelSelectionByProvider).length > 0 || draft.activeProvider !== null;
|
if (persisted !== null) {
|
||||||
if (
|
persistedDraftsByThreadKey[threadKey] =
|
||||||
draft.prompt.length === 0 &&
|
persisted as DeepMutable<PersistedComposerThreadDraftState>;
|
||||||
draft.persistedAttachments.length === 0 &&
|
|
||||||
draft.terminalContexts.length === 0 &&
|
|
||||||
draft.elementContexts.length === 0 &&
|
|
||||||
draft.previewAnnotations.length === 0 &&
|
|
||||||
draft.reviewComments.length === 0 &&
|
|
||||||
!hasModelData &&
|
|
||||||
draft.runtimeMode === null &&
|
|
||||||
draft.interactionMode === null
|
|
||||||
) {
|
|
||||||
continue;
|
|
||||||
}
|
}
|
||||||
const persistedDraft: DeepMutable<PersistedComposerThreadDraftState> = {
|
|
||||||
prompt: draft.prompt,
|
|
||||||
attachments: draft.persistedAttachments,
|
|
||||||
...(draft.terminalContexts.length > 0
|
|
||||||
? {
|
|
||||||
terminalContexts: draft.terminalContexts.map((context) => ({
|
|
||||||
id: context.id,
|
|
||||||
threadId: context.threadId,
|
|
||||||
createdAt: context.createdAt,
|
|
||||||
terminalId: context.terminalId,
|
|
||||||
terminalLabel: context.terminalLabel,
|
|
||||||
lineStart: context.lineStart,
|
|
||||||
lineEnd: context.lineEnd,
|
|
||||||
})),
|
|
||||||
}
|
|
||||||
: {}),
|
|
||||||
...(draft.elementContexts.length > 0
|
|
||||||
? {
|
|
||||||
elementContexts: draft.elementContexts.map((context) => ({
|
|
||||||
id: context.id,
|
|
||||||
threadId: context.threadId,
|
|
||||||
pickedAt: context.pickedAt,
|
|
||||||
pageUrl: context.pageUrl,
|
|
||||||
pageTitle: context.pageTitle,
|
|
||||||
tagName: context.tagName,
|
|
||||||
selector: context.selector,
|
|
||||||
htmlPreview: context.htmlPreview,
|
|
||||||
componentName: context.componentName,
|
|
||||||
source: context.source,
|
|
||||||
styles: context.styles,
|
|
||||||
})),
|
|
||||||
}
|
|
||||||
: {}),
|
|
||||||
...(draft.previewAnnotations.length > 0
|
|
||||||
? {
|
|
||||||
previewAnnotations: draft.previewAnnotations.map(
|
|
||||||
(annotation) => ({ ...annotation }) as DeepMutable<PreviewAnnotationPayload>,
|
|
||||||
),
|
|
||||||
}
|
|
||||||
: {}),
|
|
||||||
...(draft.reviewComments.length > 0
|
|
||||||
? {
|
|
||||||
reviewComments: draft.reviewComments.map((comment) => ({ ...comment })),
|
|
||||||
}
|
|
||||||
: {}),
|
|
||||||
...(hasModelData
|
|
||||||
? {
|
|
||||||
modelSelectionByProvider: compactModelSelectionByProvider(
|
|
||||||
draft.modelSelectionByProvider,
|
|
||||||
),
|
|
||||||
activeProvider: draft.activeProvider,
|
|
||||||
}
|
|
||||||
: {}),
|
|
||||||
...(draft.runtimeMode ? { runtimeMode: draft.runtimeMode } : {}),
|
|
||||||
...(draft.interactionMode ? { interactionMode: draft.interactionMode } : {}),
|
|
||||||
};
|
|
||||||
persistedDraftsByThreadKey[threadKey] = persistedDraft;
|
|
||||||
}
|
}
|
||||||
return {
|
return {
|
||||||
draftsByThreadKey: persistedDraftsByThreadKey,
|
draftsByThreadKey: persistedDraftsByThreadKey,
|
||||||
@@ -1910,6 +1843,80 @@ function partializeComposerDraftStoreState(
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function partializeComposerThreadDraft(
|
||||||
|
draft: ComposerThreadDraftState,
|
||||||
|
): PersistedComposerThreadDraftState | null {
|
||||||
|
const hasModelData =
|
||||||
|
Object.keys(draft.modelSelectionByProvider).length > 0 || draft.activeProvider !== null;
|
||||||
|
if (
|
||||||
|
draft.prompt.length === 0 &&
|
||||||
|
draft.persistedAttachments.length === 0 &&
|
||||||
|
draft.terminalContexts.length === 0 &&
|
||||||
|
draft.elementContexts.length === 0 &&
|
||||||
|
draft.previewAnnotations.length === 0 &&
|
||||||
|
draft.reviewComments.length === 0 &&
|
||||||
|
!hasModelData &&
|
||||||
|
draft.runtimeMode === null &&
|
||||||
|
draft.interactionMode === null
|
||||||
|
) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
prompt: draft.prompt,
|
||||||
|
attachments: draft.persistedAttachments,
|
||||||
|
...(draft.terminalContexts.length > 0
|
||||||
|
? {
|
||||||
|
terminalContexts: draft.terminalContexts.map((context) => ({
|
||||||
|
id: context.id,
|
||||||
|
threadId: context.threadId,
|
||||||
|
createdAt: context.createdAt,
|
||||||
|
terminalId: context.terminalId,
|
||||||
|
terminalLabel: context.terminalLabel,
|
||||||
|
lineStart: context.lineStart,
|
||||||
|
lineEnd: context.lineEnd,
|
||||||
|
})),
|
||||||
|
}
|
||||||
|
: {}),
|
||||||
|
...(draft.elementContexts.length > 0
|
||||||
|
? {
|
||||||
|
elementContexts: draft.elementContexts.map((context) => ({
|
||||||
|
id: context.id,
|
||||||
|
threadId: context.threadId,
|
||||||
|
pickedAt: context.pickedAt,
|
||||||
|
pageUrl: context.pageUrl,
|
||||||
|
pageTitle: context.pageTitle,
|
||||||
|
tagName: context.tagName,
|
||||||
|
selector: context.selector,
|
||||||
|
htmlPreview: context.htmlPreview,
|
||||||
|
componentName: context.componentName,
|
||||||
|
source: context.source,
|
||||||
|
styles: context.styles,
|
||||||
|
})),
|
||||||
|
}
|
||||||
|
: {}),
|
||||||
|
...(draft.previewAnnotations.length > 0
|
||||||
|
? {
|
||||||
|
previewAnnotations: draft.previewAnnotations.map(
|
||||||
|
(annotation) => ({ ...annotation }) as DeepMutable<PreviewAnnotationPayload>,
|
||||||
|
),
|
||||||
|
}
|
||||||
|
: {}),
|
||||||
|
...(draft.reviewComments.length > 0
|
||||||
|
? {
|
||||||
|
reviewComments: draft.reviewComments.map((comment) => ({ ...comment })),
|
||||||
|
}
|
||||||
|
: {}),
|
||||||
|
...(hasModelData
|
||||||
|
? {
|
||||||
|
modelSelectionByProvider: compactModelSelectionByProvider(draft.modelSelectionByProvider),
|
||||||
|
activeProvider: draft.activeProvider,
|
||||||
|
}
|
||||||
|
: {}),
|
||||||
|
...(draft.runtimeMode ? { runtimeMode: draft.runtimeMode } : {}),
|
||||||
|
...(draft.interactionMode ? { interactionMode: draft.interactionMode } : {}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
function normalizeCurrentPersistedComposerDraftStoreState(
|
function normalizeCurrentPersistedComposerDraftStoreState(
|
||||||
persistedState: unknown,
|
persistedState: unknown,
|
||||||
): PersistedComposerDraftStoreState {
|
): PersistedComposerDraftStoreState {
|
||||||
@@ -3341,7 +3348,7 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
|
|||||||
{
|
{
|
||||||
name: COMPOSER_DRAFT_STORAGE_KEY,
|
name: COMPOSER_DRAFT_STORAGE_KEY,
|
||||||
version: COMPOSER_DRAFT_STORAGE_VERSION,
|
version: COMPOSER_DRAFT_STORAGE_VERSION,
|
||||||
storage: createJSONStorage(() => composerDebouncedStorage),
|
storage: composerDebouncedStorage,
|
||||||
migrate: migratePersistedComposerDraftStoreState,
|
migrate: migratePersistedComposerDraftStoreState,
|
||||||
partialize: partializeComposerDraftStoreState,
|
partialize: partializeComposerDraftStoreState,
|
||||||
merge: (persistedState, currentState) => {
|
merge: (persistedState, currentState) => {
|
||||||
|
|||||||
@@ -5,12 +5,33 @@ import { readDesktopSecondaryBootstraps } from "./desktopLocal";
|
|||||||
|
|
||||||
const DESKTOP_LOCAL_BOOTSTRAP_POLL_MS = 2_000;
|
const DESKTOP_LOCAL_BOOTSTRAP_POLL_MS = 2_000;
|
||||||
|
|
||||||
|
function bootstrapsEqual(
|
||||||
|
left: ReadonlyArray<DesktopEnvironmentBootstrap>,
|
||||||
|
right: ReadonlyArray<DesktopEnvironmentBootstrap>,
|
||||||
|
): boolean {
|
||||||
|
if (left.length !== right.length) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return left.every((entry, index) => {
|
||||||
|
const other = right[index];
|
||||||
|
return (
|
||||||
|
other !== undefined &&
|
||||||
|
entry.id === other.id &&
|
||||||
|
entry.label === other.label &&
|
||||||
|
entry.runningDistro === other.runningDistro &&
|
||||||
|
entry.httpBaseUrl === other.httpBaseUrl &&
|
||||||
|
entry.wsBaseUrl === other.wsBaseUrl &&
|
||||||
|
entry.bootstrapToken === other.bootstrapToken
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Reactively track the desktop's secondary local backends (e.g. a parallel WSL
|
* Reactively track the desktop's secondary local backends (e.g. a parallel WSL
|
||||||
* backend). The bridge exposes no change event, so we re-read on an interval;
|
* backend). The bridge exposes no change event, so each hook instance re-reads
|
||||||
* failed reads retain the latest successful snapshot, while a successful empty
|
* on its own interval; a poll returns a fresh array, so the previous reference
|
||||||
* read clears it. Use this instead of polling the bridge ad hoc so every
|
* is kept when the topology is unchanged to avoid re-rendering the consumer
|
||||||
* renderer consumer reads the same topology.
|
* every tick. Use this instead of polling the bridge ad hoc.
|
||||||
*/
|
*/
|
||||||
export function useDesktopLocalBootstraps(): ReadonlyArray<DesktopEnvironmentBootstrap> {
|
export function useDesktopLocalBootstraps(): ReadonlyArray<DesktopEnvironmentBootstrap> {
|
||||||
const [bootstraps, setBootstraps] = useState<ReadonlyArray<DesktopEnvironmentBootstrap>>(
|
const [bootstraps, setBootstraps] = useState<ReadonlyArray<DesktopEnvironmentBootstrap>>(
|
||||||
@@ -18,7 +39,10 @@ export function useDesktopLocalBootstraps(): ReadonlyArray<DesktopEnvironmentBoo
|
|||||||
);
|
);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const read = () => setBootstraps(readDesktopSecondaryBootstraps());
|
const read = () => {
|
||||||
|
const next = readDesktopSecondaryBootstraps();
|
||||||
|
setBootstraps((previous) => (bootstrapsEqual(previous, next) ? previous : next));
|
||||||
|
};
|
||||||
read();
|
read();
|
||||||
const interval = setInterval(read, DESKTOP_LOCAL_BOOTSTRAP_POLL_MS);
|
const interval = setInterval(read, DESKTOP_LOCAL_BOOTSTRAP_POLL_MS);
|
||||||
return () => clearInterval(interval);
|
return () => clearInterval(interval);
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { Debouncer } from "@tanstack/react-pacer";
|
import { Debouncer } from "@tanstack/react-pacer";
|
||||||
|
import type { PersistStorage, StorageValue } from "zustand/middleware";
|
||||||
|
|
||||||
export interface StateStorage<R = unknown> {
|
export interface StateStorage<R = unknown> {
|
||||||
getItem: (name: string) => string | null | Promise<string | null>;
|
getItem: (name: string) => string | null | Promise<string | null>;
|
||||||
@@ -6,10 +7,6 @@ export interface StateStorage<R = unknown> {
|
|||||||
removeItem: (name: string) => R;
|
removeItem: (name: string) => R;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface DebouncedStorage<R = unknown> extends StateStorage<R> {
|
|
||||||
flush: () => void;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function createMemoryStorage(): StateStorage {
|
export function createMemoryStorage(): StateStorage {
|
||||||
const store = new Map<string, string>();
|
const store = new Map<string, string>();
|
||||||
return {
|
return {
|
||||||
@@ -39,20 +36,35 @@ export function resolveStorage(storage: Partial<StateStorage> | null | undefined
|
|||||||
return isStateStorage(storage) ? storage : createMemoryStorage();
|
return isStateStorage(storage) ? storage : createMemoryStorage();
|
||||||
}
|
}
|
||||||
|
|
||||||
export function createDebouncedStorage(
|
export interface DebouncedPersistStorage<S> extends PersistStorage<S> {
|
||||||
|
flush: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A zustand `PersistStorage` that debounces the JSON serialization as well as
|
||||||
|
* the storage write. `createJSONStorage` + a debounced `StateStorage` only
|
||||||
|
* delays the write — the full state is still stringified on every store
|
||||||
|
* update; here it happens once per debounce window instead.
|
||||||
|
*/
|
||||||
|
export function createDebouncedJsonStorage<S>(
|
||||||
baseStorage: Partial<StateStorage> | null | undefined,
|
baseStorage: Partial<StateStorage> | null | undefined,
|
||||||
debounceMs: number = 300,
|
debounceMs: number = 300,
|
||||||
): DebouncedStorage {
|
): DebouncedPersistStorage<S> {
|
||||||
const resolvedStorage = resolveStorage(baseStorage);
|
const resolvedStorage = resolveStorage(baseStorage);
|
||||||
const debouncedSetItem = new Debouncer(
|
const debouncedSetItem = new Debouncer(
|
||||||
(name: string, value: string) => {
|
(name: string, value: StorageValue<S>) => {
|
||||||
resolvedStorage.setItem(name, value);
|
resolvedStorage.setItem(name, JSON.stringify(value));
|
||||||
},
|
},
|
||||||
{ wait: debounceMs },
|
{ wait: debounceMs },
|
||||||
);
|
);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
getItem: (name) => resolvedStorage.getItem(name),
|
getItem: (name) => {
|
||||||
|
const raw = resolvedStorage.getItem(name);
|
||||||
|
const parse = (value: string | null): StorageValue<S> | null =>
|
||||||
|
value === null ? null : (JSON.parse(value) as StorageValue<S>);
|
||||||
|
return raw instanceof Promise ? raw.then(parse) : parse(raw);
|
||||||
|
},
|
||||||
setItem: (name, value) => {
|
setItem: (name, value) => {
|
||||||
debouncedSetItem.maybeExecute(name, value);
|
debouncedSetItem.maybeExecute(name, value);
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -356,7 +356,7 @@ export function derivePendingApprovals(
|
|||||||
activities: ReadonlyArray<OrchestrationThreadActivity>,
|
activities: ReadonlyArray<OrchestrationThreadActivity>,
|
||||||
): PendingApproval[] {
|
): PendingApproval[] {
|
||||||
const openByRequestId = new Map<ApprovalRequestId, PendingApproval>();
|
const openByRequestId = new Map<ApprovalRequestId, PendingApproval>();
|
||||||
const ordered = [...activities].toSorted(compareActivitiesByOrder);
|
const ordered = orderActivities(activities);
|
||||||
|
|
||||||
for (const activity of ordered) {
|
for (const activity of ordered) {
|
||||||
const payload =
|
const payload =
|
||||||
@@ -462,7 +462,7 @@ export function derivePendingUserInputs(
|
|||||||
activities: ReadonlyArray<OrchestrationThreadActivity>,
|
activities: ReadonlyArray<OrchestrationThreadActivity>,
|
||||||
): PendingUserInput[] {
|
): PendingUserInput[] {
|
||||||
const openByRequestId = new Map<ApprovalRequestId, PendingUserInput>();
|
const openByRequestId = new Map<ApprovalRequestId, PendingUserInput>();
|
||||||
const ordered = [...activities].toSorted(compareActivitiesByOrder);
|
const ordered = orderActivities(activities);
|
||||||
|
|
||||||
for (const activity of ordered) {
|
for (const activity of ordered) {
|
||||||
const payload =
|
const payload =
|
||||||
@@ -511,7 +511,7 @@ export function deriveActivePlanState(
|
|||||||
activities: ReadonlyArray<OrchestrationThreadActivity>,
|
activities: ReadonlyArray<OrchestrationThreadActivity>,
|
||||||
latestTurnId: TurnId | undefined,
|
latestTurnId: TurnId | undefined,
|
||||||
): ActivePlanState | null {
|
): ActivePlanState | null {
|
||||||
const ordered = [...activities].toSorted(compareActivitiesByOrder);
|
const ordered = orderActivities(activities);
|
||||||
const allPlanActivities = ordered.filter((activity) => activity.kind === "turn.plan.updated");
|
const allPlanActivities = ordered.filter((activity) => activity.kind === "turn.plan.updated");
|
||||||
// Prefer plan from the current turn; fall back to the most recent plan from any turn
|
// Prefer plan from the current turn; fall back to the most recent plan from any turn
|
||||||
// so that TodoWrite tasks persist across follow-up messages.
|
// so that TodoWrite tasks persist across follow-up messages.
|
||||||
@@ -627,7 +627,7 @@ export function hasActionableProposedPlan(
|
|||||||
export function deriveWorkLogEntries(
|
export function deriveWorkLogEntries(
|
||||||
activities: ReadonlyArray<OrchestrationThreadActivity>,
|
activities: ReadonlyArray<OrchestrationThreadActivity>,
|
||||||
): WorkLogEntry[] {
|
): WorkLogEntry[] {
|
||||||
const ordered = [...activities].toSorted(compareActivitiesByOrder);
|
const ordered = orderActivities(activities);
|
||||||
const entries: DerivedWorkLogEntry[] = [];
|
const entries: DerivedWorkLogEntry[] = [];
|
||||||
for (const activity of ordered) {
|
for (const activity of ordered) {
|
||||||
if (activity.kind === "tool.started") continue;
|
if (activity.kind === "tool.started") continue;
|
||||||
@@ -1296,6 +1296,35 @@ function extractChangedFiles(payload: Record<string, unknown> | null): string[]
|
|||||||
return changedFiles;
|
return changedFiles;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Several independent derivations (work log, pending approvals, pending user
|
||||||
|
// inputs, active plan) order the same activities array per render. The reducer
|
||||||
|
// appends in order, so the input is almost always already sorted — detect that
|
||||||
|
// in O(n) and share the result per array identity instead of copying and
|
||||||
|
// re-sorting the whole history in each derivation.
|
||||||
|
const orderedActivitiesCache = new WeakMap<
|
||||||
|
ReadonlyArray<OrchestrationThreadActivity>,
|
||||||
|
ReadonlyArray<OrchestrationThreadActivity>
|
||||||
|
>();
|
||||||
|
|
||||||
|
function orderActivities(
|
||||||
|
activities: ReadonlyArray<OrchestrationThreadActivity>,
|
||||||
|
): ReadonlyArray<OrchestrationThreadActivity> {
|
||||||
|
const cached = orderedActivitiesCache.get(activities);
|
||||||
|
if (cached) {
|
||||||
|
return cached;
|
||||||
|
}
|
||||||
|
let isSorted = true;
|
||||||
|
for (let index = 1; index < activities.length; index += 1) {
|
||||||
|
if (compareActivitiesByOrder(activities[index - 1]!, activities[index]!) > 0) {
|
||||||
|
isSorted = false;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const ordered = isSorted ? activities : [...activities].toSorted(compareActivitiesByOrder);
|
||||||
|
orderedActivitiesCache.set(activities, ordered);
|
||||||
|
return ordered;
|
||||||
|
}
|
||||||
|
|
||||||
function compareActivitiesByOrder(
|
function compareActivitiesByOrder(
|
||||||
left: OrchestrationThreadActivity,
|
left: OrchestrationThreadActivity,
|
||||||
right: OrchestrationThreadActivity,
|
right: OrchestrationThreadActivity,
|
||||||
|
|||||||
@@ -457,12 +457,21 @@ export function applyThreadDetailEvent(
|
|||||||
|
|
||||||
// ── Activities ──────────────────────────────────────────────────
|
// ── Activities ──────────────────────────────────────────────────
|
||||||
case "thread.activity-appended": {
|
case "thread.activity-appended": {
|
||||||
const activities = pipe(
|
const activity = event.payload.activity;
|
||||||
thread.activities,
|
// Live activities arrive in order and are new: keep the sorted invariant
|
||||||
Arr.filter((activity) => activity.id !== event.payload.activity.id),
|
// with a single append instead of filter+append+sort over the (possibly
|
||||||
Arr.append(event.payload.activity),
|
// very long) history on every event.
|
||||||
Arr.sort(activityOrder),
|
const lastActivity = thread.activities.at(-1);
|
||||||
);
|
const activities =
|
||||||
|
(lastActivity === undefined || activityOrder(lastActivity, activity) <= 0) &&
|
||||||
|
!thread.activities.some((entry) => entry.id === activity.id)
|
||||||
|
? Arr.append(thread.activities, activity)
|
||||||
|
: pipe(
|
||||||
|
thread.activities,
|
||||||
|
Arr.filter((entry) => entry.id !== activity.id),
|
||||||
|
Arr.append(activity),
|
||||||
|
Arr.sort(activityOrder),
|
||||||
|
);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
kind: "updated",
|
kind: "updated",
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import {
|
|||||||
ProjectId,
|
ProjectId,
|
||||||
ProviderInstanceId,
|
ProviderInstanceId,
|
||||||
ThreadId,
|
ThreadId,
|
||||||
|
TurnId,
|
||||||
type OrchestrationThread,
|
type OrchestrationThread,
|
||||||
type OrchestrationThreadDetailSnapshot,
|
type OrchestrationThreadDetailSnapshot,
|
||||||
type OrchestrationThreadStreamItem,
|
type OrchestrationThreadStreamItem,
|
||||||
@@ -304,6 +305,67 @@ describe("EnvironmentThreads", () => {
|
|||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
it.effect("skips snapshot persistence while the session is running a turn", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const harness = yield* makeHarness({ cached: BASE_THREAD });
|
||||||
|
yield* Queue.offer(harness.inputs, snapshot(BASE_THREAD));
|
||||||
|
const sessionSet = (
|
||||||
|
status: "running" | "idle",
|
||||||
|
sequence: number,
|
||||||
|
): OrchestrationThreadStreamItem => ({
|
||||||
|
kind: "event",
|
||||||
|
event: {
|
||||||
|
eventId: EventId.make(`event-session-${sequence}`),
|
||||||
|
sequence,
|
||||||
|
occurredAt: "2026-04-01T01:00:00.000Z",
|
||||||
|
commandId: null,
|
||||||
|
causationEventId: null,
|
||||||
|
correlationId: null,
|
||||||
|
metadata: {},
|
||||||
|
aggregateKind: "thread",
|
||||||
|
aggregateId: THREAD_ID,
|
||||||
|
type: "thread.session-set",
|
||||||
|
payload: {
|
||||||
|
threadId: THREAD_ID,
|
||||||
|
session: {
|
||||||
|
threadId: THREAD_ID,
|
||||||
|
status,
|
||||||
|
providerName: null,
|
||||||
|
runtimeMode: "full-access",
|
||||||
|
activeTurnId: status === "running" ? TurnId.make("turn-1") : null,
|
||||||
|
lastError: null,
|
||||||
|
updatedAt: "2026-04-01T01:00:00.000Z",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
yield* Queue.offer(harness.inputs, sessionSet("running", 2));
|
||||||
|
yield* Queue.offer(harness.inputs, titleUpdated("Streaming title", 3));
|
||||||
|
yield* awaitThreadState(
|
||||||
|
harness.observed,
|
||||||
|
(value) => Option.isSome(value.data) && value.data.value.title === "Streaming title",
|
||||||
|
);
|
||||||
|
yield* TestClock.adjust("500 millis");
|
||||||
|
yield* Effect.yieldNow;
|
||||||
|
const savedWhileRunning = yield* Ref.get(harness.savedThreads);
|
||||||
|
expect(savedWhileRunning.some((saved) => saved.thread.title === "Streaming title")).toBe(
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
|
||||||
|
yield* Queue.offer(harness.inputs, sessionSet("idle", 4));
|
||||||
|
yield* awaitThreadState(
|
||||||
|
harness.observed,
|
||||||
|
(value) => Option.isSome(value.data) && value.data.value.session?.status === "idle",
|
||||||
|
);
|
||||||
|
yield* TestClock.adjust("500 millis");
|
||||||
|
yield* Effect.yieldNow;
|
||||||
|
const savedAfterSettle = yield* Ref.get(harness.savedThreads);
|
||||||
|
expect(savedAfterSettle.at(-1)?.thread.title).toBe("Streaming title");
|
||||||
|
expect(savedAfterSettle.at(-1)?.snapshotSequence).toBe(4);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
it.effect("seeds the thread from the HTTP snapshot and resumes live events", () =>
|
it.effect("seeds the thread from the HTTP snapshot and resumes live events", () =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const httpThread: OrchestrationThread = { ...BASE_THREAD, title: "HTTP title" };
|
const httpThread: OrchestrationThread = { ...BASE_THREAD, title: "HTTP title" };
|
||||||
|
|||||||
@@ -129,7 +129,14 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make
|
|||||||
error: Option.none(),
|
error: Option.none(),
|
||||||
});
|
});
|
||||||
// Persist the thread together with the sequence it reflects so the next warm
|
// Persist the thread together with the sequence it reflects so the next warm
|
||||||
// cache can resume from exactly here.
|
// cache can resume from exactly here. While a turn is actively running,
|
||||||
|
// events arrive many times per second and each snapshot encode covers the
|
||||||
|
// whole thread history — skip those; the session leaving "running" (and the
|
||||||
|
// scope finalizer) persists the settled state, and a stale cache only means
|
||||||
|
// resuming via a slightly longer `afterSequence` replay.
|
||||||
|
if (thread.session?.status === "running") {
|
||||||
|
return;
|
||||||
|
}
|
||||||
const snapshotSequence = yield* SubscriptionRef.get(lastSequence);
|
const snapshotSequence = yield* SubscriptionRef.get(lastSequence);
|
||||||
yield* Queue.offer(persistence, { snapshotSequence, thread });
|
yield* Queue.offer(persistence, { snapshotSequence, thread });
|
||||||
});
|
});
|
||||||
|
|||||||
Reference in new issue
Block a user