Skip to content

Commit a604df5

Browse files
committed
fix: address attachment upload review findings
1 parent 10aeb8c commit a604df5

9 files changed

Lines changed: 171 additions & 47 deletions

File tree

‎apps/server/src/attachmentStore.test.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,8 @@ describe("attachmentStore", () => {
5252
const pendingId = createPendingAttachmentId();
5353
expect(parseThreadSegmentFromAttachmentId(pendingId)).toBe("pending");
5454
expect(parseAttachmentUuid(pendingId)).toMatch(/^[a-f0-9-]{36}$/);
55-
expect(parseThreadSegmentFromAttachmentId(createAttachmentId("pending")!)).toBe(
55+
expect(parseThreadSegmentFromAttachmentId(createAttachmentId("pending")!)).toBe("_pending");
56+
expect(parseThreadSegmentFromAttachmentId(createAttachmentId("pending_thread")!)).toBe(
5657
"pending_thread",
5758
);
5859
});

‎apps/server/src/attachmentStore.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ export function toSafeThreadAttachmentSegment(threadId: string): string | null {
3636
if (segment.length === 0) {
3737
return null;
3838
}
39-
return segment === PENDING_ATTACHMENT_THREAD_SEGMENT ? "pending_thread" : segment;
39+
return segment === PENDING_ATTACHMENT_THREAD_SEGMENT ? "_pending" : segment;
4040
}
4141

4242
export function createPendingAttachmentId(): string {

‎apps/server/src/orchestration/Normalizer.attachments.test.ts‎

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ import * as Layer from "effect/Layer";
1515

1616
import * as ServerConfig from "../config.ts";
1717
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
18-
import { normalizeDispatchCommand } from "./Normalizer.ts";
18+
import { cleanupFailedUploadedAttachments, normalizeDispatchCommand } from "./Normalizer.ts";
1919

2020
const testLayer = Layer.mergeAll(
2121
WorkspacePaths.layer,
@@ -151,6 +151,35 @@ describe("normalizeDispatchCommand attachments", () => {
151151
}).pipe(Effect.provide(testLayer)),
152152
);
153153

154+
it.effect("removes failed attachment claims without deleting their pending uploads", () =>
155+
Effect.gen(function* () {
156+
const config = yield* ServerConfig.ServerConfig;
157+
const pendingPath = NodePath.join(config.attachmentsDir, `pending-${attachmentUuid}.png`);
158+
NodeFS.writeFileSync(pendingPath, Buffer.from("pixels"));
159+
const command = turnStartCommand({
160+
attachments: [
161+
{ dataUrl: "data:image/png;base64,cGl4ZWxz", sizeBytes: 6 },
162+
{ id: `pending-${attachmentUuid}`, sizeBytes: 6 },
163+
],
164+
});
165+
const normalized = yield* normalizeDispatchCommand(command);
166+
if (normalized.type !== "thread.turn.start") {
167+
throw new Error("Expected a thread.turn.start command.");
168+
}
169+
170+
const inlinePath = NodePath.join(
171+
config.attachmentsDir,
172+
`${normalized.message.attachments[0]!.id}.png`,
173+
);
174+
const claimedPath = NodePath.join(config.attachmentsDir, `thread-1-${attachmentUuid}.png`);
175+
yield* cleanupFailedUploadedAttachments(command, normalized);
176+
177+
expect(NodeFS.existsSync(pendingPath)).toBe(true);
178+
expect(NodeFS.existsSync(claimedPath)).toBe(false);
179+
expect(NodeFS.existsSync(inlinePath)).toBe(true);
180+
}).pipe(Effect.provide(testLayer)),
181+
);
182+
154183
it.effect("rejects uploaded attachments with the wrong size or thread", () =>
155184
Effect.gen(function* () {
156185
const config = yield* ServerConfig.ServerConfig;

‎apps/server/src/orchestration/Normalizer.ts‎

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,10 @@ import {
1313
import {
1414
createAttachmentId,
1515
planAttachmentClaim,
16+
PENDING_ATTACHMENT_THREAD_SEGMENT,
17+
parseThreadSegmentFromAttachmentId,
1618
resolveAttachmentPath,
19+
resolveAttachmentPathById,
1720
} from "../attachmentStore.ts";
1821
import { ServerConfig } from "../config.ts";
1922
import { parseBase64DataUrl } from "../imageMime.ts";
@@ -240,3 +243,51 @@ export const normalizeDispatchCommand = (command: ClientOrchestrationCommand) =>
240243
},
241244
} satisfies OrchestrationCommand;
242245
});
246+
247+
export const cleanupFailedUploadedAttachments = Effect.fn(
248+
"Normalizer.cleanupFailedUploadedAttachments",
249+
)(function* (command: ClientOrchestrationCommand, normalizedCommand: OrchestrationCommand) {
250+
if (command.type !== "thread.turn.start" || normalizedCommand.type !== "thread.turn.start") {
251+
return;
252+
}
253+
254+
const fileSystem = yield* FileSystem.FileSystem;
255+
const serverConfig = yield* ServerConfig;
256+
yield* Effect.forEach(
257+
normalizedCommand.message.attachments,
258+
(attachment, index) =>
259+
Effect.gen(function* () {
260+
const original = command.message.attachments[index];
261+
if (
262+
!original ||
263+
"dataUrl" in original ||
264+
parseThreadSegmentFromAttachmentId(original.id) !== PENDING_ATTACHMENT_THREAD_SEGMENT
265+
) {
266+
return;
267+
}
268+
269+
const pendingPath = resolveAttachmentPathById({
270+
attachmentsDir: serverConfig.attachmentsDir,
271+
attachmentId: original.id,
272+
});
273+
const claimedPath = resolveAttachmentPath({
274+
attachmentsDir: serverConfig.attachmentsDir,
275+
attachment,
276+
});
277+
if (!pendingPath || !claimedPath || pendingPath === claimedPath) {
278+
return;
279+
}
280+
281+
yield* fileSystem.remove(claimedPath, { force: true }).pipe(
282+
Effect.tapError((cause) =>
283+
Effect.logWarning("Failed to remove an unclaimed attachment copy.", {
284+
attachmentId: attachment.id,
285+
cause,
286+
}),
287+
),
288+
Effect.orElseSucceed(() => undefined),
289+
);
290+
}),
291+
{ concurrency: 1 },
292+
);
293+
});

‎apps/server/src/orchestration/http.ts‎

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import * as Option from "effect/Option";
88
import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
99

1010
import { projectThreadDetailSnapshot } from "./ActivityPayloadProjection.ts";
11-
import { normalizeDispatchCommand } from "./Normalizer.ts";
11+
import { cleanupFailedUploadedAttachments, normalizeDispatchCommand } from "./Normalizer.ts";
1212
import {
1313
annotateEnvironmentRequest,
1414
failEnvironmentInternal,
@@ -96,13 +96,14 @@ export const orchestrationHttpApiLayer = HttpApiBuilder.group(
9696
const normalizedCommand = yield* normalizeDispatchCommand(args.payload).pipe(
9797
Effect.catch(() => failEnvironmentInvalidRequest("invalid_command")),
9898
);
99-
return yield* orchestrationEngine
100-
.dispatch(normalizedCommand)
101-
.pipe(
102-
Effect.catch((cause) =>
103-
failEnvironmentInternal("orchestration_dispatch_failed", cause),
104-
),
105-
);
99+
return yield* orchestrationEngine.dispatch(normalizedCommand).pipe(
100+
Effect.tapError(() =>
101+
cleanupFailedUploadedAttachments(args.payload, normalizedCommand),
102+
),
103+
Effect.catch((cause) =>
104+
failEnvironmentInternal("orchestration_dispatch_failed", cause),
105+
),
106+
);
106107
}),
107108
);
108109
}),

‎apps/server/src/server.test.ts‎

Lines changed: 66 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -8042,12 +8042,14 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
80428042
it.effect("cleans up created bootstrap threads when worktree creation defects", () =>
80438043
Effect.gen(function* () {
80448044
const dispatchedCommands: Array<OrchestrationCommand> = [];
8045+
const fileSystem = yield* FileSystem.FileSystem;
8046+
const path = yield* Path.Path;
80458047
const createWorktree = vi.fn(
80468048
(_: Parameters<GitVcsDriver.GitVcsDriver["Service"]["createWorktree"]>[0]) =>
80478049
Effect.die(new Error("worktree exploded")),
80488050
);
80498051

8050-
yield* buildAppUnderTest({
8052+
const config = yield* buildAppUnderTest({
80518053
layers: {
80528054
gitVcsDriver: {
80538055
createWorktree,
@@ -8065,40 +8067,62 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
80658067

80668068
const createdAt = "2026-01-01T00:00:00.000Z";
80678069
const wsUrl = yield* getWsServerUrl("/ws");
8070+
let pendingAttachmentId: string | undefined;
80688071
const result = yield* Effect.scoped(
80698072
withWsRpcClient(wsUrl, (client) =>
8070-
client[ORCHESTRATION_WS_METHODS.dispatchCommand]({
8071-
type: "thread.turn.start",
8072-
commandId: CommandId.make("cmd-bootstrap-turn-start-defect"),
8073-
threadId: ThreadId.make("thread-bootstrap-defect"),
8074-
message: {
8075-
messageId: MessageId.make("msg-bootstrap-defect"),
8076-
role: "user",
8077-
text: "hello",
8078-
attachments: [],
8079-
},
8080-
modelSelection: defaultModelSelection,
8081-
runtimeMode: "full-access",
8082-
interactionMode: "default",
8083-
bootstrap: {
8084-
createThread: {
8085-
projectId: defaultProjectId,
8086-
title: "Bootstrap Thread",
8087-
modelSelection: defaultModelSelection,
8088-
runtimeMode: "full-access",
8089-
interactionMode: "default",
8090-
branch: "main",
8091-
worktreePath: null,
8092-
createdAt,
8073+
Effect.gen(function* () {
8074+
const upload = yield* client[WS_METHODS.attachmentsCreateUploadUrl]({
8075+
name: "screenshot.png",
8076+
mimeType: "image/png",
8077+
sizeBytes: 6,
8078+
});
8079+
pendingAttachmentId = upload.attachmentId;
8080+
const uploadResponse = yield* HttpClient.post(upload.relativeUrl, {
8081+
body: HttpBody.uint8Array(new Uint8Array([1, 2, 3, 4, 5, 6]), "image/png"),
8082+
});
8083+
assert.equal(uploadResponse.status, 204);
8084+
8085+
return yield* client[ORCHESTRATION_WS_METHODS.dispatchCommand]({
8086+
type: "thread.turn.start",
8087+
commandId: CommandId.make("cmd-bootstrap-turn-start-defect"),
8088+
threadId: ThreadId.make("thread-bootstrap-defect"),
8089+
message: {
8090+
messageId: MessageId.make("msg-bootstrap-defect"),
8091+
role: "user",
8092+
text: "hello",
8093+
attachments: [
8094+
{
8095+
type: "image",
8096+
id: upload.attachmentId,
8097+
name: "screenshot.png",
8098+
mimeType: "image/png",
8099+
sizeBytes: 6,
8100+
},
8101+
],
80938102
},
8094-
prepareWorktree: {
8095-
projectCwd: "/tmp/project",
8096-
baseBranch: "main",
8097-
branch: "t3code/bootstrap-refName",
8103+
modelSelection: defaultModelSelection,
8104+
runtimeMode: "full-access",
8105+
interactionMode: "default",
8106+
bootstrap: {
8107+
createThread: {
8108+
projectId: defaultProjectId,
8109+
title: "Bootstrap Thread",
8110+
modelSelection: defaultModelSelection,
8111+
runtimeMode: "full-access",
8112+
interactionMode: "default",
8113+
branch: "main",
8114+
worktreePath: null,
8115+
createdAt,
8116+
},
8117+
prepareWorktree: {
8118+
projectCwd: "/tmp/project",
8119+
baseBranch: "main",
8120+
branch: "t3code/bootstrap-refName",
8121+
},
8122+
runSetupScript: false,
80988123
},
8099-
runSetupScript: false,
8100-
},
8101-
createdAt,
8124+
createdAt,
8125+
});
81028126
}),
81038127
).pipe(Effect.result),
81048128
);
@@ -8111,6 +8135,17 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
81118135
dispatchedCommands.map((command) => command.type),
81128136
["thread.create", "thread.delete"],
81138137
);
8138+
assert.isDefined(pendingAttachmentId);
8139+
assert.isTrue(
8140+
yield* fileSystem.exists(path.join(config.attachmentsDir, `${pendingAttachmentId}.png`)),
8141+
);
8142+
const claimedAttachmentId = pendingAttachmentId!.replace(
8143+
/^pending-/,
8144+
"thread-bootstrap-defect-",
8145+
);
8146+
assert.isFalse(
8147+
yield* fileSystem.exists(path.join(config.attachmentsDir, `${claimedAttachmentId}.png`)),
8148+
);
81148149
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
81158150
);
81168151

‎apps/server/src/ws.ts‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,10 @@ import {
7373
projectActivityEvent,
7474
projectThreadDetailSnapshot,
7575
} from "./orchestration/ActivityPayloadProjection.ts";
76-
import { normalizeDispatchCommand } from "./orchestration/Normalizer.ts";
76+
import {
77+
cleanupFailedUploadedAttachments,
78+
normalizeDispatchCommand,
79+
} from "./orchestration/Normalizer.ts";
7780
import * as OrchestrationEngine from "./orchestration/Services/OrchestrationEngine.ts";
7881
import * as ProjectionSnapshotQuery from "./orchestration/Services/ProjectionSnapshotQuery.ts";
7982
import {
@@ -1160,7 +1163,9 @@ const makeWsRpcLayer = (
11601163
),
11611164
)
11621165
: false;
1163-
const result = yield* dispatchNormalizedCommand(normalizedCommand);
1166+
const result = yield* dispatchNormalizedCommand(normalizedCommand).pipe(
1167+
Effect.tapError(() => cleanupFailedUploadedAttachments(command, normalizedCommand)),
1168+
);
11641169
yield* recordClientCommandAnalytics(normalizedCommand);
11651170
if (parkingCommand) {
11661171
const parkingKind = parkingCommand.type === "thread.archive" ? "archive" : "settle";

‎apps/web/src/components/ChatView.tsx‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5414,20 +5414,21 @@ function ChatViewContent(props: ChatViewProps) {
54145414
return;
54155415
}
54165416

5417+
sendInFlightRef.current = true;
54175418
if (supportsAttachmentUploads && composerImagesSnapshot.length > 0) {
54185419
for (const image of composerImagesSnapshot) {
54195420
startAttachmentUpload({ environmentId, image });
54205421
}
54215422
await awaitAttachmentUploads(composerImagesSnapshot.map((image) => image.id));
54225423
if (getUploadedAttachments({ environmentId, images: composerImagesSnapshot }) === null) {
5424+
sendInFlightRef.current = false;
54235425
setThreadError(threadIdForSend, "Retry or remove failed image uploads before sending.");
54245426
return;
54255427
}
54265428
}
54275429

54285430
const resolvedSubmissionIntent =
54295431
submissionIntent === "background" && isLocalDraftThread ? "background" : "foreground";
5430-
sendInFlightRef.current = true;
54315432
if (
54325433
shouldDockDraftHeroForSubmission({
54335434
isDraftHeroState,

‎apps/web/src/components/chat/ChatComposer.tsx‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -743,7 +743,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
743743
environmentId,
744744
})
745745
: null;
746-
const sendDisabledReason = externalSendDisabledReason ?? attachmentBlockReason;
746+
const sendDisabledReason =
747+
externalSendDisabledReason ?? (activePendingProgress ? null : attachmentBlockReason);
747748
const isSendDisabled = sendDisabledReason !== null;
748749

749750
const setComposerDraftPrompt = useComposerDraftStore((store) => store.setPrompt);
@@ -3258,7 +3259,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
32583259
</Tooltip>
32593260
)}
32603261
{upload?.status === "uploading" && (
3261-
<span className="absolute inset-x-0 bottom-0 bg-background/85 px-1 text-center text-[10px] text-foreground">
3262+
<span className="pointer-events-none absolute inset-x-0 bottom-0 bg-background/85 px-1 text-center text-[10px] text-foreground">
32623263
{formatAttachmentUploadProgress(upload.progress)}
32633264
</span>
32643265
)}

0 commit comments

Comments
 (0)