diff --git a/apps/server/src/assets/AssetAccess.test.ts b/apps/server/src/assets/AssetAccess.test.ts index 06a22754e5..dc06946bfb 100644 --- a/apps/server/src/assets/AssetAccess.test.ts +++ b/apps/server/src/assets/AssetAccess.test.ts @@ -198,6 +198,32 @@ describe("AssetAccess", () => { expect(yield* resolveAsset(token, "ignored.png")).toEqual({ kind: "file", path: attachmentPath, + download: false, + }); + }).pipe(Effect.provide(testLayer)), + ); + + it.effect("marks non-image attachment capabilities for download", () => + Effect.gen(function* () { + const config = yield* ServerConfig.ServerConfig; + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const attachmentId = "thread-1-00000000-0000-4000-8000-000000000002"; + const attachmentPath = path.join(config.attachmentsDir, `${attachmentId}.pdf`); + yield* fileSystem.makeDirectory(config.attachmentsDir, { recursive: true }); + yield* fileSystem.writeFile(attachmentPath, new Uint8Array([1, 2, 3])); + + const result = yield* issueAssetUrl({ + resource: { _tag: "attachment", attachmentId }, + }); + const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length); + const separatorIndex = suffix.indexOf("/"); + const token = suffix.slice(0, separatorIndex); + + expect(yield* resolveAsset(token, "ignored.pdf")).toEqual({ + kind: "file", + path: attachmentPath, + download: true, }); }).pipe(Effect.provide(testLayer)), ); diff --git a/apps/server/src/attachmentPrompt.test.ts b/apps/server/src/attachmentPrompt.test.ts new file mode 100644 index 0000000000..2e5b8390b7 --- /dev/null +++ b/apps/server/src/attachmentPrompt.test.ts @@ -0,0 +1,97 @@ +// @effect-diagnostics nodeBuiltinImport:off +import * as NodePath from "node:path"; + +import { describe, expect, it } from "vite-plus/test"; + +import { appendFileAttachmentPromptText } from "./attachmentPrompt.ts"; + +const attachmentsDir = NodePath.join(NodePath.sep, "tmp", "t3-attachment-prompt"); + +describe("attachmentPrompt", () => { + it("appends a prompt line for file attachments", () => { + const result = appendFileAttachmentPromptText({ + text: "hello", + attachmentsDir, + attachments: [ + { + type: "file", + id: "thread-1-00000000-0000-4000-8000-000000000001", + name: "notes.txt", + mimeType: "text/plain", + sizeBytes: 2048, + }, + ], + }); + const attachmentPath = NodePath.join( + attachmentsDir, + "thread-1-00000000-0000-4000-8000-000000000001.txt", + ); + expect(result).toBe( + `hello\n\n[Attached file: ${attachmentPath} (notes.txt, text/plain, 2.0 KB). Read it from disk when needed.]`, + ); + }); + + it("returns text unchanged when only image attachments are present", () => { + expect( + appendFileAttachmentPromptText({ + text: "hello", + attachmentsDir, + attachments: [ + { + type: "image", + id: "thread-1-00000000-0000-4000-8000-000000000002", + name: "screen.png", + mimeType: "image/png", + sizeBytes: 4, + }, + ], + }), + ).toBe("hello"); + }); + + it("returns only the prompt lines when the text is empty", () => { + const result = appendFileAttachmentPromptText({ + text: "", + attachmentsDir, + attachments: [ + { + type: "file", + id: "thread-1-00000000-0000-4000-8000-000000000003", + name: "data.csv", + mimeType: "text/csv", + sizeBytes: 12, + }, + ], + }); + const attachmentPath = NodePath.join( + attachmentsDir, + "thread-1-00000000-0000-4000-8000-000000000003.csv", + ); + expect(result).toBe( + `[Attached file: ${attachmentPath} (data.csv, text/csv, 12 B). Read it from disk when needed.]`, + ); + }); + + it("strips control characters, brackets, and parentheses from attachment names", () => { + const result = appendFileAttachmentPromptText({ + text: "hello", + attachmentsDir, + attachments: [ + { + type: "file", + id: "thread-1-00000000-0000-4000-8000-000000000004", + name: "a(b)\u0001[c].txt", + mimeType: "text/plain", + sizeBytes: 5, + }, + ], + }); + const attachmentPath = NodePath.join( + attachmentsDir, + "thread-1-00000000-0000-4000-8000-000000000004.txt", + ); + expect(result).toBe( + `hello\n\n[Attached file: ${attachmentPath} (a b c .txt, text/plain, 5 B). Read it from disk when needed.]`, + ); + }); +}); diff --git a/apps/server/src/attachmentStore.test.ts b/apps/server/src/attachmentStore.test.ts index e21d9cf62c..94915650f9 100644 --- a/apps/server/src/attachmentStore.test.ts +++ b/apps/server/src/attachmentStore.test.ts @@ -6,6 +6,7 @@ import * as NodePath from "node:path"; import { describe, expect, it } from "vite-plus/test"; import { + attachmentRelativePath, createAttachmentId, parseThreadSegmentFromAttachmentId, resolveAttachmentPathById, @@ -44,6 +45,37 @@ describe("attachmentStore", () => { expect(parseThreadSegmentFromAttachmentId(attachmentId)).toBe("thread-foo"); }); + it("builds file attachment relative paths with the inferred file extension", () => { + expect( + attachmentRelativePath({ + type: "file", + id: "thread-1-00000000-0000-4000-8000-000000000001", + name: "report.pdf", + mimeType: "application/pdf", + sizeBytes: 5, + }), + ).toBe("thread-1-00000000-0000-4000-8000-000000000001.pdf"); + }); + + it("resolves attachment path by id for a written file attachment extension", () => { + const attachmentsDir = NodeFS.mkdtempSync( + NodePath.join(NodeOS.tmpdir(), "t3code-attachment-store-"), + ); + try { + const attachmentId = "thread-1-attachment"; + const pdfPath = NodePath.join(attachmentsDir, `${attachmentId}.pdf`); + NodeFS.writeFileSync(pdfPath, Buffer.from("hello")); + + const resolved = resolveAttachmentPathById({ + attachmentsDir, + attachmentId, + }); + expect(resolved).toBe(pdfPath); + } finally { + NodeFS.rmSync(attachmentsDir, { recursive: true, force: true }); + } + }); + it("resolves attachment path by id using the extension that exists on disk", () => { const attachmentsDir = NodeFS.mkdtempSync( NodePath.join(NodeOS.tmpdir(), "t3code-attachment-store-"), diff --git a/apps/server/src/imageMime.test.ts b/apps/server/src/imageMime.test.ts index e87e4dcbd0..8929b9ce31 100644 --- a/apps/server/src/imageMime.test.ts +++ b/apps/server/src/imageMime.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vite-plus/test"; -import { inferImageExtension, parseBase64DataUrl } from "./imageMime.ts"; +import { inferFileExtension, inferImageExtension, parseBase64DataUrl } from "./imageMime.ts"; describe("imageMime", () => { it("parses base64 data URL with mime type", () => { @@ -92,4 +92,39 @@ describe("imageMime", () => { it("does not read inherited keys from mime extension map", () => { expect(inferImageExtension({ mimeType: "constructor" })).toBe(".bin"); }); + + it("infers file extension from an allowlisted file name extension", () => { + expect( + inferFileExtension({ mimeType: "application/octet-stream", fileName: "report.PDF" }), + ).toBe(".pdf"); + }); + + it("infers file extension from the last segment of a multi-dot file name", () => { + expect(inferFileExtension({ mimeType: "application/octet-stream", fileName: "a.b.csv" })).toBe( + ".csv", + ); + }); + + it("falls back to an allowlisted mime extension when the file name extension is unsafe", () => { + expect(inferFileExtension({ mimeType: "application/pdf", fileName: "notes.exe" })).toBe(".pdf"); + }); + + it("falls back to an allowlisted mime extension when the file name has no extension", () => { + expect(inferFileExtension({ mimeType: "text/plain", fileName: "notes" })).toBe(".txt"); + }); + + it("defaults file extension to .bin when neither file name nor mime is allowlisted", () => { + expect(inferFileExtension({ mimeType: "application/x-unknown", fileName: "payload.exe" })).toBe( + ".bin", + ); + expect(inferFileExtension({ mimeType: "application/x-unknown", fileName: "notes" })).toBe( + ".bin", + ); + }); + + it("defaults dotfile names without an allowlisted mime to .bin", () => { + expect(inferFileExtension({ mimeType: "application/x-unknown", fileName: ".env" })).toBe( + ".bin", + ); + }); }); diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts index 0999000ed4..922ab42106 100644 --- a/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts +++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts @@ -928,6 +928,214 @@ it.layer( ); }); +it.layer( + Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-attachments-file-gc-")), +)("OrchestrationProjectionPipeline", (it) => { + it.effect("keeps referenced file attachments and prunes orphans when a thread is reverted", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const projectionPipeline = yield* OrchestrationProjectionPipeline; + const eventStore = yield* OrchestrationEventStore; + const { attachmentsDir } = yield* ServerConfig; + const now = "2026-01-01T00:00:00.000Z"; + const threadId = ThreadId.make("Thread Revert.Docs"); + const keepAttachmentId = "thread-revert-docs-00000000-0000-4000-8000-000000000001"; + const removeAttachmentId = "thread-revert-docs-00000000-0000-4000-8000-000000000002"; + const orphanAttachmentId = "thread-revert-docs-00000000-0000-4000-8000-000000000003"; + + const appendAndProject = (event: Parameters[0]) => + eventStore + .append(event) + .pipe(Effect.flatMap((savedEvent) => projectionPipeline.projectEvent(savedEvent))); + + yield* appendAndProject({ + type: "project.created", + eventId: EventId.make("evt-revert-docs-1"), + aggregateKind: "project", + aggregateId: ProjectId.make("project-revert-docs"), + occurredAt: now, + commandId: CommandId.make("cmd-revert-docs-1"), + causationEventId: null, + correlationId: CorrelationId.make("cmd-revert-docs-1"), + metadata: {}, + payload: { + projectId: ProjectId.make("project-revert-docs"), + title: "Project Revert Docs", + workspaceRoot: "/tmp/project-revert-docs", + defaultModelSelection: null, + scripts: [], + createdAt: now, + updatedAt: now, + }, + }); + + yield* appendAndProject({ + type: "thread.created", + eventId: EventId.make("evt-revert-docs-2"), + aggregateKind: "thread", + aggregateId: threadId, + occurredAt: now, + commandId: CommandId.make("cmd-revert-docs-2"), + causationEventId: null, + correlationId: CorrelationId.make("cmd-revert-docs-2"), + metadata: {}, + payload: { + threadId, + projectId: ProjectId.make("project-revert-docs"), + title: "Thread Revert Docs", + modelSelection: { + instanceId: ProviderInstanceId.make("codex"), + model: "gpt-5-codex", + }, + runtimeMode: "full-access", + branch: null, + worktreePath: null, + createdAt: now, + updatedAt: now, + }, + }); + + yield* appendAndProject({ + type: "thread.turn-diff-completed", + eventId: EventId.make("evt-revert-docs-3"), + aggregateKind: "thread", + aggregateId: threadId, + occurredAt: now, + commandId: CommandId.make("cmd-revert-docs-3"), + causationEventId: null, + correlationId: CorrelationId.make("cmd-revert-docs-3"), + metadata: {}, + payload: { + threadId, + turnId: TurnId.make("turn-keep"), + checkpointTurnCount: 1, + checkpointRef: CheckpointRef.make("refs/t3/checkpoints/thread-revert-docs/turn/1"), + status: "ready", + files: [], + assistantMessageId: MessageId.make("message-keep"), + completedAt: now, + }, + }); + + yield* appendAndProject({ + type: "thread.message-sent", + eventId: EventId.make("evt-revert-docs-4"), + aggregateKind: "thread", + aggregateId: threadId, + occurredAt: now, + commandId: CommandId.make("cmd-revert-docs-4"), + causationEventId: null, + correlationId: CorrelationId.make("cmd-revert-docs-4"), + metadata: {}, + payload: { + threadId, + messageId: MessageId.make("message-keep"), + role: "assistant", + text: "Keep", + attachments: [ + { + type: "file", + id: keepAttachmentId, + name: "keep.pdf", + mimeType: "application/pdf", + sizeBytes: 5, + }, + ], + turnId: TurnId.make("turn-keep"), + streaming: false, + createdAt: now, + updatedAt: now, + }, + }); + + yield* appendAndProject({ + type: "thread.turn-diff-completed", + eventId: EventId.make("evt-revert-docs-5"), + aggregateKind: "thread", + aggregateId: threadId, + occurredAt: now, + commandId: CommandId.make("cmd-revert-docs-5"), + causationEventId: null, + correlationId: CorrelationId.make("cmd-revert-docs-5"), + metadata: {}, + payload: { + threadId, + turnId: TurnId.make("turn-remove"), + checkpointTurnCount: 2, + checkpointRef: CheckpointRef.make("refs/t3/checkpoints/thread-revert-docs/turn/2"), + status: "ready", + files: [], + assistantMessageId: MessageId.make("message-remove"), + completedAt: now, + }, + }); + + yield* appendAndProject({ + type: "thread.message-sent", + eventId: EventId.make("evt-revert-docs-6"), + aggregateKind: "thread", + aggregateId: threadId, + occurredAt: now, + commandId: CommandId.make("cmd-revert-docs-6"), + causationEventId: null, + correlationId: CorrelationId.make("cmd-revert-docs-6"), + metadata: {}, + payload: { + threadId, + messageId: MessageId.make("message-remove"), + role: "assistant", + text: "Remove", + attachments: [ + { + type: "file", + id: removeAttachmentId, + name: "remove.pdf", + mimeType: "application/pdf", + sizeBytes: 5, + }, + ], + turnId: TurnId.make("turn-remove"), + streaming: false, + createdAt: now, + updatedAt: now, + }, + }); + + const keepPath = path.join(attachmentsDir, `${keepAttachmentId}.pdf`); + const removePath = path.join(attachmentsDir, `${removeAttachmentId}.pdf`); + const orphanPath = path.join(attachmentsDir, `${orphanAttachmentId}.pdf`); + yield* fileSystem.makeDirectory(attachmentsDir, { recursive: true }); + yield* fileSystem.writeFileString(keepPath, "keep"); + yield* fileSystem.writeFileString(removePath, "remove"); + yield* fileSystem.writeFileString(orphanPath, "orphan"); + assert.isTrue(yield* exists(keepPath)); + assert.isTrue(yield* exists(removePath)); + assert.isTrue(yield* exists(orphanPath)); + + yield* appendAndProject({ + type: "thread.reverted", + eventId: EventId.make("evt-revert-docs-7"), + aggregateKind: "thread", + aggregateId: threadId, + occurredAt: now, + commandId: CommandId.make("cmd-revert-docs-7"), + causationEventId: null, + correlationId: CorrelationId.make("cmd-revert-docs-7"), + metadata: {}, + payload: { + threadId, + turnCount: 1, + }, + }); + + assert.isTrue(yield* exists(keepPath)); + assert.isFalse(yield* exists(removePath)); + assert.isFalse(yield* exists(orphanPath)); + }), + ); +}); + it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-attachments-revert-")))( "OrchestrationProjectionPipeline", (it) => { diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts index ce464565dc..2d57cf109c 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts @@ -466,6 +466,58 @@ describe("ProviderCommandReactor", () => { expect(thread?.session?.runtimeMode).toBe("approval-required"); }); + effectIt.effect( + "sends only image attachments to the provider and appends file attachment prompt text", + () => + Effect.gen(function* () { + const harness = yield* Effect.promise(() => createHarness()); + const now = "2026-01-01T00:00:00.000Z"; + const imageAttachment = { + type: "image" as const, + id: "thread-1-00000000-0000-4000-8000-000000000001", + name: "screen.png", + mimeType: "image/png", + sizeBytes: 4, + }; + const fileAttachment = { + type: "file" as const, + id: "thread-1-00000000-0000-4000-8000-000000000002", + name: "notes.txt", + mimeType: "text/plain", + sizeBytes: 5, + }; + const attachmentsDir = NodePath.join(harness.stateDir, "attachments"); + const fileAttachmentPath = NodePath.join(attachmentsDir, `${fileAttachment.id}.txt`); + NodeFS.mkdirSync(attachmentsDir, { recursive: true }); + NodeFS.writeFileSync(fileAttachmentPath, "notes"); + + yield* harness.engine.dispatch({ + type: "thread.turn.start", + commandId: CommandId.make("cmd-turn-start-file-attachments"), + threadId: ThreadId.make("thread-1"), + message: { + messageId: asMessageId("user-message-file-attachments"), + role: "user", + text: "hello with attachments", + attachments: [imageAttachment, fileAttachment], + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + createdAt: now, + }); + + yield* Effect.promise(() => waitFor(() => harness.sendTurn.mock.calls.length === 1)); + const request = harness.sendTurn.mock.calls[0]?.[0] as { + readonly input?: string; + readonly attachments?: ReadonlyArray; + }; + expect(request.attachments).toEqual([imageAttachment]); + expect(request.input).toBe( + `hello with attachments\n\n[Attached file: ${fileAttachmentPath} (notes.txt, text/plain, 5 B). Read it from disk when needed.]`, + ); + }), + ); + it("generates a thread title on the first turn", async () => { const harness = await createHarness(); const now = "2026-01-01T00:00:00.000Z"; diff --git a/apps/server/src/orchestration/Normalizer.test.ts b/apps/server/src/orchestration/Normalizer.test.ts index 113b6e1bae..047df160b5 100644 --- a/apps/server/src/orchestration/Normalizer.test.ts +++ b/apps/server/src/orchestration/Normalizer.test.ts @@ -1,17 +1,53 @@ -import { describe, expect, it } from "vite-plus/test"; +import * as NodeServices from "@effect/platform-node/NodeServices"; import { CommandId, - type ClientOrchestrationCommand, + DEFAULT_PROVIDER_INTERACTION_MODE, MessageId, ProjectId, + PROVIDER_SEND_TURN_MAX_IMAGE_BYTES, ProviderInstanceId, ThreadId, + type ClientOrchestrationCommand, + type UploadChatAttachment, } from "@t3tools/contracts"; +import { describe, expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Path from "effect/Path"; -import { canonicalizeClientCommandTimestamps } from "./Normalizer.ts"; +import * as ServerConfig from "../config.ts"; +import * as WorkspacePaths from "../workspace/WorkspacePaths.ts"; +import { canonicalizeClientCommandTimestamps, normalizeDispatchCommand } from "./Normalizer.ts"; + +const testLayer = Layer.mergeAll( + ServerConfig.ServerConfig.layerTest(process.cwd(), { prefix: "t3-normalizer-test-" }), + WorkspacePaths.layer, +).pipe(Layer.provideMerge(NodeServices.layer)); const clientCreatedAt = "2031-01-01T00:00:00.000Z"; const serverReceivedAt = "2026-07-18T00:00:00.000Z"; +const now = "2026-01-01T00:00:00.000Z"; + +const turnStartCommand = ( + attachments: ReadonlyArray, +): ClientOrchestrationCommand => ({ + type: "thread.turn.start", + commandId: CommandId.make("cmd-turn-start-1"), + threadId: ThreadId.make("thread-1"), + message: { + messageId: MessageId.make("user-message-1"), + role: "user", + text: "hello normalizer", + attachments, + }, + runtimeMode: "full-access", + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + createdAt: now, +}); + +const asDataUrl = (mimeType: string, bytes: Buffer) => + `data:${mimeType};base64,${bytes.toString("base64")}`; describe("canonicalizeClientCommandTimestamps", () => { it("replaces a client command timestamp with the server receipt timestamp", () => { @@ -71,3 +107,86 @@ describe("canonicalizeClientCommandTimestamps", () => { expect(result.bootstrap?.createThread?.createdAt).toBe(serverReceivedAt); }); }); + +describe("Normalizer", () => { + it.effect("persists file attachments and writes their bytes to the attachments dir", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const { attachmentsDir } = yield* ServerConfig.ServerConfig; + const bytes = Buffer.from("hello world"); + + const normalized = yield* normalizeDispatchCommand( + turnStartCommand([ + { + type: "file", + name: "notes.txt", + mimeType: "text/plain", + sizeBytes: bytes.byteLength, + dataUrl: asDataUrl("text/plain", bytes), + }, + ]), + ); + + expect(normalized.type).toBe("thread.turn.start"); + if (normalized.type !== "thread.turn.start") { + return; + } + const attachment = normalized.message.attachments[0]; + expect(attachment).toMatchObject({ + type: "file", + name: "notes.txt", + mimeType: "text/plain", + sizeBytes: bytes.byteLength, + }); + expect(attachment?.id).toMatch( + /^thread-1-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/, + ); + if (!attachment) { + return; + } + + const attachmentPath = path.join(attachmentsDir, `${attachment.id}.txt`); + expect(yield* fileSystem.readFileString(attachmentPath)).toBe("hello world"); + }).pipe(Effect.provide(testLayer)), + ); + + it.effect("rejects image attachments with a non-image data URL mime type", () => + Effect.gen(function* () { + const error = yield* normalizeDispatchCommand( + turnStartCommand([ + { + type: "image", + name: "fake.png", + mimeType: "image/png", + sizeBytes: 5, + dataUrl: asDataUrl("text/plain", Buffer.from("hello")), + }, + ]), + ).pipe(Effect.flip); + + expect(error._tag).toBe("OrchestrationDispatchCommandError"); + expect(error.message).toBe("Invalid image attachment payload for 'fake.png'."); + }).pipe(Effect.provide(testLayer)), + ); + + it.effect("rejects file attachments over the maximum attachment size", () => + Effect.gen(function* () { + const bytes = Buffer.alloc(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES + 1, "a"); + const error = yield* normalizeDispatchCommand( + turnStartCommand([ + { + type: "file", + name: "big.txt", + mimeType: "text/plain", + sizeBytes: PROVIDER_SEND_TURN_MAX_IMAGE_BYTES, + dataUrl: asDataUrl("text/plain", bytes), + }, + ]), + ).pipe(Effect.flip); + + expect(error._tag).toBe("OrchestrationDispatchCommandError"); + expect(error.message).toBe("Attachment 'big.txt' is empty or too large."); + }).pipe(Effect.provide(testLayer)), + ); +});