Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
83b003fa98 | ||
|
|
f483b694c0 | ||
|
|
dbd8189dca | ||
|
|
b56272397e |
No files matched your search
@@ -1177,6 +1177,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
|
||||
const eventStore = yield* OrchestrationEventStore;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
const streamingAt = "2026-01-01T00:00:01.000Z";
|
||||
|
||||
yield* eventStore.append({
|
||||
type: "project.created",
|
||||
@@ -1254,7 +1255,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
|
||||
eventId: EventId.make("evt-a4"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.make("thread-a"),
|
||||
occurredAt: now,
|
||||
occurredAt: streamingAt,
|
||||
commandId: CommandId.make("cmd-a4"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-a4"),
|
||||
@@ -1266,8 +1267,8 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
|
||||
text: " world",
|
||||
turnId: null,
|
||||
streaming: true,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
createdAt: streamingAt,
|
||||
updatedAt: streamingAt,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1279,6 +1280,13 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
|
||||
`;
|
||||
assert.deepEqual(messageRows, [{ text: "hello world" }]);
|
||||
|
||||
const threadRows = yield* sql<{ readonly updatedAt: string }>`
|
||||
SELECT updated_at AS "updatedAt"
|
||||
FROM projection_threads
|
||||
WHERE thread_id = 'thread-a'
|
||||
`;
|
||||
assert.deepEqual(threadRows, [{ updatedAt: streamingAt }]);
|
||||
|
||||
const stateRows = yield* sql<{
|
||||
readonly projector: string;
|
||||
readonly lastAppliedSequence: number;
|
||||
|
||||
@@ -842,7 +842,30 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
return;
|
||||
}
|
||||
|
||||
case "thread.message-sent":
|
||||
case "thread.message-sent": {
|
||||
// The thread websocket already carries the incremental message event.
|
||||
// Keep activity ordering current without rebuilding the list-view shell.
|
||||
if (event.payload.role === "assistant" && event.payload.streaming) {
|
||||
yield* projectionThreadRepository.touchUpdatedAt({
|
||||
threadId: event.payload.threadId,
|
||||
updatedAt: event.occurredAt,
|
||||
});
|
||||
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.activity-appended":
|
||||
case "thread.approval-response-requested":
|
||||
@@ -942,22 +965,31 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
)(function* (event, attachmentSideEffects) {
|
||||
switch (event.type) {
|
||||
case "thread.message-sent": {
|
||||
if (event.payload.streaming) {
|
||||
const attachments =
|
||||
event.payload.attachments !== undefined
|
||||
? yield* materializeAttachmentsForProjection({
|
||||
attachments: event.payload.attachments,
|
||||
})
|
||||
: undefined;
|
||||
yield* projectionThreadMessageRepository.appendStreaming({
|
||||
messageId: event.payload.messageId,
|
||||
threadId: event.payload.threadId,
|
||||
turnId: event.payload.turnId,
|
||||
role: event.payload.role,
|
||||
text: event.payload.text,
|
||||
...(attachments !== undefined ? { attachments: [...attachments] } : {}),
|
||||
isStreaming: true,
|
||||
createdAt: event.payload.createdAt,
|
||||
updatedAt: event.payload.updatedAt,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const existingMessage = yield* projectionThreadMessageRepository.getByMessageId({
|
||||
messageId: event.payload.messageId,
|
||||
});
|
||||
const previousMessage = Option.getOrUndefined(existingMessage);
|
||||
const nextText = Option.match(existingMessage, {
|
||||
onNone: () => event.payload.text,
|
||||
onSome: (message) => {
|
||||
if (event.payload.streaming) {
|
||||
return `${message.text}${event.payload.text}`;
|
||||
}
|
||||
if (event.payload.text.length === 0) {
|
||||
return message.text;
|
||||
}
|
||||
return event.payload.text;
|
||||
},
|
||||
});
|
||||
const nextAttachments =
|
||||
event.payload.attachments !== undefined
|
||||
? yield* materializeAttachmentsForProjection({
|
||||
@@ -969,9 +1001,10 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
threadId: event.payload.threadId,
|
||||
turnId: event.payload.turnId,
|
||||
role: event.payload.role,
|
||||
text: nextText,
|
||||
text:
|
||||
event.payload.text.length === 0 ? (previousMessage?.text ?? "") : event.payload.text,
|
||||
...(nextAttachments !== undefined ? { attachments: [...nextAttachments] } : {}),
|
||||
isStreaming: event.payload.streaming,
|
||||
isStreaming: false,
|
||||
createdAt: previousMessage?.createdAt ?? event.payload.createdAt,
|
||||
updatedAt: event.payload.updatedAt,
|
||||
});
|
||||
@@ -1293,8 +1326,21 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
if (event.payload.turnId === null || event.payload.role !== "assistant") {
|
||||
return;
|
||||
}
|
||||
const existingTurn = yield* projectionTurnRepository.getByTurnId({
|
||||
threadId: event.payload.threadId,
|
||||
turnId: event.payload.turnId,
|
||||
});
|
||||
// The first chunk attaches the assistant message to the turn. Later
|
||||
// chunks do not change turn state, so avoid rewriting it per token.
|
||||
if (
|
||||
event.payload.streaming &&
|
||||
Option.isSome(existingTurn) &&
|
||||
existingTurn.value.assistantMessageId === event.payload.messageId
|
||||
) {
|
||||
return;
|
||||
}
|
||||
// A completed assistant message only settles the turn once the
|
||||
// session is no longer running it — providers may emit several
|
||||
// session is no longer running it. Providers may emit several
|
||||
// assistant messages per turn (commentary between tool calls), and
|
||||
// the turn must stay unsettled until the provider reports turn end
|
||||
// (projected as thread.session-set leaving the "running" status).
|
||||
@@ -1306,10 +1352,6 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
session.value.status === "running" &&
|
||||
session.value.activeTurnId === event.payload.turnId;
|
||||
const settlesTurn = !event.payload.streaming && !turnStillRunning;
|
||||
const existingTurn = yield* projectionTurnRepository.getByTurnId({
|
||||
threadId: event.payload.threadId,
|
||||
turnId: event.payload.turnId,
|
||||
});
|
||||
if (Option.isSome(existingTurn)) {
|
||||
yield* projectionTurnRepository.upsertByTurnId({
|
||||
...existingTurn.value,
|
||||
@@ -1686,18 +1728,51 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
),
|
||||
);
|
||||
|
||||
const projectEvent: OrchestrationProjectionPipelineShape["projectEvent"] = (event) =>
|
||||
Effect.forEach(projectors, (projector) => runProjectorForEvent(projector, event), {
|
||||
concurrency: 1,
|
||||
}).pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(Path.Path, path),
|
||||
Effect.provideService(ServerConfig, serverConfig),
|
||||
Effect.asVoid,
|
||||
Effect.catchTag("SqlError", (sqlError) =>
|
||||
Effect.fail(toPersistenceSqlError("ProjectionPipeline.projectEvent:query")(sqlError)),
|
||||
),
|
||||
);
|
||||
const projectEvent: OrchestrationProjectionPipelineShape["projectEvent"] = (event) => {
|
||||
const attachmentSideEffects: AttachmentSideEffects = {
|
||||
deletedThreadIds: new Set<string>(),
|
||||
prunedThreadRelativePaths: new Map<string, Set<string>>(),
|
||||
};
|
||||
|
||||
return sql
|
||||
.withTransaction(
|
||||
Effect.forEach(
|
||||
projectors,
|
||||
(projector) =>
|
||||
projector.apply(event, attachmentSideEffects).pipe(
|
||||
Effect.flatMap(() =>
|
||||
projectionStateRepository.upsert({
|
||||
projector: projector.name,
|
||||
lastAppliedSequence: event.sequence,
|
||||
updatedAt: event.occurredAt,
|
||||
}),
|
||||
),
|
||||
),
|
||||
{ concurrency: 1 },
|
||||
),
|
||||
)
|
||||
.pipe(
|
||||
Effect.flatMap(() =>
|
||||
runAttachmentSideEffects(attachmentSideEffects).pipe(
|
||||
Effect.catch((cause) =>
|
||||
Effect.logWarning("failed to apply projected attachment side-effects", {
|
||||
sequence: event.sequence,
|
||||
eventType: event.type,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(Path.Path, path),
|
||||
Effect.provideService(ServerConfig, serverConfig),
|
||||
Effect.asVoid,
|
||||
Effect.catchTags({
|
||||
SqlError: (sqlError) =>
|
||||
Effect.fail(toPersistenceSqlError("ProjectionPipeline.projectEvent:query")(sqlError)),
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
const bootstrap: OrchestrationProjectionPipelineShape["bootstrap"] = Effect.forEach(
|
||||
projectors,
|
||||
|
||||
@@ -66,6 +66,45 @@ layer("ProjectionThreadMessageRepository", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("atomically appends streaming text and preserves the original creation time", () =>
|
||||
Effect.gen(function* () {
|
||||
const repository = yield* ProjectionThreadMessageRepository;
|
||||
const threadId = ThreadId.make("thread-streaming-append");
|
||||
const messageId = MessageId.make("message-streaming-append");
|
||||
const createdAt = "2026-02-28T19:05:00.000Z";
|
||||
|
||||
yield* repository.appendStreaming({
|
||||
messageId,
|
||||
threadId,
|
||||
turnId: null,
|
||||
role: "assistant",
|
||||
text: "hello",
|
||||
isStreaming: true,
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
});
|
||||
yield* repository.appendStreaming({
|
||||
messageId,
|
||||
threadId,
|
||||
turnId: null,
|
||||
role: "assistant",
|
||||
text: " world",
|
||||
isStreaming: true,
|
||||
createdAt: "2026-02-28T19:05:01.000Z",
|
||||
updatedAt: "2026-02-28T19:05:01.000Z",
|
||||
});
|
||||
|
||||
const row = yield* repository.getByMessageId({ messageId });
|
||||
assert.equal(row._tag, "Some");
|
||||
if (row._tag === "Some") {
|
||||
assert.equal(row.value.text, "hello world");
|
||||
assert.equal(row.value.createdAt, createdAt);
|
||||
assert.equal(row.value.updatedAt, "2026-02-28T19:05:01.000Z");
|
||||
assert.isTrue(row.value.isStreaming);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("allows explicit attachment clearing with an empty array", () =>
|
||||
Effect.gen(function* () {
|
||||
const repository = yield* ProjectionThreadMessageRepository;
|
||||
|
||||
@@ -95,6 +95,50 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
|
||||
},
|
||||
});
|
||||
|
||||
const appendStreamingProjectionThreadMessageRow = SqlSchema.void({
|
||||
Request: ProjectionThreadMessage,
|
||||
execute: (row) => {
|
||||
const nextAttachmentsJson =
|
||||
row.attachments !== undefined ? JSON.stringify(row.attachments) : null;
|
||||
return sql`
|
||||
INSERT INTO projection_thread_messages (
|
||||
message_id,
|
||||
thread_id,
|
||||
turn_id,
|
||||
role,
|
||||
text,
|
||||
attachments_json,
|
||||
is_streaming,
|
||||
created_at,
|
||||
updated_at
|
||||
)
|
||||
VALUES (
|
||||
${row.messageId},
|
||||
${row.threadId},
|
||||
${row.turnId},
|
||||
${row.role},
|
||||
${row.text},
|
||||
${nextAttachmentsJson},
|
||||
1,
|
||||
${row.createdAt},
|
||||
${row.updatedAt}
|
||||
)
|
||||
ON CONFLICT (message_id)
|
||||
DO UPDATE SET
|
||||
thread_id = excluded.thread_id,
|
||||
turn_id = excluded.turn_id,
|
||||
role = excluded.role,
|
||||
text = projection_thread_messages.text || excluded.text,
|
||||
attachments_json = COALESCE(
|
||||
excluded.attachments_json,
|
||||
projection_thread_messages.attachments_json
|
||||
),
|
||||
is_streaming = 1,
|
||||
updated_at = excluded.updated_at
|
||||
`;
|
||||
},
|
||||
});
|
||||
|
||||
const getProjectionThreadMessageRow = SqlSchema.findOneOption({
|
||||
Request: GetProjectionThreadMessageInput,
|
||||
Result: ProjectionThreadMessageDbRowSchema,
|
||||
@@ -151,6 +195,13 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
|
||||
Effect.mapError(toPersistenceSqlError("ProjectionThreadMessageRepository.upsert:query")),
|
||||
);
|
||||
|
||||
const appendStreaming: ProjectionThreadMessageRepositoryShape["appendStreaming"] = (row) =>
|
||||
appendStreamingProjectionThreadMessageRow(row).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlError("ProjectionThreadMessageRepository.appendStreaming:query"),
|
||||
),
|
||||
);
|
||||
|
||||
const getByMessageId: ProjectionThreadMessageRepositoryShape["getByMessageId"] = (input) =>
|
||||
getProjectionThreadMessageRow(input).pipe(
|
||||
Effect.mapError(
|
||||
@@ -176,6 +227,7 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
|
||||
|
||||
return {
|
||||
upsert,
|
||||
appendStreaming,
|
||||
getByMessageId,
|
||||
listByThreadId,
|
||||
deleteByThreadId,
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
ListProjectionThreadsByProjectInput,
|
||||
ProjectionThread,
|
||||
ProjectionThreadRepository,
|
||||
TouchProjectionThreadInput,
|
||||
type ProjectionThreadRepositoryShape,
|
||||
} from "../Services/ProjectionThreads.ts";
|
||||
import { ModelSelection } from "@t3tools/contracts";
|
||||
@@ -149,6 +150,16 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
`,
|
||||
});
|
||||
|
||||
const touchProjectionThreadRow = SqlSchema.void({
|
||||
Request: TouchProjectionThreadInput,
|
||||
execute: ({ threadId, updatedAt }) =>
|
||||
sql`
|
||||
UPDATE projection_threads
|
||||
SET updated_at = ${updatedAt}
|
||||
WHERE thread_id = ${threadId}
|
||||
`,
|
||||
});
|
||||
|
||||
const listProjectionThreadRows = SqlSchema.findAll({
|
||||
Request: ListProjectionThreadsByProjectInput,
|
||||
Result: ProjectionThreadDbRow,
|
||||
@@ -205,6 +216,11 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
Effect.mapError(toPersistenceSqlError("ProjectionThreadRepository.getById:query")),
|
||||
);
|
||||
|
||||
const touchUpdatedAt: ProjectionThreadRepositoryShape["touchUpdatedAt"] = (input) =>
|
||||
touchProjectionThreadRow(input).pipe(
|
||||
Effect.mapError(toPersistenceSqlError("ProjectionThreadRepository.touchUpdatedAt:query")),
|
||||
);
|
||||
|
||||
const listByProjectId: ProjectionThreadRepositoryShape["listByProjectId"] = (input) =>
|
||||
listProjectionThreadRows(input).pipe(
|
||||
Effect.mapError(toPersistenceSqlError("ProjectionThreadRepository.listByProjectId:query")),
|
||||
@@ -218,6 +234,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
return {
|
||||
upsert,
|
||||
getById,
|
||||
touchUpdatedAt,
|
||||
listByProjectId,
|
||||
deleteById,
|
||||
} satisfies ProjectionThreadRepositoryShape;
|
||||
|
||||
@@ -62,6 +62,13 @@ export interface ProjectionThreadMessageRepositoryShape {
|
||||
message: ProjectionThreadMessage,
|
||||
) => Effect.Effect<void, ProjectionRepositoryError>;
|
||||
|
||||
/**
|
||||
* Insert a streaming message or atomically append text to its existing row.
|
||||
*/
|
||||
readonly appendStreaming: (
|
||||
message: ProjectionThreadMessage,
|
||||
) => Effect.Effect<void, ProjectionRepositoryError>;
|
||||
|
||||
/**
|
||||
* Read a projected thread message by id.
|
||||
*/
|
||||
|
||||
@@ -63,6 +63,12 @@ export const DeleteProjectionThreadInput = Schema.Struct({
|
||||
});
|
||||
export type DeleteProjectionThreadInput = typeof DeleteProjectionThreadInput.Type;
|
||||
|
||||
export const TouchProjectionThreadInput = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
updatedAt: IsoDateTime,
|
||||
});
|
||||
export type TouchProjectionThreadInput = typeof TouchProjectionThreadInput.Type;
|
||||
|
||||
export const ListProjectionThreadsByProjectInput = Schema.Struct({
|
||||
projectId: ProjectId,
|
||||
});
|
||||
@@ -86,6 +92,11 @@ export interface ProjectionThreadRepositoryShape {
|
||||
input: GetProjectionThreadInput,
|
||||
) => Effect.Effect<Option.Option<ProjectionThread>, ProjectionRepositoryError>;
|
||||
|
||||
/** Update only the activity timestamp without rewriting the thread shell. */
|
||||
readonly touchUpdatedAt: (
|
||||
input: TouchProjectionThreadInput,
|
||||
) => Effect.Effect<void, ProjectionRepositoryError>;
|
||||
|
||||
/**
|
||||
* List projected threads for a project.
|
||||
*
|
||||
|
||||
@@ -21,3 +21,15 @@ it.effect("proves a root is parked before returning and releases it with one gat
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("lets an unparked child start before returning", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const started = yield* Deferred.make<void>();
|
||||
|
||||
yield* forkParked(Deferred.succeed(started, undefined));
|
||||
|
||||
expect(yield* Deferred.isDone(started)).toBe(true);
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -16,6 +16,9 @@ export const forkParked = <A, E, R>(
|
||||
const activation = yield* ServerActivation;
|
||||
if (activation === undefined) {
|
||||
yield* Effect.forkScoped(effect);
|
||||
// Let the child reach its first suspension point before startup continues.
|
||||
// Hot-stream consumers use this turn to establish their subscription.
|
||||
yield* Effect.yieldNow;
|
||||
return;
|
||||
}
|
||||
const parked = yield* Deferred.make<void>();
|
||||
|
||||
Reference in new issue
Block a user