feat(chat): attach files to question answers (#9871)

This commit is contained in:
shivam authored and GitHub committed 2026-09-08 12:13:38 +05:30
1 parent 349ce30142
commit 7220dfe2c9
40 files changed
+2315 -153

No files matched your search

@@ -215,6 +215,7 @@ export const make = Effect.gen(function* () {
repositoryIdentity: true,
connectionProbe: true,
attachmentUploads: true,
questionAttachments: true,
fileAttachments: { maxUploadBytes: PROVIDER_SEND_TURN_MAX_FILE_BYTES },
pullRequests: true,
threadSettlement: true,
@@ -239,6 +239,17 @@ describe("OrchestrationEngine", () => {
threadId,
requestId,
answers: { "0": "pnpm", "1": "Example" },
attachmentsByQuestionId: {
"1": [
{
type: "file" as const,
id: "thread-1-00000000-0000-4000-8000-0000000000aa-txt",
name: "spec.txt",
mimeType: "text/plain",
sizeBytes: 4,
},
],
},
createdAt: "2026-01-01T00:00:02.000Z",
};
await expect(
@@ -256,8 +267,9 @@ describe("OrchestrationEngine", () => {
(message) => message.role === "user",
);
expect(userMessages).toHaveLength(1);
expect(userMessages?.[0]?.attachments).toEqual(response.attachmentsByQuestionId["1"]);
expect(userMessages?.[0]?.text).toBe(
"Which package manager?\npnpm\n\nWhat should it be named?\nExample",
"Which package manager?\npnpm\n\nWhat should it be named?\nExample\nAttached file: spec.txt (thread-1-00000000-0000-4000-8000-0000000000aa-txt)",
);
expect(
after.threads[0]?.activities.find((activity) => activity.kind === "user-input.resolved")
@@ -411,7 +411,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
FROM projection_state
ORDER BY projector ASC
`;
assert.equal(stateRows.length, Object.keys(ORCHESTRATION_PROJECTOR_NAMES).length);
assert.equal(stateRows.length, Object.keys(ORCHESTRATION_PROJECTOR_NAMES).length + 1);
for (const row of stateRows) {
assert.equal(row.lastAppliedSequence, 3);
}
@@ -1164,14 +1164,18 @@ it.layer(
yield* projectionPipeline.bootstrap;
yield* projectionPipeline.bootstrap;
assert.deepEqual(
yield* projectionState.listAll(),
cursorsBeforeFailure.map((cursor) => ({
assert.deepEqual(yield* projectionState.listAll(), [
{
projector: "projection.attachment-cleanup",
lastAppliedSequence: pendingEvent.sequence,
updatedAt: pendingEvent.occurredAt,
},
...cursorsBeforeFailure.map((cursor) => ({
...cursor,
lastAppliedSequence: pendingEvent.sequence,
updatedAt: pendingEvent.occurredAt,
})),
);
]);
const replayedMessages = yield* sql<{ readonly text: string }>`
SELECT text FROM projection_thread_messages WHERE message_id = 'message-rollback'
`;
@@ -1364,10 +1368,53 @@ it.layer(
},
});
const answerKeepId = "thread-revert-files-00000000-0000-4000-8000-000000000006-txt";
const answerRemoveId = "thread-revert-files-00000000-0000-4000-8000-000000000007-txt";
for (const [id, turnId] of [
[answerKeepId, "turn-keep"],
[answerRemoveId, "turn-remove"],
] as const) {
yield* appendAndProject({
type: "thread.activity-appended",
eventId: EventId.make(`answer-${id}`),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: now,
commandId: CommandId.make(`answer-${id}`),
causationEventId: null,
correlationId: CorrelationId.make(`answer-${id}`),
metadata: {},
payload: {
threadId,
activity: {
id: EventId.make(`answer-${id}`),
kind: "user-input.answer-submitted",
tone: "info",
summary: "Answer with file",
createdAt: now,
turnId: TurnId.make(turnId),
payload: {
requestId: ApprovalRequestId.make(id),
answers: { q: "See file" },
attachmentsByQuestionId: {
q: [
{ type: "file", id, name: "answer.txt", mimeType: "text/plain", sizeBytes: 6 },
],
},
},
},
},
});
}
const keepPath = path.join(attachmentsDir, `${keepAttachmentId}.png`);
const keepFilePath = path.join(attachmentsDir, `${keepFileAttachmentId}.pdf`);
const removePath = path.join(attachmentsDir, `${removeAttachmentId}.png`);
yield* fileSystem.makeDirectory(attachmentsDir, { recursive: true });
yield* fileSystem.writeFileString(path.join(attachmentsDir, `${answerKeepId}.txt`), "answer");
yield* fileSystem.writeFileString(
path.join(attachmentsDir, `${answerRemoveId}.txt`),
"answer",
);
yield* fileSystem.writeFileString(keepPath, "keep");
yield* fileSystem.writeFileString(keepFilePath, "keep");
yield* fileSystem.writeFileString(removePath, "remove");
@@ -1460,9 +1507,33 @@ it.layer(
assert.isTrue(yield* exists(keepPath));
assert.isTrue(yield* exists(keepFilePath));
assert.isTrue(yield* exists(path.join(attachmentsDir, `${answerKeepId}.txt`)));
assert.isFalse(yield* exists(path.join(attachmentsDir, `${answerRemoveId}.txt`)));
assert.isFalse(yield* exists(removePath));
assert.isTrue(yield* exists(laterPath));
assert.isTrue(yield* exists(otherThreadPath));
// Replay message and activity history from different cursors, as during a projection rebuild.
yield* sql`DELETE FROM projection_thread_messages WHERE thread_id = ${threadId}`;
yield* sql`DELETE FROM projection_thread_activities WHERE thread_id = ${threadId}`;
yield* sql`UPDATE projection_state SET last_applied_sequence = 0
WHERE projector IN ('projection.thread-messages', 'projection.thread-activities', 'projection.threads')`;
yield* fileSystem.writeFileString(removePath, "remove");
yield* fileSystem.writeFileString(
path.join(attachmentsDir, `${answerRemoveId}.txt`),
"answer",
);
yield* sql`CREATE TRIGGER fail_bootstrap_thread BEFORE UPDATE ON projection_threads
BEGIN SELECT RAISE(FAIL, 'forced bootstrap failure'); END`;
yield* projectionPipeline.bootstrap.pipe(Effect.flip);
assert.isTrue(yield* exists(removePath));
yield* sql`DROP TRIGGER fail_bootstrap_thread`;
yield* projectionPipeline.bootstrap;
assert.isTrue(yield* exists(keepPath));
assert.isTrue(yield* exists(laterPath));
assert.isTrue(yield* exists(path.join(attachmentsDir, `${answerKeepId}.txt`)));
assert.isFalse(yield* exists(removePath));
assert.isFalse(yield* exists(path.join(attachmentsDir, `${answerRemoveId}.txt`)));
}),
);
});
@@ -1934,6 +2005,15 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
},
});
yield* sql`CREATE TRIGGER fail_later_stream_projector BEFORE UPDATE ON projection_state
WHEN NEW.projector = 'projection.threads'
BEGIN SELECT RAISE(FAIL, 'forced later projector failure'); END`;
yield* projectionPipeline.bootstrap.pipe(Effect.flip);
const committedMessage = yield* sql<{ readonly text: string }>`
SELECT text FROM projection_thread_messages WHERE message_id = 'message-a'
`;
assert.deepEqual(committedMessage, [{ text: "hello world" }]);
yield* sql`DROP TRIGGER fail_later_stream_projector`;
yield* projectionPipeline.bootstrap;
yield* projectionPipeline.bootstrap;
@@ -3884,7 +3964,7 @@ const engineLayer = it.layer(
Layer.provideMerge(OrchestrationProjectionSnapshotQueryLive),
Layer.provide(ThreadBackgroundLiveness.layer),
Layer.provide(ThreadPlanProgress.layer),
Layer.provide(OrchestrationProjectionPipelineLive),
Layer.provideMerge(OrchestrationProjectionPipelineLive),
Layer.provide(OrchestrationEventStoreLive),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
Layer.provide(RepositoryIdentityResolver.layer),
@@ -4236,7 +4316,10 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => {
yield* readCursors,
cursorsBeforeFailure.map((cursor) => ({
...cursor,
lastAppliedSequence: result.sequence,
lastAppliedSequence:
cursor.projector === "projection.attachment-cleanup"
? cursor.lastAppliedSequence
: result.sequence,
})),
);
assert.isFalse(yield* exists(attachmentPath));
@@ -4266,6 +4349,25 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => {
WHERE command_id = ${cleanupFailureCommandId}
`;
assert.deepEqual(cleanupFailureReceipts, [{ status: "accepted" }]);
const pipeline = yield* OrchestrationProjectionPipeline;
const cleanupCursor = sql<{ readonly lastAppliedSequence: number }>`
SELECT last_applied_sequence AS "lastAppliedSequence" FROM projection_state
WHERE projector = 'projection.attachment-cleanup'
`;
const cursorBeforeRetry = yield* cleanupCursor;
yield* pipeline.bootstrap;
assert.deepEqual(yield* cleanupCursor, cursorBeforeRetry);
assert.isTrue(yield* exists(blockedAttachmentPath));
yield* fileSystem.remove(blockedAttachmentPath, { recursive: true });
yield* fileSystem.writeFileString(blockedAttachmentPath, "retry this attachment");
yield* pipeline.bootstrap;
assert.isFalse(yield* exists(blockedAttachmentPath));
assert.isAbove(
(yield* cleanupCursor)[0]!.lastAppliedSequence,
cursorBeforeRetry[0]!.lastAppliedSequence,
);
}),
);
});
@@ -1,6 +1,7 @@
import {
ApprovalRequestId,
isImportedAgentSessionMessageId,
UserInputAttachmentAnswerPayload,
type ChatAttachment,
type OrchestrationEvent,
type OrchestrationSessionStatus,
@@ -12,6 +13,7 @@ import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import * as SqlClient from "effect/unstable/sql/SqlClient";
@@ -327,6 +329,8 @@ function retainProjectionProposedPlansAfterRevert(
);
}
const decodeQuestionAttachmentAnswer = Schema.decodeUnknownOption(UserInputAttachmentAnswerPayload);
function collectThreadAttachmentRelativePaths(
threadId: string,
messages: ReadonlyArray<ProjectionThreadMessage>,
@@ -359,9 +363,9 @@ const runAttachmentSideEffects = Effect.fn("runAttachmentSideEffects")(function*
const path = yield* Effect.service(Path.Path);
const attachmentsRootDir = serverConfig.attachmentsDir;
const readAttachmentRootEntries = fileSystem
.readDirectory(attachmentsRootDir, { recursive: false })
.pipe(Effect.orElseSucceed(() => [] as Array<string>));
const readAttachmentRootEntries = fileSystem.readDirectory(attachmentsRootDir, {
recursive: false,
});
const removeDeletedThreadAttachmentEntry = Effect.fn("removeDeletedThreadAttachmentEntry")(
function* (threadSegment: string, entry: string) {
@@ -423,7 +427,7 @@ const runAttachmentSideEffects = Effect.fn("runAttachmentSideEffects")(function*
}
const absolutePath = path.join(attachmentsRootDir, relativePath);
const fileInfo = yield* fileSystem.stat(absolutePath).pipe(Effect.orElseSucceed(() => null));
const fileInfo = yield* fileSystem.stat(absolutePath);
if (!fileInfo || fileInfo.type !== "File") {
return;
}
@@ -1156,7 +1160,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
const applyThreadActivitiesProjection: ProjectorDefinition["apply"] = Effect.fn(
"applyThreadActivitiesProjection",
)(function* (event, _attachmentSideEffects) {
)(function* (event, attachmentSideEffects) {
switch (event.type) {
case "thread.created":
yield* projectionThreadActivityRepository.deleteByThreadId({
@@ -1204,6 +1208,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
yield* Effect.forEach(keptRows, projectionThreadActivityRepository.upsert, {
concurrency: 1,
}).pipe(Effect.asVoid);
attachmentSideEffects.prunedThreadRelativePaths.set(event.payload.threadId, new Set());
return;
}
@@ -1866,10 +1871,20 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
const messages = yield* projectionThreadMessageRepository.listByThreadId({
threadId: ThreadId.make(threadId),
});
prunedThreadRelativePaths.set(
threadId,
collectThreadAttachmentRelativePaths(threadId, messages),
);
const retainedPaths = collectThreadAttachmentRelativePaths(threadId, messages);
const activities = yield* projectionThreadActivityRepository.listByThreadId({
threadId: ThreadId.make(threadId),
});
for (const activity of activities) {
if (activity.kind !== "user-input.answer-submitted") continue;
const payload = decodeQuestionAttachmentAnswer(activity.payload);
if (Option.isNone(payload)) continue;
for (const attachment of Object.values(payload.value.attachmentsByQuestionId).flat()) {
const relativePath = attachmentRelativePath(attachment);
if (relativePath) retainedPaths.add(relativePath);
}
}
prunedThreadRelativePaths.set(threadId, retainedPaths);
}
yield* runAttachmentSideEffects({ deletedThreadIds, prunedThreadRelativePaths });
@@ -1879,29 +1894,17 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
Effect.provideService(ServerConfig, serverConfig),
(effect, event) =>
effect.pipe(
Effect.as(true),
Effect.catch((cause) =>
Effect.logWarning("failed to apply projected attachment side-effects", {
sequence: event.sequence,
eventType: event.type,
cause,
}),
}).pipe(Effect.as(false)),
),
),
);
const applyProjectorForEvent = Effect.fn("applyProjectorForEvent")(function* (
projector: ProjectorDefinition,
event: OrchestrationEvent,
attachmentSideEffects: AttachmentSideEffects,
) {
yield* projector.apply(event, attachmentSideEffects);
yield* projectionStateRepository.upsert({
projector: projector.name,
lastAppliedSequence: event.sequence,
updatedAt: event.occurredAt,
});
});
const runProjectorForEvent = Effect.fn("runProjectorForEvent")(function* (
projector: ProjectorDefinition,
event: OrchestrationEvent,
@@ -1911,8 +1914,16 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
prunedThreadRelativePaths: new Map<string, Set<string>>(),
};
yield* sql.withTransaction(applyProjectorForEvent(projector, event, attachmentSideEffects));
yield* applyAttachmentSideEffects(event, attachmentSideEffects);
yield* sql.withTransaction(
Effect.gen(function* () {
yield* projector.apply(event, attachmentSideEffects);
yield* projectionStateRepository.upsert({
projector: projector.name,
lastAppliedSequence: event.sequence,
updatedAt: event.occurredAt,
});
}),
);
});
const bootstrapProjector = (projector: ProjectorDefinition) =>
@@ -1958,7 +1969,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
);
// Return the cleanup effect so the caller runs it after the outer transaction commits.
// @effect-diagnostics-next-line returnEffectInGen:off
return applyAttachmentSideEffects(event, attachmentSideEffects);
return applyAttachmentSideEffects(event, attachmentSideEffects).pipe(Effect.asVoid);
},
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(Path.Path, path),
@@ -1975,11 +1986,58 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
yield* cleanup;
});
const bootstrap: OrchestrationProjectionPipelineShape["bootstrap"] = Effect.forEach(
projectors,
bootstrapProjector,
{ concurrency: 1 },
).pipe(
const bootstrap: OrchestrationProjectionPipelineShape["bootstrap"] = Effect.gen(function* () {
const cleanupProjector = "projection.attachment-cleanup";
const states = yield* projectionStateRepository.listAll();
const byProjector = new Map(states.map((state) => [state.projector, state]));
const cleanupState = byProjector.get(cleanupProjector);
const cleanupStart = Math.min(
cleanupState?.lastAppliedSequence ?? 0,
...projectors.map((projector) => byProjector.get(projector.name)?.lastAppliedSequence ?? 0),
);
// Persist this boundary before replay: a reset projector can encounter an old
// revert, then fail after other projectors have committed past that event.
yield* projectionStateRepository.upsert({
projector: cleanupProjector,
lastAppliedSequence: cleanupStart,
updatedAt: cleanupState?.updatedAt ?? "1970-01-01T00:00:00.000Z",
});
yield* Effect.forEach(projectors, bootstrapProjector, { concurrency: 1, discard: true });
// Cleanup has its own cursor so retries never have to replay committed text.
// All message and activity references are current before any files are removed.
const pendingCleanup = new Map<string, OrchestrationEvent>();
let lastEvent: OrchestrationEvent | undefined;
yield* Stream.runForEach(
eventStore.readFromSequence(cleanupStart, Number.MAX_SAFE_INTEGER),
(event) =>
Effect.sync(() => {
lastEvent = event;
if (event.type === "thread.reverted" || event.type === "thread.deleted") {
pendingCleanup.set(`${event.type}:${event.payload.threadId}`, event);
}
}),
);
for (const event of pendingCleanup.values()) {
if (event.type !== "thread.reverted" && event.type !== "thread.deleted") continue;
const threadId = event.payload.threadId;
const cleaned = yield* applyAttachmentSideEffects(event, {
deletedThreadIds: new Set(event.type === "thread.deleted" ? [threadId] : []),
prunedThreadRelativePaths: new Map(
event.type === "thread.reverted" ? [[threadId, new Set<string>()]] : [],
),
});
// Leave the cleanup cursor behind this event so the next bootstrap retries it.
if (!cleaned) return;
}
if (lastEvent) {
yield* projectionStateRepository.upsert({
projector: cleanupProjector,
lastAppliedSequence: lastEvent.sequence,
updatedAt: lastEvent.occurredAt,
});
}
}).pipe(
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(Path.Path, path),
Effect.provideService(ServerConfig, serverConfig),
@@ -1609,6 +1609,9 @@ const make = Effect.gen(function* () {
threadId: event.payload.threadId,
requestId: event.payload.requestId,
answers: event.payload.answers,
...(event.payload.attachmentsByQuestionId
? { attachmentsByQuestionId: event.payload.attachmentsByQuestionId }
: {}),
})
.pipe(
Effect.catchCause((cause) =>
@@ -5,13 +5,15 @@ import * as NodePath from "node:path";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { describe, expect, it } from "@effect/vitest";
import {
type ClientOrchestrationCommand,
ClientOrchestrationCommand,
CommandId,
ApprovalRequestId,
MessageId,
ThreadId,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import * as ServerConfig from "../config.ts";
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
@@ -23,6 +25,7 @@ const testLayer = Layer.mergeAll(
).pipe(Layer.provideMerge(NodeServices.layer));
const attachmentUuid = "00000000-0000-4000-8000-0000000000aa";
const isClientCommand = Schema.is(ClientOrchestrationCommand);
function turnStartCommand(input: {
readonly threadId?: string;
@@ -358,3 +361,201 @@ describe("normalizeDispatchCommand attachments", () => {
}).pipe(Effect.provide(testLayer)),
);
});
describe("question attachments", () => {
it.effect("enforces the total response limit and claims duplicate filenames independently", () =>
Effect.gen(function* () {
const config = yield* ServerConfig.ServerConfig;
const id = `pending-${attachmentUuid}-txt`;
NodeFS.writeFileSync(NodePath.join(config.attachmentsDir, `${id}.txt`), "report");
const attachment = {
type: "file" as const,
id,
name: 'notes "final" ü.txt',
mimeType: "text/plain",
sizeBytes: 6,
};
const command: ClientOrchestrationCommand = {
type: "thread.user-input.respond",
commandId: CommandId.make("answer-cap"),
threadId: ThreadId.make("thread-1"),
requestId: ApprovalRequestId.make("request-cap"),
answers: { first: "", second: "" },
createdAt: "2026-08-01T00:00:00.000Z",
attachmentsByQuestionId: {
first: Array.from({ length: 4 }, () => attachment),
second: Array.from({ length: 5 }, () => attachment),
},
};
const failure = yield* normalizeDispatchCommand(command).pipe(Effect.flip);
expect(failure.message).toContain("up to 8");
expect(NodeFS.readdirSync(config.attachmentsDir)).toEqual([`${id}.txt`]);
const accepted = {
...command,
attachmentsByQuestionId: {
...command.attachmentsByQuestionId,
second: Array.from({ length: 4 }, () => attachment),
},
};
const normalized = yield* normalizeDispatchCommand(accepted);
if (normalized.type !== "thread.user-input.respond") throw new Error("Wrong command");
const attachments = Object.values(normalized.attachmentsByQuestionId!).flat();
expect(attachments).toHaveLength(8);
expect(new Set(attachments.map((item) => item.id)).size).toBe(8);
for (const item of attachments) {
expect(item.name).toBe(attachment.name);
expect(
NodeFS.readFileSync(NodePath.join(config.attachmentsDir, `${item.id}.txt`), "utf8"),
).toBe("report");
}
yield* cleanupFailedUploadedAttachments(accepted, normalized);
expect(NodeFS.readdirSync(config.attachmentsDir)).toEqual([`${id}.txt`]);
}).pipe(Effect.provide(testLayer)),
);
it("requires uploaded metadata for question images, including pasted images", () => {
expect(
isClientCommand({
type: "thread.user-input.respond",
commandId: "answer",
threadId: "thread-1",
requestId: "request",
answers: { q: "" },
createdAt: "2026-08-01T00:00:00.000Z",
attachmentsByQuestionId: {
q: [
{
type: "image",
name: "image.png",
mimeType: "image/png",
sizeBytes: 6,
dataUrl: "data:image/png;base64,cGl4ZWxz",
},
],
},
}),
).toBe(false);
});
it.effect("preserves a __proto__ question key and cleans up its claimed files", () =>
Effect.gen(function* () {
const config = yield* ServerConfig.ServerConfig;
const id = `pending-${attachmentUuid}`;
NodeFS.writeFileSync(NodePath.join(config.attachmentsDir, `${id}.png`), "pixels");
const command: ClientOrchestrationCommand = {
type: "thread.user-input.respond",
commandId: CommandId.make("answer"),
threadId: ThreadId.make("thread-1"),
requestId: ApprovalRequestId.make("request"),
answers: { ["__proto__"]: "" },
createdAt: "2026-08-01T00:00:00.000Z",
attachmentsByQuestionId: {
["__proto__"]: [
{ type: "image", id, name: "image.png", mimeType: "image/png", sizeBytes: 6 },
],
},
};
const normalized = yield* normalizeDispatchCommand(command);
if (normalized.type !== "thread.user-input.respond") throw new Error("Wrong command");
expect(Object.keys(normalized.attachmentsByQuestionId!)).toEqual(["__proto__"]);
const attachment = normalized.attachmentsByQuestionId!["__proto__"]![0]!;
const claimedPath = NodePath.join(config.attachmentsDir, `${attachment.id}.png`);
expect(NodeFS.existsSync(claimedPath)).toBe(true);
yield* cleanupFailedUploadedAttachments(command, normalized);
expect(NodeFS.existsSync(claimedPath)).toBe(false);
}).pipe(Effect.provide(testLayer)),
);
it.effect(
"claims images and files by question, preserves answers, and cleans up failed dispatches",
() =>
Effect.gen(function* () {
const config = yield* ServerConfig.ServerConfig;
const imageId = `pending-${attachmentUuid}`;
const fileId = `pending-${attachmentUuid}-txt`;
NodeFS.writeFileSync(NodePath.join(config.attachmentsDir, `${imageId}.png`), "pixels");
NodeFS.writeFileSync(NodePath.join(config.attachmentsDir, `${fileId}.txt`), "report");
const command: ClientOrchestrationCommand = {
type: "thread.user-input.respond",
commandId: CommandId.make("answer"),
threadId: ThreadId.make("thread-1"),
requestId: ApprovalRequestId.make("request"),
answers: { q1: ["Selected option"], q2: "" },
createdAt: "2026-08-01T00:00:00.000Z",
attachmentsByQuestionId: {
q1: [
{
type: "image",
id: imageId,
name: "image.png",
mimeType: "image/png",
sizeBytes: 6,
},
],
q2: [
{
type: "file",
id: fileId,
name: "report.txt",
mimeType: "text/plain",
sizeBytes: 6,
},
],
},
};
const normalized = yield* normalizeDispatchCommand(command);
if (normalized.type !== "thread.user-input.respond") throw new Error("Wrong command");
expect(normalized.answers).toEqual(command.answers);
const image = normalized.attachmentsByQuestionId!.q1![0]!;
const file = normalized.attachmentsByQuestionId!.q2![0]!;
expect(
NodeFS.readFileSync(NodePath.join(config.attachmentsDir, `${image.id}.png`), "utf8"),
).toBe("pixels");
expect(
NodeFS.readFileSync(NodePath.join(config.attachmentsDir, `${file.id}.txt`), "utf8"),
).toBe("report");
yield* cleanupFailedUploadedAttachments(command, normalized);
expect(NodeFS.existsSync(NodePath.join(config.attachmentsDir, `${image.id}.png`))).toBe(
false,
);
expect(NodeFS.existsSync(NodePath.join(config.attachmentsDir, `${file.id}.txt`))).toBe(
false,
);
expect(NodeFS.existsSync(NodePath.join(config.attachmentsDir, `${imageId}.png`))).toBe(
true,
);
const retry = yield* normalizeDispatchCommand(command);
expect(retry.type).toBe("thread.user-input.respond");
}).pipe(Effect.provide(testLayer)),
);
it.effect("removes all claimed copies if a later question upload is missing", () =>
Effect.gen(function* () {
const config = yield* ServerConfig.ServerConfig;
const id = `pending-${attachmentUuid}`;
NodeFS.writeFileSync(NodePath.join(config.attachmentsDir, `${id}.png`), "pixels");
const result = yield* normalizeDispatchCommand({
type: "thread.user-input.respond",
commandId: CommandId.make("answer"),
threadId: ThreadId.make("thread-1"),
requestId: ApprovalRequestId.make("request"),
answers: { q1: "", q2: "" },
createdAt: "2026-08-01T00:00:00.000Z",
attachmentsByQuestionId: {
q1: [{ type: "image", id, name: "image.png", mimeType: "image/png", sizeBytes: 6 }],
q2: [
{
type: "file",
id: `${id}-txt`,
name: "missing.txt",
mimeType: "text/plain",
sizeBytes: 6,
},
],
},
}).pipe(Effect.result);
expect(result._tag).toBe("Failure");
expect(
NodeFS.readdirSync(config.attachmentsDir).filter((name) => name.startsWith("thread-1-")),
).toEqual([]);
}).pipe(Effect.provide(testLayer)),
);
});
+53 -7
View File
@@ -4,6 +4,8 @@ import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import {
type ClientOrchestrationCommand,
type UserInputAttachments,
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
type IsoDateTime,
type OrchestrationCommand,
OrchestrationDispatchCommandError,
@@ -129,13 +131,28 @@ export const normalizeDispatchCommand = (command: ClientOrchestrationCommand) =>
} satisfies OrchestrationCommand;
}
if (canonicalCommand.type !== "thread.turn.start") {
if (
canonicalCommand.type !== "thread.turn.start" &&
canonicalCommand.type !== "thread.user-input.respond"
) {
return canonicalCommand as OrchestrationCommand;
}
const attachments =
canonicalCommand.type === "thread.turn.start"
? canonicalCommand.message.attachments
: Object.values(canonicalCommand.attachmentsByQuestionId ?? {}).flat();
if (
canonicalCommand.type === "thread.user-input.respond" &&
attachments.length > PROVIDER_SEND_TURN_MAX_ATTACHMENTS
) {
return yield* new OrchestrationDispatchCommandError({
message: `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} files per question response.`,
});
}
const claimedAttachmentPaths: string[] = [];
const normalizedAttachments = yield* Effect.forEach(
canonicalCommand.message.attachments,
attachments,
(attachment) =>
Effect.gen(function* () {
if (!("dataUrl" in attachment)) {
@@ -260,6 +277,25 @@ export const normalizeDispatchCommand = (command: ClientOrchestrationCommand) =>
{ concurrency: 1 },
).pipe(Effect.tapError(() => removeClaimedAttachmentPaths(claimedAttachmentPaths)));
if (canonicalCommand.type === "thread.user-input.respond") {
let index = 0;
const attachmentsByQuestionId = Object.fromEntries(
Object.entries(canonicalCommand.attachmentsByQuestionId ?? {}).map(
([questionId, original]) => {
const claimed = normalizedAttachments.slice(
index,
index + original.length,
) as UserInputAttachments[string];
index += original.length;
return [questionId, claimed];
},
),
);
return {
...canonicalCommand,
...(attachments.length > 0 ? { attachmentsByQuestionId } : {}),
};
}
return {
...canonicalCommand,
message: {
@@ -272,14 +308,24 @@ export const normalizeDispatchCommand = (command: ClientOrchestrationCommand) =>
export const cleanupFailedUploadedAttachments = Effect.fn(
"Normalizer.cleanupFailedUploadedAttachments",
)(function* (command: ClientOrchestrationCommand, normalizedCommand: OrchestrationCommand) {
if (command.type !== "thread.turn.start" || normalizedCommand.type !== "thread.turn.start") {
return;
}
const originalAttachments =
command.type === "thread.turn.start"
? command.message.attachments
: command.type === "thread.user-input.respond"
? Object.values(command.attachmentsByQuestionId ?? {}).flat()
: [];
const normalizedAttachments =
normalizedCommand.type === "thread.turn.start"
? normalizedCommand.message.attachments
: normalizedCommand.type === "thread.user-input.respond"
? Object.values(normalizedCommand.attachmentsByQuestionId ?? {}).flat()
: [];
if (normalizedAttachments.length === 0) return;
const serverConfig = yield* ServerConfig;
const claimedPaths: string[] = [];
for (const [index, attachment] of normalizedCommand.message.attachments.entries()) {
const original = command.message.attachments[index];
for (const [index, attachment] of normalizedAttachments.entries()) {
const original = originalAttachments[index];
if (
!original ||
"dataUrl" in original ||
@@ -0,0 +1,130 @@
import {
ApprovalRequestId,
EventId,
CommandId,
ProjectId,
ProviderInstanceId,
ThreadId,
type OrchestrationReadModel,
} from "@t3tools/contracts";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import { decideOrchestrationCommand } from "./decider.ts";
const UPDATED_AT = "2026-01-01T00:00:00.000Z";
const readModel: OrchestrationReadModel = {
snapshotSequence: 0,
projects: [],
threads: [
{
id: ThreadId.make("thread-1"),
projectId: ProjectId.make("project-1"),
title: "Manual title",
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
latestTurn: null,
createdAt: UPDATED_AT,
updatedAt: UPDATED_AT,
archivedAt: null,
settledOverride: null,
settledAt: null,
snoozedUntil: null,
snoozedAt: null,
deletedAt: null,
messages: [],
proposedPlans: [],
activities: [],
checkpoints: [],
session: null,
},
],
updatedAt: UPDATED_AT,
};
const requestId = ApprovalRequestId.make("question-request");
const command = {
type: "thread.user-input.respond" as const,
commandId: CommandId.make("answer"),
threadId: ThreadId.make("thread-1"),
requestId,
answers: { q: "" },
createdAt: UPDATED_AT,
attachmentsByQuestionId: {
q: [
{
type: "file" as const,
id: "thread-1-00000000-0000-4000-8000-0000000000aa-txt",
name: "spec.txt",
mimeType: "text/plain",
sizeBytes: 4,
},
],
},
};
const request = {
id: EventId.make("question"),
kind: "user-input.requested",
summary: "Question",
tone: "info" as const,
turnId: null,
createdAt: UPDATED_AT,
payload: {
requestId,
questions: [
{ id: "q", header: "Spec", question: "Provide a spec", options: [], allowCustomAnswer: true },
],
},
};
it.layer(NodeServices.layer)("question attachment answers", (it) => {
it.effect("persists the original answer with its attachment and emits a provider response", () =>
Effect.gen(function* () {
const result = yield* decideOrchestrationCommand({
readModel,
command,
userInputActivity: request,
});
const events = Array.isArray(result) ? result : [result];
expect(events.map((event) => event.type)).toEqual([
"thread.activity-appended",
"thread.user-input-response-requested",
]);
expect(events[0]?.payload).toMatchObject({
activity: {
kind: "user-input.answer-submitted",
payload: { answers: { q: "" }, attachmentsByQuestionId: command.attachmentsByQuestionId },
},
});
expect(events[1]?.payload).toMatchObject({
answers: { q: "" },
attachmentsByQuestionId: command.attachmentsByQuestionId,
});
}),
);
it.effect("rejects attachments for a resolved or unknown request", () =>
Effect.gen(function* () {
const result = yield* decideOrchestrationCommand({ readModel, command }).pipe(Effect.result);
expect(result._tag).toBe("Failure");
}),
);
it.effect("rejects unknown question IDs and predefined-choice-only protocols", () =>
Effect.gen(function* () {
for (const question of [
{ ...request.payload.questions[0], id: "other" },
{ ...request.payload.questions[0], allowCustomAnswer: false },
]) {
const result = yield* decideOrchestrationCommand({
readModel,
command,
userInputActivity: { ...request, payload: { ...request.payload, questions: [question] } },
}).pipe(Effect.result);
expect(result._tag).toBe("Failure");
}
}),
);
});
+76 -8
View File
@@ -1222,6 +1222,35 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
threadId: command.threadId,
});
const request = userInputActivity;
const attachments = Object.values(command.attachmentsByQuestionId ?? {}).flat();
let questionTextById: Record<string, string> = {};
if (attachments.length > 0) {
const payload =
request?.kind === "user-input.requested"
? decodeUserInputRequestedPayload(request.payload)
: Option.none();
if (Option.isNone(payload)) {
return yield* new OrchestrationCommandInvariantError({
commandType: command.type,
detail:
request?.kind === "user-input.resolved"
? "This question has already been answered."
: "This question is no longer pending.",
});
}
questionTextById = Object.fromEntries(
payload.value.questions.map((question) => [question.id, question.question]),
);
for (const questionId of Object.keys(command.attachmentsByQuestionId ?? {})) {
const question = payload.value.questions.find((question) => question.id === questionId);
if (!question || question.allowCustomAnswer === false) {
return yield* new OrchestrationCommandInvariantError({
commandType: command.type,
detail: "This question does not accept file references.",
});
}
}
}
if (
request &&
Predicate.isObject(request.payload) &&
@@ -1237,13 +1266,22 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
const replies: string[] = [];
for (const question of payload.value.questions) {
const answer = command.answers[question.id];
if (typeof answer !== "string" || answer.trim().length === 0) {
if (
typeof answer !== "string" ||
(answer.trim().length === 0 && !command.attachmentsByQuestionId?.[question.id]?.length)
) {
return yield* new OrchestrationCommandInvariantError({
commandType: command.type,
detail: "Answer each question before sending.",
});
}
replies.push(`${question.question}\n${answer.trim()}`);
const questionAttachments = command.attachmentsByQuestionId?.[question.id] ?? [];
const attachmentLabels = questionAttachments
.map((attachment) => `Attached file: ${attachment.name} (${attachment.id})`)
.join("\n");
replies.push(
[`${question.question}\n${answer.trim()}`, attachmentLabels].filter(Boolean).join("\n"),
);
}
// Commit the answer and its message together. The normal turn path
// steers a running agent or resumes an idle session.
@@ -1266,6 +1304,9 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
requestId: command.requestId,
responseMode: "message",
answers: command.answers,
...(command.attachmentsByQuestionId
? { attachmentsByQuestionId: command.attachmentsByQuestionId }
: {}),
},
},
},
@@ -1280,30 +1321,57 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
messageId: MessageId.make(`async-answer:${command.requestId}`),
role: "user",
text: replies.join("\n\n"),
attachments: [],
attachments,
},
},
],
});
}
return {
const responseEvent = {
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
metadata: {
requestId: command.requestId,
},
metadata: { requestId: command.requestId },
})),
type: "thread.user-input-response-requested",
type: "thread.user-input-response-requested" as const,
payload: {
threadId: command.threadId,
requestId: command.requestId,
answers: command.answers,
...(command.attachmentsByQuestionId
? { attachmentsByQuestionId: command.attachmentsByQuestionId }
: {}),
createdAt: command.createdAt,
},
};
if (attachments.length === 0) return responseEvent;
const historyEvent = yield* decideOrchestrationCommand({
readModel,
command: {
type: "thread.activity.append",
commandId: command.commandId,
threadId: command.threadId,
createdAt: command.createdAt,
activity: {
id: EventId.make(`question-answer:${command.commandId}`),
kind: "user-input.answer-submitted",
summary: "Question answer submitted",
tone: "info",
turnId: request?.turnId ?? null,
createdAt: command.createdAt,
payload: {
requestId: command.requestId,
answers: command.answers,
questionTextById,
attachmentsByQuestionId: command.attachmentsByQuestionId,
detail: attachments.map((attachment) => attachment.name).join("\n"),
},
},
},
});
return [...(Array.isArray(historyEvent) ? historyEvent : [historyEvent]), responseEvent];
}
case "thread.user-input.dismiss": {
@@ -49,6 +49,7 @@ import * as Schema from "effect/Schema";
import * as SchemaIssue from "effect/SchemaIssue";
import * as Stream from "effect/Stream";
import { appendUserInputAttachmentPaths } from "../userInputAttachments.ts";
import { resolveAttachmentPath } from "../../attachmentStore.ts";
import * as ServerConfig from "../../config.ts";
import {
@@ -1919,7 +1920,11 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
"provider.thread_id": input.threadId,
"provider.request_id": input.requestId,
});
yield* routed.adapter.respondToUserInput(routed.threadId, input.requestId, input.answers);
const answers = yield* appendUserInputAttachmentPaths({
...input,
attachmentsDir: serverConfig.attachmentsDir,
}).pipe(Effect.provideService(FileSystem.FileSystem, fileSystem));
yield* routed.adapter.respondToUserInput(routed.threadId, input.requestId, answers);
}).pipe(
withMetrics({
counter: providerTurnsTotal,
@@ -0,0 +1,61 @@
// @effect-diagnostics nodeBuiltinImport:off
import * as NodeFS from "node:fs";
import * as NodePath from "node:path";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as ServerConfig from "../config.ts";
import { appendUserInputAttachmentPaths } from "./userInputAttachments.ts";
const layer = ServerConfig.layerTest(process.cwd(), { prefix: "t3-answer-paths-" }).pipe(
Layer.provideMerge(NodeServices.layer),
);
const attachment = {
type: "file" as const,
id: "thread-1-00000000-0000-4000-8000-0000000000aa-txt",
name: 'spec "final".txt',
mimeType: "text/plain",
sizeBytes: 4,
};
describe("question answer paths", () => {
it.effect("keeps selected values intact and appends an actual readable server path", () =>
Effect.gen(function* () {
const config = yield* ServerConfig.ServerConfig;
const path = NodePath.join(config.attachmentsDir, `${attachment.id}.txt`);
NodeFS.writeFileSync(path, "spec");
const original = { q: ["First", "Second"], other: "No file" };
const answers = yield* appendUserInputAttachmentPaths({
answers: original,
attachmentsDir: config.attachmentsDir,
attachmentsByQuestionId: { q: [attachment] },
});
expect(answers.q).toEqual([
"First",
"Second",
`Attached file "spec \\"final\\".txt": "${path}"`,
]);
expect(answers.other).toBe("No file");
expect(original.q).toEqual(["First", "Second"]);
expect(NodeFS.readFileSync(path, "utf8")).toBe("spec");
const specialKey = yield* appendUserInputAttachmentPaths({
answers: {},
attachmentsDir: config.attachmentsDir,
attachmentsByQuestionId: { ["__proto__"]: [attachment] },
});
expect(Object.keys(specialKey)).toEqual(["__proto__"]);
expect(specialKey["__proto__"]).toContain(path);
}).pipe(Effect.provide(layer)),
);
it.effect("does not send an unavailable attachment path", () =>
Effect.gen(function* () {
const config = yield* ServerConfig.ServerConfig;
const result = yield* appendUserInputAttachmentPaths({
answers: { q: "" },
attachmentsDir: config.attachmentsDir,
attachmentsByQuestionId: { q: [attachment] },
}).pipe(Effect.result);
expect(result._tag).toBe("Failure");
}).pipe(Effect.provide(layer)),
);
});
@@ -0,0 +1,59 @@
import type { ProviderUserInputAnswers, UserInputAttachments } from "@t3tools/contracts";
import * as Schema from "effect/Schema";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import { resolveAttachmentPath } from "../attachmentStore.ts";
import { ProviderValidationError } from "./Errors.ts";
const quoteReference = Schema.encodeSync(Schema.fromJsonString(Schema.String));
/** Keep provider answer protocols unchanged; paths refer to files on the provider's server. */
export const appendUserInputAttachmentPaths = Effect.fn("appendUserInputAttachmentPaths")(
function* (input: {
answers: ProviderUserInputAnswers;
attachmentsByQuestionId?: UserInputAttachments | undefined;
attachmentsDir: string;
}) {
const answers = new Map(Object.entries(input.answers));
const fs = yield* FileSystem.FileSystem;
for (const [questionId, attachments] of Object.entries(input.attachmentsByQuestionId ?? {})) {
if (attachments.length === 0) continue;
const references: string[] = [];
for (const attachment of attachments) {
const path = resolveAttachmentPath({ attachmentsDir: input.attachmentsDir, attachment });
if (
!path ||
!(yield* fs.exists(path).pipe(
Effect.mapError(
(cause) =>
new ProviderValidationError({
operation: "respondToUserInput",
issue: `Could not access attachment '${attachment.name}'.`,
cause,
}),
),
))
) {
return yield* new ProviderValidationError({
operation: "respondToUserInput",
issue: `Attachment '${attachment.name}' is no longer available. Attach it again.`,
});
}
references.push(
`Attached ${attachment.type} ${quoteReference(attachment.name)}: ${quoteReference(path)}`,
);
}
const answer = answers.get(questionId);
const text = references.join("\n");
answers.set(
questionId,
Array.isArray(answer)
? [...answer, text]
: typeof answer === "string" && answer.length > 0
? `${answer}\n\n${text}`
: text,
);
}
return Object.fromEntries(answers);
},
);