perf(server): finish runtime messages without full thread reads (#10120)
Co-authored-by: Ross Cawston <[email protected]>
This commit is contained in:
1 parent
e63ddb48e2
commit
e4e9fa9a0b
11 files changed
+692
-271
No files matched your search
@@ -286,9 +286,20 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
Layer.provide(RepositoryIdentityResolver.layer),
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
);
|
||||
const ingestionProjectionSnapshotLayer = Layer.effect(
|
||||
ProjectionSnapshotQuery,
|
||||
Effect.gen(function* () {
|
||||
const query = yield* ProjectionSnapshotQuery;
|
||||
return ProjectionSnapshotQuery.of({
|
||||
...query,
|
||||
getThreadDetailById: () =>
|
||||
Effect.die("provider runtime ingestion must not hydrate thread detail"),
|
||||
});
|
||||
}),
|
||||
).pipe(Layer.provide(projectionSnapshotLayer));
|
||||
const layer = ProviderRuntimeIngestionLive.pipe(
|
||||
Layer.provideMerge(orchestrationLayer),
|
||||
Layer.provideMerge(projectionSnapshotLayer),
|
||||
Layer.provideMerge(ingestionProjectionSnapshotLayer),
|
||||
// Single shared liveness instance across ingestion (writer), the
|
||||
// engine, and the snapshot query (reader).
|
||||
Layer.provideMerge(ThreadBackgroundLiveness.layer),
|
||||
@@ -483,6 +494,89 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it.each(["turn.completed", "turn.aborted"] as const)(
|
||||
"finalizes old buffered text on late %s without stopping the newer turn",
|
||||
async (terminalType) => {
|
||||
const harness = await createHarness({
|
||||
serverSettings: { enableLegacyTokenStreaming: false },
|
||||
});
|
||||
const threadId = asThreadId("thread-1");
|
||||
const oldTurnId = asTurnId("old-buffered-turn");
|
||||
const newTurnId = asTurnId("new-active-turn");
|
||||
const base = {
|
||||
provider: ProviderDriverKind.make("opencode"),
|
||||
threadId,
|
||||
createdAt: "2026-01-01T00:00:01.000Z",
|
||||
};
|
||||
await harness.emitAndDrain([
|
||||
{
|
||||
...base,
|
||||
type: "turn.started",
|
||||
eventId: asEventId("old-buffered-started"),
|
||||
turnId: oldTurnId,
|
||||
},
|
||||
{
|
||||
...base,
|
||||
type: "content.delta",
|
||||
eventId: asEventId("old-buffered-delta"),
|
||||
turnId: oldTurnId,
|
||||
itemId: asItemId("old-buffered-message"),
|
||||
payload: { streamKind: "assistant_text", delta: "Keep the old answer." },
|
||||
},
|
||||
]);
|
||||
await harness.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("start-new-while-old-finishes"),
|
||||
threadId,
|
||||
message: {
|
||||
messageId: asMessageId("new-turn-prompt"),
|
||||
role: "user",
|
||||
text: "Continue",
|
||||
attachments: [],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: base.createdAt,
|
||||
});
|
||||
harness.setProviderSession({
|
||||
provider: base.provider,
|
||||
status: "running",
|
||||
runtimeMode: "approval-required",
|
||||
threadId,
|
||||
createdAt: base.createdAt,
|
||||
updatedAt: base.createdAt,
|
||||
activeTurnId: newTurnId,
|
||||
});
|
||||
await harness.emitAndDrain([
|
||||
{
|
||||
...base,
|
||||
type: "turn.started",
|
||||
eventId: asEventId("new-active-started"),
|
||||
turnId: newTurnId,
|
||||
},
|
||||
{
|
||||
...base,
|
||||
type: terminalType,
|
||||
eventId: asEventId("old-buffered-terminal"),
|
||||
turnId: oldTurnId,
|
||||
payload:
|
||||
terminalType === "turn.completed"
|
||||
? { state: "completed" }
|
||||
: { reason: "Interrupted by user." },
|
||||
},
|
||||
]);
|
||||
const thread = (await harness.readModel()).threads.find((entry) => entry.id === threadId);
|
||||
expect(thread?.session).toMatchObject({ activeTurnId: newTurnId, status: "running" });
|
||||
expect(thread?.messages).toContainEqual(
|
||||
expect.objectContaining({
|
||||
turnId: oldTurnId,
|
||||
text: "Keep the old answer.",
|
||||
streaming: false,
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
{ source: "the previous turn", turnId: asTurnId("opencode-stopped-turn") },
|
||||
{ source: "an unspecified turn", turnId: undefined },
|
||||
@@ -1690,6 +1784,31 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
).toMatchObject({
|
||||
implementationThreadId: "thread-implement",
|
||||
});
|
||||
const implementedPlan = sourceThreadAfterStart.proposedPlans.find(
|
||||
(entry) => entry.id === sourcePlan.id,
|
||||
);
|
||||
await harness.emitAndDrain([
|
||||
{
|
||||
type: "turn.proposed.completed",
|
||||
eventId: asEventId("evt-plan-source-late-completion"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
createdAt: "2026-01-01T00:01:00.000Z",
|
||||
threadId: sourceThreadId,
|
||||
turnId: sourceTurnId,
|
||||
payload: { planMarkdown: "# Source plan with late details" },
|
||||
},
|
||||
]);
|
||||
const sourceAfterLateCompletion = (await harness.readModel()).threads.find(
|
||||
(entry) => entry.id === sourceThreadId,
|
||||
);
|
||||
expect(
|
||||
sourceAfterLateCompletion?.proposedPlans.find((entry) => entry.id === sourcePlan.id),
|
||||
).toMatchObject({
|
||||
planMarkdown: "# Source plan with late details",
|
||||
createdAt: sourcePlan.createdAt,
|
||||
implementedAt: implementedPlan?.implementedAt,
|
||||
implementationThreadId: targetThreadId,
|
||||
});
|
||||
});
|
||||
|
||||
it("does not mark the source proposed plan implemented for a rejected turn.started event", async () => {
|
||||
@@ -2120,7 +2239,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
type: "turn.proposed.delta",
|
||||
eventId: asEventId("evt-plan-delta-1"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
createdAt: now,
|
||||
createdAt: "",
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-plan-buffer"),
|
||||
payload: {
|
||||
@@ -2131,7 +2250,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
type: "turn.proposed.delta",
|
||||
eventId: asEventId("evt-plan-delta-2"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
createdAt: now,
|
||||
createdAt: "",
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-plan-buffer"),
|
||||
payload: {
|
||||
@@ -2161,6 +2280,42 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
entry.id === "plan:thread-1:turn:turn-plan-buffer",
|
||||
);
|
||||
expect(proposedPlan?.planMarkdown).toBe("## Buffered plan\n\n- first\n- second");
|
||||
expect(proposedPlan?.createdAt).toBe(now);
|
||||
});
|
||||
|
||||
it("releases a blank completed plan before a late replacement", async () => {
|
||||
const harness = await createHarness();
|
||||
const threadId = asThreadId("thread-1");
|
||||
const turnId = asTurnId("blank-plan-turn");
|
||||
const base = { provider: ProviderDriverKind.make("codex"), threadId, turnId };
|
||||
const replacementTime = "2026-01-01T00:00:02.000Z";
|
||||
await harness.emitAndDrain([
|
||||
{
|
||||
...base,
|
||||
type: "turn.proposed.delta",
|
||||
eventId: asEventId("blank-plan-delta"),
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
payload: { delta: " \n " },
|
||||
},
|
||||
{
|
||||
...base,
|
||||
type: "turn.completed",
|
||||
eventId: asEventId("blank-plan-completed"),
|
||||
createdAt: "2026-01-01T00:00:01.000Z",
|
||||
payload: { state: "completed" },
|
||||
},
|
||||
{
|
||||
...base,
|
||||
type: "turn.proposed.completed",
|
||||
eventId: asEventId("late-plan-completed"),
|
||||
createdAt: replacementTime,
|
||||
payload: { planMarkdown: "# Replacement plan" },
|
||||
},
|
||||
]);
|
||||
const thread = (await harness.readModel()).threads.find((entry) => entry.id === threadId);
|
||||
expect(thread?.proposedPlans).toEqual([
|
||||
expect.objectContaining({ planMarkdown: "# Replacement plan", createdAt: replacementTime }),
|
||||
]);
|
||||
});
|
||||
|
||||
it("buffers assistant deltas with one lifecycle query per event until completion", async () => {
|
||||
@@ -4037,71 +4192,65 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
expect(completedPayload?.title).toBe("wait for codex review to finish");
|
||||
});
|
||||
|
||||
it("titles task completion from persisted activities after the description cache is swept", async () => {
|
||||
it("recovers a task title past untitled progress after the cache is swept", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
const threadId = asThreadId("thread-1");
|
||||
const turnId = asTurnId("turn-swept-task");
|
||||
const provider = ProviderDriverKind.make("claudeAgent");
|
||||
|
||||
harness.emit({
|
||||
type: "task.progress",
|
||||
eventId: asEventId("evt-swept-task-progress"),
|
||||
provider: ProviderDriverKind.make("claudeAgent"),
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-swept-task"),
|
||||
payload: {
|
||||
taskId: "swept-task-1",
|
||||
description: "Watch round-3 CI and bots",
|
||||
await harness.emitAndDrain([
|
||||
{
|
||||
type: "task.started",
|
||||
eventId: asEventId("evt-swept-task-started"),
|
||||
provider,
|
||||
createdAt: now,
|
||||
threadId,
|
||||
turnId,
|
||||
payload: { taskId: "swept-task-1", description: "Watch round-3 CI and bots" },
|
||||
},
|
||||
]);
|
||||
// Older saved progress rows can have no title even when the start has one.
|
||||
await harness.dispatch({
|
||||
type: "thread.activity.append",
|
||||
commandId: CommandId.make("cmd-swept-task-progress"),
|
||||
threadId,
|
||||
activity: {
|
||||
id: asEventId("evt-swept-task-progress"),
|
||||
kind: "task.progress",
|
||||
tone: "info",
|
||||
summary: "Polling CI checks.",
|
||||
payload: { taskId: "swept-task-1" },
|
||||
turnId,
|
||||
createdAt: "2026-01-01T00:00:01.000Z",
|
||||
},
|
||||
createdAt: "2026-01-01T00:00:01.000Z",
|
||||
});
|
||||
|
||||
await waitForThread(harness.readModel, (entry) =>
|
||||
entry.activities.some(
|
||||
(activity: ProviderRuntimeTestActivity) =>
|
||||
activity.id === "task-progress:thread-1:swept-task-1",
|
||||
),
|
||||
);
|
||||
|
||||
// session.exited sweeps the in-memory description cache; the completion
|
||||
// that follows must recover the name from persisted activities.
|
||||
harness.emit({
|
||||
type: "session.exited",
|
||||
eventId: asEventId("evt-swept-task-session-exited"),
|
||||
provider: ProviderDriverKind.make("claudeAgent"),
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
payload: {},
|
||||
});
|
||||
|
||||
harness.emit({
|
||||
type: "task.completed",
|
||||
eventId: asEventId("evt-swept-task-completed"),
|
||||
provider: ProviderDriverKind.make("claudeAgent"),
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-swept-task"),
|
||||
payload: {
|
||||
taskId: "swept-task-1",
|
||||
status: "completed",
|
||||
summary: "CI is green.",
|
||||
await harness.emitAndDrain([
|
||||
{
|
||||
type: "session.exited",
|
||||
eventId: asEventId("evt-swept-task-session-exited"),
|
||||
provider,
|
||||
createdAt: "2026-01-01T00:00:02.000Z",
|
||||
threadId,
|
||||
payload: {},
|
||||
},
|
||||
});
|
||||
{
|
||||
type: "task.completed",
|
||||
eventId: asEventId("evt-swept-task-completed"),
|
||||
provider,
|
||||
createdAt: "2026-01-01T00:00:03.000Z",
|
||||
threadId,
|
||||
turnId,
|
||||
payload: { taskId: "swept-task-1", status: "completed", summary: "CI is green." },
|
||||
},
|
||||
]);
|
||||
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
entry.activities.some(
|
||||
(activity: ProviderRuntimeTestActivity) => activity.id === "evt-swept-task-completed",
|
||||
),
|
||||
const thread = (await harness.readModel()).threads.find((entry) => entry.id === threadId);
|
||||
const completed = thread?.activities.find(
|
||||
(activity) => activity.id === "evt-swept-task-completed",
|
||||
);
|
||||
|
||||
const completed = thread.activities.find(
|
||||
(activity: ProviderRuntimeTestActivity) => activity.id === "evt-swept-task-completed",
|
||||
);
|
||||
const completedPayload =
|
||||
completed?.payload && typeof completed.payload === "object"
|
||||
? (completed.payload as Record<string, unknown>)
|
||||
: undefined;
|
||||
|
||||
expect(completedPayload?.title).toBe("Watch round-3 CI and bots");
|
||||
expect(completed?.payload).toMatchObject({ title: "Watch round-3 CI and bots" });
|
||||
});
|
||||
|
||||
it("projects structured user input request and resolution as thread activities", async () => {
|
||||
|
||||
@@ -4,8 +4,7 @@ import {
|
||||
CommandId,
|
||||
MessageId,
|
||||
type OrchestrationEvent,
|
||||
type OrchestrationMessage,
|
||||
type OrchestrationProposedPlanId,
|
||||
OrchestrationProposedPlanId,
|
||||
CheckpointRef,
|
||||
classifyTaskAgentKind,
|
||||
EventId,
|
||||
@@ -14,8 +13,6 @@ import {
|
||||
type ThreadTokenUsageSnapshot,
|
||||
TurnId,
|
||||
type OrchestrationCheckpointSummary,
|
||||
type OrchestrationProposedPlan,
|
||||
type OrchestrationThread,
|
||||
type OrchestrationThreadActivity,
|
||||
type ProviderRuntimeEvent,
|
||||
RuntimeRequestId,
|
||||
@@ -39,6 +36,10 @@ import { ProjectionTurnRepositoryLive } from "../../persistence/Layers/Projectio
|
||||
import { ProjectionThreadActivityRepository } from "../../persistence/Services/ProjectionThreadActivities.ts";
|
||||
import { ProjectionThreadActivityRepositoryLive } from "../../persistence/Layers/ProjectionThreadActivities.ts";
|
||||
import * as CheckpointStore from "../../checkpointing/CheckpointStore.ts";
|
||||
import { ProjectionThreadMessageRepository } from "../../persistence/Services/ProjectionThreadMessages.ts";
|
||||
import { ProjectionThreadMessageRepositoryLive } from "../../persistence/Layers/ProjectionThreadMessages.ts";
|
||||
import { ProjectionThreadProposedPlanRepository } from "../../persistence/Services/ProjectionThreadProposedPlans.ts";
|
||||
import { ProjectionThreadProposedPlanRepositoryLive } from "../../persistence/Layers/ProjectionThreadProposedPlans.ts";
|
||||
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
||||
import { ThreadBackgroundLivenessService } from "../ThreadBackgroundLiveness.ts";
|
||||
import { ThreadPlanProgressService } from "../ThreadPlanProgress.ts";
|
||||
@@ -54,13 +55,12 @@ import { canReplaceThreadTitle } from "../threadTitles.ts";
|
||||
|
||||
const providerTurnKey = (threadId: ThreadId, turnId: TurnId) => `${threadId}:${turnId}`;
|
||||
const providerTaskKey = (threadId: ThreadId, taskId: string) => `${threadId}:${taskId}`;
|
||||
const TASK_TITLE_ACTIVITY_KINDS = ["task.started", "task.progress"] as const;
|
||||
|
||||
// Fallback when the in-memory description cache no longer has the task name
|
||||
// (server restart, session-exit sweep, TTL/capacity eviction): earlier
|
||||
// task.started/task.progress activities for the task are persisted with it.
|
||||
function findTaskTitleInActivities(
|
||||
activities: ReadonlyArray<OrchestrationThreadActivity> | undefined,
|
||||
activities: ReadonlyArray<{ readonly kind: string; readonly payload: unknown }> | undefined,
|
||||
taskId: string,
|
||||
): string | undefined {
|
||||
if (!activities) {
|
||||
@@ -138,57 +138,6 @@ function sameId(left: string | null | undefined, right: string | null | undefine
|
||||
return left === right;
|
||||
}
|
||||
|
||||
function hasAssistantMessageForTurn(
|
||||
messages: ReadonlyArray<OrchestrationMessage>,
|
||||
turnId: TurnId,
|
||||
options?: { readonly streamingOnly?: boolean },
|
||||
): boolean {
|
||||
for (let index = 0; index < messages.length; index += 1) {
|
||||
const message = messages[index];
|
||||
if (!message) {
|
||||
continue;
|
||||
}
|
||||
if (message.role !== "assistant" || message.turnId !== turnId) {
|
||||
continue;
|
||||
}
|
||||
if (options?.streamingOnly === true && !message.streaming) {
|
||||
continue;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function findMessageById(
|
||||
messages: ReadonlyArray<OrchestrationMessage>,
|
||||
messageId: MessageId,
|
||||
): OrchestrationMessage | undefined {
|
||||
for (let index = 0; index < messages.length; index += 1) {
|
||||
const message = messages[index];
|
||||
if (message?.id === messageId) {
|
||||
return message;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function findProposedPlanById(
|
||||
proposedPlans: ReadonlyArray<
|
||||
Pick<OrchestrationProposedPlan, "id" | "createdAt" | "implementedAt" | "implementationThreadId">
|
||||
>,
|
||||
planId: string,
|
||||
):
|
||||
| Pick<OrchestrationProposedPlan, "id" | "createdAt" | "implementedAt" | "implementationThreadId">
|
||||
| undefined {
|
||||
for (let index = 0; index < proposedPlans.length; index += 1) {
|
||||
const proposedPlan = proposedPlans[index];
|
||||
if (proposedPlan?.id === planId) {
|
||||
return proposedPlan;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function hasCheckpointForTurn(
|
||||
checkpoints: ReadonlyArray<OrchestrationCheckpointSummary>,
|
||||
turnId: TurnId,
|
||||
@@ -264,16 +213,15 @@ function buildContextWindowActivityPayload(
|
||||
}
|
||||
|
||||
function compactedTokenCountsFromActivities(
|
||||
activities: ReadonlyArray<OrchestrationThreadActivity> | undefined,
|
||||
activities: ReadonlyArray<
|
||||
Pick<OrchestrationThreadActivity, "kind" | "payload" | "sequence" | "createdAt">
|
||||
>,
|
||||
): { readonly beforeTokens: number; readonly afterTokens: number } | undefined {
|
||||
const lastCompactionIndex = activities?.findLastIndex(
|
||||
const lastCompactionIndex = activities.findLastIndex(
|
||||
(activity) => activity.kind === "context-compaction",
|
||||
);
|
||||
const lastCompaction =
|
||||
lastCompactionIndex !== undefined && lastCompactionIndex >= 0
|
||||
? activities?.[lastCompactionIndex]
|
||||
: undefined;
|
||||
const activitiesSinceLastCompaction = activities?.slice((lastCompactionIndex ?? -1) + 1) ?? [];
|
||||
const lastCompaction = activities[lastCompactionIndex];
|
||||
const activitiesSinceLastCompaction = activities.slice(lastCompactionIndex + 1);
|
||||
const usedTokens = activitiesSinceLastCompaction.flatMap((activity) => {
|
||||
if (activity.kind !== "context-window.updated") return [];
|
||||
if (lastCompaction !== undefined) {
|
||||
@@ -956,6 +904,8 @@ const make = Effect.gen(function* () {
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
const providerService = yield* ProviderService;
|
||||
const projectionThreadMessages = yield* ProjectionThreadMessageRepository;
|
||||
const projectionThreadProposedPlans = yield* ProjectionThreadProposedPlanRepository;
|
||||
const projectionTurnRepository = yield* ProjectionTurnRepository;
|
||||
const projectionThreadActivityRepository = yield* ProjectionThreadActivityRepository;
|
||||
const serverSettingsService = yield* ServerSettingsService;
|
||||
@@ -1013,15 +963,6 @@ const make = Effect.gen(function* () {
|
||||
),
|
||||
);
|
||||
|
||||
const resolveThreadDetail = Effect.fn("resolveThreadDetail")(function* (
|
||||
threadId: ThreadId,
|
||||
activityKinds: ReadonlyArray<string> = [],
|
||||
) {
|
||||
return yield* projectionSnapshotQuery
|
||||
.getThreadDetailById(threadId, { activityKinds })
|
||||
.pipe(Effect.map(Option.getOrUndefined));
|
||||
});
|
||||
|
||||
const resolveThreadRuntimeContext = Effect.fn("resolveThreadRuntimeContext")(function* (
|
||||
threadId: ThreadId,
|
||||
) {
|
||||
@@ -1030,6 +971,16 @@ const make = Effect.gen(function* () {
|
||||
.pipe(Effect.map(Option.getOrUndefined));
|
||||
});
|
||||
|
||||
const getThreadMessageById = Effect.fn("getThreadMessageById")(function* (
|
||||
threadId: ThreadId,
|
||||
messageId: MessageId,
|
||||
) {
|
||||
const message = yield* projectionThreadMessages.getByMessageId({ messageId });
|
||||
return Option.filter(message, (entry) => entry.threadId === threadId).pipe(
|
||||
Option.getOrUndefined,
|
||||
);
|
||||
});
|
||||
|
||||
const rememberAssistantMessageId = (threadId: ThreadId, turnId: TurnId, messageId: MessageId) =>
|
||||
Cache.getOption(turnMessageIdsByTurnKey, providerTurnKey(threadId, turnId)).pipe(
|
||||
Effect.flatMap((existingIds) =>
|
||||
@@ -1195,15 +1146,6 @@ const make = Effect.gen(function* () {
|
||||
}),
|
||||
);
|
||||
|
||||
const takeBufferedProposedPlan = (planId: string) =>
|
||||
Cache.getOption(bufferedProposedPlanById, planId).pipe(
|
||||
Effect.flatMap((existingEntry) =>
|
||||
Cache.invalidate(bufferedProposedPlanById, planId).pipe(
|
||||
Effect.as(Option.getOrUndefined(existingEntry)),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const clearBufferedProposedPlan = (planId: string) =>
|
||||
Cache.invalidate(bufferedProposedPlanById, planId);
|
||||
|
||||
@@ -1357,83 +1299,45 @@ const make = Effect.gen(function* () {
|
||||
}
|
||||
});
|
||||
|
||||
const upsertProposedPlan = (input: {
|
||||
const finalizeBufferedProposedPlan = Effect.fn("finalizeBufferedProposedPlan")(function* (input: {
|
||||
event: ProviderRuntimeEvent;
|
||||
threadId: ThreadId;
|
||||
threadProposedPlans: ReadonlyArray<{
|
||||
id: string;
|
||||
createdAt: string;
|
||||
implementedAt: string | null;
|
||||
implementationThreadId: ThreadId | null;
|
||||
}>;
|
||||
planId: string;
|
||||
turnId?: TurnId;
|
||||
planMarkdown: string | undefined;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}) =>
|
||||
Effect.gen(function* () {
|
||||
const planMarkdown = normalizeProposedPlanMarkdown(input.planMarkdown);
|
||||
if (!planMarkdown) {
|
||||
return;
|
||||
}
|
||||
|
||||
const existingPlan = findProposedPlanById(input.threadProposedPlans, input.planId);
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.proposed-plan.upsert",
|
||||
commandId: yield* providerCommandId(input.event, "proposed-plan-upsert"),
|
||||
threadId: input.threadId,
|
||||
proposedPlan: {
|
||||
id: input.planId,
|
||||
turnId: input.turnId ?? null,
|
||||
planMarkdown,
|
||||
implementedAt: existingPlan?.implementedAt ?? null,
|
||||
implementationThreadId: existingPlan?.implementationThreadId ?? null,
|
||||
createdAt: existingPlan?.createdAt ?? input.createdAt,
|
||||
updatedAt: input.updatedAt,
|
||||
},
|
||||
createdAt: input.updatedAt,
|
||||
});
|
||||
});
|
||||
|
||||
const finalizeBufferedProposedPlan = (input: {
|
||||
event: ProviderRuntimeEvent;
|
||||
threadId: ThreadId;
|
||||
threadProposedPlans: ReadonlyArray<{
|
||||
id: string;
|
||||
createdAt: string;
|
||||
implementedAt: string | null;
|
||||
implementationThreadId: ThreadId | null;
|
||||
}>;
|
||||
planId: string;
|
||||
turnId?: TurnId;
|
||||
fallbackMarkdown?: string;
|
||||
updatedAt: string;
|
||||
}) =>
|
||||
Effect.gen(function* () {
|
||||
const bufferedPlan = yield* takeBufferedProposedPlan(input.planId);
|
||||
const bufferedMarkdown = normalizeProposedPlanMarkdown(bufferedPlan?.text);
|
||||
const fallbackMarkdown = normalizeProposedPlanMarkdown(input.fallbackMarkdown);
|
||||
const planMarkdown = bufferedMarkdown ?? fallbackMarkdown;
|
||||
if (!planMarkdown) {
|
||||
return;
|
||||
}
|
||||
}) {
|
||||
const bufferedPlan = Option.getOrUndefined(
|
||||
yield* Cache.getOption(bufferedProposedPlanById, input.planId),
|
||||
);
|
||||
const planMarkdown =
|
||||
normalizeProposedPlanMarkdown(bufferedPlan?.text) ??
|
||||
normalizeProposedPlanMarkdown(input.fallbackMarkdown);
|
||||
if (!planMarkdown) return yield* clearBufferedProposedPlan(input.planId);
|
||||
|
||||
yield* upsertProposedPlan({
|
||||
event: input.event,
|
||||
const existingPlan = Option.getOrUndefined(
|
||||
yield* projectionThreadProposedPlans.getByPlanId({
|
||||
threadId: input.threadId,
|
||||
threadProposedPlans: input.threadProposedPlans,
|
||||
planId: input.planId,
|
||||
...(input.turnId ? { turnId: input.turnId } : {}),
|
||||
planId: OrchestrationProposedPlanId.make(input.planId),
|
||||
}),
|
||||
);
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.proposed-plan.upsert",
|
||||
commandId: yield* providerCommandId(input.event, "proposed-plan-upsert"),
|
||||
threadId: input.threadId,
|
||||
proposedPlan: {
|
||||
id: input.planId,
|
||||
turnId: input.turnId ?? null,
|
||||
planMarkdown,
|
||||
createdAt:
|
||||
bufferedPlan?.createdAt && bufferedPlan.createdAt.length > 0
|
||||
? bufferedPlan.createdAt
|
||||
: input.updatedAt,
|
||||
implementedAt: existingPlan?.implementedAt ?? null,
|
||||
implementationThreadId: existingPlan?.implementationThreadId ?? null,
|
||||
createdAt: existingPlan?.createdAt ?? (bufferedPlan?.createdAt || input.updatedAt),
|
||||
updatedAt: input.updatedAt,
|
||||
});
|
||||
yield* clearBufferedProposedPlan(input.planId);
|
||||
},
|
||||
createdAt: input.updatedAt,
|
||||
});
|
||||
yield* clearBufferedProposedPlan(input.planId);
|
||||
});
|
||||
|
||||
const clearTurnStateForSession = (threadId: ThreadId) =>
|
||||
Effect.gen(function* () {
|
||||
@@ -1538,8 +1442,13 @@ const make = Effect.gen(function* () {
|
||||
implementationThreadId: ThreadId,
|
||||
implementedAt: string,
|
||||
) {
|
||||
const sourceThread = yield* resolveThreadDetail(sourceThreadId);
|
||||
const sourcePlan = sourceThread?.proposedPlans.find((entry) => entry.id === sourcePlanId);
|
||||
const sourceThread = yield* resolveThreadRuntimeContext(sourceThreadId);
|
||||
const sourcePlan = Option.getOrUndefined(
|
||||
yield* projectionThreadProposedPlans.getByPlanId({
|
||||
threadId: sourceThreadId,
|
||||
planId: sourcePlanId,
|
||||
}),
|
||||
);
|
||||
if (!sourceThread || !sourcePlan || sourcePlan.implementedAt !== null) {
|
||||
return;
|
||||
}
|
||||
@@ -1550,9 +1459,12 @@ const make = Effect.gen(function* () {
|
||||
commandId: CommandId.make(
|
||||
`provider:source-proposed-plan-implemented:${implementationThreadId}:${commandUuid}`,
|
||||
),
|
||||
threadId: sourceThread.id,
|
||||
threadId: sourceThreadId,
|
||||
proposedPlan: {
|
||||
...sourcePlan,
|
||||
id: sourcePlan.planId,
|
||||
turnId: sourcePlan.turnId,
|
||||
planMarkdown: sourcePlan.planMarkdown,
|
||||
createdAt: sourcePlan.createdAt,
|
||||
implementedAt,
|
||||
implementationThreadId,
|
||||
updatedAt: implementedAt,
|
||||
@@ -1571,16 +1483,6 @@ const make = Effect.gen(function* () {
|
||||
const thread = yield* resolveThreadRuntimeContext(event.threadId);
|
||||
if (!thread) return;
|
||||
|
||||
let loadedThreadDetail: OrchestrationThread | null | undefined;
|
||||
const getLoadedThreadDetail = () =>
|
||||
Effect.gen(function* () {
|
||||
if (loadedThreadDetail !== undefined) {
|
||||
return loadedThreadDetail;
|
||||
}
|
||||
loadedThreadDetail = (yield* resolveThreadDetail(thread.id)) ?? null;
|
||||
return loadedThreadDetail;
|
||||
});
|
||||
|
||||
const now = event.createdAt;
|
||||
const eventTurnId = toTurnId(event.turnId);
|
||||
const activeTurnId = thread.session?.activeTurnId ?? null;
|
||||
@@ -1800,7 +1702,11 @@ const make = Effect.gen(function* () {
|
||||
? toTurnId(event.turnId)
|
||||
: undefined;
|
||||
if (pauseForUserTurnId) {
|
||||
const detailedThread = yield* getLoadedThreadDetail();
|
||||
const hasProjectedMessage = yield* projectionThreadMessages.hasAssistantMessageForTurn({
|
||||
threadId: thread.id,
|
||||
turnId: pauseForUserTurnId,
|
||||
streamingOnly: true,
|
||||
});
|
||||
const assistantDeliveryMode: AssistantDeliveryMode = yield* Effect.map(
|
||||
serverSettingsService.getSettings,
|
||||
(settings) => (settings.enableLegacyTokenStreaming ? "streaming" : "buffered"),
|
||||
@@ -1831,11 +1737,7 @@ const make = Effect.gen(function* () {
|
||||
event.type === "request.opened"
|
||||
? "assistant-delta-finalize-on-request-opened"
|
||||
: "assistant-delta-finalize-on-user-input-requested",
|
||||
hasProjectedMessage:
|
||||
detailedThread !== null &&
|
||||
hasAssistantMessageForTurn(detailedThread.messages, pauseForUserTurnId, {
|
||||
streamingOnly: true,
|
||||
}),
|
||||
hasProjectedMessage,
|
||||
flushedMessageIds,
|
||||
});
|
||||
}
|
||||
@@ -1864,19 +1766,24 @@ const make = Effect.gen(function* () {
|
||||
: undefined;
|
||||
|
||||
if (assistantCompletion) {
|
||||
const detailedThread = yield* getLoadedThreadDetail();
|
||||
const messages = detailedThread?.messages ?? [];
|
||||
const turnId = toTurnId(event.turnId);
|
||||
const activeAssistantMessageId = turnId
|
||||
? yield* getActiveAssistantMessageIdForTurn(thread.id, turnId)
|
||||
: Option.none<MessageId>();
|
||||
const hasAssistantMessagesForTurn =
|
||||
turnId !== undefined ? hasAssistantMessageForTurn(messages, turnId) : false;
|
||||
const assistantMessageId = Option.getOrElse(
|
||||
activeAssistantMessageId,
|
||||
() => assistantCompletion.messageId,
|
||||
);
|
||||
const existingAssistantMessage = findMessageById(messages, assistantMessageId);
|
||||
const [existingAssistantMessage, hasAssistantMessagesForTurn] = yield* Effect.all([
|
||||
getThreadMessageById(thread.id, assistantMessageId),
|
||||
turnId === undefined
|
||||
? Effect.succeed(false)
|
||||
: projectionThreadMessages.hasAssistantMessageForTurn({
|
||||
threadId: thread.id,
|
||||
turnId,
|
||||
streamingOnly: false,
|
||||
}),
|
||||
]);
|
||||
const shouldApplyFallbackCompletionText =
|
||||
!existingAssistantMessage || existingAssistantMessage.text.length === 0;
|
||||
|
||||
@@ -1916,11 +1823,9 @@ const make = Effect.gen(function* () {
|
||||
}
|
||||
|
||||
if (proposedPlanCompletion) {
|
||||
const detailedThread = yield* getLoadedThreadDetail();
|
||||
yield* finalizeBufferedProposedPlan({
|
||||
event,
|
||||
threadId: thread.id,
|
||||
threadProposedPlans: detailedThread?.proposedPlans ?? [],
|
||||
planId: proposedPlanCompletion.planId,
|
||||
...(proposedPlanCompletion.turnId ? { turnId: proposedPlanCompletion.turnId } : {}),
|
||||
fallbackMarkdown: proposedPlanCompletion.planMarkdown,
|
||||
@@ -1929,9 +1834,6 @@ const make = Effect.gen(function* () {
|
||||
}
|
||||
|
||||
if (isTerminalTurn) {
|
||||
const detailedThread = yield* getLoadedThreadDetail();
|
||||
const messages = detailedThread?.messages ?? [];
|
||||
const proposedPlans = detailedThread?.proposedPlans ?? [];
|
||||
const turnId = toTurnId(event.turnId);
|
||||
if (turnId) {
|
||||
const userInputActivities =
|
||||
@@ -1979,16 +1881,20 @@ const make = Effect.gen(function* () {
|
||||
yield* Effect.forEach(
|
||||
assistantMessageIds,
|
||||
(assistantMessageId) =>
|
||||
finalizeAssistantMessage({
|
||||
event,
|
||||
threadId: thread.id,
|
||||
messageId: assistantMessageId,
|
||||
turnId,
|
||||
createdAt: now,
|
||||
commandTag: "assistant-complete-finalize",
|
||||
finalDeltaCommandTag: "assistant-delta-finalize-fallback",
|
||||
hasProjectedMessage: findMessageById(messages, assistantMessageId) !== undefined,
|
||||
}),
|
||||
getThreadMessageById(thread.id, assistantMessageId).pipe(
|
||||
Effect.flatMap((existingMessage) =>
|
||||
finalizeAssistantMessage({
|
||||
event,
|
||||
threadId: thread.id,
|
||||
messageId: assistantMessageId,
|
||||
turnId,
|
||||
createdAt: now,
|
||||
commandTag: "assistant-complete-finalize",
|
||||
finalDeltaCommandTag: "assistant-delta-finalize-fallback",
|
||||
hasProjectedMessage: existingMessage !== undefined,
|
||||
}),
|
||||
),
|
||||
),
|
||||
{ concurrency: 1 },
|
||||
).pipe(Effect.asVoid);
|
||||
yield* clearAssistantMessageIdsForTurn(thread.id, turnId);
|
||||
@@ -1997,7 +1903,6 @@ const make = Effect.gen(function* () {
|
||||
yield* finalizeBufferedProposedPlan({
|
||||
event,
|
||||
threadId: thread.id,
|
||||
threadProposedPlans: proposedPlans,
|
||||
planId: proposedPlanIdForTurn(thread.id, turnId),
|
||||
turnId,
|
||||
updatedAt: now,
|
||||
@@ -2153,8 +2058,17 @@ const make = Effect.gen(function* () {
|
||||
if (event.type === "task.completed") {
|
||||
taskTitle = yield* lookupTaskDescription(thread.id, event.payload.taskId);
|
||||
if (!taskTitle) {
|
||||
const threadDetail = yield* resolveThreadDetail(thread.id, TASK_TITLE_ACTIVITY_KINDS);
|
||||
taskTitle = findTaskTitleInActivities(threadDetail?.activities, event.payload.taskId);
|
||||
const taskActivity = yield* projectionThreadActivityRepository.getLatestTaskActivity({
|
||||
threadId: thread.id,
|
||||
taskId: event.payload.taskId,
|
||||
});
|
||||
taskTitle = findTaskTitleInActivities(
|
||||
Option.match(taskActivity, {
|
||||
onNone: () => undefined,
|
||||
onSome: (activity) => [activity],
|
||||
}),
|
||||
event.payload.taskId,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2172,8 +2086,9 @@ const make = Effect.gen(function* () {
|
||||
DateTime.makeUnsafe(pendingTurnStart.value.requestedAt),
|
||||
)
|
||||
) {
|
||||
const pendingMessage = (yield* getLoadedThreadDetail())?.messages.find(
|
||||
(message) => message.id === pendingTurnStart.value.messageId,
|
||||
const pendingMessage = yield* getThreadMessageById(
|
||||
thread.id,
|
||||
pendingTurnStart.value.messageId,
|
||||
);
|
||||
if (
|
||||
pendingMessage?.role === "user" &&
|
||||
@@ -2192,11 +2107,13 @@ const make = Effect.gen(function* () {
|
||||
(activityEvent.payload.beforeTokens === undefined ||
|
||||
activityEvent.payload.afterTokens === undefined)
|
||||
) {
|
||||
const threadDetail = yield* resolveThreadDetail(thread.id, [
|
||||
"context-window.updated",
|
||||
"context-compaction",
|
||||
]);
|
||||
const tokenCounts = compactedTokenCountsFromActivities(threadDetail?.activities);
|
||||
const activities = yield* projectionThreadActivityRepository.listByThreadId({
|
||||
threadId: thread.id,
|
||||
activityKinds: ["context-window.updated", "context-compaction"],
|
||||
// Preserve the previous thread-detail read's context-history bound.
|
||||
limit: 500,
|
||||
});
|
||||
const tokenCounts = compactedTokenCountsFromActivities(activities);
|
||||
if (tokenCounts) {
|
||||
activityEvent = {
|
||||
...activityEvent,
|
||||
@@ -2274,6 +2191,8 @@ export const ProviderRuntimeIngestionLive = Layer.effect(
|
||||
ProviderRuntimeIngestionService,
|
||||
make,
|
||||
).pipe(
|
||||
Layer.provide(ProjectionTurnRepositoryLive),
|
||||
Layer.provide(ProjectionThreadActivityRepositoryLive),
|
||||
Layer.provide(ProjectionThreadMessageRepositoryLive),
|
||||
Layer.provide(ProjectionThreadProposedPlanRepositoryLive),
|
||||
Layer.provide(ProjectionTurnRepositoryLive),
|
||||
);
|
||||
@@ -1,4 +1,10 @@
|
||||
import { ProjectId, ThreadId, TurnId, ProviderInstanceId } from "@t3tools/contracts";
|
||||
import {
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
ProviderInstanceId,
|
||||
OrchestrationProposedPlanId,
|
||||
} from "@t3tools/contracts";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
@@ -229,6 +235,46 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reads only the requested plan in its thread", () =>
|
||||
Effect.gen(function* () {
|
||||
const plans = yield* ProjectionThreadProposedPlanRepository;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const threadId = ThreadId.make("plan-query-thread");
|
||||
const planId = OrchestrationProposedPlanId.make("plan-query-target");
|
||||
yield* plans.upsert({
|
||||
planId,
|
||||
threadId,
|
||||
turnId: null,
|
||||
planMarkdown: "Keep this plan",
|
||||
implementedAt: "2026-03-01T00:01:00.000Z",
|
||||
implementationThreadId: ThreadId.make("implementation-thread"),
|
||||
createdAt: "2026-03-01T00:00:00.000Z",
|
||||
updatedAt: "2026-03-01T00:01:00.000Z",
|
||||
});
|
||||
// An unrelated old row must not be loaded or decoded by the exact lookup.
|
||||
yield* sql`
|
||||
INSERT INTO projection_thread_proposed_plans (
|
||||
plan_id, thread_id, turn_id, plan_markdown, implemented_at,
|
||||
implementation_thread_id, created_at, updated_at
|
||||
) VALUES (
|
||||
'unrelated-plan', ${threadId}, NULL, '', NULL, NULL,
|
||||
'2026-03-01T00:00:00.000Z', '2026-03-01T00:00:00.000Z'
|
||||
)
|
||||
`;
|
||||
const plan = Option.getOrThrow(yield* plans.getByPlanId({ threadId, planId }));
|
||||
assert.equal(plan.planMarkdown, "Keep this plan");
|
||||
assert.equal(plan.implementedAt, "2026-03-01T00:01:00.000Z");
|
||||
assert.isTrue(
|
||||
Option.isNone(
|
||||
yield* plans.getByPlanId({
|
||||
threadId: ThreadId.make("another-thread"),
|
||||
planId,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("stores SQL NULL for missing project model options", () =>
|
||||
Effect.gen(function* () {
|
||||
const projects = yield* ProjectionProjectRepository;
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
import { EventId, ThreadId } from "@t3tools/contracts";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
import { ProjectionThreadActivityRepository } from "../Services/ProjectionThreadActivities.ts";
|
||||
import { ProjectionThreadActivityRepositoryLive } from "./ProjectionThreadActivities.ts";
|
||||
import { SqlitePersistenceMemory } from "./Sqlite.ts";
|
||||
|
||||
const layer = it.layer(
|
||||
ProjectionThreadActivityRepositoryLive.pipe(Layer.provideMerge(SqlitePersistenceMemory)),
|
||||
);
|
||||
|
||||
layer("ProjectionThreadActivityRepository", (it) => {
|
||||
it.effect("reads only the latest matching task activity", () =>
|
||||
Effect.gen(function* () {
|
||||
const repository = yield* ProjectionThreadActivityRepository;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const threadId = ThreadId.make("thread-latest-task-activity");
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_thread_activities (
|
||||
activity_id, thread_id, turn_id, tone, kind, summary, payload_json, sequence, created_at
|
||||
)
|
||||
VALUES
|
||||
(
|
||||
'activity-task-unrelated-tool', ${threadId}, NULL, 'tool', 'tool.completed',
|
||||
'large tool output', 'not-json', 1, '2026-03-01T00:00:00.000Z'
|
||||
),
|
||||
(
|
||||
'activity-task-started', ${threadId}, NULL, 'info', 'task.started',
|
||||
'started', '{"taskId":"task-1","title":"Initial title"}', 2,
|
||||
'2026-03-01T00:00:01.000Z'
|
||||
),
|
||||
(
|
||||
'activity-task-progress', ${threadId}, NULL, 'info', 'task.progress',
|
||||
'progress', '{"taskId":"task-1","title":"Updated title"}', 3,
|
||||
'2026-03-01T00:00:02.000Z'
|
||||
),
|
||||
(
|
||||
'activity-task-other', ${threadId}, NULL, 'info', 'task.progress',
|
||||
'other', '{"taskId":"task-2","title":"Other title"}', 4,
|
||||
'2026-03-01T00:00:03.000Z'
|
||||
)
|
||||
`;
|
||||
|
||||
yield* repository.upsert({
|
||||
activityId: EventId.make("activity-task-untitled"),
|
||||
threadId,
|
||||
turnId: null,
|
||||
tone: "info",
|
||||
kind: "task.progress",
|
||||
summary: "Still running",
|
||||
payload: { taskId: "task-1" },
|
||||
sequence: 5,
|
||||
createdAt: "2026-03-01T00:00:04.000Z",
|
||||
});
|
||||
yield* repository.upsert({
|
||||
activityId: EventId.make("activity-task-blank-title"),
|
||||
threadId,
|
||||
turnId: null,
|
||||
tone: "info",
|
||||
kind: "task.progress",
|
||||
summary: "Still running",
|
||||
payload: { taskId: "task-1", title: " \t\n\u00a0" },
|
||||
sequence: 6,
|
||||
createdAt: "2026-03-01T00:00:05.000Z",
|
||||
});
|
||||
|
||||
const recent = yield* repository.listByThreadId({
|
||||
threadId,
|
||||
activityKinds: ["task.progress"],
|
||||
limit: 2,
|
||||
});
|
||||
assert.deepEqual(
|
||||
recent.map((entry) => entry.activityId),
|
||||
["activity-task-untitled", "activity-task-blank-title"],
|
||||
);
|
||||
|
||||
const activity = yield* repository.getLatestTaskActivity({
|
||||
threadId,
|
||||
taskId: "task-1",
|
||||
});
|
||||
assert.equal(activity._tag, "Some");
|
||||
if (activity._tag === "Some") {
|
||||
assert.equal(activity.value.activityId, EventId.make("activity-task-progress"));
|
||||
assert.deepEqual(activity.value.payload, {
|
||||
taskId: "task-1",
|
||||
title: "Updated title",
|
||||
});
|
||||
}
|
||||
|
||||
assert.equal(
|
||||
(yield* repository.getLatestTaskActivity({ threadId, taskId: "missing" }))._tag,
|
||||
"None",
|
||||
);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -3,6 +3,7 @@ import * as SqlSchema from "effect/unstable/sql/SqlSchema";
|
||||
import { NonNegativeInt } from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Struct from "effect/Struct";
|
||||
|
||||
@@ -11,6 +12,7 @@ import { toPersistenceDecodeError, toPersistenceSqlError } from "../Errors.ts";
|
||||
import {
|
||||
DeleteProjectionThreadActivitiesInput,
|
||||
ListProjectionThreadActivitiesInput,
|
||||
GetLatestProjectionThreadTaskActivityInput,
|
||||
ProjectionThreadActivity,
|
||||
ProjectionThreadActivityRepository,
|
||||
type ProjectionThreadActivityRepositoryShape,
|
||||
@@ -23,10 +25,10 @@ const ProjectionThreadActivityDbRowSchema = ProjectionThreadActivity.mapFields(
|
||||
}),
|
||||
);
|
||||
|
||||
const mapActivityRows = (
|
||||
rows: ReadonlyArray<Schema.Schema.Type<typeof ProjectionThreadActivityDbRowSchema>>,
|
||||
): ReadonlyArray<ProjectionThreadActivity> =>
|
||||
rows.map((row) => ({
|
||||
function toProjectionThreadActivity(
|
||||
row: Schema.Schema.Type<typeof ProjectionThreadActivityDbRowSchema>,
|
||||
): ProjectionThreadActivity {
|
||||
return {
|
||||
activityId: row.activityId,
|
||||
threadId: row.threadId,
|
||||
turnId: row.turnId,
|
||||
@@ -36,7 +38,8 @@ const mapActivityRows = (
|
||||
payload: row.payload,
|
||||
...(row.sequence !== null ? { sequence: row.sequence } : {}),
|
||||
createdAt: row.createdAt,
|
||||
}));
|
||||
};
|
||||
}
|
||||
|
||||
function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) {
|
||||
return (cause: unknown) =>
|
||||
@@ -45,6 +48,10 @@ function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: st
|
||||
: toPersistenceSqlError(sqlOperation)(cause);
|
||||
}
|
||||
|
||||
// Match String.trim so blank saved titles cannot hide an earlier task name.
|
||||
const taskTitleWhitespace =
|
||||
"\u0009\u000a\u000b\u000c\u000d\u0020\u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000\ufeff";
|
||||
|
||||
const makeProjectionThreadActivityRepository = Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
@@ -90,7 +97,7 @@ const makeProjectionThreadActivityRepository = Effect.gen(function* () {
|
||||
const listProjectionThreadActivityRows = SqlSchema.findAll({
|
||||
Request: ListProjectionThreadActivitiesInput,
|
||||
Result: ProjectionThreadActivityDbRowSchema,
|
||||
execute: ({ threadId }) =>
|
||||
execute: ({ threadId, activityKinds, limit }) =>
|
||||
sql`
|
||||
SELECT
|
||||
activity_id AS "activityId",
|
||||
@@ -102,8 +109,14 @@ const makeProjectionThreadActivityRepository = Effect.gen(function* () {
|
||||
payload_json AS "payload",
|
||||
sequence,
|
||||
created_at AS "createdAt"
|
||||
FROM projection_thread_activities
|
||||
WHERE thread_id = ${threadId}
|
||||
FROM (
|
||||
SELECT *
|
||||
FROM projection_thread_activities
|
||||
WHERE thread_id = ${threadId}
|
||||
${activityKinds === undefined ? sql`` : sql`AND ${sql.in("kind", activityKinds)}`}
|
||||
ORDER BY sequence DESC, created_at DESC, activity_id DESC
|
||||
${limit === undefined ? sql`` : sql`LIMIT ${limit}`}
|
||||
) AS recent_activities
|
||||
ORDER BY
|
||||
CASE WHEN sequence IS NULL THEN 0 ELSE 1 END ASC,
|
||||
sequence ASC,
|
||||
@@ -142,6 +155,40 @@ const makeProjectionThreadActivityRepository = Effect.gen(function* () {
|
||||
`,
|
||||
});
|
||||
|
||||
const getLatestProjectionThreadTaskActivityRow = SqlSchema.findOneOption({
|
||||
Request: GetLatestProjectionThreadTaskActivityInput,
|
||||
Result: ProjectionThreadActivityDbRowSchema,
|
||||
execute: ({ threadId, taskId }) =>
|
||||
sql`
|
||||
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"
|
||||
FROM projection_thread_activities
|
||||
WHERE thread_id = ${threadId}
|
||||
AND kind IN ('task.started', 'task.progress')
|
||||
AND json_extract(payload_json, '$.taskId') = ${taskId}
|
||||
AND length(trim(
|
||||
CASE
|
||||
WHEN json_type(payload_json, '$.title') = 'text'
|
||||
THEN json_extract(payload_json, '$.title')
|
||||
WHEN kind = 'task.started' AND json_type(payload_json, '$.detail') = 'text'
|
||||
THEN json_extract(payload_json, '$.detail')
|
||||
ELSE ''
|
||||
END,
|
||||
${taskTitleWhitespace}
|
||||
)) > 0
|
||||
ORDER BY sequence DESC, created_at DESC, activity_id DESC
|
||||
LIMIT 1
|
||||
`,
|
||||
});
|
||||
|
||||
const deleteProjectionThreadActivityRows = SqlSchema.void({
|
||||
Request: DeleteProjectionThreadActivitiesInput,
|
||||
execute: ({ threadId }) =>
|
||||
@@ -169,7 +216,7 @@ const makeProjectionThreadActivityRepository = Effect.gen(function* () {
|
||||
"ProjectionThreadActivityRepository.listByThreadId:decodeRows",
|
||||
),
|
||||
),
|
||||
Effect.map(mapActivityRows),
|
||||
Effect.map((rows) => rows.map(toProjectionThreadActivity)),
|
||||
);
|
||||
|
||||
const listUserInputLifecycleByThreadId: ProjectionThreadActivityRepositoryShape["listUserInputLifecycleByThreadId"] =
|
||||
@@ -181,9 +228,22 @@ const makeProjectionThreadActivityRepository = Effect.gen(function* () {
|
||||
"ProjectionThreadActivityRepository.listUserInputLifecycleByThreadId:decodeRows",
|
||||
),
|
||||
),
|
||||
Effect.map(mapActivityRows),
|
||||
Effect.map((rows) => rows.map(toProjectionThreadActivity)),
|
||||
);
|
||||
|
||||
const getLatestTaskActivity: ProjectionThreadActivityRepositoryShape["getLatestTaskActivity"] = (
|
||||
input,
|
||||
) =>
|
||||
getLatestProjectionThreadTaskActivityRow(input).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionThreadActivityRepository.getLatestTaskActivity:query",
|
||||
"ProjectionThreadActivityRepository.getLatestTaskActivity:decodeRow",
|
||||
),
|
||||
),
|
||||
Effect.map(Option.map(toProjectionThreadActivity)),
|
||||
);
|
||||
|
||||
const deleteByThreadId: ProjectionThreadActivityRepositoryShape["deleteByThreadId"] = (input) =>
|
||||
deleteProjectionThreadActivityRows(input).pipe(
|
||||
Effect.mapError(
|
||||
@@ -195,6 +255,7 @@ const makeProjectionThreadActivityRepository = Effect.gen(function* () {
|
||||
upsert,
|
||||
listByThreadId,
|
||||
listUserInputLifecycleByThreadId,
|
||||
getLatestTaskActivity,
|
||||
deleteByThreadId,
|
||||
} satisfies ProjectionThreadActivityRepositoryShape;
|
||||
});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { MessageId, ThreadId } from "@t3tools/contracts";
|
||||
import { MessageId, ThreadId, TurnId } from "@t3tools/contracts";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
@@ -231,4 +231,49 @@ layer("ProjectionThreadMessageRepository", (it) => {
|
||||
assert.deepEqual(rows[0]?.attachments, []);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("checks assistant turn state without hydrating message text", () =>
|
||||
Effect.gen(function* () {
|
||||
const repository = yield* ProjectionThreadMessageRepository;
|
||||
const threadId = ThreadId.make("thread-assistant-turn-state");
|
||||
const turnId = TurnId.make("turn-assistant-state");
|
||||
const createdAt = "2026-03-01T00:00:00.000Z";
|
||||
|
||||
yield* repository.upsert({
|
||||
messageId: MessageId.make("message-assistant-turn-state"),
|
||||
threadId,
|
||||
turnId,
|
||||
role: "assistant",
|
||||
text: "large text that the existence query must not select",
|
||||
isStreaming: false,
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
});
|
||||
|
||||
assert.equal(
|
||||
yield* repository.hasAssistantMessageForTurn({
|
||||
threadId,
|
||||
turnId,
|
||||
streamingOnly: false,
|
||||
}),
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
yield* repository.hasAssistantMessageForTurn({
|
||||
threadId,
|
||||
turnId,
|
||||
streamingOnly: true,
|
||||
}),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
yield* repository.hasAssistantMessageForTurn({
|
||||
threadId,
|
||||
turnId: TurnId.make("turn-assistant-state-missing"),
|
||||
streamingOnly: false,
|
||||
}),
|
||||
false,
|
||||
);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -11,6 +11,7 @@ import { toPersistenceSqlError } from "../Errors.ts";
|
||||
import {
|
||||
AppendStreamingProjectionThreadMessage,
|
||||
GetProjectionThreadMessageInput,
|
||||
HasProjectionThreadAssistantMessageInput,
|
||||
ProjectionThreadMessageRepository,
|
||||
type ProjectionThreadMessageRepositoryShape,
|
||||
DeleteProjectionThreadMessagesInput,
|
||||
@@ -24,6 +25,7 @@ const ProjectionThreadMessageDbRowSchema = ProjectionThreadMessage.mapFields(
|
||||
attachments: Schema.NullOr(Schema.fromJsonString(Schema.Array(ChatAttachment))),
|
||||
}),
|
||||
);
|
||||
const ProjectionThreadMessageExistsDbRowSchema = Schema.Struct({ exists: Schema.Number });
|
||||
|
||||
function toProjectionThreadMessage(
|
||||
row: Schema.Schema.Type<typeof ProjectionThreadMessageDbRowSchema>,
|
||||
@@ -161,6 +163,23 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
|
||||
`,
|
||||
});
|
||||
|
||||
const hasProjectionThreadAssistantMessageRow = SqlSchema.findOne({
|
||||
Request: HasProjectionThreadAssistantMessageInput,
|
||||
Result: ProjectionThreadMessageExistsDbRowSchema,
|
||||
execute: ({ threadId, turnId, streamingOnly }) =>
|
||||
sql`
|
||||
SELECT EXISTS (
|
||||
SELECT 1
|
||||
FROM projection_thread_messages
|
||||
WHERE thread_id = ${threadId}
|
||||
AND turn_id = ${turnId}
|
||||
AND role = 'assistant'
|
||||
AND (${streamingOnly ? 1 : 0} = 0 OR is_streaming = 1)
|
||||
LIMIT 1
|
||||
) AS "exists"
|
||||
`,
|
||||
});
|
||||
|
||||
const listProjectionThreadMessageRows = SqlSchema.findAll({
|
||||
Request: ListProjectionThreadMessagesInput,
|
||||
Result: ProjectionThreadMessageDbRowSchema,
|
||||
@@ -224,6 +243,17 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
|
||||
Effect.map(Option.map(toProjectionThreadMessage)),
|
||||
);
|
||||
|
||||
const hasAssistantMessageForTurn: ProjectionThreadMessageRepositoryShape["hasAssistantMessageForTurn"] =
|
||||
(input) =>
|
||||
hasProjectionThreadAssistantMessageRow(input).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlError(
|
||||
"ProjectionThreadMessageRepository.hasAssistantMessageForTurn:query",
|
||||
),
|
||||
),
|
||||
Effect.map((row) => row.exists === 1),
|
||||
);
|
||||
|
||||
const listByThreadId: ProjectionThreadMessageRepositoryShape["listByThreadId"] = (input) =>
|
||||
listProjectionThreadMessageRows(input).pipe(
|
||||
Effect.mapError(
|
||||
@@ -253,6 +283,7 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
|
||||
upsert,
|
||||
appendStreaming,
|
||||
getByMessageId,
|
||||
hasAssistantMessageForTurn,
|
||||
listByThreadId,
|
||||
getLatestUserMessageAt,
|
||||
deleteByThreadId,
|
||||
|
||||
@@ -8,6 +8,7 @@ import { toPersistenceSqlError } from "../Errors.ts";
|
||||
import {
|
||||
DeleteProjectionThreadProposedPlansInput,
|
||||
HasActionableProjectionThreadProposedPlanInput,
|
||||
GetProjectionThreadProposedPlanInput,
|
||||
ListProjectionThreadProposedPlansInput,
|
||||
ProjectionThreadProposedPlan,
|
||||
ProjectionThreadProposedPlanRepository,
|
||||
@@ -52,6 +53,24 @@ const makeProjectionThreadProposedPlanRepository = Effect.gen(function* () {
|
||||
`,
|
||||
});
|
||||
|
||||
const getProjectionThreadProposedPlanRow = SqlSchema.findOneOption({
|
||||
Request: GetProjectionThreadProposedPlanInput,
|
||||
Result: ProjectionThreadProposedPlan,
|
||||
execute: ({ threadId, planId }) => sql`
|
||||
SELECT
|
||||
plan_id AS "planId",
|
||||
thread_id AS "threadId",
|
||||
turn_id AS "turnId",
|
||||
plan_markdown AS "planMarkdown",
|
||||
implemented_at AS "implementedAt",
|
||||
implementation_thread_id AS "implementationThreadId",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt"
|
||||
FROM projection_thread_proposed_plans
|
||||
WHERE thread_id = ${threadId} AND plan_id = ${planId}
|
||||
`,
|
||||
});
|
||||
|
||||
const listProjectionThreadProposedPlanRows = SqlSchema.findAll({
|
||||
Request: ListProjectionThreadProposedPlansInput,
|
||||
Result: ProjectionThreadProposedPlan,
|
||||
@@ -133,6 +152,13 @@ const makeProjectionThreadProposedPlanRepository = Effect.gen(function* () {
|
||||
Effect.mapError(toPersistenceSqlError("ProjectionThreadProposedPlanRepository.upsert:query")),
|
||||
);
|
||||
|
||||
const getByPlanId: ProjectionThreadProposedPlanRepositoryShape["getByPlanId"] = (input) =>
|
||||
getProjectionThreadProposedPlanRow(input).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlError("ProjectionThreadProposedPlanRepository.getByPlanId:query"),
|
||||
),
|
||||
);
|
||||
|
||||
const listByThreadId: ProjectionThreadProposedPlanRepositoryShape["listByThreadId"] = (input) =>
|
||||
listProjectionThreadProposedPlanRows(input).pipe(
|
||||
Effect.mapError(
|
||||
@@ -153,6 +179,7 @@ const makeProjectionThreadProposedPlanRepository = Effect.gen(function* () {
|
||||
upsert,
|
||||
listByThreadId,
|
||||
hasActionableByThreadId,
|
||||
getByPlanId,
|
||||
deleteByThreadId,
|
||||
} satisfies ProjectionThreadProposedPlanRepositoryShape;
|
||||
});
|
||||
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Context from "effect/Context";
|
||||
import type * as Effect from "effect/Effect";
|
||||
import type * as Option from "effect/Option";
|
||||
|
||||
import type { ProjectionRepositoryError } from "../Errors.ts";
|
||||
|
||||
@@ -35,9 +36,18 @@ export type ProjectionThreadActivity = typeof ProjectionThreadActivity.Type;
|
||||
|
||||
export const ListProjectionThreadActivitiesInput = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
activityKinds: Schema.optional(Schema.Array(Schema.String)),
|
||||
limit: Schema.optional(NonNegativeInt),
|
||||
});
|
||||
export type ListProjectionThreadActivitiesInput = typeof ListProjectionThreadActivitiesInput.Type;
|
||||
|
||||
export const GetLatestProjectionThreadTaskActivityInput = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
taskId: Schema.String,
|
||||
});
|
||||
export type GetLatestProjectionThreadTaskActivityInput =
|
||||
typeof GetLatestProjectionThreadTaskActivityInput.Type;
|
||||
|
||||
export const DeleteProjectionThreadActivitiesInput = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
});
|
||||
@@ -61,7 +71,7 @@ export interface ProjectionThreadActivityRepositoryShape {
|
||||
* List projected thread activity rows for a thread.
|
||||
*
|
||||
* Returned in ascending runtime sequence order (or creation order when
|
||||
* sequence is unavailable).
|
||||
* sequence is unavailable). A limit selects the newest matching rows.
|
||||
*/
|
||||
readonly listByThreadId: (
|
||||
input: ListProjectionThreadActivitiesInput,
|
||||
@@ -76,6 +86,13 @@ export interface ProjectionThreadActivityRepositoryShape {
|
||||
input: ListProjectionThreadActivitiesInput,
|
||||
) => Effect.Effect<ReadonlyArray<ProjectionThreadActivity>, ProjectionRepositoryError>;
|
||||
|
||||
/**
|
||||
* Read the latest task-start or task-progress activity with a usable title.
|
||||
*/
|
||||
readonly getLatestTaskActivity: (
|
||||
input: GetLatestProjectionThreadTaskActivityInput,
|
||||
) => Effect.Effect<Option.Option<ProjectionThreadActivity>, ProjectionRepositoryError>;
|
||||
|
||||
/**
|
||||
* Delete projected thread activity rows by thread.
|
||||
*/
|
||||
|
||||
@@ -51,6 +51,14 @@ export const GetProjectionThreadMessageInput = Schema.Struct({
|
||||
});
|
||||
export type GetProjectionThreadMessageInput = typeof GetProjectionThreadMessageInput.Type;
|
||||
|
||||
export const HasProjectionThreadAssistantMessageInput = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
turnId: TurnId,
|
||||
streamingOnly: Schema.Boolean,
|
||||
});
|
||||
export type HasProjectionThreadAssistantMessageInput =
|
||||
typeof HasProjectionThreadAssistantMessageInput.Type;
|
||||
|
||||
export const DeleteProjectionThreadMessagesInput = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
});
|
||||
@@ -81,6 +89,13 @@ export interface ProjectionThreadMessageRepositoryShape {
|
||||
input: GetProjectionThreadMessageInput,
|
||||
) => Effect.Effect<Option.Option<ProjectionThreadMessage>, ProjectionRepositoryError>;
|
||||
|
||||
/**
|
||||
* Check for an assistant message in a turn without hydrating message text.
|
||||
*/
|
||||
readonly hasAssistantMessageForTurn: (
|
||||
input: HasProjectionThreadAssistantMessageInput,
|
||||
) => Effect.Effect<boolean, ProjectionRepositoryError>;
|
||||
|
||||
/**
|
||||
* List projected thread messages for a thread.
|
||||
*
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Context from "effect/Context";
|
||||
import type * as Effect from "effect/Effect";
|
||||
import type * as Option from "effect/Option";
|
||||
|
||||
import type { ProjectionRepositoryError } from "../Errors.ts";
|
||||
|
||||
@@ -36,6 +37,12 @@ export const HasActionableProjectionThreadProposedPlanInput = Schema.Struct({
|
||||
export type HasActionableProjectionThreadProposedPlanInput =
|
||||
typeof HasActionableProjectionThreadProposedPlanInput.Type;
|
||||
|
||||
export const GetProjectionThreadProposedPlanInput = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
planId: OrchestrationProposedPlanId,
|
||||
});
|
||||
export type GetProjectionThreadProposedPlanInput = typeof GetProjectionThreadProposedPlanInput.Type;
|
||||
|
||||
export const DeleteProjectionThreadProposedPlansInput = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
});
|
||||
@@ -46,6 +53,10 @@ export interface ProjectionThreadProposedPlanRepositoryShape {
|
||||
readonly upsert: (
|
||||
proposedPlan: ProjectionThreadProposedPlan,
|
||||
) => Effect.Effect<void, ProjectionRepositoryError>;
|
||||
/** Read one plan without loading the thread's other plans. */
|
||||
readonly getByPlanId: (
|
||||
input: GetProjectionThreadProposedPlanInput,
|
||||
) => Effect.Effect<Option.Option<ProjectionThreadProposedPlan>, ProjectionRepositoryError>;
|
||||
readonly listByThreadId: (
|
||||
input: ListProjectionThreadProposedPlansInput,
|
||||
) => Effect.Effect<ReadonlyArray<ProjectionThreadProposedPlan>, ProjectionRepositoryError>;
|
||||
|
||||
Reference in new issue
Block a user