GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — feat(server): claim uploaded attachments at v2 dispatch · pingdotgg/t3code@d481bf3

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • apps
    • server/src
      • orchestration-v2
        • AttachmentClaims.test.ts
        • AttachmentClaims.ts
      • ws.ts
    • web/src/components
      • ChatView.tsx
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎apps/server/src/orchestration-v2/AttachmentClaims.test.ts‎

Copy file name to clipboard
+184Lines changed: 184 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,184 @@
1+
// @effect-diagnostics nodeBuiltinImport:off
2+
import * as NodeFS from "node:fs";
3+
import * as NodePath from "node:path";
4+
5+
import * as NodeServices from "@effect/platform-node/NodeServices";
6+
import { describe, expect, it } from "@effect/vitest";
7+
import { ChatAttachmentId, type ChatAttachment } from "@t3tools/contracts";
8+
import * as Effect from "effect/Effect";
9+
import * as Layer from "effect/Layer";
10+
11+
import {
12+
createPendingAttachmentId,
13+
parseThreadSegmentFromAttachmentId,
14+
} from "../attachmentStore.ts";
15+
import * as ServerConfig from "../config.ts";
16+
import {
17+
attachmentIsPendingUpload,
18+
claimPendingAttachments,
19+
releaseClaimedAttachments,
20+
} from "./AttachmentClaims.ts";
21+
22+
const testLayer = Layer.mergeAll(NodeServices.layer).pipe(
23+
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-attachment-claims-" })),
24+
Layer.provideMerge(NodeServices.layer),
25+
);
26+
27+
const stagePendingUpload = Effect.fn("test.stagePendingUpload")(function* (input: {
28+
readonly name: string;
29+
readonly bytes: Uint8Array;
30+
readonly mimeType: string;
31+
}) {
32+
const config = yield* ServerConfig.ServerConfig;
33+
const pendingId = createPendingAttachmentId();
34+
const attachment: ChatAttachment = {
35+
type: "image",
36+
id: ChatAttachmentId.make(pendingId!),
37+
name: input.name,
38+
mimeType: input.mimeType,
39+
sizeBytes: input.bytes.byteLength,
40+
};
41+
yield* Effect.sync(() => {
42+
NodeFS.mkdirSync(config.attachmentsDir, { recursive: true });
43+
NodeFS.writeFileSync(NodePath.join(config.attachmentsDir, `${pendingId}.png`), input.bytes);
44+
});
45+
return attachment;
46+
});
47+
48+
describe("AttachmentClaims", () => {
49+
it.effect("claims a pending upload into the thread store and rewrites the id", () =>
50+
Effect.gen(function* () {
51+
const pending = yield* stagePendingUpload({
52+
name: "screenshot.png",
53+
bytes: new Uint8Array([1, 2, 3, 4]),
54+
mimeType: "image/png",
55+
});
56+
const config = yield* ServerConfig.ServerConfig;
57+
58+
const claimed = yield* claimPendingAttachments({
59+
threadId: "thread-claims-1",
60+
attachments: [pending],
61+
});
62+
63+
expect(claimed.attachments).toHaveLength(1);
64+
const attachment = claimed.attachments[0]!;
65+
expect(attachmentIsPendingUpload(attachment)).toBe(false);
66+
expect(parseThreadSegmentFromAttachmentId(attachment.id)).toBe("thread-claims-1");
67+
expect(claimed.claimedPaths).toHaveLength(1);
68+
expect(NodeFS.existsSync(claimed.claimedPaths[0]!)).toBe(true);
69+
// The pending copy stays behind as the retry source.
70+
const pendingFiles = NodeFS.readdirSync(config.attachmentsDir).filter((entry) =>
71+
entry.startsWith("pending-"),
72+
);
73+
expect(pendingFiles).toHaveLength(1);
74+
}).pipe(Effect.provide(testLayer)),
75+
);
76+
77+
it.effect("passes already-claimed attachments through untouched", () =>
78+
Effect.gen(function* () {
79+
const stored: ChatAttachment = {
80+
type: "image",
81+
id: ChatAttachmentId.make("thread-claims-2-00000000-0000-4000-8000-000000000001"),
82+
name: "existing.png",
83+
mimeType: "image/png",
84+
sizeBytes: 4,
85+
};
86+
const claimed = yield* claimPendingAttachments({
87+
threadId: "thread-claims-2",
88+
attachments: [stored],
89+
});
90+
expect(claimed.attachments[0]).toBe(stored);
91+
expect(claimed.claimedPaths).toHaveLength(0);
92+
}).pipe(Effect.provide(testLayer)),
93+
);
94+
95+
it.effect("rejects a pending ref whose staged file is missing", () =>
96+
Effect.gen(function* () {
97+
const missing: ChatAttachment = {
98+
type: "image",
99+
id: ChatAttachmentId.make(createPendingAttachmentId()!),
100+
name: "gone.png",
101+
mimeType: "image/png",
102+
sizeBytes: 4,
103+
};
104+
const result = yield* Effect.exit(
105+
claimPendingAttachments({ threadId: "thread-claims-3", attachments: [missing] }),
106+
);
107+
expect(result._tag).toBe("Failure");
108+
}).pipe(Effect.provide(testLayer)),
109+
);
110+
111+
it.effect("rejects a size mismatch and cleans up earlier claims from the batch", () =>
112+
Effect.gen(function* () {
113+
const good = yield* stagePendingUpload({
114+
name: "one.png",
115+
bytes: new Uint8Array([1, 2, 3, 4]),
116+
mimeType: "image/png",
117+
});
118+
const staged = yield* stagePendingUpload({
119+
name: "two.png",
120+
bytes: new Uint8Array([1, 2, 3, 4]),
121+
mimeType: "image/png",
122+
});
123+
const mismatched = { ...staged, sizeBytes: 999 };
124+
const config = yield* ServerConfig.ServerConfig;
125+
126+
const result = yield* Effect.exit(
127+
claimPendingAttachments({
128+
threadId: "thread-claims-4",
129+
attachments: [good, mismatched],
130+
}),
131+
);
132+
133+
expect(result._tag).toBe("Failure");
134+
if (result._tag === "Failure") {
135+
const error = result.cause;
136+
expect(String(error)).toContain("stored size does not match");
137+
}
138+
// The successfully claimed first attachment was rolled back.
139+
const claimedFiles = NodeFS.readdirSync(config.attachmentsDir).filter((entry) =>
140+
entry.startsWith("thread-claims-4-"),
141+
);
142+
expect(claimedFiles).toHaveLength(0);
143+
}).pipe(Effect.provide(testLayer)),
144+
);
145+
146+
it.effect("releaseClaimedAttachments removes claimed copies best-effort", () =>
147+
Effect.gen(function* () {
148+
const pending = yield* stagePendingUpload({
149+
name: "release.png",
150+
bytes: new Uint8Array([9, 9]),
151+
mimeType: "image/png",
152+
});
153+
const claimed = yield* claimPendingAttachments({
154+
threadId: "thread-claims-5",
155+
attachments: [pending],
156+
});
157+
expect(NodeFS.existsSync(claimed.claimedPaths[0]!)).toBe(true);
158+
yield* releaseClaimedAttachments(claimed.claimedPaths);
159+
expect(NodeFS.existsSync(claimed.claimedPaths[0]!)).toBe(false);
160+
// Releasing again is a no-op, not an error.
161+
yield* releaseClaimedAttachments(claimed.claimedPaths);
162+
}).pipe(Effect.provide(testLayer)),
163+
);
164+
165+
it.effect("treats malformed ids as non-pending and passes them through", () =>
166+
Effect.gen(function* () {
167+
// Not a parseable pending ref: nothing to claim, so the ref flows
168+
// through unchanged and downstream delivery decides what to do with it.
169+
const bogus: ChatAttachment = {
170+
type: "image",
171+
id: ChatAttachmentId.make("pending-not-a-uuid"),
172+
name: "weird.png",
173+
mimeType: "image/png",
174+
sizeBytes: 1,
175+
};
176+
const claimed = yield* claimPendingAttachments({
177+
threadId: "thread-claims-6",
178+
attachments: [bogus],
179+
});
180+
expect(claimed.attachments[0]).toBe(bogus);
181+
expect(claimed.claimedPaths).toHaveLength(0);
182+
}).pipe(Effect.provide(testLayer)),
183+
);
184+
});
Collapse file

‎apps/server/src/orchestration-v2/AttachmentClaims.ts‎

Copy file name to clipboard
+126Lines changed: 126 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,126 @@
1+
import * as FileSystem from "effect/FileSystem";
2+
import { ChatAttachmentId, type ChatAttachment } from "@t3tools/contracts";
3+
import * as Effect from "effect/Effect";
4+
import * as Schema from "effect/Schema";
5+
6+
import {
7+
parseThreadSegmentFromAttachmentId,
8+
PENDING_ATTACHMENT_THREAD_SEGMENT,
9+
planAttachmentClaim,
10+
resolveAttachmentPath,
11+
} from "../attachmentStore.ts";
12+
import * as ServerConfig from "../config.ts";
13+
14+
export class AttachmentClaimError extends Schema.TaggedErrorClass<AttachmentClaimError>()(
15+
"AttachmentClaimError",
16+
{
17+
message: Schema.String,
18+
cause: Schema.optional(Schema.Defect()),
19+
},
20+
) {}
21+
22+
export interface ClaimedAttachments {
23+
readonly attachments: ReadonlyArray<ChatAttachment>;
24+
readonly claimedPaths: ReadonlyArray<string>;
25+
}
26+
27+
export function attachmentIsPendingUpload(attachment: ChatAttachment): boolean {
28+
return parseThreadSegmentFromAttachmentId(attachment.id) === PENDING_ATTACHMENT_THREAD_SEGMENT;
29+
}
30+
31+
/** Best-effort removal of claimed copies after a failed dispatch: the pending
32+
* upload remains the retry source, so only the thread-scoped copies go. */
33+
export const releaseClaimedAttachments = Effect.fn("AttachmentClaims.releaseClaimedAttachments")(
34+
function* (claimedPaths: ReadonlyArray<string>) {
35+
if (claimedPaths.length === 0) return;
36+
const fileSystem = yield* FileSystem.FileSystem;
37+
yield* Effect.forEach(claimedPaths, (path) => fileSystem.remove(path).pipe(Effect.ignore), {
38+
concurrency: 1,
39+
discard: true,
40+
});
41+
},
42+
);
43+
44+
/**
45+
* Claims pending uploads into the target thread's attachment store before the
46+
* command enters the orchestrator: verifies the staged file, copies it under a
47+
* thread-scoped id, and rewrites the attachment ref. A copy, not a move — the
48+
* pending file stays behind as the retry source for a failed bootstrap, and
49+
* the periodic pending sweep reclaims it later. Already-claimed attachments
50+
* pass through untouched.
51+
*/
52+
export const claimPendingAttachments = Effect.fn("AttachmentClaims.claimPendingAttachments")(
53+
function* (input: {
54+
readonly threadId: string;
55+
readonly attachments: ReadonlyArray<ChatAttachment>;
56+
}) {
57+
if (!input.attachments.some(attachmentIsPendingUpload)) {
58+
return { attachments: input.attachments, claimedPaths: [] } satisfies ClaimedAttachments;
59+
}
60+
const serverConfig = yield* ServerConfig.ServerConfig;
61+
const fileSystem = yield* FileSystem.FileSystem;
62+
const claimedPaths: string[] = [];
63+
const attachments = yield* Effect.forEach(
64+
input.attachments,
65+
(attachment) =>
66+
Effect.gen(function* () {
67+
if (!attachmentIsPendingUpload(attachment)) {
68+
return attachment;
69+
}
70+
const claim = planAttachmentClaim({
71+
attachmentsDir: serverConfig.attachmentsDir,
72+
threadId: input.threadId,
73+
attachmentId: attachment.id,
74+
});
75+
if (!claim.ok) {
76+
return yield* new AttachmentClaimError({
77+
message: `Attachment '${attachment.name}' cannot be sent: ${claim.reason}.`,
78+
});
79+
}
80+
const info = yield* fileSystem.stat(claim.currentPath).pipe(
81+
Effect.mapError(
82+
(cause) =>
83+
new AttachmentClaimError({
84+
message: `Attachment '${attachment.name}' cannot be sent: attachment not found.`,
85+
cause,
86+
}),
87+
),
88+
);
89+
if (Number(info.size) !== attachment.sizeBytes) {
90+
return yield* new AttachmentClaimError({
91+
message: `Attachment '${attachment.name}' cannot be sent: stored size does not match.`,
92+
});
93+
}
94+
const normalized: ChatAttachment = {
95+
...attachment,
96+
id: ChatAttachmentId.make(claim.finalId),
97+
mimeType: attachment.mimeType.toLowerCase(),
98+
};
99+
const expectedPath = resolveAttachmentPath({
100+
attachmentsDir: serverConfig.attachmentsDir,
101+
attachment: normalized,
102+
});
103+
if (expectedPath !== claim.finalPath) {
104+
return yield* new AttachmentClaimError({
105+
message: `Attachment '${attachment.name}' cannot be sent: attachment type does not match the upload.`,
106+
});
107+
}
108+
// A copy, not a hard link: an agent editing the delivered file in
109+
// place must not mutate the retry source.
110+
yield* fileSystem.copyFile(claim.currentPath, claim.finalPath).pipe(
111+
Effect.mapError(
112+
(cause) =>
113+
new AttachmentClaimError({
114+
message: `Failed to claim attachment '${attachment.name}' for this thread.`,
115+
cause,
116+
}),
117+
),
118+
);
119+
claimedPaths.push(claim.finalPath);
120+
return normalized;
121+
}),
122+
{ concurrency: 1 },
123+
).pipe(Effect.tapError(() => releaseClaimedAttachments(claimedPaths)));
124+
return { attachments, claimedPaths } satisfies ClaimedAttachments;
125+
},
126+
);

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.